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