clang  6.0.0svn
Expr.h
Go to the documentation of this file.
1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the Expr interface and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_AST_EXPR_H
15 #define LLVM_CLANG_AST_EXPR_H
16 
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTVector.h"
19 #include "clang/AST/Decl.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/SyncScope.h"
28 #include "clang/Basic/TypeTraits.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/AtomicOrdering.h"
34 #include "llvm/Support/Compiler.h"
35 
36 namespace clang {
37  class APValue;
38  class ASTContext;
39  class BlockDecl;
40  class CXXBaseSpecifier;
41  class CXXMemberCallExpr;
42  class CXXOperatorCallExpr;
43  class CastExpr;
44  class Decl;
45  class IdentifierInfo;
46  class MaterializeTemporaryExpr;
47  class NamedDecl;
48  class ObjCPropertyRefExpr;
49  class OpaqueValueExpr;
50  class ParmVarDecl;
51  class StringLiteral;
52  class TargetInfo;
53  class ValueDecl;
54 
55 /// \brief A simple array of base specifiers.
57 
58 /// \brief An adjustment to be made to the temporary created when emitting a
59 /// reference binding, which accesses a particular subobject of that temporary.
61  enum {
65  } Kind;
66 
67  struct DTB {
70  };
71 
72  struct P {
75  };
76 
77  union {
80  struct P Ptr;
81  };
82 
85  : Kind(DerivedToBaseAdjustment) {
88  }
89 
91  : Kind(FieldAdjustment) {
92  this->Field = Field;
93  }
94 
96  : Kind(MemberPointerAdjustment) {
97  this->Ptr.MPT = MPT;
98  this->Ptr.RHS = RHS;
99  }
100 };
101 
102 /// Expr - This represents one expression. Note that Expr's are subclasses of
103 /// Stmt. This allows an expression to be transparently used any place a Stmt
104 /// is required.
105 ///
106 class Expr : public Stmt {
107  QualType TR;
108 
109 protected:
111  bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112  : Stmt(SC)
113  {
114  ExprBits.TypeDependent = TD;
115  ExprBits.ValueDependent = VD;
116  ExprBits.InstantiationDependent = ID;
117  ExprBits.ValueKind = VK;
118  ExprBits.ObjectKind = OK;
119  assert(ExprBits.ObjectKind == OK && "truncated kind");
120  ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121  setType(T);
122  }
123 
124  /// \brief Construct an empty expression.
125  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
126 
127 public:
128  QualType getType() const { return TR; }
129  void setType(QualType t) {
130  // In C++, the type of an expression is always adjusted so that it
131  // will not have reference type (C++ [expr]p6). Use
132  // QualType::getNonReferenceType() to retrieve the non-reference
133  // type. Additionally, inspect Expr::isLvalue to determine whether
134  // an expression that is adjusted in this manner should be
135  // considered an lvalue.
136  assert((t.isNull() || !t->isReferenceType()) &&
137  "Expressions can't have reference type");
138 
139  TR = t;
140  }
141 
142  /// isValueDependent - Determines whether this expression is
143  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
144  /// array bound of "Chars" in the following example is
145  /// value-dependent.
146  /// @code
147  /// template<int Size, char (&Chars)[Size]> struct meta_string;
148  /// @endcode
149  bool isValueDependent() const { return ExprBits.ValueDependent; }
150 
151  /// \brief Set whether this expression is value-dependent or not.
152  void setValueDependent(bool VD) {
153  ExprBits.ValueDependent = VD;
154  }
155 
156  /// isTypeDependent - Determines whether this expression is
157  /// type-dependent (C++ [temp.dep.expr]), which means that its type
158  /// could change from one template instantiation to the next. For
159  /// example, the expressions "x" and "x + y" are type-dependent in
160  /// the following code, but "y" is not type-dependent:
161  /// @code
162  /// template<typename T>
163  /// void add(T x, int y) {
164  /// x + y;
165  /// }
166  /// @endcode
167  bool isTypeDependent() const { return ExprBits.TypeDependent; }
168 
169  /// \brief Set whether this expression is type-dependent or not.
170  void setTypeDependent(bool TD) {
171  ExprBits.TypeDependent = TD;
172  }
173 
174  /// \brief Whether this expression is instantiation-dependent, meaning that
175  /// it depends in some way on a template parameter, even if neither its type
176  /// nor (constant) value can change due to the template instantiation.
177  ///
178  /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
179  /// instantiation-dependent (since it involves a template parameter \c T), but
180  /// is neither type- nor value-dependent, since the type of the inner
181  /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
182  /// \c sizeof is known.
183  ///
184  /// \code
185  /// template<typename T>
186  /// void f(T x, T y) {
187  /// sizeof(sizeof(T() + T());
188  /// }
189  /// \endcode
190  ///
192  return ExprBits.InstantiationDependent;
193  }
194 
195  /// \brief Set whether this expression is instantiation-dependent or not.
197  ExprBits.InstantiationDependent = ID;
198  }
199 
200  /// \brief Whether this expression contains an unexpanded parameter
201  /// pack (for C++11 variadic templates).
202  ///
203  /// Given the following function template:
204  ///
205  /// \code
206  /// template<typename F, typename ...Types>
207  /// void forward(const F &f, Types &&...args) {
208  /// f(static_cast<Types&&>(args)...);
209  /// }
210  /// \endcode
211  ///
212  /// The expressions \c args and \c static_cast<Types&&>(args) both
213  /// contain parameter packs.
215  return ExprBits.ContainsUnexpandedParameterPack;
216  }
217 
218  /// \brief Set the bit that describes whether this expression
219  /// contains an unexpanded parameter pack.
220  void setContainsUnexpandedParameterPack(bool PP = true) {
221  ExprBits.ContainsUnexpandedParameterPack = PP;
222  }
223 
224  /// getExprLoc - Return the preferred location for the arrow when diagnosing
225  /// a problem with a generic expression.
226  SourceLocation getExprLoc() const LLVM_READONLY;
227 
228  /// isUnusedResultAWarning - Return true if this immediate expression should
229  /// be warned about if the result is unused. If so, fill in expr, location,
230  /// and ranges with expr to warn on and source locations/ranges appropriate
231  /// for a warning.
232  bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
233  SourceRange &R1, SourceRange &R2,
234  ASTContext &Ctx) const;
235 
236  /// isLValue - True if this expression is an "l-value" according to
237  /// the rules of the current language. C and C++ give somewhat
238  /// different rules for this concept, but in general, the result of
239  /// an l-value expression identifies a specific object whereas the
240  /// result of an r-value expression is a value detached from any
241  /// specific storage.
242  ///
243  /// C++11 divides the concept of "r-value" into pure r-values
244  /// ("pr-values") and so-called expiring values ("x-values"), which
245  /// identify specific objects that can be safely cannibalized for
246  /// their resources. This is an unfortunate abuse of terminology on
247  /// the part of the C++ committee. In Clang, when we say "r-value",
248  /// we generally mean a pr-value.
249  bool isLValue() const { return getValueKind() == VK_LValue; }
250  bool isRValue() const { return getValueKind() == VK_RValue; }
251  bool isXValue() const { return getValueKind() == VK_XValue; }
252  bool isGLValue() const { return getValueKind() != VK_RValue; }
253 
264  LV_ArrayTemporary
265  };
266  /// Reasons why an expression might not be an l-value.
267  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
268 
275  MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
286  MLV_ArrayTemporary
287  };
288  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289  /// does not have an incomplete type, does not have a const-qualified type,
290  /// and if it is a structure or union, does not have any member (including,
291  /// recursively, any member or element of all contained aggregates or unions)
292  /// with a const-qualified type.
293  ///
294  /// \param Loc [in,out] - A source location which *may* be filled
295  /// in with the location of the expression making this a
296  /// non-modifiable lvalue, if specified.
298  isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
299 
300  /// \brief The return type of classify(). Represents the C++11 expression
301  /// taxonomy.
303  public:
304  /// \brief The various classification results. Most of these mean prvalue.
305  enum Kinds {
308  CL_Function, // Functions cannot be lvalues in C.
309  CL_Void, // Void cannot be an lvalue in C.
310  CL_AddressableVoid, // Void expression whose address can be taken in C.
311  CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312  CL_MemberFunction, // An expression referring to a member function
314  CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315  CL_ArrayTemporary, // A temporary of array type.
316  CL_ObjCMessageRValue, // ObjC message is an rvalue
317  CL_PRValue // A prvalue for any other reason, of any other type
318  };
319  /// \brief The results of modification testing.
321  CM_Untested, // testModifiable was false.
323  CM_RValue, // Not modifiable because it's an rvalue
324  CM_Function, // Not modifiable because it's a function; C++ only
325  CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326  CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
331  CM_IncompleteType
332  };
333 
334  private:
335  friend class Expr;
336 
337  unsigned short Kind;
338  unsigned short Modifiable;
339 
340  explicit Classification(Kinds k, ModifiableType m)
341  : Kind(k), Modifiable(m)
342  {}
343 
344  public:
346 
347  Kinds getKind() const { return static_cast<Kinds>(Kind); }
349  assert(Modifiable != CM_Untested && "Did not test for modifiability.");
350  return static_cast<ModifiableType>(Modifiable);
351  }
352  bool isLValue() const { return Kind == CL_LValue; }
353  bool isXValue() const { return Kind == CL_XValue; }
354  bool isGLValue() const { return Kind <= CL_XValue; }
355  bool isPRValue() const { return Kind >= CL_Function; }
356  bool isRValue() const { return Kind >= CL_XValue; }
357  bool isModifiable() const { return getModifiable() == CM_Modifiable; }
358 
359  /// \brief Create a simple, modifiably lvalue
361  return Classification(CL_LValue, CM_Modifiable);
362  }
363 
364  };
365  /// \brief Classify - Classify this expression according to the C++11
366  /// expression taxonomy.
367  ///
368  /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
369  /// old lvalue vs rvalue. This function determines the type of expression this
370  /// is. There are three expression types:
371  /// - lvalues are classical lvalues as in C++03.
372  /// - prvalues are equivalent to rvalues in C++03.
373  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
374  /// function returning an rvalue reference.
375  /// lvalues and xvalues are collectively referred to as glvalues, while
376  /// prvalues and xvalues together form rvalues.
378  return ClassifyImpl(Ctx, nullptr);
379  }
380 
381  /// \brief ClassifyModifiable - Classify this expression according to the
382  /// C++11 expression taxonomy, and see if it is valid on the left side
383  /// of an assignment.
384  ///
385  /// This function extends classify in that it also tests whether the
386  /// expression is modifiable (C99 6.3.2.1p1).
387  /// \param Loc A source location that might be filled with a relevant location
388  /// if the expression is not modifiable.
390  return ClassifyImpl(Ctx, &Loc);
391  }
392 
393  /// getValueKindForType - Given a formal return or parameter type,
394  /// give its value kind.
396  if (const ReferenceType *RT = T->getAs<ReferenceType>())
397  return (isa<LValueReferenceType>(RT)
398  ? VK_LValue
399  : (RT->getPointeeType()->isFunctionType()
400  ? VK_LValue : VK_XValue));
401  return VK_RValue;
402  }
403 
404  /// getValueKind - The value kind that this expression produces.
406  return static_cast<ExprValueKind>(ExprBits.ValueKind);
407  }
408 
409  /// getObjectKind - The object kind that this expression produces.
410  /// Object kinds are meaningful only for expressions that yield an
411  /// l-value or x-value.
413  return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
414  }
415 
417  ExprObjectKind OK = getObjectKind();
418  return (OK == OK_Ordinary || OK == OK_BitField);
419  }
420 
421  /// setValueKind - Set the value kind produced by this expression.
422  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
423 
424  /// setObjectKind - Set the object kind produced by this expression.
425  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
426 
427 private:
428  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429 
430 public:
431 
432  /// \brief Returns true if this expression is a gl-value that
433  /// potentially refers to a bit-field.
434  ///
435  /// In C++, whether a gl-value refers to a bitfield is essentially
436  /// an aspect of the value-kind type system.
437  bool refersToBitField() const { return getObjectKind() == OK_BitField; }
438 
439  /// \brief If this expression refers to a bit-field, retrieve the
440  /// declaration of that bit-field.
441  ///
442  /// Note that this returns a non-null pointer in subtly different
443  /// places than refersToBitField returns true. In particular, this can
444  /// return a non-null pointer even for r-values loaded from
445  /// bit-fields, but it will return null for a conditional bit-field.
446  FieldDecl *getSourceBitField();
447 
448  const FieldDecl *getSourceBitField() const {
449  return const_cast<Expr*>(this)->getSourceBitField();
450  }
451 
452  Decl *getReferencedDeclOfCallee();
454  return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
455  }
456 
457  /// \brief If this expression is an l-value for an Objective C
458  /// property, find the underlying property reference expression.
459  const ObjCPropertyRefExpr *getObjCProperty() const;
460 
461  /// \brief Check if this expression is the ObjC 'self' implicit parameter.
462  bool isObjCSelfExpr() const;
463 
464  /// \brief Returns whether this expression refers to a vector element.
465  bool refersToVectorElement() const;
466 
467  /// \brief Returns whether this expression refers to a global register
468  /// variable.
469  bool refersToGlobalRegisterVar() const;
470 
471  /// \brief Returns whether this expression has a placeholder type.
472  bool hasPlaceholderType() const {
473  return getType()->isPlaceholderType();
474  }
475 
476  /// \brief Returns whether this expression has a specific placeholder type.
479  if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
480  return BT->getKind() == K;
481  return false;
482  }
483 
484  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
485  /// that is known to return 0 or 1. This happens for _Bool/bool expressions
486  /// but also int expressions which are produced by things like comparisons in
487  /// C.
488  bool isKnownToHaveBooleanValue() const;
489 
490  /// isIntegerConstantExpr - Return true if this expression is a valid integer
491  /// constant expression, and, if so, return its value in Result. If not a
492  /// valid i-c-e, return false and fill in Loc (if specified) with the location
493  /// of the invalid expression.
494  ///
495  /// Note: This does not perform the implicit conversions required by C++11
496  /// [expr.const]p5.
497  bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
498  SourceLocation *Loc = nullptr,
499  bool isEvaluated = true) const;
500  bool isIntegerConstantExpr(const ASTContext &Ctx,
501  SourceLocation *Loc = nullptr) const;
502 
503  /// isCXX98IntegralConstantExpr - Return true if this expression is an
504  /// integral constant expression in C++98. Can only be used in C++.
505  bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
506 
507  /// isCXX11ConstantExpr - Return true if this expression is a constant
508  /// expression in C++11. Can only be used in C++.
509  ///
510  /// Note: This does not perform the implicit conversions required by C++11
511  /// [expr.const]p5.
512  bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
513  SourceLocation *Loc = nullptr) const;
514 
515  /// isPotentialConstantExpr - Return true if this function's definition
516  /// might be usable in a constant expression in C++11, if it were marked
517  /// constexpr. Return false if the function can never produce a constant
518  /// expression, along with diagnostics describing why not.
519  static bool isPotentialConstantExpr(const FunctionDecl *FD,
521  PartialDiagnosticAt> &Diags);
522 
523  /// isPotentialConstantExprUnevaluted - Return true if this expression might
524  /// be usable in a constant expression in C++11 in an unevaluated context, if
525  /// it were in function FD marked constexpr. Return false if the function can
526  /// never produce a constant expression, along with diagnostics describing
527  /// why not.
528  static bool isPotentialConstantExprUnevaluated(Expr *E,
529  const FunctionDecl *FD,
531  PartialDiagnosticAt> &Diags);
532 
533  /// isConstantInitializer - Returns true if this expression can be emitted to
534  /// IR as a constant, and thus can be used as a constant initializer in C.
535  /// If this expression is not constant and Culprit is non-null,
536  /// it is used to store the address of first non constant expr.
537  bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
538  const Expr **Culprit = nullptr) const;
539 
540  /// EvalStatus is a struct with detailed info about an evaluation in progress.
541  struct EvalStatus {
542  /// \brief Whether the evaluated expression has side effects.
543  /// For example, (f() && 0) can be folded, but it still has side effects.
545 
546  /// \brief Whether the evaluation hit undefined behavior.
547  /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
548  /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
550 
551  /// Diag - If this is non-null, it will be filled in with a stack of notes
552  /// indicating why evaluation failed (or why it failed to produce a constant
553  /// expression).
554  /// If the expression is unfoldable, the notes will indicate why it's not
555  /// foldable. If the expression is foldable, but not a constant expression,
556  /// the notes will describes why it isn't a constant expression. If the
557  /// expression *is* a constant expression, no notes will be produced.
559 
561  : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
562 
563  // hasSideEffects - Return true if the evaluated expression has
564  // side effects.
565  bool hasSideEffects() const {
566  return HasSideEffects;
567  }
568  };
569 
570  /// EvalResult is a struct with detailed info about an evaluated expression.
572  /// Val - This is the value the expression can be folded to.
574 
575  // isGlobalLValue - Return true if the evaluated lvalue expression
576  // is global.
577  bool isGlobalLValue() const;
578  };
579 
580  /// EvaluateAsRValue - Return true if this is a constant which we can fold to
581  /// an rvalue using any crazy technique (that has nothing to do with language
582  /// standards) that we want to, even if the expression has side-effects. If
583  /// this function returns true, it returns the folded constant in Result. If
584  /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
585  /// applied.
586  bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
587 
588  /// EvaluateAsBooleanCondition - Return true if this is a constant
589  /// which we we can fold and convert to a boolean condition using
590  /// any crazy technique that we want to, even if the expression has
591  /// side-effects.
592  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
593 
595  SE_NoSideEffects, ///< Strictly evaluate the expression.
596  SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
597  ///< arbitrary unmodeled side effects.
598  SE_AllowSideEffects ///< Allow any unmodeled side effect.
599  };
600 
601  /// EvaluateAsInt - Return true if this is a constant which we can fold and
602  /// convert to an integer, using any crazy technique that we want to.
603  bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
604  SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
605 
606  /// EvaluateAsFloat - Return true if this is a constant which we can fold and
607  /// convert to a floating point value, using any crazy technique that we
608  /// want to.
609  bool
610  EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
611  SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
612 
613  /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
614  /// constant folded without side-effects, but discard the result.
615  bool isEvaluatable(const ASTContext &Ctx,
616  SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
617 
618  /// HasSideEffects - This routine returns true for all those expressions
619  /// which have any effect other than producing a value. Example is a function
620  /// call, volatile variable read, or throwing an exception. If
621  /// IncludePossibleEffects is false, this call treats certain expressions with
622  /// potential side effects (such as function call-like expressions,
623  /// instantiation-dependent expressions, or invocations from a macro) as not
624  /// having side effects.
625  bool HasSideEffects(const ASTContext &Ctx,
626  bool IncludePossibleEffects = true) const;
627 
628  /// \brief Determine whether this expression involves a call to any function
629  /// that is not trivial.
630  bool hasNonTrivialCall(const ASTContext &Ctx) const;
631 
632  /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
633  /// integer. This must be called on an expression that constant folds to an
634  /// integer.
635  llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
636  SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
637 
638  void EvaluateForOverflow(const ASTContext &Ctx) const;
639 
640  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
641  /// lvalue with link time known address, with no side-effects.
642  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
643 
644  /// EvaluateAsInitializer - Evaluate an expression as if it were the
645  /// initializer of the given declaration. Returns true if the initializer
646  /// can be folded to a constant, and produces any relevant notes. In C++11,
647  /// notes will be produced if the expression is not a constant expression.
648  bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
649  const VarDecl *VD,
651 
652  /// EvaluateWithSubstitution - Evaluate an expression as if from the context
653  /// of a call to the given function with the given arguments, inside an
654  /// unevaluated context. Returns true if the expression could be folded to a
655  /// constant.
656  bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
657  const FunctionDecl *Callee,
659  const Expr *This = nullptr) const;
660 
661  /// \brief If the current Expr is a pointer, this will try to statically
662  /// determine the number of bytes available where the pointer is pointing.
663  /// Returns true if all of the above holds and we were able to figure out the
664  /// size, false otherwise.
665  ///
666  /// \param Type - How to evaluate the size of the Expr, as defined by the
667  /// "type" parameter of __builtin_object_size
668  bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
669  unsigned Type) const;
670 
671  /// \brief Enumeration used to describe the kind of Null pointer constant
672  /// returned from \c isNullPointerConstant().
674  /// \brief Expression is not a Null pointer constant.
675  NPCK_NotNull = 0,
676 
677  /// \brief Expression is a Null pointer constant built from a zero integer
678  /// expression that is not a simple, possibly parenthesized, zero literal.
679  /// C++ Core Issue 903 will classify these expressions as "not pointers"
680  /// once it is adopted.
681  /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
683 
684  /// \brief Expression is a Null pointer constant built from a literal zero.
686 
687  /// \brief Expression is a C++11 nullptr.
689 
690  /// \brief Expression is a GNU-style __null constant.
691  NPCK_GNUNull
692  };
693 
694  /// \brief Enumeration used to describe how \c isNullPointerConstant()
695  /// should cope with value-dependent expressions.
697  /// \brief Specifies that the expression should never be value-dependent.
698  NPC_NeverValueDependent = 0,
699 
700  /// \brief Specifies that a value-dependent expression of integral or
701  /// dependent type should be considered a null pointer constant.
703 
704  /// \brief Specifies that a value-dependent expression should be considered
705  /// to never be a null pointer constant.
706  NPC_ValueDependentIsNotNull
707  };
708 
709  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
710  /// a Null pointer constant. The return value can further distinguish the
711  /// kind of NULL pointer constant that was detected.
712  NullPointerConstantKind isNullPointerConstant(
713  ASTContext &Ctx,
715 
716  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
717  /// write barrier.
718  bool isOBJCGCCandidate(ASTContext &Ctx) const;
719 
720  /// \brief Returns true if this expression is a bound member function.
721  bool isBoundMemberFunction(ASTContext &Ctx) const;
722 
723  /// \brief Given an expression of bound-member type, find the type
724  /// of the member. Returns null if this is an *overloaded* bound
725  /// member expression.
726  static QualType findBoundMemberType(const Expr *expr);
727 
728  /// IgnoreImpCasts - Skip past any implicit casts which might
729  /// surround this expression. Only skips ImplicitCastExprs.
730  Expr *IgnoreImpCasts() LLVM_READONLY;
731 
732  /// IgnoreImplicit - Skip past any implicit AST nodes which might
733  /// surround this expression.
734  Expr *IgnoreImplicit() LLVM_READONLY {
735  return cast<Expr>(Stmt::IgnoreImplicit());
736  }
737 
738  const Expr *IgnoreImplicit() const LLVM_READONLY {
739  return const_cast<Expr*>(this)->IgnoreImplicit();
740  }
741 
742  /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
743  /// its subexpression. If that subexpression is also a ParenExpr,
744  /// then this method recursively returns its subexpression, and so forth.
745  /// Otherwise, the method returns the current Expr.
746  Expr *IgnoreParens() LLVM_READONLY;
747 
748  /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
749  /// or CastExprs, returning their operand.
750  Expr *IgnoreParenCasts() LLVM_READONLY;
751 
752  /// Ignore casts. Strip off any CastExprs, returning their operand.
753  Expr *IgnoreCasts() LLVM_READONLY;
754 
755  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
756  /// any ParenExpr or ImplicitCastExprs, returning their operand.
757  Expr *IgnoreParenImpCasts() LLVM_READONLY;
758 
759  /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
760  /// call to a conversion operator, return the argument.
761  Expr *IgnoreConversionOperator() LLVM_READONLY;
762 
763  const Expr *IgnoreConversionOperator() const LLVM_READONLY {
764  return const_cast<Expr*>(this)->IgnoreConversionOperator();
765  }
766 
767  const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
768  return const_cast<Expr*>(this)->IgnoreParenImpCasts();
769  }
770 
771  /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
772  /// CastExprs that represent lvalue casts, returning their operand.
773  Expr *IgnoreParenLValueCasts() LLVM_READONLY;
774 
775  const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
776  return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
777  }
778 
779  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
780  /// value (including ptr->int casts of the same size). Strip off any
781  /// ParenExpr or CastExprs, returning their operand.
782  Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
783 
784  /// Ignore parentheses and derived-to-base casts.
785  Expr *ignoreParenBaseCasts() LLVM_READONLY;
786 
787  const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
788  return const_cast<Expr*>(this)->ignoreParenBaseCasts();
789  }
790 
791  /// \brief Determine whether this expression is a default function argument.
792  ///
793  /// Default arguments are implicitly generated in the abstract syntax tree
794  /// by semantic analysis for function calls, object constructions, etc. in
795  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
796  /// this routine also looks through any implicit casts to determine whether
797  /// the expression is a default argument.
798  bool isDefaultArgument() const;
799 
800  /// \brief Determine whether the result of this expression is a
801  /// temporary object of the given class type.
802  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
803 
804  /// \brief Whether this expression is an implicit reference to 'this' in C++.
805  bool isImplicitCXXThis() const;
806 
807  const Expr *IgnoreImpCasts() const LLVM_READONLY {
808  return const_cast<Expr*>(this)->IgnoreImpCasts();
809  }
810  const Expr *IgnoreParens() const LLVM_READONLY {
811  return const_cast<Expr*>(this)->IgnoreParens();
812  }
813  const Expr *IgnoreParenCasts() const LLVM_READONLY {
814  return const_cast<Expr*>(this)->IgnoreParenCasts();
815  }
816  /// Strip off casts, but keep parentheses.
817  const Expr *IgnoreCasts() const LLVM_READONLY {
818  return const_cast<Expr*>(this)->IgnoreCasts();
819  }
820 
821  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
822  return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
823  }
824 
825  static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
826 
827  /// \brief For an expression of class type or pointer to class type,
828  /// return the most derived class decl the expression is known to refer to.
829  ///
830  /// If this expression is a cast, this method looks through it to find the
831  /// most derived decl that can be inferred from the expression.
832  /// This is valid because derived-to-base conversions have undefined
833  /// behavior if the object isn't dynamically of the derived type.
834  const CXXRecordDecl *getBestDynamicClassType() const;
835 
836  /// \brief Get the inner expression that determines the best dynamic class.
837  /// If this is a prvalue, we guarantee that it is of the most-derived type
838  /// for the object itself.
839  const Expr *getBestDynamicClassTypeExpr() const;
840 
841  /// Walk outwards from an expression we want to bind a reference to and
842  /// find the expression whose lifetime needs to be extended. Record
843  /// the LHSs of comma expressions and adjustments needed along the path.
844  const Expr *skipRValueSubobjectAdjustments(
846  SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
850  return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
851  }
852 
853  static bool classof(const Stmt *T) {
854  return T->getStmtClass() >= firstExprConstant &&
855  T->getStmtClass() <= lastExprConstant;
856  }
857 };
858 
859 //===----------------------------------------------------------------------===//
860 // Primary Expressions.
861 //===----------------------------------------------------------------------===//
862 
863 /// OpaqueValueExpr - An expression referring to an opaque object of a
864 /// fixed type and value class. These don't correspond to concrete
865 /// syntax; instead they're used to express operations (usually copy
866 /// operations) on values whose source is generally obvious from
867 /// context.
868 class OpaqueValueExpr : public Expr {
869  friend class ASTStmtReader;
870  Expr *SourceExpr;
871  SourceLocation Loc;
872 
873 public:
876  Expr *SourceExpr = nullptr)
877  : Expr(OpaqueValueExprClass, T, VK, OK,
878  T->isDependentType() ||
879  (SourceExpr && SourceExpr->isTypeDependent()),
880  T->isDependentType() ||
881  (SourceExpr && SourceExpr->isValueDependent()),
882  T->isInstantiationDependentType() ||
883  (SourceExpr && SourceExpr->isInstantiationDependent()),
884  false),
885  SourceExpr(SourceExpr), Loc(Loc) {
886  }
887 
888  /// Given an expression which invokes a copy constructor --- i.e. a
889  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
890  /// find the OpaqueValueExpr that's the source of the construction.
891  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
892 
893  explicit OpaqueValueExpr(EmptyShell Empty)
894  : Expr(OpaqueValueExprClass, Empty) { }
895 
896  /// \brief Retrieve the location of this expression.
897  SourceLocation getLocation() const { return Loc; }
898 
899  SourceLocation getLocStart() const LLVM_READONLY {
900  return SourceExpr ? SourceExpr->getLocStart() : Loc;
901  }
902  SourceLocation getLocEnd() const LLVM_READONLY {
903  return SourceExpr ? SourceExpr->getLocEnd() : Loc;
904  }
905  SourceLocation getExprLoc() const LLVM_READONLY {
906  if (SourceExpr) return SourceExpr->getExprLoc();
907  return Loc;
908  }
909 
912  }
913 
916  }
917 
918  /// The source expression of an opaque value expression is the
919  /// expression which originally generated the value. This is
920  /// provided as a convenience for analyses that don't wish to
921  /// precisely model the execution behavior of the program.
922  ///
923  /// The source expression is typically set when building the
924  /// expression which binds the opaque value expression in the first
925  /// place.
926  Expr *getSourceExpr() const { return SourceExpr; }
927 
928  static bool classof(const Stmt *T) {
929  return T->getStmtClass() == OpaqueValueExprClass;
930  }
931 };
932 
933 /// \brief A reference to a declared variable, function, enum, etc.
934 /// [C99 6.5.1p2]
935 ///
936 /// This encodes all the information about how a declaration is referenced
937 /// within an expression.
938 ///
939 /// There are several optional constructs attached to DeclRefExprs only when
940 /// they apply in order to conserve memory. These are laid out past the end of
941 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
942 ///
943 /// DeclRefExprBits.HasQualifier:
944 /// Specifies when this declaration reference expression has a C++
945 /// nested-name-specifier.
946 /// DeclRefExprBits.HasFoundDecl:
947 /// Specifies when this declaration reference expression has a record of
948 /// a NamedDecl (different from the referenced ValueDecl) which was found
949 /// during name lookup and/or overload resolution.
950 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
951 /// Specifies when this declaration reference expression has an explicit
952 /// C++ template keyword and/or template argument list.
953 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
954 /// Specifies when this declaration reference expression (validly)
955 /// refers to an enclosed local or a captured variable.
956 class DeclRefExpr final
957  : public Expr,
958  private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
959  NamedDecl *, ASTTemplateKWAndArgsInfo,
960  TemplateArgumentLoc> {
961  /// \brief The declaration that we are referencing.
962  ValueDecl *D;
963 
964  /// \brief The location of the declaration name itself.
965  SourceLocation Loc;
966 
967  /// \brief Provides source/type location info for the declaration name
968  /// embedded in D.
969  DeclarationNameLoc DNLoc;
970 
971  size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
972  return hasQualifier() ? 1 : 0;
973  }
974 
975  size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
976  return hasFoundDecl() ? 1 : 0;
977  }
978 
979  size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
980  return hasTemplateKWAndArgsInfo() ? 1 : 0;
981  }
982 
983  /// \brief Test whether there is a distinct FoundDecl attached to the end of
984  /// this DRE.
985  bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
986 
987  DeclRefExpr(const ASTContext &Ctx,
988  NestedNameSpecifierLoc QualifierLoc,
989  SourceLocation TemplateKWLoc,
990  ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
991  const DeclarationNameInfo &NameInfo,
992  NamedDecl *FoundD,
993  const TemplateArgumentListInfo *TemplateArgs,
994  QualType T, ExprValueKind VK);
995 
996  /// \brief Construct an empty declaration reference expression.
997  explicit DeclRefExpr(EmptyShell Empty)
998  : Expr(DeclRefExprClass, Empty) { }
999 
1000  /// \brief Computes the type- and value-dependence flags for this
1001  /// declaration reference expression.
1002  void computeDependence(const ASTContext &C);
1003 
1004 public:
1005  DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1007  const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1008  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1009  D(D), Loc(L), DNLoc(LocInfo) {
1010  DeclRefExprBits.HasQualifier = 0;
1011  DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1012  DeclRefExprBits.HasFoundDecl = 0;
1013  DeclRefExprBits.HadMultipleCandidates = 0;
1014  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1015  RefersToEnclosingVariableOrCapture;
1016  computeDependence(D->getASTContext());
1017  }
1018 
1019  static DeclRefExpr *
1020  Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1021  SourceLocation TemplateKWLoc, ValueDecl *D,
1022  bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1023  QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1024  const TemplateArgumentListInfo *TemplateArgs = nullptr);
1025 
1026  static DeclRefExpr *
1027  Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1028  SourceLocation TemplateKWLoc, ValueDecl *D,
1029  bool RefersToEnclosingVariableOrCapture,
1030  const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1031  NamedDecl *FoundD = nullptr,
1032  const TemplateArgumentListInfo *TemplateArgs = nullptr);
1033 
1034  /// \brief Construct an empty declaration reference expression.
1035  static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1036  bool HasQualifier,
1037  bool HasFoundDecl,
1038  bool HasTemplateKWAndArgsInfo,
1039  unsigned NumTemplateArgs);
1040 
1041  ValueDecl *getDecl() { return D; }
1042  const ValueDecl *getDecl() const { return D; }
1043  void setDecl(ValueDecl *NewD) { D = NewD; }
1044 
1046  return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1047  }
1048 
1049  SourceLocation getLocation() const { return Loc; }
1050  void setLocation(SourceLocation L) { Loc = L; }
1051  SourceLocation getLocStart() const LLVM_READONLY;
1052  SourceLocation getLocEnd() const LLVM_READONLY;
1053 
1054  /// \brief Determine whether this declaration reference was preceded by a
1055  /// C++ nested-name-specifier, e.g., \c N::foo.
1056  bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1057 
1058  /// \brief If the name was qualified, retrieves the nested-name-specifier
1059  /// that precedes the name, with source-location information.
1061  if (!hasQualifier())
1062  return NestedNameSpecifierLoc();
1063  return *getTrailingObjects<NestedNameSpecifierLoc>();
1064  }
1065 
1066  /// \brief If the name was qualified, retrieves the nested-name-specifier
1067  /// that precedes the name. Otherwise, returns NULL.
1069  return getQualifierLoc().getNestedNameSpecifier();
1070  }
1071 
1072  /// \brief Get the NamedDecl through which this reference occurred.
1073  ///
1074  /// This Decl may be different from the ValueDecl actually referred to in the
1075  /// presence of using declarations, etc. It always returns non-NULL, and may
1076  /// simple return the ValueDecl when appropriate.
1077 
1079  return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1080  }
1081 
1082  /// \brief Get the NamedDecl through which this reference occurred.
1083  /// See non-const variant.
1084  const NamedDecl *getFoundDecl() const {
1085  return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1086  }
1087 
1089  return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1090  }
1091 
1092  /// \brief Retrieve the location of the template keyword preceding
1093  /// this name, if any.
1095  if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1096  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1097  }
1098 
1099  /// \brief Retrieve the location of the left angle bracket starting the
1100  /// explicit template argument list following the name, if any.
1102  if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1103  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1104  }
1105 
1106  /// \brief Retrieve the location of the right angle bracket ending the
1107  /// explicit template argument list following the name, if any.
1109  if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1110  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1111  }
1112 
1113  /// \brief Determines whether the name in this declaration reference
1114  /// was preceded by the template keyword.
1115  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1116 
1117  /// \brief Determines whether this declaration reference was followed by an
1118  /// explicit template argument list.
1119  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1120 
1121  /// \brief Copies the template arguments (if present) into the given
1122  /// structure.
1124  if (hasExplicitTemplateArgs())
1125  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1126  getTrailingObjects<TemplateArgumentLoc>(), List);
1127  }
1128 
1129  /// \brief Retrieve the template arguments provided as part of this
1130  /// template-id.
1132  if (!hasExplicitTemplateArgs())
1133  return nullptr;
1134 
1135  return getTrailingObjects<TemplateArgumentLoc>();
1136  }
1137 
1138  /// \brief Retrieve the number of template arguments provided as part of this
1139  /// template-id.
1140  unsigned getNumTemplateArgs() const {
1141  if (!hasExplicitTemplateArgs())
1142  return 0;
1143 
1144  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1145  }
1146 
1148  return {getTemplateArgs(), getNumTemplateArgs()};
1149  }
1150 
1151  /// \brief Returns true if this expression refers to a function that
1152  /// was resolved from an overloaded set having size greater than 1.
1153  bool hadMultipleCandidates() const {
1154  return DeclRefExprBits.HadMultipleCandidates;
1155  }
1156  /// \brief Sets the flag telling whether this expression refers to
1157  /// a function that was resolved from an overloaded set having size
1158  /// greater than 1.
1159  void setHadMultipleCandidates(bool V = true) {
1160  DeclRefExprBits.HadMultipleCandidates = V;
1161  }
1162 
1163  /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1164  /// variable?
1166  return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1167  }
1168 
1169  static bool classof(const Stmt *T) {
1170  return T->getStmtClass() == DeclRefExprClass;
1171  }
1172 
1173  // Iterators
1176  }
1177 
1180  }
1181 
1183  friend class ASTStmtReader;
1184  friend class ASTStmtWriter;
1185 };
1186 
1187 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1188 class PredefinedExpr : public Expr {
1189 public:
1190  enum IdentType {
1193  LFunction, // Same as Function, but as wide string.
1197  /// \brief The same as PrettyFunction, except that the
1198  /// 'virtual' keyword is omitted for virtual member functions.
1199  PrettyFunctionNoVirtual
1200  };
1201 
1202 private:
1203  SourceLocation Loc;
1204  IdentType Type;
1205  Stmt *FnName;
1206 
1207 public:
1209  StringLiteral *SL);
1210 
1211  /// \brief Construct an empty predefined expression.
1212  explicit PredefinedExpr(EmptyShell Empty)
1213  : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1214 
1215  IdentType getIdentType() const { return Type; }
1216 
1217  SourceLocation getLocation() const { return Loc; }
1218  void setLocation(SourceLocation L) { Loc = L; }
1219 
1220  StringLiteral *getFunctionName();
1222  return const_cast<PredefinedExpr *>(this)->getFunctionName();
1223  }
1224 
1225  static StringRef getIdentTypeName(IdentType IT);
1226  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1227 
1228  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1229  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1230 
1231  static bool classof(const Stmt *T) {
1232  return T->getStmtClass() == PredefinedExprClass;
1233  }
1234 
1235  // Iterators
1236  child_range children() { return child_range(&FnName, &FnName + 1); }
1238  return const_child_range(&FnName, &FnName + 1);
1239  }
1240 
1241  friend class ASTStmtReader;
1242 };
1243 
1244 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1245 /// leaking memory.
1246 ///
1247 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1248 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1249 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1250 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1251 /// ASTContext's allocator for memory allocation.
1253  union {
1254  uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1255  uint64_t *pVal; ///< Used to store the >64 bits integer value.
1256  };
1257  unsigned BitWidth;
1258 
1259  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1260 
1261  APNumericStorage(const APNumericStorage &) = delete;
1262  void operator=(const APNumericStorage &) = delete;
1263 
1264 protected:
1265  APNumericStorage() : VAL(0), BitWidth(0) { }
1266 
1267  llvm::APInt getIntValue() const {
1268  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1269  if (NumWords > 1)
1270  return llvm::APInt(BitWidth, NumWords, pVal);
1271  else
1272  return llvm::APInt(BitWidth, VAL);
1273  }
1274  void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1275 };
1276 
1278 public:
1279  llvm::APInt getValue() const { return getIntValue(); }
1280  void setValue(const ASTContext &C, const llvm::APInt &Val) {
1281  setIntValue(C, Val);
1282  }
1283 };
1284 
1286 public:
1287  llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1288  return llvm::APFloat(Semantics, getIntValue());
1289  }
1290  void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1291  setIntValue(C, Val.bitcastToAPInt());
1292  }
1293 };
1294 
1295 class IntegerLiteral : public Expr, public APIntStorage {
1296  SourceLocation Loc;
1297 
1298  /// \brief Construct an empty integer literal.
1299  explicit IntegerLiteral(EmptyShell Empty)
1300  : Expr(IntegerLiteralClass, Empty) { }
1301 
1302 public:
1303  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1304  // or UnsignedLongLongTy
1305  IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1306  SourceLocation l);
1307 
1308  /// \brief Returns a new integer literal with value 'V' and type 'type'.
1309  /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1310  /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1311  /// \param V - the value that the returned integer literal contains.
1312  static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1313  QualType type, SourceLocation l);
1314  /// \brief Returns a new empty integer literal.
1315  static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1316 
1317  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1318  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1319 
1320  /// \brief Retrieve the location of the literal.
1321  SourceLocation getLocation() const { return Loc; }
1322 
1323  void setLocation(SourceLocation Location) { Loc = Location; }
1324 
1325  static bool classof(const Stmt *T) {
1326  return T->getStmtClass() == IntegerLiteralClass;
1327  }
1328 
1329  // Iterators
1332  }
1335  }
1336 };
1337 
1338 class CharacterLiteral : public Expr {
1339 public:
1345  UTF32
1346  };
1347 
1348 private:
1349  unsigned Value;
1350  SourceLocation Loc;
1351 public:
1352  // type should be IntTy
1354  SourceLocation l)
1355  : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1356  false, false),
1357  Value(value), Loc(l) {
1358  CharacterLiteralBits.Kind = kind;
1359  }
1360 
1361  /// \brief Construct an empty character literal.
1362  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1363 
1364  SourceLocation getLocation() const { return Loc; }
1366  return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1367  }
1368 
1369  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1370  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1371 
1372  unsigned getValue() const { return Value; }
1373 
1374  void setLocation(SourceLocation Location) { Loc = Location; }
1375  void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1376  void setValue(unsigned Val) { Value = Val; }
1377 
1378  static bool classof(const Stmt *T) {
1379  return T->getStmtClass() == CharacterLiteralClass;
1380  }
1381 
1382  // Iterators
1385  }
1388  }
1389 };
1390 
1391 class FloatingLiteral : public Expr, private APFloatStorage {
1392  SourceLocation Loc;
1393 
1394  FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1396 
1397  /// \brief Construct an empty floating-point literal.
1398  explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1399 
1400 public:
1401  static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1402  bool isexact, QualType Type, SourceLocation L);
1403  static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1404 
1405  llvm::APFloat getValue() const {
1406  return APFloatStorage::getValue(getSemantics());
1407  }
1408  void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1409  assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1410  APFloatStorage::setValue(C, Val);
1411  }
1412 
1413  /// Get a raw enumeration value representing the floating-point semantics of
1414  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1416  return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1417  }
1418 
1419  /// Set the raw enumeration value representing the floating-point semantics of
1420  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1422  FloatingLiteralBits.Semantics = Sem;
1423  }
1424 
1425  /// Return the APFloat semantics this literal uses.
1426  const llvm::fltSemantics &getSemantics() const;
1427 
1428  /// Set the APFloat semantics this literal uses.
1429  void setSemantics(const llvm::fltSemantics &Sem);
1430 
1431  bool isExact() const { return FloatingLiteralBits.IsExact; }
1432  void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1433 
1434  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1435  /// double. Note that this may cause loss of precision, but is useful for
1436  /// debugging dumps, etc.
1437  double getValueAsApproximateDouble() const;
1438 
1439  SourceLocation getLocation() const { return Loc; }
1440  void setLocation(SourceLocation L) { Loc = L; }
1441 
1442  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1443  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1444 
1445  static bool classof(const Stmt *T) {
1446  return T->getStmtClass() == FloatingLiteralClass;
1447  }
1448 
1449  // Iterators
1452  }
1455  }
1456 };
1457 
1458 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1459 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1460 /// IntegerLiteral classes. Instances of this class always have a Complex type
1461 /// whose element type matches the subexpression.
1462 ///
1463 class ImaginaryLiteral : public Expr {
1464  Stmt *Val;
1465 public:
1467  : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1468  false, false),
1469  Val(val) {}
1470 
1471  /// \brief Build an empty imaginary literal.
1473  : Expr(ImaginaryLiteralClass, Empty) { }
1474 
1475  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1476  Expr *getSubExpr() { return cast<Expr>(Val); }
1477  void setSubExpr(Expr *E) { Val = E; }
1478 
1479  SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1480  SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1481 
1482  static bool classof(const Stmt *T) {
1483  return T->getStmtClass() == ImaginaryLiteralClass;
1484  }
1485 
1486  // Iterators
1487  child_range children() { return child_range(&Val, &Val+1); }
1489  return const_child_range(&Val, &Val + 1);
1490  }
1491 };
1492 
1493 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1494 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1495 /// is NOT null-terminated, and the length of the string is determined by
1496 /// calling getByteLength(). The C type for a string is always a
1497 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1498 /// not.
1499 ///
1500 /// Note that strings in C can be formed by concatenation of multiple string
1501 /// literal pptokens in translation phase #6. This keeps track of the locations
1502 /// of each of these pieces.
1503 ///
1504 /// Strings in C can also be truncated and extended by assigning into arrays,
1505 /// e.g. with constructs like:
1506 /// char X[2] = "foobar";
1507 /// In this case, getByteLength() will return 6, but the string literal will
1508 /// have type "char[2]".
1509 class StringLiteral : public Expr {
1510 public:
1511  enum StringKind {
1516  UTF32
1517  };
1518 
1519 private:
1520  friend class ASTStmtReader;
1521 
1522  union {
1523  const char *asChar;
1524  const uint16_t *asUInt16;
1525  const uint32_t *asUInt32;
1526  } StrData;
1527  unsigned Length;
1528  unsigned CharByteWidth : 4;
1529  unsigned Kind : 3;
1530  unsigned IsPascal : 1;
1531  unsigned NumConcatenated;
1532  SourceLocation TokLocs[1];
1533 
1534  StringLiteral(QualType Ty) :
1535  Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1536  false) {}
1537 
1538  static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1539 
1540 public:
1541  /// This is the "fully general" constructor that allows representation of
1542  /// strings formed from multiple concatenated tokens.
1543  static StringLiteral *Create(const ASTContext &C, StringRef Str,
1544  StringKind Kind, bool Pascal, QualType Ty,
1545  const SourceLocation *Loc, unsigned NumStrs);
1546 
1547  /// Simple constructor for string literals made from one token.
1548  static StringLiteral *Create(const ASTContext &C, StringRef Str,
1549  StringKind Kind, bool Pascal, QualType Ty,
1550  SourceLocation Loc) {
1551  return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1552  }
1553 
1554  /// \brief Construct an empty string literal.
1555  static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1556 
1557  StringRef getString() const {
1558  assert(CharByteWidth==1
1559  && "This function is used in places that assume strings use char");
1560  return StringRef(StrData.asChar, getByteLength());
1561  }
1562 
1563  /// Allow access to clients that need the byte representation, such as
1564  /// ASTWriterStmt::VisitStringLiteral().
1565  StringRef getBytes() const {
1566  // FIXME: StringRef may not be the right type to use as a result for this.
1567  if (CharByteWidth == 1)
1568  return StringRef(StrData.asChar, getByteLength());
1569  if (CharByteWidth == 4)
1570  return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1571  getByteLength());
1572  assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1573  return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1574  getByteLength());
1575  }
1576 
1577  void outputString(raw_ostream &OS) const;
1578 
1579  uint32_t getCodeUnit(size_t i) const {
1580  assert(i < Length && "out of bounds access");
1581  if (CharByteWidth == 1)
1582  return static_cast<unsigned char>(StrData.asChar[i]);
1583  if (CharByteWidth == 4)
1584  return StrData.asUInt32[i];
1585  assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1586  return StrData.asUInt16[i];
1587  }
1588 
1589  unsigned getByteLength() const { return CharByteWidth*Length; }
1590  unsigned getLength() const { return Length; }
1591  unsigned getCharByteWidth() const { return CharByteWidth; }
1592 
1593  /// \brief Sets the string data to the given string data.
1594  void setString(const ASTContext &C, StringRef Str,
1595  StringKind Kind, bool IsPascal);
1596 
1597  StringKind getKind() const { return static_cast<StringKind>(Kind); }
1598 
1599 
1600  bool isAscii() const { return Kind == Ascii; }
1601  bool isWide() const { return Kind == Wide; }
1602  bool isUTF8() const { return Kind == UTF8; }
1603  bool isUTF16() const { return Kind == UTF16; }
1604  bool isUTF32() const { return Kind == UTF32; }
1605  bool isPascal() const { return IsPascal; }
1606 
1607  bool containsNonAsciiOrNull() const {
1608  StringRef Str = getString();
1609  for (unsigned i = 0, e = Str.size(); i != e; ++i)
1610  if (!isASCII(Str[i]) || !Str[i])
1611  return true;
1612  return false;
1613  }
1614 
1615  /// getNumConcatenated - Get the number of string literal tokens that were
1616  /// concatenated in translation phase #6 to form this string literal.
1617  unsigned getNumConcatenated() const { return NumConcatenated; }
1618 
1619  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1620  assert(TokNum < NumConcatenated && "Invalid tok number");
1621  return TokLocs[TokNum];
1622  }
1623  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1624  assert(TokNum < NumConcatenated && "Invalid tok number");
1625  TokLocs[TokNum] = L;
1626  }
1627 
1628  /// getLocationOfByte - Return a source location that points to the specified
1629  /// byte of this string literal.
1630  ///
1631  /// Strings are amazingly complex. They can be formed from multiple tokens
1632  /// and can have escape sequences in them in addition to the usual trigraph
1633  /// and escaped newline business. This routine handles this complexity.
1634  ///
1636  getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1637  const LangOptions &Features, const TargetInfo &Target,
1638  unsigned *StartToken = nullptr,
1639  unsigned *StartTokenByteOffset = nullptr) const;
1640 
1642  tokloc_iterator tokloc_begin() const { return TokLocs; }
1643  tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1644 
1645  SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1646  SourceLocation getLocEnd() const LLVM_READONLY {
1647  return TokLocs[NumConcatenated - 1];
1648  }
1649 
1650  static bool classof(const Stmt *T) {
1651  return T->getStmtClass() == StringLiteralClass;
1652  }
1653 
1654  // Iterators
1657  }
1660  }
1661 };
1662 
1663 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1664 /// AST node is only formed if full location information is requested.
1665 class ParenExpr : public Expr {
1666  SourceLocation L, R;
1667  Stmt *Val;
1668 public:
1670  : Expr(ParenExprClass, val->getType(),
1671  val->getValueKind(), val->getObjectKind(),
1672  val->isTypeDependent(), val->isValueDependent(),
1673  val->isInstantiationDependent(),
1674  val->containsUnexpandedParameterPack()),
1675  L(l), R(r), Val(val) {}
1676 
1677  /// \brief Construct an empty parenthesized expression.
1678  explicit ParenExpr(EmptyShell Empty)
1679  : Expr(ParenExprClass, Empty) { }
1680 
1681  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1682  Expr *getSubExpr() { return cast<Expr>(Val); }
1683  void setSubExpr(Expr *E) { Val = E; }
1684 
1685  SourceLocation getLocStart() const LLVM_READONLY { return L; }
1686  SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1687 
1688  /// \brief Get the location of the left parentheses '('.
1689  SourceLocation getLParen() const { return L; }
1690  void setLParen(SourceLocation Loc) { L = Loc; }
1691 
1692  /// \brief Get the location of the right parentheses ')'.
1693  SourceLocation getRParen() const { return R; }
1694  void setRParen(SourceLocation Loc) { R = Loc; }
1695 
1696  static bool classof(const Stmt *T) {
1697  return T->getStmtClass() == ParenExprClass;
1698  }
1699 
1700  // Iterators
1701  child_range children() { return child_range(&Val, &Val+1); }
1703  return const_child_range(&Val, &Val + 1);
1704  }
1705 };
1706 
1707 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1708 /// alignof), the postinc/postdec operators from postfix-expression, and various
1709 /// extensions.
1710 ///
1711 /// Notes on various nodes:
1712 ///
1713 /// Real/Imag - These return the real/imag part of a complex operand. If
1714 /// applied to a non-complex value, the former returns its operand and the
1715 /// later returns zero in the type of the operand.
1716 ///
1717 class UnaryOperator : public Expr {
1718 public:
1720 
1721 private:
1722  unsigned Opc : 5;
1723  SourceLocation Loc;
1724  Stmt *Val;
1725 public:
1726 
1727  UnaryOperator(Expr *input, Opcode opc, QualType type,
1729  : Expr(UnaryOperatorClass, type, VK, OK,
1730  input->isTypeDependent() || type->isDependentType(),
1731  input->isValueDependent(),
1732  (input->isInstantiationDependent() ||
1733  type->isInstantiationDependentType()),
1734  input->containsUnexpandedParameterPack()),
1735  Opc(opc), Loc(l), Val(input) {}
1736 
1737  /// \brief Build an empty unary operator.
1738  explicit UnaryOperator(EmptyShell Empty)
1739  : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1740 
1741  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1742  void setOpcode(Opcode O) { Opc = O; }
1743 
1744  Expr *getSubExpr() const { return cast<Expr>(Val); }
1745  void setSubExpr(Expr *E) { Val = E; }
1746 
1747  /// getOperatorLoc - Return the location of the operator.
1748  SourceLocation getOperatorLoc() const { return Loc; }
1749  void setOperatorLoc(SourceLocation L) { Loc = L; }
1750 
1751  /// isPostfix - Return true if this is a postfix operation, like x++.
1752  static bool isPostfix(Opcode Op) {
1753  return Op == UO_PostInc || Op == UO_PostDec;
1754  }
1755 
1756  /// isPrefix - Return true if this is a prefix operation, like --x.
1757  static bool isPrefix(Opcode Op) {
1758  return Op == UO_PreInc || Op == UO_PreDec;
1759  }
1760 
1761  bool isPrefix() const { return isPrefix(getOpcode()); }
1762  bool isPostfix() const { return isPostfix(getOpcode()); }
1763 
1764  static bool isIncrementOp(Opcode Op) {
1765  return Op == UO_PreInc || Op == UO_PostInc;
1766  }
1767  bool isIncrementOp() const {
1768  return isIncrementOp(getOpcode());
1769  }
1770 
1771  static bool isDecrementOp(Opcode Op) {
1772  return Op == UO_PreDec || Op == UO_PostDec;
1773  }
1774  bool isDecrementOp() const {
1775  return isDecrementOp(getOpcode());
1776  }
1777 
1778  static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1779  bool isIncrementDecrementOp() const {
1780  return isIncrementDecrementOp(getOpcode());
1781  }
1782 
1783  static bool isArithmeticOp(Opcode Op) {
1784  return Op >= UO_Plus && Op <= UO_LNot;
1785  }
1786  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1787 
1788  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1789  /// corresponds to, e.g. "sizeof" or "[pre]++"
1790  static StringRef getOpcodeStr(Opcode Op);
1791 
1792  /// \brief Retrieve the unary opcode that corresponds to the given
1793  /// overloaded operator.
1794  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1795 
1796  /// \brief Retrieve the overloaded operator kind that corresponds to
1797  /// the given unary opcode.
1798  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1799 
1800  SourceLocation getLocStart() const LLVM_READONLY {
1801  return isPostfix() ? Val->getLocStart() : Loc;
1802  }
1803  SourceLocation getLocEnd() const LLVM_READONLY {
1804  return isPostfix() ? Loc : Val->getLocEnd();
1805  }
1806  SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1807 
1808  static bool classof(const Stmt *T) {
1809  return T->getStmtClass() == UnaryOperatorClass;
1810  }
1811 
1812  // Iterators
1813  child_range children() { return child_range(&Val, &Val+1); }
1815  return const_child_range(&Val, &Val + 1);
1816  }
1817 };
1818 
1819 /// Helper class for OffsetOfExpr.
1820 
1821 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1823 public:
1824  /// \brief The kind of offsetof node we have.
1825  enum Kind {
1826  /// \brief An index into an array.
1827  Array = 0x00,
1828  /// \brief A field.
1829  Field = 0x01,
1830  /// \brief A field in a dependent type, known only by its name.
1831  Identifier = 0x02,
1832  /// \brief An implicit indirection through a C++ base class, when the
1833  /// field found is in a base class.
1834  Base = 0x03
1835  };
1836 
1837 private:
1838  enum { MaskBits = 2, Mask = 0x03 };
1839 
1840  /// \brief The source range that covers this part of the designator.
1841  SourceRange Range;
1842 
1843  /// \brief The data describing the designator, which comes in three
1844  /// different forms, depending on the lower two bits.
1845  /// - An unsigned index into the array of Expr*'s stored after this node
1846  /// in memory, for [constant-expression] designators.
1847  /// - A FieldDecl*, for references to a known field.
1848  /// - An IdentifierInfo*, for references to a field with a given name
1849  /// when the class type is dependent.
1850  /// - A CXXBaseSpecifier*, for references that look at a field in a
1851  /// base class.
1852  uintptr_t Data;
1853 
1854 public:
1855  /// \brief Create an offsetof node that refers to an array element.
1856  OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1857  SourceLocation RBracketLoc)
1858  : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1859 
1860  /// \brief Create an offsetof node that refers to a field.
1862  : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1863  Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1864 
1865  /// \brief Create an offsetof node that refers to an identifier.
1867  SourceLocation NameLoc)
1868  : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1869  Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1870 
1871  /// \brief Create an offsetof node that refers into a C++ base class.
1873  : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1874 
1875  /// \brief Determine what kind of offsetof node this is.
1876  Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1877 
1878  /// \brief For an array element node, returns the index into the array
1879  /// of expressions.
1880  unsigned getArrayExprIndex() const {
1881  assert(getKind() == Array);
1882  return Data >> 2;
1883  }
1884 
1885  /// \brief For a field offsetof node, returns the field.
1886  FieldDecl *getField() const {
1887  assert(getKind() == Field);
1888  return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1889  }
1890 
1891  /// \brief For a field or identifier offsetof node, returns the name of
1892  /// the field.
1893  IdentifierInfo *getFieldName() const;
1894 
1895  /// \brief For a base class node, returns the base specifier.
1897  assert(getKind() == Base);
1898  return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1899  }
1900 
1901  /// \brief Retrieve the source range that covers this offsetof node.
1902  ///
1903  /// For an array element node, the source range contains the locations of
1904  /// the square brackets. For a field or identifier node, the source range
1905  /// contains the location of the period (if there is one) and the
1906  /// identifier.
1907  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1908  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1909  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1910 };
1911 
1912 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1913 /// offsetof(record-type, member-designator). For example, given:
1914 /// @code
1915 /// struct S {
1916 /// float f;
1917 /// double d;
1918 /// };
1919 /// struct T {
1920 /// int i;
1921 /// struct S s[10];
1922 /// };
1923 /// @endcode
1924 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1925 
1926 class OffsetOfExpr final
1927  : public Expr,
1928  private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1929  SourceLocation OperatorLoc, RParenLoc;
1930  // Base type;
1931  TypeSourceInfo *TSInfo;
1932  // Number of sub-components (i.e. instances of OffsetOfNode).
1933  unsigned NumComps;
1934  // Number of sub-expressions (i.e. array subscript expressions).
1935  unsigned NumExprs;
1936 
1937  size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1938  return NumComps;
1939  }
1940 
1942  SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1944  SourceLocation RParenLoc);
1945 
1946  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1947  : Expr(OffsetOfExprClass, EmptyShell()),
1948  TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1949 
1950 public:
1951 
1952  static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1953  SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1954  ArrayRef<OffsetOfNode> comps,
1955  ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1956 
1957  static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1958  unsigned NumComps, unsigned NumExprs);
1959 
1960  /// getOperatorLoc - Return the location of the operator.
1961  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1962  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1963 
1964  /// \brief Return the location of the right parentheses.
1965  SourceLocation getRParenLoc() const { return RParenLoc; }
1966  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1967 
1969  return TSInfo;
1970  }
1972  TSInfo = tsi;
1973  }
1974 
1975  const OffsetOfNode &getComponent(unsigned Idx) const {
1976  assert(Idx < NumComps && "Subscript out of range");
1977  return getTrailingObjects<OffsetOfNode>()[Idx];
1978  }
1979 
1980  void setComponent(unsigned Idx, OffsetOfNode ON) {
1981  assert(Idx < NumComps && "Subscript out of range");
1982  getTrailingObjects<OffsetOfNode>()[Idx] = ON;
1983  }
1984 
1985  unsigned getNumComponents() const {
1986  return NumComps;
1987  }
1988 
1989  Expr* getIndexExpr(unsigned Idx) {
1990  assert(Idx < NumExprs && "Subscript out of range");
1991  return getTrailingObjects<Expr *>()[Idx];
1992  }
1993 
1994  const Expr *getIndexExpr(unsigned Idx) const {
1995  assert(Idx < NumExprs && "Subscript out of range");
1996  return getTrailingObjects<Expr *>()[Idx];
1997  }
1998 
1999  void setIndexExpr(unsigned Idx, Expr* E) {
2000  assert(Idx < NumComps && "Subscript out of range");
2001  getTrailingObjects<Expr *>()[Idx] = E;
2002  }
2003 
2004  unsigned getNumExpressions() const {
2005  return NumExprs;
2006  }
2007 
2008  SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
2009  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2010 
2011  static bool classof(const Stmt *T) {
2012  return T->getStmtClass() == OffsetOfExprClass;
2013  }
2014 
2015  // Iterators
2017  Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2018  return child_range(begin, begin + NumExprs);
2019  }
2021  Stmt *const *begin =
2022  reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2023  return const_child_range(begin, begin + NumExprs);
2024  }
2026 };
2027 
2028 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2029 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2030 /// vec_step (OpenCL 1.1 6.11.12).
2032  union {
2035  } Argument;
2036  SourceLocation OpLoc, RParenLoc;
2037 
2038 public:
2040  QualType resultType, SourceLocation op,
2041  SourceLocation rp) :
2042  Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2043  false, // Never type-dependent (C++ [temp.dep.expr]p3).
2044  // Value-dependent if the argument is type-dependent.
2045  TInfo->getType()->isDependentType(),
2046  TInfo->getType()->isInstantiationDependentType(),
2047  TInfo->getType()->containsUnexpandedParameterPack()),
2048  OpLoc(op), RParenLoc(rp) {
2049  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2050  UnaryExprOrTypeTraitExprBits.IsType = true;
2051  Argument.Ty = TInfo;
2052  }
2053 
2055  QualType resultType, SourceLocation op,
2056  SourceLocation rp);
2057 
2058  /// \brief Construct an empty sizeof/alignof expression.
2060  : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2061 
2063  return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2064  }
2065  void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2066 
2067  bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2069  return getArgumentTypeInfo()->getType();
2070  }
2072  assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2073  return Argument.Ty;
2074  }
2076  assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2077  return static_cast<Expr*>(Argument.Ex);
2078  }
2079  const Expr *getArgumentExpr() const {
2080  return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2081  }
2082 
2083  void setArgument(Expr *E) {
2084  Argument.Ex = E;
2085  UnaryExprOrTypeTraitExprBits.IsType = false;
2086  }
2088  Argument.Ty = TInfo;
2089  UnaryExprOrTypeTraitExprBits.IsType = true;
2090  }
2091 
2092  /// Gets the argument type, or the type of the argument expression, whichever
2093  /// is appropriate.
2095  return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2096  }
2097 
2098  SourceLocation getOperatorLoc() const { return OpLoc; }
2099  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2100 
2101  SourceLocation getRParenLoc() const { return RParenLoc; }
2102  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2103 
2104  SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2105  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2106 
2107  static bool classof(const Stmt *T) {
2108  return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2109  }
2110 
2111  // Iterators
2113  const_child_range children() const;
2114 };
2115 
2116 //===----------------------------------------------------------------------===//
2117 // Postfix Operators.
2118 //===----------------------------------------------------------------------===//
2119 
2120 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2121 class ArraySubscriptExpr : public Expr {
2122  enum { LHS, RHS, END_EXPR=2 };
2123  Stmt* SubExprs[END_EXPR];
2124  SourceLocation RBracketLoc;
2125 public:
2128  SourceLocation rbracketloc)
2129  : Expr(ArraySubscriptExprClass, t, VK, OK,
2130  lhs->isTypeDependent() || rhs->isTypeDependent(),
2131  lhs->isValueDependent() || rhs->isValueDependent(),
2132  (lhs->isInstantiationDependent() ||
2133  rhs->isInstantiationDependent()),
2134  (lhs->containsUnexpandedParameterPack() ||
2135  rhs->containsUnexpandedParameterPack())),
2136  RBracketLoc(rbracketloc) {
2137  SubExprs[LHS] = lhs;
2138  SubExprs[RHS] = rhs;
2139  }
2140 
2141  /// \brief Create an empty array subscript expression.
2143  : Expr(ArraySubscriptExprClass, Shell) { }
2144 
2145  /// An array access can be written A[4] or 4[A] (both are equivalent).
2146  /// - getBase() and getIdx() always present the normalized view: A[4].
2147  /// In this case getBase() returns "A" and getIdx() returns "4".
2148  /// - getLHS() and getRHS() present the syntactic view. e.g. for
2149  /// 4[A] getLHS() returns "4".
2150  /// Note: Because vector element access is also written A[4] we must
2151  /// predicate the format conversion in getBase and getIdx only on the
2152  /// the type of the RHS, as it is possible for the LHS to be a vector of
2153  /// integer type
2154  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2155  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2156  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2157 
2158  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2159  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2160  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2161 
2163  return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2164  }
2165 
2166  const Expr *getBase() const {
2167  return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2168  }
2169 
2171  return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2172  }
2173 
2174  const Expr *getIdx() const {
2175  return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2176  }
2177 
2178  SourceLocation getLocStart() const LLVM_READONLY {
2179  return getLHS()->getLocStart();
2180  }
2181  SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2182 
2183  SourceLocation getRBracketLoc() const { return RBracketLoc; }
2184  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2185 
2186  SourceLocation getExprLoc() const LLVM_READONLY {
2187  return getBase()->getExprLoc();
2188  }
2189 
2190  static bool classof(const Stmt *T) {
2191  return T->getStmtClass() == ArraySubscriptExprClass;
2192  }
2193 
2194  // Iterators
2196  return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2197  }
2199  return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2200  }
2201 };
2202 
2203 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2204 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2205 /// while its subclasses may represent alternative syntax that (semantically)
2206 /// results in a function call. For example, CXXOperatorCallExpr is
2207 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2208 /// "str1 + str2" to resolve to a function call.
2209 class CallExpr : public Expr {
2210  enum { FN=0, PREARGS_START=1 };
2211  Stmt **SubExprs;
2212  unsigned NumArgs;
2213  SourceLocation RParenLoc;
2214 
2215  void updateDependenciesFromArg(Expr *Arg);
2216 
2217 protected:
2218  // These versions of the constructor are for derived classes.
2219  CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2220  ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2221  ExprValueKind VK, SourceLocation rparenloc);
2222  CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2223  QualType t, ExprValueKind VK, SourceLocation rparenloc);
2224  CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2225  EmptyShell Empty);
2226 
2227  Stmt *getPreArg(unsigned i) {
2228  assert(i < getNumPreArgs() && "Prearg access out of range!");
2229  return SubExprs[PREARGS_START+i];
2230  }
2231  const Stmt *getPreArg(unsigned i) const {
2232  assert(i < getNumPreArgs() && "Prearg access out of range!");
2233  return SubExprs[PREARGS_START+i];
2234  }
2235  void setPreArg(unsigned i, Stmt *PreArg) {
2236  assert(i < getNumPreArgs() && "Prearg access out of range!");
2237  SubExprs[PREARGS_START+i] = PreArg;
2238  }
2239 
2240  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2241 
2242 public:
2243  CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2244  ExprValueKind VK, SourceLocation rparenloc);
2245 
2246  /// \brief Build an empty call expression.
2247  CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2248 
2249  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2250  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2251  void setCallee(Expr *F) { SubExprs[FN] = F; }
2252 
2253  Decl *getCalleeDecl();
2254  const Decl *getCalleeDecl() const {
2255  return const_cast<CallExpr*>(this)->getCalleeDecl();
2256  }
2257 
2258  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2259  FunctionDecl *getDirectCallee();
2261  return const_cast<CallExpr*>(this)->getDirectCallee();
2262  }
2263 
2264  /// getNumArgs - Return the number of actual arguments to this call.
2265  ///
2266  unsigned getNumArgs() const { return NumArgs; }
2267 
2268  /// \brief Retrieve the call arguments.
2270  return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2271  }
2272  const Expr *const *getArgs() const {
2273  return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2274  PREARGS_START);
2275  }
2276 
2277  /// getArg - Return the specified argument.
2278  Expr *getArg(unsigned Arg) {
2279  assert(Arg < NumArgs && "Arg access out of range!");
2280  return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2281  }
2282  const Expr *getArg(unsigned Arg) const {
2283  assert(Arg < NumArgs && "Arg access out of range!");
2284  return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2285  }
2286 
2287  /// setArg - Set the specified argument.
2288  void setArg(unsigned Arg, Expr *ArgExpr) {
2289  assert(Arg < NumArgs && "Arg access out of range!");
2290  SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2291  }
2292 
2293  /// setNumArgs - This changes the number of arguments present in this call.
2294  /// Any orphaned expressions are deleted by this, and any new operands are set
2295  /// to null.
2296  void setNumArgs(const ASTContext& C, unsigned NumArgs);
2297 
2300  typedef llvm::iterator_range<arg_iterator> arg_range;
2301  typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2302 
2303  arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2304  arg_const_range arguments() const {
2305  return arg_const_range(arg_begin(), arg_end());
2306  }
2307 
2308  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2309  arg_iterator arg_end() {
2310  return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2311  }
2312  const_arg_iterator arg_begin() const {
2313  return SubExprs+PREARGS_START+getNumPreArgs();
2314  }
2315  const_arg_iterator arg_end() const {
2316  return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2317  }
2318 
2319  /// This method provides fast access to all the subexpressions of
2320  /// a CallExpr without going through the slower virtual child_iterator
2321  /// interface. This provides efficient reverse iteration of the
2322  /// subexpressions. This is currently used for CFG construction.
2324  return llvm::makeArrayRef(SubExprs,
2325  getNumPreArgs() + PREARGS_START + getNumArgs());
2326  }
2327 
2328  /// getNumCommas - Return the number of commas that must have been present in
2329  /// this function call.
2330  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2331 
2332  /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2333  /// of the callee. If not, return 0.
2334  unsigned getBuiltinCallee() const;
2335 
2336  /// \brief Returns \c true if this is a call to a builtin which does not
2337  /// evaluate side-effects within its arguments.
2338  bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2339 
2340  /// getCallReturnType - Get the return type of the call expr. This is not
2341  /// always the type of the expr itself, if the return type is a reference
2342  /// type.
2343  QualType getCallReturnType(const ASTContext &Ctx) const;
2344 
2345  SourceLocation getRParenLoc() const { return RParenLoc; }
2346  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2347 
2348  SourceLocation getLocStart() const LLVM_READONLY;
2349  SourceLocation getLocEnd() const LLVM_READONLY;
2350 
2351  static bool classof(const Stmt *T) {
2352  return T->getStmtClass() >= firstCallExprConstant &&
2353  T->getStmtClass() <= lastCallExprConstant;
2354  }
2355 
2356  // Iterators
2358  return child_range(&SubExprs[0],
2359  &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2360  }
2361 
2363  return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2364  getNumPreArgs() + PREARGS_START);
2365  }
2366 };
2367 
2368 /// Extra data stored in some MemberExpr objects.
2370  /// \brief The nested-name-specifier that qualifies the name, including
2371  /// source-location information.
2373 
2374  /// \brief The DeclAccessPair through which the MemberDecl was found due to
2375  /// name qualifiers.
2377 };
2378 
2379 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2380 ///
2381 class MemberExpr final
2382  : public Expr,
2383  private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2384  ASTTemplateKWAndArgsInfo,
2385  TemplateArgumentLoc> {
2386  /// Base - the expression for the base pointer or structure references. In
2387  /// X.F, this is "X".
2388  Stmt *Base;
2389 
2390  /// MemberDecl - This is the decl being referenced by the field/member name.
2391  /// In X.F, this is the decl referenced by F.
2392  ValueDecl *MemberDecl;
2393 
2394  /// MemberDNLoc - Provides source/type location info for the
2395  /// declaration name embedded in MemberDecl.
2396  DeclarationNameLoc MemberDNLoc;
2397 
2398  /// MemberLoc - This is the location of the member name.
2399  SourceLocation MemberLoc;
2400 
2401  /// This is the location of the -> or . in the expression.
2402  SourceLocation OperatorLoc;
2403 
2404  /// IsArrow - True if this is "X->F", false if this is "X.F".
2405  bool IsArrow : 1;
2406 
2407  /// \brief True if this member expression used a nested-name-specifier to
2408  /// refer to the member, e.g., "x->Base::f", or found its member via a using
2409  /// declaration. When true, a MemberExprNameQualifier
2410  /// structure is allocated immediately after the MemberExpr.
2411  bool HasQualifierOrFoundDecl : 1;
2412 
2413  /// \brief True if this member expression specified a template keyword
2414  /// and/or a template argument list explicitly, e.g., x->f<int>,
2415  /// x->template f, x->template f<int>.
2416  /// When true, an ASTTemplateKWAndArgsInfo structure and its
2417  /// TemplateArguments (if any) are present.
2418  bool HasTemplateKWAndArgsInfo : 1;
2419 
2420  /// \brief True if this member expression refers to a method that
2421  /// was resolved from an overloaded set having size greater than 1.
2422  bool HadMultipleCandidates : 1;
2423 
2424  size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2425  return HasQualifierOrFoundDecl ? 1 : 0;
2426  }
2427 
2428  size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2429  return HasTemplateKWAndArgsInfo ? 1 : 0;
2430  }
2431 
2432 public:
2433  MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2434  ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2436  : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2437  base->isValueDependent(), base->isInstantiationDependent(),
2438  base->containsUnexpandedParameterPack()),
2439  Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2440  MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2441  IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2442  HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2443  assert(memberdecl->getDeclName() == NameInfo.getName());
2444  }
2445 
2446  // NOTE: this constructor should be used only when it is known that
2447  // the member name can not provide additional syntactic info
2448  // (i.e., source locations for C++ operator names or type source info
2449  // for constructors, destructors and conversion operators).
2450  MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2451  ValueDecl *memberdecl, SourceLocation l, QualType ty,
2453  : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2454  base->isValueDependent(), base->isInstantiationDependent(),
2455  base->containsUnexpandedParameterPack()),
2456  Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2457  OperatorLoc(operatorloc), IsArrow(isarrow),
2458  HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2459  HadMultipleCandidates(false) {}
2460 
2461  static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2462  SourceLocation OperatorLoc,
2463  NestedNameSpecifierLoc QualifierLoc,
2464  SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2465  DeclAccessPair founddecl,
2466  DeclarationNameInfo MemberNameInfo,
2467  const TemplateArgumentListInfo *targs, QualType ty,
2468  ExprValueKind VK, ExprObjectKind OK);
2469 
2470  void setBase(Expr *E) { Base = E; }
2471  Expr *getBase() const { return cast<Expr>(Base); }
2472 
2473  /// \brief Retrieve the member declaration to which this expression refers.
2474  ///
2475  /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2476  /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2477  ValueDecl *getMemberDecl() const { return MemberDecl; }
2478  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2479 
2480  /// \brief Retrieves the declaration found by lookup.
2482  if (!HasQualifierOrFoundDecl)
2483  return DeclAccessPair::make(getMemberDecl(),
2484  getMemberDecl()->getAccess());
2485  return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2486  }
2487 
2488  /// \brief Determines whether this member expression actually had
2489  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2490  /// x->Base::foo.
2491  bool hasQualifier() const { return getQualifier() != nullptr; }
2492 
2493  /// \brief If the member name was qualified, retrieves the
2494  /// nested-name-specifier that precedes the member name, with source-location
2495  /// information.
2497  if (!HasQualifierOrFoundDecl)
2498  return NestedNameSpecifierLoc();
2499 
2500  return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2501  }
2502 
2503  /// \brief If the member name was qualified, retrieves the
2504  /// nested-name-specifier that precedes the member name. Otherwise, returns
2505  /// NULL.
2507  return getQualifierLoc().getNestedNameSpecifier();
2508  }
2509 
2510  /// \brief Retrieve the location of the template keyword preceding
2511  /// the member name, if any.
2513  if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2514  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2515  }
2516 
2517  /// \brief Retrieve the location of the left angle bracket starting the
2518  /// explicit template argument list following the member name, if any.
2520  if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2521  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2522  }
2523 
2524  /// \brief Retrieve the location of the right angle bracket ending the
2525  /// explicit template argument list following the member name, if any.
2527  if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2528  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2529  }
2530 
2531  /// Determines whether the member name was preceded by the template keyword.
2532  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2533 
2534  /// \brief Determines whether the member name was followed by an
2535  /// explicit template argument list.
2536  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2537 
2538  /// \brief Copies the template arguments (if present) into the given
2539  /// structure.
2541  if (hasExplicitTemplateArgs())
2542  getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2543  getTrailingObjects<TemplateArgumentLoc>(), List);
2544  }
2545 
2546  /// \brief Retrieve the template arguments provided as part of this
2547  /// template-id.
2549  if (!hasExplicitTemplateArgs())
2550  return nullptr;
2551 
2552  return getTrailingObjects<TemplateArgumentLoc>();
2553  }
2554 
2555  /// \brief Retrieve the number of template arguments provided as part of this
2556  /// template-id.
2557  unsigned getNumTemplateArgs() const {
2558  if (!hasExplicitTemplateArgs())
2559  return 0;
2560 
2561  return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2562  }
2563 
2565  return {getTemplateArgs(), getNumTemplateArgs()};
2566  }
2567 
2568  /// \brief Retrieve the member declaration name info.
2570  return DeclarationNameInfo(MemberDecl->getDeclName(),
2571  MemberLoc, MemberDNLoc);
2572  }
2573 
2574  SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2575 
2576  bool isArrow() const { return IsArrow; }
2577  void setArrow(bool A) { IsArrow = A; }
2578 
2579  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2580  /// location of 'F'.
2581  SourceLocation getMemberLoc() const { return MemberLoc; }
2582  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2583 
2584  SourceLocation getLocStart() const LLVM_READONLY;
2585  SourceLocation getLocEnd() const LLVM_READONLY;
2586 
2587  SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2588 
2589  /// \brief Determine whether the base of this explicit is implicit.
2590  bool isImplicitAccess() const {
2591  return getBase() && getBase()->isImplicitCXXThis();
2592  }
2593 
2594  /// \brief Returns true if this member expression refers to a method that
2595  /// was resolved from an overloaded set having size greater than 1.
2596  bool hadMultipleCandidates() const {
2597  return HadMultipleCandidates;
2598  }
2599  /// \brief Sets the flag telling whether this expression refers to
2600  /// a method that was resolved from an overloaded set having size
2601  /// greater than 1.
2602  void setHadMultipleCandidates(bool V = true) {
2603  HadMultipleCandidates = V;
2604  }
2605 
2606  /// \brief Returns true if virtual dispatch is performed.
2607  /// If the member access is fully qualified, (i.e. X::f()), virtual
2608  /// dispatching is not performed. In -fapple-kext mode qualified
2609  /// calls to virtual method will still go through the vtable.
2610  bool performsVirtualDispatch(const LangOptions &LO) const {
2611  return LO.AppleKext || !hasQualifier();
2612  }
2613 
2614  static bool classof(const Stmt *T) {
2615  return T->getStmtClass() == MemberExprClass;
2616  }
2617 
2618  // Iterators
2619  child_range children() { return child_range(&Base, &Base+1); }
2621  return const_child_range(&Base, &Base + 1);
2622  }
2623 
2625  friend class ASTReader;
2626  friend class ASTStmtWriter;
2627 };
2628 
2629 /// CompoundLiteralExpr - [C99 6.5.2.5]
2630 ///
2631 class CompoundLiteralExpr : public Expr {
2632  /// LParenLoc - If non-null, this is the location of the left paren in a
2633  /// compound literal like "(int){4}". This can be null if this is a
2634  /// synthesized compound expression.
2635  SourceLocation LParenLoc;
2636 
2637  /// The type as written. This can be an incomplete array type, in
2638  /// which case the actual expression type will be different.
2639  /// The int part of the pair stores whether this expr is file scope.
2640  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2641  Stmt *Init;
2642 public:
2644  QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2645  : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2646  tinfo->getType()->isDependentType(),
2647  init->isValueDependent(),
2648  (init->isInstantiationDependent() ||
2649  tinfo->getType()->isInstantiationDependentType()),
2650  init->containsUnexpandedParameterPack()),
2651  LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2652 
2653  /// \brief Construct an empty compound literal.
2655  : Expr(CompoundLiteralExprClass, Empty) { }
2656 
2657  const Expr *getInitializer() const { return cast<Expr>(Init); }
2658  Expr *getInitializer() { return cast<Expr>(Init); }
2659  void setInitializer(Expr *E) { Init = E; }
2660 
2661  bool isFileScope() const { return TInfoAndScope.getInt(); }
2662  void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2663 
2664  SourceLocation getLParenLoc() const { return LParenLoc; }
2665  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2666 
2668  return TInfoAndScope.getPointer();
2669  }
2671  TInfoAndScope.setPointer(tinfo);
2672  }
2673 
2674  SourceLocation getLocStart() const LLVM_READONLY {
2675  // FIXME: Init should never be null.
2676  if (!Init)
2677  return SourceLocation();
2678  if (LParenLoc.isInvalid())
2679  return Init->getLocStart();
2680  return LParenLoc;
2681  }
2682  SourceLocation getLocEnd() const LLVM_READONLY {
2683  // FIXME: Init should never be null.
2684  if (!Init)
2685  return SourceLocation();
2686  return Init->getLocEnd();
2687  }
2688 
2689  static bool classof(const Stmt *T) {
2690  return T->getStmtClass() == CompoundLiteralExprClass;
2691  }
2692 
2693  // Iterators
2694  child_range children() { return child_range(&Init, &Init+1); }
2696  return const_child_range(&Init, &Init + 1);
2697  }
2698 };
2699 
2700 /// CastExpr - Base class for type casts, including both implicit
2701 /// casts (ImplicitCastExpr) and explicit casts that have some
2702 /// representation in the source code (ExplicitCastExpr's derived
2703 /// classes).
2704 class CastExpr : public Expr {
2705 private:
2706  Stmt *Op;
2707 
2708  bool CastConsistency() const;
2709 
2710  const CXXBaseSpecifier * const *path_buffer() const {
2711  return const_cast<CastExpr*>(this)->path_buffer();
2712  }
2713  CXXBaseSpecifier **path_buffer();
2714 
2715  void setBasePathSize(unsigned basePathSize) {
2716  CastExprBits.BasePathSize = basePathSize;
2717  assert(CastExprBits.BasePathSize == basePathSize &&
2718  "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2719  }
2720 
2721 protected:
2723  Expr *op, unsigned BasePathSize)
2724  : Expr(SC, ty, VK, OK_Ordinary,
2725  // Cast expressions are type-dependent if the type is
2726  // dependent (C++ [temp.dep.expr]p3).
2727  ty->isDependentType(),
2728  // Cast expressions are value-dependent if the type is
2729  // dependent or if the subexpression is value-dependent.
2730  ty->isDependentType() || (op && op->isValueDependent()),
2731  (ty->isInstantiationDependentType() ||
2732  (op && op->isInstantiationDependent())),
2733  // An implicit cast expression doesn't (lexically) contain an
2734  // unexpanded pack, even if its target type does.
2735  ((SC != ImplicitCastExprClass &&
2736  ty->containsUnexpandedParameterPack()) ||
2737  (op && op->containsUnexpandedParameterPack()))),
2738  Op(op) {
2739  assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2740  CastExprBits.Kind = kind;
2741  setBasePathSize(BasePathSize);
2742  assert(CastConsistency());
2743  }
2744 
2745  /// \brief Construct an empty cast.
2746  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2747  : Expr(SC, Empty) {
2748  setBasePathSize(BasePathSize);
2749  }
2750 
2751 public:
2752  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2753  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2754  const char *getCastKindName() const;
2755 
2756  Expr *getSubExpr() { return cast<Expr>(Op); }
2757  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2758  void setSubExpr(Expr *E) { Op = E; }
2759 
2760  /// \brief Retrieve the cast subexpression as it was written in the source
2761  /// code, looking through any implicit casts or other intermediate nodes
2762  /// introduced by semantic analysis.
2763  Expr *getSubExprAsWritten();
2764  const Expr *getSubExprAsWritten() const {
2765  return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2766  }
2767 
2769  typedef const CXXBaseSpecifier * const *path_const_iterator;
2770  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2771  unsigned path_size() const { return CastExprBits.BasePathSize; }
2772  path_iterator path_begin() { return path_buffer(); }
2773  path_iterator path_end() { return path_buffer() + path_size(); }
2774  path_const_iterator path_begin() const { return path_buffer(); }
2775  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2776 
2778  assert(getCastKind() == CK_ToUnion);
2779  return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2780  }
2781 
2782  static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2783  QualType opType);
2784  static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2785  QualType opType);
2786 
2787  static bool classof(const Stmt *T) {
2788  return T->getStmtClass() >= firstCastExprConstant &&
2789  T->getStmtClass() <= lastCastExprConstant;
2790  }
2791 
2792  // Iterators
2793  child_range children() { return child_range(&Op, &Op+1); }
2794  const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2795 };
2796 
2797 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2798 /// conversions, which have no direct representation in the original
2799 /// source code. For example: converting T[]->T*, void f()->void
2800 /// (*f)(), float->double, short->int, etc.
2801 ///
2802 /// In C, implicit casts always produce rvalues. However, in C++, an
2803 /// implicit cast whose result is being bound to a reference will be
2804 /// an lvalue or xvalue. For example:
2805 ///
2806 /// @code
2807 /// class Base { };
2808 /// class Derived : public Base { };
2809 /// Derived &&ref();
2810 /// void f(Derived d) {
2811 /// Base& b = d; // initializer is an ImplicitCastExpr
2812 /// // to an lvalue of type Base
2813 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2814 /// // to an xvalue of type Base
2815 /// }
2816 /// @endcode
2817 class ImplicitCastExpr final
2818  : public CastExpr,
2819  private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2820 private:
2822  unsigned BasePathLength, ExprValueKind VK)
2823  : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2824  }
2825 
2826  /// \brief Construct an empty implicit cast.
2827  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2828  : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2829 
2830 public:
2831  enum OnStack_t { OnStack };
2833  ExprValueKind VK)
2834  : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2835  }
2836 
2837  static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2838  CastKind Kind, Expr *Operand,
2839  const CXXCastPath *BasePath,
2840  ExprValueKind Cat);
2841 
2842  static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2843  unsigned PathSize);
2844 
2845  SourceLocation getLocStart() const LLVM_READONLY {
2846  return getSubExpr()->getLocStart();
2847  }
2848  SourceLocation getLocEnd() const LLVM_READONLY {
2849  return getSubExpr()->getLocEnd();
2850  }
2851 
2852  static bool classof(const Stmt *T) {
2853  return T->getStmtClass() == ImplicitCastExprClass;
2854  }
2855 
2857  friend class CastExpr;
2858 };
2859 
2861  Expr *e = this;
2862  while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2863  e = ice->getSubExpr();
2864  return e;
2865 }
2866 
2867 /// ExplicitCastExpr - An explicit cast written in the source
2868 /// code.
2869 ///
2870 /// This class is effectively an abstract class, because it provides
2871 /// the basic representation of an explicitly-written cast without
2872 /// specifying which kind of cast (C cast, functional cast, static
2873 /// cast, etc.) was written; specific derived classes represent the
2874 /// particular style of cast and its location information.
2875 ///
2876 /// Unlike implicit casts, explicit cast nodes have two different
2877 /// types: the type that was written into the source code, and the
2878 /// actual type of the expression as determined by semantic
2879 /// analysis. These types may differ slightly. For example, in C++ one
2880 /// can cast to a reference type, which indicates that the resulting
2881 /// expression will be an lvalue or xvalue. The reference type, however,
2882 /// will not be used as the type of the expression.
2883 class ExplicitCastExpr : public CastExpr {
2884  /// TInfo - Source type info for the (written) type
2885  /// this expression is casting to.
2886  TypeSourceInfo *TInfo;
2887 
2888 protected:
2890  CastKind kind, Expr *op, unsigned PathSize,
2891  TypeSourceInfo *writtenTy)
2892  : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2893 
2894  /// \brief Construct an empty explicit cast.
2895  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2896  : CastExpr(SC, Shell, PathSize) { }
2897 
2898 public:
2899  /// getTypeInfoAsWritten - Returns the type source info for the type
2900  /// that this expression is casting to.
2901  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2902  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2903 
2904  /// getTypeAsWritten - Returns the type that this expression is
2905  /// casting to, as written in the source code.
2906  QualType getTypeAsWritten() const { return TInfo->getType(); }
2907 
2908  static bool classof(const Stmt *T) {
2909  return T->getStmtClass() >= firstExplicitCastExprConstant &&
2910  T->getStmtClass() <= lastExplicitCastExprConstant;
2911  }
2912 };
2913 
2914 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2915 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2916 /// (Type)expr. For example: @c (int)f.
2917 class CStyleCastExpr final
2918  : public ExplicitCastExpr,
2919  private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2920  SourceLocation LPLoc; // the location of the left paren
2921  SourceLocation RPLoc; // the location of the right paren
2922 
2924  unsigned PathSize, TypeSourceInfo *writtenTy,
2926  : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2927  writtenTy), LPLoc(l), RPLoc(r) {}
2928 
2929  /// \brief Construct an empty C-style explicit cast.
2930  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2931  : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2932 
2933 public:
2934  static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2935  ExprValueKind VK, CastKind K,
2936  Expr *Op, const CXXCastPath *BasePath,
2937  TypeSourceInfo *WrittenTy, SourceLocation L,
2938  SourceLocation R);
2939 
2940  static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2941  unsigned PathSize);
2942 
2943  SourceLocation getLParenLoc() const { return LPLoc; }
2944  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2945 
2946  SourceLocation getRParenLoc() const { return RPLoc; }
2947  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2948 
2949  SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2950  SourceLocation getLocEnd() const LLVM_READONLY {
2951  return getSubExpr()->getLocEnd();
2952  }
2953 
2954  static bool classof(const Stmt *T) {
2955  return T->getStmtClass() == CStyleCastExprClass;
2956  }
2957 
2959  friend class CastExpr;
2960 };
2961 
2962 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2963 ///
2964 /// This expression node kind describes a builtin binary operation,
2965 /// such as "x + y" for integer values "x" and "y". The operands will
2966 /// already have been converted to appropriate types (e.g., by
2967 /// performing promotions or conversions).
2968 ///
2969 /// In C++, where operators may be overloaded, a different kind of
2970 /// expression node (CXXOperatorCallExpr) is used to express the
2971 /// invocation of an overloaded operator with operator syntax. Within
2972 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2973 /// used to store an expression "x + y" depends on the subexpressions
2974 /// for x and y. If neither x or y is type-dependent, and the "+"
2975 /// operator resolves to a built-in operation, BinaryOperator will be
2976 /// used to express the computation (x and y may still be
2977 /// value-dependent). If either x or y is type-dependent, or if the
2978 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2979 /// be used to express the computation.
2980 class BinaryOperator : public Expr {
2981 public:
2983 
2984 private:
2985  unsigned Opc : 6;
2986 
2987  // This is only meaningful for operations on floating point types and 0
2988  // otherwise.
2989  unsigned FPFeatures : 2;
2990  SourceLocation OpLoc;
2991 
2992  enum { LHS, RHS, END_EXPR };
2993  Stmt* SubExprs[END_EXPR];
2994 public:
2995 
2996  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2998  SourceLocation opLoc, FPOptions FPFeatures)
2999  : Expr(BinaryOperatorClass, ResTy, VK, OK,
3000  lhs->isTypeDependent() || rhs->isTypeDependent(),
3001  lhs->isValueDependent() || rhs->isValueDependent(),
3002  (lhs->isInstantiationDependent() ||
3003  rhs->isInstantiationDependent()),
3004  (lhs->containsUnexpandedParameterPack() ||
3005  rhs->containsUnexpandedParameterPack())),
3006  Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3007  SubExprs[LHS] = lhs;
3008  SubExprs[RHS] = rhs;
3009  assert(!isCompoundAssignmentOp() &&
3010  "Use CompoundAssignOperator for compound assignments");
3011  }
3012 
3013  /// \brief Construct an empty binary operator.
3014  explicit BinaryOperator(EmptyShell Empty)
3015  : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
3016 
3017  SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
3018  SourceLocation getOperatorLoc() const { return OpLoc; }
3019  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3020 
3021  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3022  void setOpcode(Opcode O) { Opc = O; }
3023 
3024  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3025  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3026  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3027  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3028 
3029  SourceLocation getLocStart() const LLVM_READONLY {
3030  return getLHS()->getLocStart();
3031  }
3032  SourceLocation getLocEnd() const LLVM_READONLY {
3033  return getRHS()->getLocEnd();
3034  }
3035 
3036  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3037  /// corresponds to, e.g. "<<=".
3038  static StringRef getOpcodeStr(Opcode Op);
3039 
3040  StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3041 
3042  /// \brief Retrieve the binary opcode that corresponds to the given
3043  /// overloaded operator.
3044  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3045 
3046  /// \brief Retrieve the overloaded operator kind that corresponds to
3047  /// the given binary opcode.
3048  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3049 
3050  /// predicates to categorize the respective opcodes.
3051  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
3052  static bool isMultiplicativeOp(Opcode Opc) {
3053  return Opc >= BO_Mul && Opc <= BO_Rem;
3054  }
3056  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3057  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3058  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3059  bool isShiftOp() const { return isShiftOp(getOpcode()); }
3060 
3061  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3062  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3063 
3064  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3065  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3066 
3067  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3068  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3069 
3070  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
3071  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3072 
3073  static Opcode negateComparisonOp(Opcode Opc) {
3074  switch (Opc) {
3075  default:
3076  llvm_unreachable("Not a comparsion operator.");
3077  case BO_LT: return BO_GE;
3078  case BO_GT: return BO_LE;
3079  case BO_LE: return BO_GT;
3080  case BO_GE: return BO_LT;
3081  case BO_EQ: return BO_NE;
3082  case BO_NE: return BO_EQ;
3083  }
3084  }
3085 
3086  static Opcode reverseComparisonOp(Opcode Opc) {
3087  switch (Opc) {
3088  default:
3089  llvm_unreachable("Not a comparsion operator.");
3090  case BO_LT: return BO_GT;
3091  case BO_GT: return BO_LT;
3092  case BO_LE: return BO_GE;
3093  case BO_GE: return BO_LE;
3094  case BO_EQ:
3095  case BO_NE:
3096  return Opc;
3097  }
3098  }
3099 
3100  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3101  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3102 
3103  static bool isAssignmentOp(Opcode Opc) {
3104  return Opc >= BO_Assign && Opc <= BO_OrAssign;
3105  }
3106  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3107 
3108  static bool isCompoundAssignmentOp(Opcode Opc) {
3109  return Opc > BO_Assign && Opc <= BO_OrAssign;
3110  }
3111  bool isCompoundAssignmentOp() const {
3112  return isCompoundAssignmentOp(getOpcode());
3113  }
3114  static Opcode getOpForCompoundAssignment(Opcode Opc) {
3115  assert(isCompoundAssignmentOp(Opc));
3116  if (Opc >= BO_AndAssign)
3117  return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3118  else
3119  return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3120  }
3121 
3122  static bool isShiftAssignOp(Opcode Opc) {
3123  return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3124  }
3125  bool isShiftAssignOp() const {
3126  return isShiftAssignOp(getOpcode());
3127  }
3128 
3129  // Return true if a binary operator using the specified opcode and operands
3130  // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3131  // integer to a pointer.
3132  static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3133  Expr *LHS, Expr *RHS);
3134 
3135  static bool classof(const Stmt *S) {
3136  return S->getStmtClass() >= firstBinaryOperatorConstant &&
3137  S->getStmtClass() <= lastBinaryOperatorConstant;
3138  }
3139 
3140  // Iterators
3142  return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3143  }
3145  return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3146  }
3147 
3148  // Set the FP contractability status of this operator. Only meaningful for
3149  // operations on floating point types.
3150  void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3151 
3152  FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3153 
3154  // Get the FP contractability status of this operator. Only meaningful for
3155  // operations on floating point types.
3157  return FPOptions(FPFeatures).allowFPContractWithinStatement();
3158  }
3159 
3160 protected:
3161  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3163  SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3164  : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3165  lhs->isTypeDependent() || rhs->isTypeDependent(),
3166  lhs->isValueDependent() || rhs->isValueDependent(),
3167  (lhs->isInstantiationDependent() ||
3168  rhs->isInstantiationDependent()),
3169  (lhs->containsUnexpandedParameterPack() ||
3170  rhs->containsUnexpandedParameterPack())),
3171  Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3172  SubExprs[LHS] = lhs;
3173  SubExprs[RHS] = rhs;
3174  }
3175 
3177  : Expr(SC, Empty), Opc(BO_MulAssign) { }
3178 };
3179 
3180 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3181 /// track of the type the operation is performed in. Due to the semantics of
3182 /// these operators, the operands are promoted, the arithmetic performed, an
3183 /// implicit conversion back to the result type done, then the assignment takes
3184 /// place. This captures the intermediate type which the computation is done
3185 /// in.
3187  QualType ComputationLHSType;
3188  QualType ComputationResultType;
3189 public:
3190  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3192  QualType CompLHSType, QualType CompResultType,
3193  SourceLocation OpLoc, FPOptions FPFeatures)
3194  : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3195  true),
3196  ComputationLHSType(CompLHSType),
3197  ComputationResultType(CompResultType) {
3198  assert(isCompoundAssignmentOp() &&
3199  "Only should be used for compound assignments");
3200  }
3201 
3202  /// \brief Build an empty compound assignment operator expression.
3204  : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3205 
3206  // The two computation types are the type the LHS is converted
3207  // to for the computation and the type of the result; the two are
3208  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3209  QualType getComputationLHSType() const { return ComputationLHSType; }
3210  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3211 
3212  QualType getComputationResultType() const { return ComputationResultType; }
3213  void setComputationResultType(QualType T) { ComputationResultType = T; }
3214 
3215  static bool classof(const Stmt *S) {
3216  return S->getStmtClass() == CompoundAssignOperatorClass;
3217  }
3218 };
3219 
3220 /// AbstractConditionalOperator - An abstract base class for
3221 /// ConditionalOperator and BinaryConditionalOperator.
3223  SourceLocation QuestionLoc, ColonLoc;
3224  friend class ASTStmtReader;
3225 
3226 protected:
3229  bool TD, bool VD, bool ID,
3230  bool ContainsUnexpandedParameterPack,
3231  SourceLocation qloc,
3232  SourceLocation cloc)
3233  : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3234  QuestionLoc(qloc), ColonLoc(cloc) {}
3235 
3237  : Expr(SC, Empty) { }
3238 
3239 public:
3240  // getCond - Return the expression representing the condition for
3241  // the ?: operator.
3242  Expr *getCond() const;
3243 
3244  // getTrueExpr - Return the subexpression representing the value of
3245  // the expression if the condition evaluates to true.
3246  Expr *getTrueExpr() const;
3247 
3248  // getFalseExpr - Return the subexpression representing the value of
3249  // the expression if the condition evaluates to false. This is
3250  // the same as getRHS.
3251  Expr *getFalseExpr() const;
3252 
3253  SourceLocation getQuestionLoc() const { return QuestionLoc; }
3255 
3256  static bool classof(const Stmt *T) {
3257  return T->getStmtClass() == ConditionalOperatorClass ||
3258  T->getStmtClass() == BinaryConditionalOperatorClass;
3259  }
3260 };
3261 
3262 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3263 /// middle" extension is a BinaryConditionalOperator.
3265  enum { COND, LHS, RHS, END_EXPR };
3266  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3267 
3268  friend class ASTStmtReader;
3269 public:
3271  SourceLocation CLoc, Expr *rhs,
3273  : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3274  // FIXME: the type of the conditional operator doesn't
3275  // depend on the type of the conditional, but the standard
3276  // seems to imply that it could. File a bug!
3277  (lhs->isTypeDependent() || rhs->isTypeDependent()),
3278  (cond->isValueDependent() || lhs->isValueDependent() ||
3279  rhs->isValueDependent()),
3280  (cond->isInstantiationDependent() ||
3281  lhs->isInstantiationDependent() ||
3282  rhs->isInstantiationDependent()),
3283  (cond->containsUnexpandedParameterPack() ||
3284  lhs->containsUnexpandedParameterPack() ||
3285  rhs->containsUnexpandedParameterPack()),
3286  QLoc, CLoc) {
3287  SubExprs[COND] = cond;
3288  SubExprs[LHS] = lhs;
3289  SubExprs[RHS] = rhs;
3290  }
3291 
3292  /// \brief Build an empty conditional operator.
3294  : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3295 
3296  // getCond - Return the expression representing the condition for
3297  // the ?: operator.
3298  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3299 
3300  // getTrueExpr - Return the subexpression representing the value of
3301  // the expression if the condition evaluates to true.
3302  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3303 
3304  // getFalseExpr - Return the subexpression representing the value of
3305  // the expression if the condition evaluates to false. This is
3306  // the same as getRHS.
3307  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3308 
3309  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3310  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3311 
3312  SourceLocation getLocStart() const LLVM_READONLY {
3313  return getCond()->getLocStart();
3314  }
3315  SourceLocation getLocEnd() const LLVM_READONLY {
3316  return getRHS()->getLocEnd();
3317  }
3318 
3319  static bool classof(const Stmt *T) {
3320  return T->getStmtClass() == ConditionalOperatorClass;
3321  }
3322 
3323  // Iterators
3325  return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3326  }
3328  return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3329  }
3330 };
3331 
3332 /// BinaryConditionalOperator - The GNU extension to the conditional
3333 /// operator which allows the middle operand to be omitted.
3334 ///
3335 /// This is a different expression kind on the assumption that almost
3336 /// every client ends up needing to know that these are different.
3338  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3339 
3340  /// - the common condition/left-hand-side expression, which will be
3341  /// evaluated as the opaque value
3342  /// - the condition, expressed in terms of the opaque value
3343  /// - the left-hand-side, expressed in terms of the opaque value
3344  /// - the right-hand-side
3345  Stmt *SubExprs[NUM_SUBEXPRS];
3346  OpaqueValueExpr *OpaqueValue;
3347 
3348  friend class ASTStmtReader;
3349 public:
3351  Expr *cond, Expr *lhs, Expr *rhs,
3352  SourceLocation qloc, SourceLocation cloc,
3354  : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3355  (common->isTypeDependent() || rhs->isTypeDependent()),
3356  (common->isValueDependent() || rhs->isValueDependent()),
3357  (common->isInstantiationDependent() ||
3358  rhs->isInstantiationDependent()),
3359  (common->containsUnexpandedParameterPack() ||
3360  rhs->containsUnexpandedParameterPack()),
3361  qloc, cloc),
3362  OpaqueValue(opaqueValue) {
3363  SubExprs[COMMON] = common;
3364  SubExprs[COND] = cond;
3365  SubExprs[LHS] = lhs;
3366  SubExprs[RHS] = rhs;
3367  assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3368  }
3369 
3370  /// \brief Build an empty conditional operator.
3372  : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3373 
3374  /// \brief getCommon - Return the common expression, written to the
3375  /// left of the condition. The opaque value will be bound to the
3376  /// result of this expression.
3377  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3378 
3379  /// \brief getOpaqueValue - Return the opaque value placeholder.
3380  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3381 
3382  /// \brief getCond - Return the condition expression; this is defined
3383  /// in terms of the opaque value.
3384  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3385 
3386  /// \brief getTrueExpr - Return the subexpression which will be
3387  /// evaluated if the condition evaluates to true; this is defined
3388  /// in terms of the opaque value.
3389  Expr *getTrueExpr() const {
3390  return cast<Expr>(SubExprs[LHS]);
3391  }
3392 
3393  /// \brief getFalseExpr - Return the subexpression which will be
3394  /// evaluated if the condnition evaluates to false; this is
3395  /// defined in terms of the opaque value.
3396  Expr *getFalseExpr() const {
3397  return cast<Expr>(SubExprs[RHS]);
3398  }
3399 
3400  SourceLocation getLocStart() const LLVM_READONLY {
3401  return getCommon()->getLocStart();
3402  }
3403  SourceLocation getLocEnd() const LLVM_READONLY {
3404  return getFalseExpr()->getLocEnd();
3405  }
3406 
3407  static bool classof(const Stmt *T) {
3408  return T->getStmtClass() == BinaryConditionalOperatorClass;
3409  }
3410 
3411  // Iterators
3413  return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3414  }
3416  return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3417  }
3418 };
3419 
3421  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3422  return co->getCond();
3423  return cast<BinaryConditionalOperator>(this)->getCond();
3424 }
3425 
3427  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3428  return co->getTrueExpr();
3429  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3430 }
3431 
3433  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3434  return co->getFalseExpr();
3435  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3436 }
3437 
3438 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3439 class AddrLabelExpr : public Expr {
3440  SourceLocation AmpAmpLoc, LabelLoc;
3441  LabelDecl *Label;
3442 public:
3444  QualType t)
3445  : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3446  false),
3447  AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3448 
3449  /// \brief Build an empty address of a label expression.
3450  explicit AddrLabelExpr(EmptyShell Empty)
3451  : Expr(AddrLabelExprClass, Empty) { }
3452 
3453  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3454  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3455  SourceLocation getLabelLoc() const { return LabelLoc; }
3456  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3457 
3458  SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3459  SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3460 
3461  LabelDecl *getLabel() const { return Label; }
3462  void setLabel(LabelDecl *L) { Label = L; }
3463 
3464  static bool classof(const Stmt *T) {
3465  return T->getStmtClass() == AddrLabelExprClass;
3466  }
3467 
3468  // Iterators
3471  }
3474  }
3475 };
3476 
3477 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3478 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3479 /// takes the value of the last subexpression.
3480 ///
3481 /// A StmtExpr is always an r-value; values "returned" out of a
3482 /// StmtExpr will be copied.
3483 class StmtExpr : public Expr {
3484  Stmt *SubStmt;
3485  SourceLocation LParenLoc, RParenLoc;
3486 public:
3487  // FIXME: Does type-dependence need to be computed differently?
3488  // FIXME: Do we need to compute instantiation instantiation-dependence for
3489  // statements? (ugh!)
3491  SourceLocation lp, SourceLocation rp) :
3492  Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3493  T->isDependentType(), false, false, false),
3494  SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3495 
3496  /// \brief Build an empty statement expression.
3497  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3498 
3499  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3500  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3501  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3502 
3503  SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3504  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3505 
3506  SourceLocation getLParenLoc() const { return LParenLoc; }
3507  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3508  SourceLocation getRParenLoc() const { return RParenLoc; }
3509  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3510 
3511  static bool classof(const Stmt *T) {
3512  return T->getStmtClass() == StmtExprClass;
3513  }
3514 
3515  // Iterators
3516  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3518  return const_child_range(&SubStmt, &SubStmt + 1);
3519  }
3520 };
3521 
3522 /// ShuffleVectorExpr - clang-specific builtin-in function
3523 /// __builtin_shufflevector.
3524 /// This AST node represents a operator that does a constant
3525 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3526 /// two vectors and a variable number of constant indices,
3527 /// and returns the appropriately shuffled vector.
3528 class ShuffleVectorExpr : public Expr {
3529  SourceLocation BuiltinLoc, RParenLoc;
3530 
3531  // SubExprs - the list of values passed to the __builtin_shufflevector
3532  // function. The first two are vectors, and the rest are constant
3533  // indices. The number of values in this list is always
3534  // 2+the number of indices in the vector type.
3535  Stmt **SubExprs;
3536  unsigned NumExprs;
3537 
3538 public:
3540  SourceLocation BLoc, SourceLocation RP);
3541 
3542  /// \brief Build an empty vector-shuffle expression.
3544  : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3545 
3546  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3547  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3548 
3549  SourceLocation getRParenLoc() const { return RParenLoc; }
3550  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3551 
3552  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3553  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3554 
3555  static bool classof(const Stmt *T) {
3556  return T->getStmtClass() == ShuffleVectorExprClass;
3557  }
3558 
3559  /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3560  /// constant expression, the actual arguments passed in, and the function
3561  /// pointers.
3562  unsigned getNumSubExprs() const { return NumExprs; }
3563 
3564  /// \brief Retrieve the array of expressions.
3565  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3566 
3567  /// getExpr - Return the Expr at the specified index.
3568  Expr *getExpr(unsigned Index) {
3569  assert((Index < NumExprs) && "Arg access out of range!");
3570  return cast<Expr>(SubExprs[Index]);
3571  }
3572  const Expr *getExpr(unsigned Index) const {
3573  assert((Index < NumExprs) && "Arg access out of range!");
3574  return cast<Expr>(SubExprs[Index]);
3575  }
3576 
3577  void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3578 
3579  llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3580  assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3581  return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3582  }
3583 
3584  // Iterators
3586  return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3587  }
3589  return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
3590  }
3591 };
3592 
3593 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3594 /// This AST node provides support for converting a vector type to another
3595 /// vector type of the same arity.
3596 class ConvertVectorExpr : public Expr {
3597 private:
3598  Stmt *SrcExpr;
3599  TypeSourceInfo *TInfo;
3600  SourceLocation BuiltinLoc, RParenLoc;
3601 
3602  friend class ASTReader;
3603  friend class ASTStmtReader;
3604  explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3605 
3606 public:
3609  SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3610  : Expr(ConvertVectorExprClass, DstType, VK, OK,
3611  DstType->isDependentType(),
3612  DstType->isDependentType() || SrcExpr->isValueDependent(),
3613  (DstType->isInstantiationDependentType() ||
3614  SrcExpr->isInstantiationDependent()),
3615  (DstType->containsUnexpandedParameterPack() ||
3616  SrcExpr->containsUnexpandedParameterPack())),
3617  SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3618 
3619  /// getSrcExpr - Return the Expr to be converted.
3620  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3621 
3622  /// getTypeSourceInfo - Return the destination type.
3624  return TInfo;
3625  }
3627  TInfo = ti;
3628  }
3629 
3630  /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3631  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3632 
3633  /// getRParenLoc - Return the location of final right parenthesis.
3634  SourceLocation getRParenLoc() const { return RParenLoc; }
3635 
3636  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3637  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3638 
3639  static bool classof(const Stmt *T) {
3640  return T->getStmtClass() == ConvertVectorExprClass;
3641  }
3642 
3643  // Iterators
3644  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3646  return const_child_range(&SrcExpr, &SrcExpr + 1);
3647  }
3648 };
3649 
3650 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3651 /// This AST node is similar to the conditional operator (?:) in C, with
3652 /// the following exceptions:
3653 /// - the test expression must be a integer constant expression.
3654 /// - the expression returned acts like the chosen subexpression in every
3655 /// visible way: the type is the same as that of the chosen subexpression,
3656 /// and all predicates (whether it's an l-value, whether it's an integer
3657 /// constant expression, etc.) return the same result as for the chosen
3658 /// sub-expression.
3659 class ChooseExpr : public Expr {
3660  enum { COND, LHS, RHS, END_EXPR };
3661  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3662  SourceLocation BuiltinLoc, RParenLoc;
3663  bool CondIsTrue;
3664 public:
3665  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3667  SourceLocation RP, bool condIsTrue,
3668  bool TypeDependent, bool ValueDependent)
3669  : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3670  (cond->isInstantiationDependent() ||
3671  lhs->isInstantiationDependent() ||
3672  rhs->isInstantiationDependent()),
3673  (cond->containsUnexpandedParameterPack() ||
3674  lhs->containsUnexpandedParameterPack() ||
3675  rhs->containsUnexpandedParameterPack())),
3676  BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3677  SubExprs[COND] = cond;
3678  SubExprs[LHS] = lhs;
3679  SubExprs[RHS] = rhs;
3680  }
3681 
3682  /// \brief Build an empty __builtin_choose_expr.
3683  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3684 
3685  /// isConditionTrue - Return whether the condition is true (i.e. not
3686  /// equal to zero).
3687  bool isConditionTrue() const {
3688  assert(!isConditionDependent() &&
3689  "Dependent condition isn't true or false");
3690  return CondIsTrue;
3691  }
3692  void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3693 
3694  bool isConditionDependent() const {
3695  return getCond()->isTypeDependent() || getCond()->isValueDependent();
3696  }
3697 
3698  /// getChosenSubExpr - Return the subexpression chosen according to the
3699  /// condition.
3701  return isConditionTrue() ? getLHS() : getRHS();
3702  }
3703 
3704  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3705  void setCond(Expr *E) { SubExprs[COND] = E; }
3706  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3707  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3708  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3709  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3710 
3711  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3712  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3713 
3714  SourceLocation getRParenLoc() const { return RParenLoc; }
3715  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3716 
3717  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3718  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3719 
3720  static bool classof(const Stmt *T) {
3721  return T->getStmtClass() == ChooseExprClass;
3722  }
3723 
3724  // Iterators
3726  return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3727  }
3729  return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3730  }
3731 };
3732 
3733 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3734 /// for a null pointer constant that has integral type (e.g., int or
3735 /// long) and is the same size and alignment as a pointer. The __null
3736 /// extension is typically only used by system headers, which define
3737 /// NULL as __null in C++ rather than using 0 (which is an integer
3738 /// that may not match the size of a pointer).
3739 class GNUNullExpr : public Expr {
3740  /// TokenLoc - The location of the __null keyword.
3741  SourceLocation TokenLoc;
3742 
3743 public:
3745  : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3746  false),
3747  TokenLoc(Loc) { }
3748 
3749  /// \brief Build an empty GNU __null expression.
3750  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3751 
3752  /// getTokenLocation - The location of the __null token.
3753  SourceLocation getTokenLocation() const { return TokenLoc; }
3754  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3755 
3756  SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3757  SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3758 
3759  static bool classof(const Stmt *T) {
3760  return T->getStmtClass() == GNUNullExprClass;
3761  }
3762 
3763  // Iterators
3766  }
3769  }
3770 };
3771 
3772 /// Represents a call to the builtin function \c __builtin_va_arg.
3773 class VAArgExpr : public Expr {
3774  Stmt *Val;
3775  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3776  SourceLocation BuiltinLoc, RParenLoc;
3777 public:
3779  SourceLocation RPLoc, QualType t, bool IsMS)
3780  : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3781  false, (TInfo->getType()->isInstantiationDependentType() ||
3782  e->isInstantiationDependent()),
3783  (TInfo->getType()->containsUnexpandedParameterPack() ||
3784  e->containsUnexpandedParameterPack())),
3785  Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3786 
3787  /// Create an empty __builtin_va_arg expression.
3788  explicit VAArgExpr(EmptyShell Empty)
3789  : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3790 
3791  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3792  Expr *getSubExpr() { return cast<Expr>(Val); }
3793  void setSubExpr(Expr *E) { Val = E; }
3794 
3795  /// Returns whether this is really a Win64 ABI va_arg expression.
3796  bool isMicrosoftABI() const { return TInfo.getInt(); }
3797  void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3798 
3799  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3800  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3801 
3802  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3803  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3804 
3805  SourceLocation getRParenLoc() const { return RParenLoc; }
3806  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3807 
3808  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3809  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3810 
3811  static bool classof(const Stmt *T) {
3812  return T->getStmtClass() == VAArgExprClass;
3813  }
3814 
3815  // Iterators
3816  child_range children() { return child_range(&Val, &Val+1); }
3818  return const_child_range(&Val, &Val + 1);
3819  }
3820 };
3821 
3822 /// @brief Describes an C or C++ initializer list.
3823 ///
3824 /// InitListExpr describes an initializer list, which can be used to
3825 /// initialize objects of different types, including
3826 /// struct/class/union types, arrays, and vectors. For example:
3827 ///
3828 /// @code
3829 /// struct foo x = { 1, { 2, 3 } };
3830 /// @endcode
3831 ///
3832 /// Prior to semantic analysis, an initializer list will represent the
3833 /// initializer list as written by the user, but will have the
3834 /// placeholder type "void". This initializer list is called the
3835 /// syntactic form of the initializer, and may contain C99 designated
3836 /// initializers (represented as DesignatedInitExprs), initializations
3837 /// of subobject members without explicit braces, and so on. Clients
3838 /// interested in the original syntax of the initializer list should
3839 /// use the syntactic form of the initializer list.
3840 ///
3841 /// After semantic analysis, the initializer list will represent the
3842 /// semantic form of the initializer, where the initializations of all
3843 /// subobjects are made explicit with nested InitListExpr nodes and
3844 /// C99 designators have been eliminated by placing the designated
3845 /// initializations into the subobject they initialize. Additionally,
3846 /// any "holes" in the initialization, where no initializer has been
3847 /// specified for a particular subobject, will be replaced with
3848 /// implicitly-generated ImplicitValueInitExpr expressions that
3849 /// value-initialize the subobjects. Note, however, that the
3850 /// initializer lists may still have fewer initializers than there are
3851 /// elements to initialize within the object.
3852 ///
3853 /// After semantic analysis has completed, given an initializer list,
3854 /// method isSemanticForm() returns true if and only if this is the
3855 /// semantic form of the initializer list (note: the same AST node
3856 /// may at the same time be the syntactic form).
3857 /// Given the semantic form of the initializer list, one can retrieve
3858 /// the syntactic form of that initializer list (when different)
3859 /// using method getSyntacticForm(); the method returns null if applied
3860 /// to a initializer list which is already in syntactic form.
3861 /// Similarly, given the syntactic form (i.e., an initializer list such
3862 /// that isSemanticForm() returns false), one can retrieve the semantic
3863 /// form using method getSemanticForm().
3864 /// Since many initializer lists have the same syntactic and semantic forms,
3865 /// getSyntacticForm() may return NULL, indicating that the current
3866 /// semantic initializer list also serves as its syntactic form.
3867 class InitListExpr : public Expr {
3868  // FIXME: Eliminate this vector in favor of ASTContext allocation
3870  InitExprsTy InitExprs;
3871  SourceLocation LBraceLoc, RBraceLoc;
3872 
3873  /// The alternative form of the initializer list (if it exists).
3874  /// The int part of the pair stores whether this initializer list is
3875  /// in semantic form. If not null, the pointer points to:
3876  /// - the syntactic form, if this is in semantic form;
3877  /// - the semantic form, if this is in syntactic form.
3878  llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3879 
3880  /// \brief Either:
3881  /// If this initializer list initializes an array with more elements than
3882  /// there are initializers in the list, specifies an expression to be used
3883  /// for value initialization of the rest of the elements.
3884  /// Or
3885  /// If this initializer list initializes a union, specifies which
3886  /// field within the union will be initialized.
3887  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3888 
3889 public:
3890  InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3891  ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3892 
3893  /// \brief Build an empty initializer list.
3894  explicit InitListExpr(EmptyShell Empty)
3895  : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
3896 
3897  unsigned getNumInits() const { return InitExprs.size(); }
3898 
3899  /// \brief Retrieve the set of initializers.
3900  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3901 
3902  /// \brief Retrieve the set of initializers.
3903  Expr * const *getInits() const {
3904  return reinterpret_cast<Expr * const *>(InitExprs.data());
3905  }
3906 
3908  return llvm::makeArrayRef(getInits(), getNumInits());
3909  }
3910 
3912  return llvm::makeArrayRef(getInits(), getNumInits());
3913  }
3914 
3915  const Expr *getInit(unsigned Init) const {
3916  assert(Init < getNumInits() && "Initializer access out of range!");
3917  return cast_or_null<Expr>(InitExprs[Init]);
3918  }
3919 
3920  Expr *getInit(unsigned Init) {
3921  assert(Init < getNumInits() && "Initializer access out of range!");
3922  return cast_or_null<Expr>(InitExprs[Init]);
3923  }
3924 
3925  void setInit(unsigned Init, Expr *expr) {
3926  assert(Init < getNumInits() && "Initializer access out of range!");
3927  InitExprs[Init] = expr;
3928 
3929  if (expr) {
3930  ExprBits.TypeDependent |= expr->isTypeDependent();
3931  ExprBits.ValueDependent |= expr->isValueDependent();
3932  ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3933  ExprBits.ContainsUnexpandedParameterPack |=
3935  }
3936  }
3937 
3938  /// \brief Reserve space for some number of initializers.
3939  void reserveInits(const ASTContext &C, unsigned NumInits);
3940 
3941  /// @brief Specify the number of initializers
3942  ///
3943  /// If there are more than @p NumInits initializers, the remaining
3944  /// initializers will be destroyed. If there are fewer than @p
3945  /// NumInits initializers, NULL expressions will be added for the
3946  /// unknown initializers.
3947  void resizeInits(const ASTContext &Context, unsigned NumInits);
3948 
3949  /// @brief Updates the initializer at index @p Init with the new
3950  /// expression @p expr, and returns the old expression at that
3951  /// location.
3952  ///
3953  /// When @p Init is out of range for this initializer list, the
3954  /// initializer list will be extended with NULL expressions to
3955  /// accommodate the new entry.
3956  Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3957 
3958  /// \brief If this initializer list initializes an array with more elements
3959  /// than there are initializers in the list, specifies an expression to be
3960  /// used for value initialization of the rest of the elements.
3962  return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3963  }
3964  const Expr *getArrayFiller() const {
3965  return const_cast<InitListExpr *>(this)->getArrayFiller();
3966  }
3967  void setArrayFiller(Expr *filler);
3968 
3969  /// \brief Return true if this is an array initializer and its array "filler"
3970  /// has been set.
3971  bool hasArrayFiller() const { return getArrayFiller(); }
3972 
3973  /// \brief If this initializes a union, specifies which field in the
3974  /// union to initialize.
3975  ///
3976  /// Typically, this field is the first named field within the
3977  /// union. However, a designated initializer can specify the
3978  /// initialization of a different field within the union.
3980  return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3981  }
3983  return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3984  }
3986  assert((FD == nullptr
3987  || getInitializedFieldInUnion() == nullptr
3988  || getInitializedFieldInUnion() == FD)
3989  && "Only one field of a union may be initialized at a time!");
3990  ArrayFillerOrUnionFieldInit = FD;
3991  }
3992 
3993  // Explicit InitListExpr's originate from source code (and have valid source
3994  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3995  bool isExplicit() const {
3996  return LBraceLoc.isValid() && RBraceLoc.isValid();
3997  }
3998 
3999  // Is this an initializer for an array of characters, initialized by a string
4000  // literal or an @encode?
4001  bool isStringLiteralInit() const;
4002 
4003  /// Is this a transparent initializer list (that is, an InitListExpr that is
4004  /// purely syntactic, and whose semantics are that of the sole contained
4005  /// initializer)?
4006  bool isTransparent() const;
4007 
4008  SourceLocation getLBraceLoc() const { return LBraceLoc; }
4009  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4010  SourceLocation getRBraceLoc() const { return RBraceLoc; }
4011  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4012 
4013  bool isSemanticForm() const { return AltForm.getInt(); }
4015  return isSemanticForm() ? nullptr : AltForm.getPointer();
4016  }
4018  return isSemanticForm() ? AltForm.getPointer() : nullptr;
4019  }
4020 
4022  AltForm.setPointer(Init);
4023  AltForm.setInt(true);
4024  Init->AltForm.setPointer(this);
4025  Init->AltForm.setInt(false);
4026  }
4027 
4029  return InitListExprBits.HadArrayRangeDesignator != 0;
4030  }
4031  void sawArrayRangeDesignator(bool ARD = true) {
4032  InitListExprBits.HadArrayRangeDesignator = ARD;
4033  }
4034 
4035  SourceLocation getLocStart() const LLVM_READONLY;
4036  SourceLocation getLocEnd() const LLVM_READONLY;
4037 
4038  static bool classof(const Stmt *T) {
4039  return T->getStmtClass() == InitListExprClass;
4040  }
4041 
4042  // Iterators
4044  const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4045  return child_range(cast_away_const(CCR.begin()),
4046  cast_away_const(CCR.end()));
4047  }
4048 
4050  // FIXME: This does not include the array filler expression.
4051  if (InitExprs.empty())
4053  return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4054  }
4055 
4060 
4061  iterator begin() { return InitExprs.begin(); }
4062  const_iterator begin() const { return InitExprs.begin(); }
4063  iterator end() { return InitExprs.end(); }
4064  const_iterator end() const { return InitExprs.end(); }
4065  reverse_iterator rbegin() { return InitExprs.rbegin(); }
4066  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4067  reverse_iterator rend() { return InitExprs.rend(); }
4068  const_reverse_iterator rend() const { return InitExprs.rend(); }
4069 
4070  friend class ASTStmtReader;
4071  friend class ASTStmtWriter;
4072 };
4073 
4074 /// @brief Represents a C99 designated initializer expression.
4075 ///
4076 /// A designated initializer expression (C99 6.7.8) contains one or
4077 /// more designators (which can be field designators, array
4078 /// designators, or GNU array-range designators) followed by an
4079 /// expression that initializes the field or element(s) that the
4080 /// designators refer to. For example, given:
4081 ///
4082 /// @code
4083 /// struct point {
4084 /// double x;
4085 /// double y;
4086 /// };
4087 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4088 /// @endcode
4089 ///
4090 /// The InitListExpr contains three DesignatedInitExprs, the first of
4091 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4092 /// designators, one array designator for @c [2] followed by one field
4093 /// designator for @c .y. The initialization expression will be 1.0.
4095  : public Expr,
4096  private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4097 public:
4098  /// \brief Forward declaration of the Designator class.
4099  class Designator;
4100 
4101 private:
4102  /// The location of the '=' or ':' prior to the actual initializer
4103  /// expression.
4104  SourceLocation EqualOrColonLoc;
4105 
4106  /// Whether this designated initializer used the GNU deprecated
4107  /// syntax rather than the C99 '=' syntax.
4108  unsigned GNUSyntax : 1;
4109 
4110  /// The number of designators in this initializer expression.
4111  unsigned NumDesignators : 15;
4112 
4113  /// The number of subexpressions of this initializer expression,
4114  /// which contains both the initializer and any additional
4115  /// expressions used by array and array-range designators.
4116  unsigned NumSubExprs : 16;
4117 
4118  /// \brief The designators in this designated initialization
4119  /// expression.
4120  Designator *Designators;
4121 
4122  DesignatedInitExpr(const ASTContext &C, QualType Ty,
4123  llvm::ArrayRef<Designator> Designators,
4124  SourceLocation EqualOrColonLoc, bool GNUSyntax,
4125  ArrayRef<Expr *> IndexExprs, Expr *Init);
4126 
4127  explicit DesignatedInitExpr(unsigned NumSubExprs)
4128  : Expr(DesignatedInitExprClass, EmptyShell()),
4129  NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4130 
4131 public:
4132  /// A field designator, e.g., ".x".
4134  /// Refers to the field that is being initialized. The low bit
4135  /// of this field determines whether this is actually a pointer
4136  /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4137  /// initially constructed, a field designator will store an
4138  /// IdentifierInfo*. After semantic analysis has resolved that
4139  /// name, the field designator will instead store a FieldDecl*.
4141 
4142  /// The location of the '.' in the designated initializer.
4143  unsigned DotLoc;
4144 
4145  /// The location of the field name in the designated initializer.
4146  unsigned FieldLoc;
4147  };
4148 
4149  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4151  /// Location of the first index expression within the designated
4152  /// initializer expression's list of subexpressions.
4153  unsigned Index;
4154  /// The location of the '[' starting the array range designator.
4155  unsigned LBracketLoc;
4156  /// The location of the ellipsis separating the start and end
4157  /// indices. Only valid for GNU array-range designators.
4158  unsigned EllipsisLoc;
4159  /// The location of the ']' terminating the array range designator.
4160  unsigned RBracketLoc;
4161  };
4162 
4163  /// @brief Represents a single C99 designator.
4164  ///
4165  /// @todo This class is infuriatingly similar to clang::Designator,
4166  /// but minor differences (storing indices vs. storing pointers)
4167  /// keep us from reusing it. Try harder, later, to rectify these
4168  /// differences.
4169  class Designator {
4170  /// @brief The kind of designator this describes.
4171  enum {
4173  ArrayDesignator,
4174  ArrayRangeDesignator
4175  } Kind;
4176 
4177  union {
4178  /// A field designator, e.g., ".x".
4180  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4181  struct ArrayOrRangeDesignator ArrayOrRange;
4182  };
4183  friend class DesignatedInitExpr;
4184 
4185  public:
4187 
4188  /// @brief Initializes a field designator.
4189  Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4190  SourceLocation FieldLoc)
4191  : Kind(FieldDesignator) {
4192  Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4193  Field.DotLoc = DotLoc.getRawEncoding();
4194  Field.FieldLoc = FieldLoc.getRawEncoding();
4195  }
4196 
4197  /// @brief Initializes an array designator.
4198  Designator(unsigned Index, SourceLocation LBracketLoc,
4199  SourceLocation RBracketLoc)
4200  : Kind(ArrayDesignator) {
4201  ArrayOrRange.Index = Index;
4202  ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4203  ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4204  ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4205  }
4206 
4207  /// @brief Initializes a GNU array-range designator.
4208  Designator(unsigned Index, SourceLocation LBracketLoc,
4209  SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4210  : Kind(ArrayRangeDesignator) {
4211  ArrayOrRange.Index = Index;
4212  ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4213  ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4214  ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4215  }
4216 
4217  bool isFieldDesignator() const { return Kind == FieldDesignator; }
4218  bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4219  bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4220 
4221  IdentifierInfo *getFieldName() const;
4222 
4223  FieldDecl *getField() const {
4224  assert(Kind == FieldDesignator && "Only valid on a field designator");
4225  if (Field.NameOrField & 0x01)
4226  return nullptr;
4227  else
4228  return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4229  }
4230 
4231  void setField(FieldDecl *FD) {
4232  assert(Kind == FieldDesignator && "Only valid on a field designator");
4233  Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4234  }
4235 
4237  assert(Kind == FieldDesignator && "Only valid on a field designator");
4239  }
4240 
4242  assert(Kind == FieldDesignator && "Only valid on a field designator");
4243  return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4244  }
4245 
4247  assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4248  "Only valid on an array or array-range designator");
4249  return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4250  }
4251 
4253  assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4254  "Only valid on an array or array-range designator");
4255  return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4256  }
4257 
4259  assert(Kind == ArrayRangeDesignator &&
4260  "Only valid on an array-range designator");
4261  return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4262  }
4263 
4264  unsigned getFirstExprIndex() const {
4265  assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4266  "Only valid on an array or array-range designator");
4267  return ArrayOrRange.Index;
4268  }
4269 
4270  SourceLocation getLocStart() const LLVM_READONLY {
4271  if (Kind == FieldDesignator)
4272  return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4273  else
4274  return getLBracketLoc();
4275  }
4276  SourceLocation getLocEnd() const LLVM_READONLY {
4277  return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4278  }
4279  SourceRange getSourceRange() const LLVM_READONLY {
4280  return SourceRange(getLocStart(), getLocEnd());
4281  }
4282  };
4283 
4284  static DesignatedInitExpr *Create(const ASTContext &C,
4285  llvm::ArrayRef<Designator> Designators,
4286  ArrayRef<Expr*> IndexExprs,
4287  SourceLocation EqualOrColonLoc,
4288  bool GNUSyntax, Expr *Init);
4289 
4290  static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4291  unsigned NumIndexExprs);
4292 
4293  /// @brief Returns the number of designators in this initializer.
4294  unsigned size() const { return NumDesignators; }
4295 
4296  // Iterator access to the designators.
4298  return {Designators, NumDesignators};
4299  }
4300 
4302  return {Designators, NumDesignators};
4303  }
4304 
4305  Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4306  const Designator *getDesignator(unsigned Idx) const {
4307  return &designators()[Idx];
4308  }
4309 
4310  void setDesignators(const ASTContext &C, const Designator *Desigs,
4311  unsigned NumDesigs);
4312 
4313  Expr *getArrayIndex(const Designator &D) const;
4314  Expr *getArrayRangeStart(const Designator &D) const;
4315  Expr *getArrayRangeEnd(const Designator &D) const;
4316 
4317  /// @brief Retrieve the location of the '=' that precedes the
4318  /// initializer value itself, if present.
4319  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4320  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4321 
4322  /// @brief Determines whether this designated initializer used the
4323  /// deprecated GNU syntax for designated initializers.
4324  bool usesGNUSyntax() const { return GNUSyntax; }
4325  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4326 
4327  /// @brief Retrieve the initializer value.
4328  Expr *getInit() const {
4329  return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4330  }
4331 
4332  void setInit(Expr *init) {
4333  *child_begin() = init;
4334  }
4335 
4336  /// \brief Retrieve the total number of subexpressions in this
4337  /// designated initializer expression, including the actual
4338  /// initialized value and any expressions that occur within array
4339  /// and array-range designators.
4340  unsigned getNumSubExprs() const { return NumSubExprs; }
4341 
4342  Expr *getSubExpr(unsigned Idx) const {
4343  assert(Idx < NumSubExprs && "Subscript out of range");
4344  return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4345  }
4346 
4347  void setSubExpr(unsigned Idx, Expr *E) {
4348  assert(Idx < NumSubExprs && "Subscript out of range");
4349  getTrailingObjects<Stmt *>()[Idx] = E;
4350  }
4351 
4352  /// \brief Replaces the designator at index @p Idx with the series
4353  /// of designators in [First, Last).
4354  void ExpandDesignator(const ASTContext &C, unsigned Idx,
4355  const Designator *First, const Designator *Last);
4356 
4357  SourceRange getDesignatorsSourceRange() const;
4358 
4359  SourceLocation getLocStart() const LLVM_READONLY;
4360  SourceLocation getLocEnd() const LLVM_READONLY;
4361 
4362  static bool classof(const Stmt *T) {
4363  return T->getStmtClass() == DesignatedInitExprClass;
4364  }
4365 
4366  // Iterators
4368  Stmt **begin = getTrailingObjects<Stmt *>();
4369  return child_range(begin, begin + NumSubExprs);
4370  }
4372  Stmt * const *begin = getTrailingObjects<Stmt *>();
4373  return const_child_range(begin, begin + NumSubExprs);
4374  }
4375 
4377 };
4378 
4379 /// \brief Represents a place-holder for an object not to be initialized by
4380 /// anything.
4381 ///
4382 /// This only makes sense when it appears as part of an updater of a
4383 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4384 /// initializes a big object, and the NoInitExpr's mark the spots within the
4385 /// big object not to be overwritten by the updater.
4386 ///
4387 /// \see DesignatedInitUpdateExpr
4388 class NoInitExpr : public Expr {
4389 public:
4390  explicit NoInitExpr(QualType ty)
4391  : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4392  false, false, ty->isInstantiationDependentType(), false) { }
4393 
4394  explicit NoInitExpr(EmptyShell Empty)
4395  : Expr(NoInitExprClass, Empty) { }
4396 
4397  static bool classof(const Stmt *T) {
4398  return T->getStmtClass() == NoInitExprClass;
4399  }
4400 
4401  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4402  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4403 
4404  // Iterators
4407  }
4410  }
4411 };
4412 
4413 // In cases like:
4414 // struct Q { int a, b, c; };
4415 // Q *getQ();
4416 // void foo() {
4417 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4418 // }
4419 //
4420 // We will have an InitListExpr for a, with type A, and then a
4421 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4422 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4423 //
4425  // BaseAndUpdaterExprs[0] is the base expression;
4426  // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4427  Stmt *BaseAndUpdaterExprs[2];
4428 
4429 public:
4431  Expr *baseExprs, SourceLocation rBraceLoc);
4432 
4434  : Expr(DesignatedInitUpdateExprClass, Empty) { }
4435 
4436  SourceLocation getLocStart() const LLVM_READONLY;
4437  SourceLocation getLocEnd() const LLVM_READONLY;
4438 
4439  static bool classof(const Stmt *T) {
4440  return T->getStmtClass() == DesignatedInitUpdateExprClass;
4441  }
4442 
4443  Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4444  void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4445 
4447  return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4448  }
4449  void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4450 
4451  // Iterators
4452  // children = the base and the updater
4454  return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4455  }
4457  return const_child_range(&BaseAndUpdaterExprs[0],
4458  &BaseAndUpdaterExprs[0] + 2);
4459  }
4460 };
4461 
4462 /// \brief Represents a loop initializing the elements of an array.
4463 ///
4464 /// The need to initialize the elements of an array occurs in a number of
4465 /// contexts:
4466 ///
4467 /// * in the implicit copy/move constructor for a class with an array member
4468 /// * when a lambda-expression captures an array by value
4469 /// * when a decomposition declaration decomposes an array
4470 ///
4471 /// There are two subexpressions: a common expression (the source array)
4472 /// that is evaluated once up-front, and a per-element initializer that
4473 /// runs once for each array element.
4474 ///
4475 /// Within the per-element initializer, the common expression may be referenced
4476 /// via an OpaqueValueExpr, and the current index may be obtained via an
4477 /// ArrayInitIndexExpr.
4478 class ArrayInitLoopExpr : public Expr {
4479  Stmt *SubExprs[2];
4480 
4481  explicit ArrayInitLoopExpr(EmptyShell Empty)
4482  : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4483 
4484 public:
4485  explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4486  : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4487  CommonInit->isValueDependent() || ElementInit->isValueDependent(),
4488  T->isInstantiationDependentType(),
4489  CommonInit->containsUnexpandedParameterPack() ||
4490  ElementInit->containsUnexpandedParameterPack()),
4491  SubExprs{CommonInit, ElementInit} {}
4492 
4493  /// Get the common subexpression shared by all initializations (the source
4494  /// array).
4496  return cast<OpaqueValueExpr>(SubExprs[0]);
4497  }
4498 
4499  /// Get the initializer to use for each array element.
4500  Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
4501 
4502  llvm::APInt getArraySize() const {
4503  return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
4504  ->getSize();
4505  }
4506 
4507  static bool classof(const Stmt *S) {
4508  return S->getStmtClass() == ArrayInitLoopExprClass;
4509  }
4510 
4511  SourceLocation getLocStart() const LLVM_READONLY {
4512  return getCommonExpr()->getLocStart();
4513  }
4514  SourceLocation getLocEnd() const LLVM_READONLY {
4515  return getCommonExpr()->getLocEnd();
4516  }
4517 
4519  return child_range(SubExprs, SubExprs + 2);
4520  }
4522  return const_child_range(SubExprs, SubExprs + 2);
4523  }
4524 
4525  friend class ASTReader;
4526  friend class ASTStmtReader;
4527  friend class ASTStmtWriter;
4528 };
4529 
4530 /// \brief Represents the index of the current element of an array being
4531 /// initialized by an ArrayInitLoopExpr. This can only appear within the
4532 /// subexpression of an ArrayInitLoopExpr.
4533 class ArrayInitIndexExpr : public Expr {
4534  explicit ArrayInitIndexExpr(EmptyShell Empty)
4535  : Expr(ArrayInitIndexExprClass, Empty) {}
4536 
4537 public:
4539  : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
4540  false, false, false, false) {}
4541 
4542  static bool classof(const Stmt *S) {
4543  return S->getStmtClass() == ArrayInitIndexExprClass;
4544  }
4545 
4546  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4547  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4548 
4551  }
4554  }
4555 
4556  friend class ASTReader;
4557  friend class ASTStmtReader;
4558 };
4559 
4560 /// \brief Represents an implicitly-generated value initialization of
4561 /// an object of a given type.
4562 ///
4563 /// Implicit value initializations occur within semantic initializer
4564 /// list expressions (InitListExpr) as placeholders for subobject
4565 /// initializations not explicitly specified by the user.
4566 ///
4567 /// \see InitListExpr
4568 class ImplicitValueInitExpr : public Expr {
4569 public:
4571  : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4572  false, false, ty->isInstantiationDependentType(), false) { }
4573 
4574  /// \brief Construct an empty implicit value initialization.
4576  : Expr(ImplicitValueInitExprClass, Empty) { }
4577 
4578  static bool classof(const Stmt *T) {
4579  return T->getStmtClass() == ImplicitValueInitExprClass;
4580  }
4581 
4582  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4583  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4584 
4585  // Iterators
4588  }
4591  }
4592 };
4593 
4594 class ParenListExpr : public Expr {
4595  Stmt **Exprs;
4596  unsigned NumExprs;
4597  SourceLocation LParenLoc, RParenLoc;
4598 
4599 public:
4600  ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4601  ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4602 
4603  /// \brief Build an empty paren list.
4604  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4605 
4606  unsigned getNumExprs() const { return NumExprs; }
4607 
4608  const Expr* getExpr(unsigned Init) const {
4609  assert(Init < getNumExprs() && "Initializer access out of range!");
4610  return cast_or_null<Expr>(Exprs[Init]);
4611  }
4612 
4613  Expr* getExpr(unsigned Init) {
4614  assert(Init < getNumExprs() && "Initializer access out of range!");
4615  return cast_or_null<Expr>(Exprs[Init]);
4616  }
4617 
4618  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4619 
4621  return llvm::makeArrayRef(getExprs(), getNumExprs());
4622  }
4623 
4624  SourceLocation getLParenLoc() const { return LParenLoc; }
4625  SourceLocation getRParenLoc() const { return RParenLoc; }
4626 
4627  SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4628  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4629 
4630  static bool classof(const Stmt *T) {
4631  return T->getStmtClass() == ParenListExprClass;
4632  }
4633 
4634  // Iterators
4636  return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4637  }
4639  return const_child_range(&Exprs[0], &Exprs[0] + NumExprs);
4640  }
4641 
4642  friend class ASTStmtReader;
4643  friend class ASTStmtWriter;
4644 };
4645 
4646 /// \brief Represents a C11 generic selection.
4647 ///
4648 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4649 /// expression, followed by one or more generic associations. Each generic
4650 /// association specifies a type name and an expression, or "default" and an
4651 /// expression (in which case it is known as a default generic association).
4652 /// The type and value of the generic selection are identical to those of its
4653 /// result expression, which is defined as the expression in the generic
4654 /// association with a type name that is compatible with the type of the
4655 /// controlling expression, or the expression in the default generic association
4656 /// if no types are compatible. For example:
4657 ///
4658 /// @code
4659 /// _Generic(X, double: 1, float: 2, default: 3)
4660 /// @endcode
4661 ///
4662 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4663 /// or 3 if "hello".
4664 ///
4665 /// As an extension, generic selections are allowed in C++, where the following
4666 /// additional semantics apply:
4667 ///
4668 /// Any generic selection whose controlling expression is type-dependent or
4669 /// which names a dependent type in its association list is result-dependent,
4670 /// which means that the choice of result expression is dependent.
4671 /// Result-dependent generic associations are both type- and value-dependent.
4672 class GenericSelectionExpr : public Expr {
4673  enum { CONTROLLING, END_EXPR };
4674  TypeSourceInfo **AssocTypes;
4675  Stmt **SubExprs;
4676  unsigned NumAssocs, ResultIndex;
4677  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4678 
4679 public:
4680  GenericSelectionExpr(const ASTContext &Context,
4681  SourceLocation GenericLoc, Expr *ControllingExpr,
4682  ArrayRef<TypeSourceInfo*> AssocTypes,
4683  ArrayRef<Expr*> AssocExprs,
4684  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4685  bool ContainsUnexpandedParameterPack,
4686  unsigned ResultIndex);
4687 
4688  /// This constructor is used in the result-dependent case.
4689  GenericSelectionExpr(const ASTContext &Context,
4690  SourceLocation GenericLoc, Expr *ControllingExpr,
4691  ArrayRef<TypeSourceInfo*> AssocTypes,
4692  ArrayRef<Expr*> AssocExprs,
4693  SourceLocation DefaultLoc, SourceLocation RParenLoc,
4694  bool ContainsUnexpandedParameterPack);
4695 
4697  : Expr(GenericSelectionExprClass, Empty) { }
4698 
4699  unsigned getNumAssocs() const { return NumAssocs; }
4700 
4701  SourceLocation getGenericLoc() const { return GenericLoc; }
4702  SourceLocation getDefaultLoc() const { return DefaultLoc; }
4703  SourceLocation getRParenLoc() const { return RParenLoc; }
4704 
4705  const Expr *getAssocExpr(unsigned i) const {
4706  return cast<Expr>(SubExprs[END_EXPR+i]);
4707  }
4708  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4710  return NumAssocs
4711  ? llvm::makeArrayRef(
4712  &reinterpret_cast<Expr **>(SubExprs)[END_EXPR], NumAssocs)
4713  : None;
4714  }
4715  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4716  return AssocTypes[i];
4717  }
4718  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4720  return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : None;
4721  }
4722 
4723  QualType getAssocType(unsigned i) const {
4724  if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4725  return TS->getType();
4726  else
4727  return QualType();
4728  }
4729 
4730  const Expr *getControllingExpr() const {
4731  return cast<Expr>(SubExprs[CONTROLLING]);
4732  }
4733  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4734 
4735  /// Whether this generic selection is result-dependent.
4736  bool isResultDependent() const { return ResultIndex == -1U; }
4737 
4738  /// The zero-based index of the result expression's generic association in
4739  /// the generic selection's association list. Defined only if the
4740  /// generic selection is not result-dependent.
4741  unsigned getResultIndex() const {
4742  assert(!isResultDependent() && "Generic selection is result-dependent");
4743  return ResultIndex;
4744  }
4745 
4746  /// The generic selection's result expression. Defined only if the
4747  /// generic selection is not result-dependent.
4748  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4749  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4750 
4751  SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4752  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4753 
4754  static bool classof(const Stmt *T) {
4755  return T->getStmtClass() == GenericSelectionExprClass;
4756  }
4757 
4759  return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4760  }
4762  return const_child_range(SubExprs, SubExprs + END_EXPR + NumAssocs);
4763  }
4764  friend class ASTStmtReader;
4765 };
4766 
4767 //===----------------------------------------------------------------------===//
4768 // Clang Extensions
4769 //===----------------------------------------------------------------------===//
4770 
4771 /// ExtVectorElementExpr - This represents access to specific elements of a
4772 /// vector, and may occur on the left hand side or right hand side. For example
4773 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4774 ///
4775 /// Note that the base may have either vector or pointer to vector type, just
4776 /// like a struct field reference.
4777 ///
4778 class ExtVectorElementExpr : public Expr {
4779  Stmt *Base;
4780  IdentifierInfo *Accessor;
4781  SourceLocation AccessorLoc;
4782 public:
4784  IdentifierInfo &accessor, SourceLocation loc)
4785  : Expr(ExtVectorElementExprClass, ty, VK,
4787  base->isTypeDependent(), base->isValueDependent(),
4788  base->isInstantiationDependent(),
4789  base->containsUnexpandedParameterPack()),
4790  Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4791 
4792  /// \brief Build an empty vector element expression.
4794  : Expr(ExtVectorElementExprClass, Empty) { }
4795 
4796  const Expr *getBase() const { return cast<Expr>(Base); }
4797  Expr *getBase() { return cast<Expr>(Base); }
4798  void setBase(Expr *E) { Base = E; }
4799 
4800  IdentifierInfo &getAccessor() const { return *Accessor; }
4801  void setAccessor(IdentifierInfo *II) { Accessor = II; }
4802 
4803  SourceLocation getAccessorLoc() const { return AccessorLoc; }
4804  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4805 
4806  /// getNumElements - Get the number of components being selected.
4807  unsigned getNumElements() const;
4808 
4809  /// containsDuplicateElements - Return true if any element access is
4810  /// repeated.
4811  bool containsDuplicateElements() const;
4812 
4813  /// getEncodedElementAccess - Encode the elements accessed into an llvm
4814  /// aggregate Constant of ConstantInt(s).
4815  void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4816 
4817  SourceLocation getLocStart() const LLVM_READONLY {
4818  return getBase()->getLocStart();
4819  }
4820  SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4821 
4822  /// isArrow - Return true if the base expression is a pointer to vector,
4823  /// return false if the base expression is a vector.
4824  bool isArrow() const;
4825 
4826  static bool classof(const Stmt *T) {
4827  return T->getStmtClass() == ExtVectorElementExprClass;
4828  }
4829 
4830  // Iterators
4831  child_range children() { return child_range(&Base, &Base+1); }
4833  return const_child_range(&Base, &Base + 1);
4834  }
4835 };
4836 
4837 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.