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