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