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