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