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