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