Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:35

0001 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 //  This file defines the Expr interface and subclasses.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_CLANG_AST_EXPR_H
0014 #define LLVM_CLANG_AST_EXPR_H
0015 
0016 #include "clang/AST/APNumericStorage.h"
0017 #include "clang/AST/APValue.h"
0018 #include "clang/AST/ASTVector.h"
0019 #include "clang/AST/ComputeDependence.h"
0020 #include "clang/AST/Decl.h"
0021 #include "clang/AST/DeclAccessPair.h"
0022 #include "clang/AST/DependenceFlags.h"
0023 #include "clang/AST/OperationKinds.h"
0024 #include "clang/AST/Stmt.h"
0025 #include "clang/AST/TemplateBase.h"
0026 #include "clang/AST/Type.h"
0027 #include "clang/Basic/CharInfo.h"
0028 #include "clang/Basic/LangOptions.h"
0029 #include "clang/Basic/SyncScope.h"
0030 #include "clang/Basic/TypeTraits.h"
0031 #include "llvm/ADT/APFloat.h"
0032 #include "llvm/ADT/APSInt.h"
0033 #include "llvm/ADT/SmallVector.h"
0034 #include "llvm/ADT/StringRef.h"
0035 #include "llvm/ADT/iterator.h"
0036 #include "llvm/ADT/iterator_range.h"
0037 #include "llvm/Support/AtomicOrdering.h"
0038 #include "llvm/Support/Compiler.h"
0039 #include "llvm/Support/TrailingObjects.h"
0040 #include <optional>
0041 
0042 namespace clang {
0043   class APValue;
0044   class ASTContext;
0045   class BlockDecl;
0046   class CXXBaseSpecifier;
0047   class CXXMemberCallExpr;
0048   class CXXOperatorCallExpr;
0049   class CastExpr;
0050   class Decl;
0051   class IdentifierInfo;
0052   class MaterializeTemporaryExpr;
0053   class NamedDecl;
0054   class ObjCPropertyRefExpr;
0055   class OpaqueValueExpr;
0056   class ParmVarDecl;
0057   class StringLiteral;
0058   class TargetInfo;
0059   class ValueDecl;
0060 
0061 /// A simple array of base specifiers.
0062 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
0063 
0064 /// An adjustment to be made to the temporary created when emitting a
0065 /// reference binding, which accesses a particular subobject of that temporary.
0066 struct SubobjectAdjustment {
0067   enum {
0068     DerivedToBaseAdjustment,
0069     FieldAdjustment,
0070     MemberPointerAdjustment
0071   } Kind;
0072 
0073   struct DTB {
0074     const CastExpr *BasePath;
0075     const CXXRecordDecl *DerivedClass;
0076   };
0077 
0078   struct P {
0079     const MemberPointerType *MPT;
0080     Expr *RHS;
0081   };
0082 
0083   union {
0084     struct DTB DerivedToBase;
0085     const FieldDecl *Field;
0086     struct P Ptr;
0087   };
0088 
0089   SubobjectAdjustment(const CastExpr *BasePath,
0090                       const CXXRecordDecl *DerivedClass)
0091     : Kind(DerivedToBaseAdjustment) {
0092     DerivedToBase.BasePath = BasePath;
0093     DerivedToBase.DerivedClass = DerivedClass;
0094   }
0095 
0096   SubobjectAdjustment(const FieldDecl *Field) : Kind(FieldAdjustment) {
0097     this->Field = Field;
0098   }
0099 
0100   SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
0101     : Kind(MemberPointerAdjustment) {
0102     this->Ptr.MPT = MPT;
0103     this->Ptr.RHS = RHS;
0104   }
0105 };
0106 
0107 /// This represents one expression.  Note that Expr's are subclasses of Stmt.
0108 /// This allows an expression to be transparently used any place a Stmt is
0109 /// required.
0110 class Expr : public ValueStmt {
0111   QualType TR;
0112 
0113 public:
0114   Expr() = delete;
0115   Expr(const Expr&) = delete;
0116   Expr(Expr &&) = delete;
0117   Expr &operator=(const Expr&) = delete;
0118   Expr &operator=(Expr&&) = delete;
0119 
0120 protected:
0121   Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
0122       : ValueStmt(SC) {
0123     ExprBits.Dependent = 0;
0124     ExprBits.ValueKind = VK;
0125     ExprBits.ObjectKind = OK;
0126     assert(ExprBits.ObjectKind == OK && "truncated kind");
0127     setType(T);
0128   }
0129 
0130   /// Construct an empty expression.
0131   explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
0132 
0133   /// Each concrete expr subclass is expected to compute its dependence and call
0134   /// this in the constructor.
0135   void setDependence(ExprDependence Deps) {
0136     ExprBits.Dependent = static_cast<unsigned>(Deps);
0137   }
0138   friend class ASTImporter;   // Sets dependence directly.
0139   friend class ASTStmtReader; // Sets dependence directly.
0140 
0141 public:
0142   QualType getType() const { return TR; }
0143   void setType(QualType t) {
0144     // In C++, the type of an expression is always adjusted so that it
0145     // will not have reference type (C++ [expr]p6). Use
0146     // QualType::getNonReferenceType() to retrieve the non-reference
0147     // type. Additionally, inspect Expr::isLvalue to determine whether
0148     // an expression that is adjusted in this manner should be
0149     // considered an lvalue.
0150     assert((t.isNull() || !t->isReferenceType()) &&
0151            "Expressions can't have reference type");
0152 
0153     TR = t;
0154   }
0155 
0156   /// If this expression is an enumeration constant, return the
0157   /// enumeration type under which said constant was declared.
0158   /// Otherwise return the expression's type.
0159   /// Note this effectively circumvents the weak typing of C's enum constants
0160   QualType getEnumCoercedType(const ASTContext &Ctx) const;
0161 
0162   ExprDependence getDependence() const {
0163     return static_cast<ExprDependence>(ExprBits.Dependent);
0164   }
0165 
0166   /// Determines whether the value of this expression depends on
0167   ///   - a template parameter (C++ [temp.dep.constexpr])
0168   ///   - or an error, whose resolution is unknown
0169   ///
0170   /// For example, the array bound of "Chars" in the following example is
0171   /// value-dependent.
0172   /// @code
0173   /// template<int Size, char (&Chars)[Size]> struct meta_string;
0174   /// @endcode
0175   bool isValueDependent() const {
0176     return static_cast<bool>(getDependence() & ExprDependence::Value);
0177   }
0178 
0179   /// Determines whether the type of this expression depends on
0180   ///   - a template parameter (C++ [temp.dep.expr], which means that its type
0181   ///     could change from one template instantiation to the next)
0182   ///   - or an error
0183   ///
0184   /// For example, the expressions "x" and "x + y" are type-dependent in
0185   /// the following code, but "y" is not type-dependent:
0186   /// @code
0187   /// template<typename T>
0188   /// void add(T x, int y) {
0189   ///   x + y;
0190   /// }
0191   /// @endcode
0192   bool isTypeDependent() const {
0193     return static_cast<bool>(getDependence() & ExprDependence::Type);
0194   }
0195 
0196   /// Whether this expression is instantiation-dependent, meaning that
0197   /// it depends in some way on
0198   ///    - a template parameter (even if neither its type nor (constant) value
0199   ///      can change due to the template instantiation)
0200   ///    - or an error
0201   ///
0202   /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
0203   /// instantiation-dependent (since it involves a template parameter \c T), but
0204   /// is neither type- nor value-dependent, since the type of the inner
0205   /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
0206   /// \c sizeof is known.
0207   ///
0208   /// \code
0209   /// template<typename T>
0210   /// void f(T x, T y) {
0211   ///   sizeof(sizeof(T() + T());
0212   /// }
0213   /// \endcode
0214   ///
0215   /// \code
0216   /// void func(int) {
0217   ///   func(); // the expression is instantiation-dependent, because it depends
0218   ///           // on an error.
0219   /// }
0220   /// \endcode
0221   bool isInstantiationDependent() const {
0222     return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
0223   }
0224 
0225   /// Whether this expression contains an unexpanded parameter
0226   /// pack (for C++11 variadic templates).
0227   ///
0228   /// Given the following function template:
0229   ///
0230   /// \code
0231   /// template<typename F, typename ...Types>
0232   /// void forward(const F &f, Types &&...args) {
0233   ///   f(static_cast<Types&&>(args)...);
0234   /// }
0235   /// \endcode
0236   ///
0237   /// The expressions \c args and \c static_cast<Types&&>(args) both
0238   /// contain parameter packs.
0239   bool containsUnexpandedParameterPack() const {
0240     return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
0241   }
0242 
0243   /// Whether this expression contains subexpressions which had errors, e.g. a
0244   /// TypoExpr.
0245   bool containsErrors() const {
0246     return static_cast<bool>(getDependence() & ExprDependence::Error);
0247   }
0248 
0249   /// getExprLoc - Return the preferred location for the arrow when diagnosing
0250   /// a problem with a generic expression.
0251   SourceLocation getExprLoc() const LLVM_READONLY;
0252 
0253   /// Determine whether an lvalue-to-rvalue conversion should implicitly be
0254   /// applied to this expression if it appears as a discarded-value expression
0255   /// in C++11 onwards. This applies to certain forms of volatile glvalues.
0256   bool isReadIfDiscardedInCPlusPlus11() const;
0257 
0258   /// isUnusedResultAWarning - Return true if this immediate expression should
0259   /// be warned about if the result is unused.  If so, fill in expr, location,
0260   /// and ranges with expr to warn on and source locations/ranges appropriate
0261   /// for a warning.
0262   bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
0263                               SourceRange &R1, SourceRange &R2,
0264                               ASTContext &Ctx) const;
0265 
0266   /// isLValue - True if this expression is an "l-value" according to
0267   /// the rules of the current language.  C and C++ give somewhat
0268   /// different rules for this concept, but in general, the result of
0269   /// an l-value expression identifies a specific object whereas the
0270   /// result of an r-value expression is a value detached from any
0271   /// specific storage.
0272   ///
0273   /// C++11 divides the concept of "r-value" into pure r-values
0274   /// ("pr-values") and so-called expiring values ("x-values"), which
0275   /// identify specific objects that can be safely cannibalized for
0276   /// their resources.
0277   bool isLValue() const { return getValueKind() == VK_LValue; }
0278   bool isPRValue() const { return getValueKind() == VK_PRValue; }
0279   bool isXValue() const { return getValueKind() == VK_XValue; }
0280   bool isGLValue() const { return getValueKind() != VK_PRValue; }
0281 
0282   enum LValueClassification {
0283     LV_Valid,
0284     LV_NotObjectType,
0285     LV_IncompleteVoidType,
0286     LV_DuplicateVectorComponents,
0287     LV_InvalidExpression,
0288     LV_InvalidMessageExpression,
0289     LV_MemberFunction,
0290     LV_SubObjCPropertySetting,
0291     LV_ClassTemporary,
0292     LV_ArrayTemporary
0293   };
0294   /// Reasons why an expression might not be an l-value.
0295   LValueClassification ClassifyLValue(ASTContext &Ctx) const;
0296 
0297   enum isModifiableLvalueResult {
0298     MLV_Valid,
0299     MLV_NotObjectType,
0300     MLV_IncompleteVoidType,
0301     MLV_DuplicateVectorComponents,
0302     MLV_InvalidExpression,
0303     MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
0304     MLV_IncompleteType,
0305     MLV_ConstQualified,
0306     MLV_ConstQualifiedField,
0307     MLV_ConstAddrSpace,
0308     MLV_ArrayType,
0309     MLV_NoSetterProperty,
0310     MLV_MemberFunction,
0311     MLV_SubObjCPropertySetting,
0312     MLV_InvalidMessageExpression,
0313     MLV_ClassTemporary,
0314     MLV_ArrayTemporary
0315   };
0316   /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
0317   /// does not have an incomplete type, does not have a const-qualified type,
0318   /// and if it is a structure or union, does not have any member (including,
0319   /// recursively, any member or element of all contained aggregates or unions)
0320   /// with a const-qualified type.
0321   ///
0322   /// \param Loc [in,out] - A source location which *may* be filled
0323   /// in with the location of the expression making this a
0324   /// non-modifiable lvalue, if specified.
0325   isModifiableLvalueResult
0326   isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
0327 
0328   /// The return type of classify(). Represents the C++11 expression
0329   ///        taxonomy.
0330   class Classification {
0331   public:
0332     /// The various classification results. Most of these mean prvalue.
0333     enum Kinds {
0334       CL_LValue,
0335       CL_XValue,
0336       CL_Function, // Functions cannot be lvalues in C.
0337       CL_Void, // Void cannot be an lvalue in C.
0338       CL_AddressableVoid, // Void expression whose address can be taken in C.
0339       CL_DuplicateVectorComponents, // A vector shuffle with dupes.
0340       CL_MemberFunction, // An expression referring to a member function
0341       CL_SubObjCPropertySetting,
0342       CL_ClassTemporary, // A temporary of class type, or subobject thereof.
0343       CL_ArrayTemporary, // A temporary of array type.
0344       CL_ObjCMessageRValue, // ObjC message is an rvalue
0345       CL_PRValue // A prvalue for any other reason, of any other type
0346     };
0347     /// The results of modification testing.
0348     enum ModifiableType {
0349       CM_Untested, // testModifiable was false.
0350       CM_Modifiable,
0351       CM_RValue, // Not modifiable because it's an rvalue
0352       CM_Function, // Not modifiable because it's a function; C++ only
0353       CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
0354       CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
0355       CM_ConstQualified,
0356       CM_ConstQualifiedField,
0357       CM_ConstAddrSpace,
0358       CM_ArrayType,
0359       CM_IncompleteType
0360     };
0361 
0362   private:
0363     friend class Expr;
0364 
0365     unsigned short Kind;
0366     unsigned short Modifiable;
0367 
0368     explicit Classification(Kinds k, ModifiableType m)
0369       : Kind(k), Modifiable(m)
0370     {}
0371 
0372   public:
0373     Classification() {}
0374 
0375     Kinds getKind() const { return static_cast<Kinds>(Kind); }
0376     ModifiableType getModifiable() const {
0377       assert(Modifiable != CM_Untested && "Did not test for modifiability.");
0378       return static_cast<ModifiableType>(Modifiable);
0379     }
0380     bool isLValue() const { return Kind == CL_LValue; }
0381     bool isXValue() const { return Kind == CL_XValue; }
0382     bool isGLValue() const { return Kind <= CL_XValue; }
0383     bool isPRValue() const { return Kind >= CL_Function; }
0384     bool isRValue() const { return Kind >= CL_XValue; }
0385     bool isModifiable() const { return getModifiable() == CM_Modifiable; }
0386 
0387     /// Create a simple, modifiable lvalue
0388     static Classification makeSimpleLValue() {
0389       return Classification(CL_LValue, CM_Modifiable);
0390     }
0391 
0392   };
0393   /// Classify - Classify this expression according to the C++11
0394   ///        expression taxonomy.
0395   ///
0396   /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
0397   /// old lvalue vs rvalue. This function determines the type of expression this
0398   /// is. There are three expression types:
0399   /// - lvalues are classical lvalues as in C++03.
0400   /// - prvalues are equivalent to rvalues in C++03.
0401   /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
0402   ///   function returning an rvalue reference.
0403   /// lvalues and xvalues are collectively referred to as glvalues, while
0404   /// prvalues and xvalues together form rvalues.
0405   Classification Classify(ASTContext &Ctx) const {
0406     return ClassifyImpl(Ctx, nullptr);
0407   }
0408 
0409   /// ClassifyModifiable - Classify this expression according to the
0410   ///        C++11 expression taxonomy, and see if it is valid on the left side
0411   ///        of an assignment.
0412   ///
0413   /// This function extends classify in that it also tests whether the
0414   /// expression is modifiable (C99 6.3.2.1p1).
0415   /// \param Loc A source location that might be filled with a relevant location
0416   ///            if the expression is not modifiable.
0417   Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
0418     return ClassifyImpl(Ctx, &Loc);
0419   }
0420 
0421   /// Returns the set of floating point options that apply to this expression.
0422   /// Only meaningful for operations on floating point values.
0423   FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
0424 
0425   /// getValueKindForType - Given a formal return or parameter type,
0426   /// give its value kind.
0427   static ExprValueKind getValueKindForType(QualType T) {
0428     if (const ReferenceType *RT = T->getAs<ReferenceType>())
0429       return (isa<LValueReferenceType>(RT)
0430                 ? VK_LValue
0431                 : (RT->getPointeeType()->isFunctionType()
0432                      ? VK_LValue : VK_XValue));
0433     return VK_PRValue;
0434   }
0435 
0436   /// getValueKind - The value kind that this expression produces.
0437   ExprValueKind getValueKind() const {
0438     return static_cast<ExprValueKind>(ExprBits.ValueKind);
0439   }
0440 
0441   /// getObjectKind - The object kind that this expression produces.
0442   /// Object kinds are meaningful only for expressions that yield an
0443   /// l-value or x-value.
0444   ExprObjectKind getObjectKind() const {
0445     return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
0446   }
0447 
0448   bool isOrdinaryOrBitFieldObject() const {
0449     ExprObjectKind OK = getObjectKind();
0450     return (OK == OK_Ordinary || OK == OK_BitField);
0451   }
0452 
0453   /// setValueKind - Set the value kind produced by this expression.
0454   void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
0455 
0456   /// setObjectKind - Set the object kind produced by this expression.
0457   void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
0458 
0459 private:
0460   Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
0461 
0462 public:
0463 
0464   /// Returns true if this expression is a gl-value that
0465   /// potentially refers to a bit-field.
0466   ///
0467   /// In C++, whether a gl-value refers to a bitfield is essentially
0468   /// an aspect of the value-kind type system.
0469   bool refersToBitField() const { return getObjectKind() == OK_BitField; }
0470 
0471   /// If this expression refers to a bit-field, retrieve the
0472   /// declaration of that bit-field.
0473   ///
0474   /// Note that this returns a non-null pointer in subtly different
0475   /// places than refersToBitField returns true.  In particular, this can
0476   /// return a non-null pointer even for r-values loaded from
0477   /// bit-fields, but it will return null for a conditional bit-field.
0478   FieldDecl *getSourceBitField();
0479 
0480   /// If this expression refers to an enum constant, retrieve its declaration
0481   EnumConstantDecl *getEnumConstantDecl();
0482 
0483   const EnumConstantDecl *getEnumConstantDecl() const {
0484     return const_cast<Expr *>(this)->getEnumConstantDecl();
0485   }
0486 
0487   const FieldDecl *getSourceBitField() const {
0488     return const_cast<Expr*>(this)->getSourceBitField();
0489   }
0490 
0491   Decl *getReferencedDeclOfCallee();
0492   const Decl *getReferencedDeclOfCallee() const {
0493     return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
0494   }
0495 
0496   /// If this expression is an l-value for an Objective C
0497   /// property, find the underlying property reference expression.
0498   const ObjCPropertyRefExpr *getObjCProperty() const;
0499 
0500   /// Check if this expression is the ObjC 'self' implicit parameter.
0501   bool isObjCSelfExpr() const;
0502 
0503   /// Returns whether this expression refers to a vector element.
0504   bool refersToVectorElement() const;
0505 
0506   /// Returns whether this expression refers to a matrix element.
0507   bool refersToMatrixElement() const {
0508     return getObjectKind() == OK_MatrixComponent;
0509   }
0510 
0511   /// Returns whether this expression refers to a global register
0512   /// variable.
0513   bool refersToGlobalRegisterVar() const;
0514 
0515   /// Returns whether this expression has a placeholder type.
0516   bool hasPlaceholderType() const {
0517     return getType()->isPlaceholderType();
0518   }
0519 
0520   /// Returns whether this expression has a specific placeholder type.
0521   bool hasPlaceholderType(BuiltinType::Kind K) const {
0522     assert(BuiltinType::isPlaceholderTypeKind(K));
0523     if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
0524       return BT->getKind() == K;
0525     return false;
0526   }
0527 
0528   /// isKnownToHaveBooleanValue - Return true if this is an integer expression
0529   /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
0530   /// but also int expressions which are produced by things like comparisons in
0531   /// C.
0532   ///
0533   /// \param Semantic If true, only return true for expressions that are known
0534   /// to be semantically boolean, which might not be true even for expressions
0535   /// that are known to evaluate to 0/1. For instance, reading an unsigned
0536   /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
0537   /// semantically correspond to a bool.
0538   bool isKnownToHaveBooleanValue(bool Semantic = true) const;
0539 
0540   /// Check whether this array fits the idiom of a flexible array member,
0541   /// depending on the value of -fstrict-flex-array.
0542   /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
0543   /// resulting from the substitution of a macro or a template as special sizes.
0544   bool isFlexibleArrayMemberLike(
0545       ASTContext &Context,
0546       LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
0547       bool IgnoreTemplateOrMacroSubstitution = false) const;
0548 
0549   /// isIntegerConstantExpr - Return the value if this expression is a valid
0550   /// integer constant expression.  If not a valid i-c-e, return std::nullopt
0551   /// and fill in Loc (if specified) with the location of the invalid
0552   /// expression.
0553   ///
0554   /// Note: This does not perform the implicit conversions required by C++11
0555   /// [expr.const]p5.
0556   std::optional<llvm::APSInt>
0557   getIntegerConstantExpr(const ASTContext &Ctx,
0558                          SourceLocation *Loc = nullptr) const;
0559   bool isIntegerConstantExpr(const ASTContext &Ctx,
0560                              SourceLocation *Loc = nullptr) const;
0561 
0562   /// isCXX98IntegralConstantExpr - Return true if this expression is an
0563   /// integral constant expression in C++98. Can only be used in C++.
0564   bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
0565 
0566   /// isCXX11ConstantExpr - Return true if this expression is a constant
0567   /// expression in C++11. Can only be used in C++.
0568   ///
0569   /// Note: This does not perform the implicit conversions required by C++11
0570   /// [expr.const]p5.
0571   bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
0572                            SourceLocation *Loc = nullptr) const;
0573 
0574   /// isPotentialConstantExpr - Return true if this function's definition
0575   /// might be usable in a constant expression in C++11, if it were marked
0576   /// constexpr. Return false if the function can never produce a constant
0577   /// expression, along with diagnostics describing why not.
0578   static bool isPotentialConstantExpr(const FunctionDecl *FD,
0579                                       SmallVectorImpl<
0580                                         PartialDiagnosticAt> &Diags);
0581 
0582   /// isPotentialConstantExprUnevaluated - Return true if this expression might
0583   /// be usable in a constant expression in C++11 in an unevaluated context, if
0584   /// it were in function FD marked constexpr. Return false if the function can
0585   /// never produce a constant expression, along with diagnostics describing
0586   /// why not.
0587   static bool isPotentialConstantExprUnevaluated(Expr *E,
0588                                                  const FunctionDecl *FD,
0589                                                  SmallVectorImpl<
0590                                                    PartialDiagnosticAt> &Diags);
0591 
0592   /// isConstantInitializer - Returns true if this expression can be emitted to
0593   /// IR as a constant, and thus can be used as a constant initializer in C.
0594   /// If this expression is not constant and Culprit is non-null,
0595   /// it is used to store the address of first non constant expr.
0596   bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
0597                              const Expr **Culprit = nullptr) const;
0598 
0599   /// If this expression is an unambiguous reference to a single declaration,
0600   /// in the style of __builtin_function_start, return that declaration.  Note
0601   /// that this may return a non-static member function or field in C++ if this
0602   /// expression is a member pointer constant.
0603   const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
0604 
0605   /// EvalStatus is a struct with detailed info about an evaluation in progress.
0606   struct EvalStatus {
0607     /// Whether the evaluated expression has side effects.
0608     /// For example, (f() && 0) can be folded, but it still has side effects.
0609     bool HasSideEffects = false;
0610 
0611     /// Whether the evaluation hit undefined behavior.
0612     /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
0613     /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
0614     bool HasUndefinedBehavior = false;
0615 
0616     /// Diag - If this is non-null, it will be filled in with a stack of notes
0617     /// indicating why evaluation failed (or why it failed to produce a constant
0618     /// expression).
0619     /// If the expression is unfoldable, the notes will indicate why it's not
0620     /// foldable. If the expression is foldable, but not a constant expression,
0621     /// the notes will describes why it isn't a constant expression. If the
0622     /// expression *is* a constant expression, no notes will be produced.
0623     ///
0624     /// FIXME: this causes significant performance concerns and should be
0625     /// refactored at some point. Not all evaluations of the constant
0626     /// expression interpreter will display the given diagnostics, this means
0627     /// those kinds of uses are paying the expense of generating a diagnostic
0628     /// (which may include expensive operations like converting APValue objects
0629     /// to a string representation).
0630     SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr;
0631 
0632     EvalStatus() = default;
0633 
0634     // hasSideEffects - Return true if the evaluated expression has
0635     // side effects.
0636     bool hasSideEffects() const {
0637       return HasSideEffects;
0638     }
0639   };
0640 
0641   /// EvalResult is a struct with detailed info about an evaluated expression.
0642   struct EvalResult : EvalStatus {
0643     /// Val - This is the value the expression can be folded to.
0644     APValue Val;
0645 
0646     // isGlobalLValue - Return true if the evaluated lvalue expression
0647     // is global.
0648     bool isGlobalLValue() const;
0649   };
0650 
0651   /// EvaluateAsRValue - Return true if this is a constant which we can fold to
0652   /// an rvalue using any crazy technique (that has nothing to do with language
0653   /// standards) that we want to, even if the expression has side-effects. If
0654   /// this function returns true, it returns the folded constant in Result. If
0655   /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
0656   /// applied.
0657   bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
0658                         bool InConstantContext = false) const;
0659 
0660   /// EvaluateAsBooleanCondition - Return true if this is a constant
0661   /// which we can fold and convert to a boolean condition using
0662   /// any crazy technique that we want to, even if the expression has
0663   /// side-effects.
0664   bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
0665                                   bool InConstantContext = false) const;
0666 
0667   enum SideEffectsKind {
0668     SE_NoSideEffects,          ///< Strictly evaluate the expression.
0669     SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
0670                                ///< arbitrary unmodeled side effects.
0671     SE_AllowSideEffects        ///< Allow any unmodeled side effect.
0672   };
0673 
0674   /// EvaluateAsInt - Return true if this is a constant which we can fold and
0675   /// convert to an integer, using any crazy technique that we want to.
0676   bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
0677                      SideEffectsKind AllowSideEffects = SE_NoSideEffects,
0678                      bool InConstantContext = false) const;
0679 
0680   /// EvaluateAsFloat - Return true if this is a constant which we can fold and
0681   /// convert to a floating point value, using any crazy technique that we
0682   /// want to.
0683   bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
0684                        SideEffectsKind AllowSideEffects = SE_NoSideEffects,
0685                        bool InConstantContext = false) const;
0686 
0687   /// EvaluateAsFixedPoint - Return true if this is a constant which we can fold
0688   /// and convert to a fixed point value.
0689   bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
0690                             SideEffectsKind AllowSideEffects = SE_NoSideEffects,
0691                             bool InConstantContext = false) const;
0692 
0693   /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
0694   /// constant folded without side-effects, but discard the result.
0695   bool isEvaluatable(const ASTContext &Ctx,
0696                      SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
0697 
0698   /// HasSideEffects - This routine returns true for all those expressions
0699   /// which have any effect other than producing a value. Example is a function
0700   /// call, volatile variable read, or throwing an exception. If
0701   /// IncludePossibleEffects is false, this call treats certain expressions with
0702   /// potential side effects (such as function call-like expressions,
0703   /// instantiation-dependent expressions, or invocations from a macro) as not
0704   /// having side effects.
0705   bool HasSideEffects(const ASTContext &Ctx,
0706                       bool IncludePossibleEffects = true) const;
0707 
0708   /// Determine whether this expression involves a call to any function
0709   /// that is not trivial.
0710   bool hasNonTrivialCall(const ASTContext &Ctx) const;
0711 
0712   /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
0713   /// integer. This must be called on an expression that constant folds to an
0714   /// integer.
0715   llvm::APSInt EvaluateKnownConstInt(
0716       const ASTContext &Ctx,
0717       SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
0718 
0719   llvm::APSInt EvaluateKnownConstIntCheckOverflow(
0720       const ASTContext &Ctx,
0721       SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
0722 
0723   void EvaluateForOverflow(const ASTContext &Ctx) const;
0724 
0725   /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
0726   /// lvalue with link time known address, with no side-effects.
0727   bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
0728                         bool InConstantContext = false) const;
0729 
0730   /// EvaluateAsInitializer - Evaluate an expression as if it were the
0731   /// initializer of the given declaration. Returns true if the initializer
0732   /// can be folded to a constant, and produces any relevant notes. In C++11,
0733   /// notes will be produced if the expression is not a constant expression.
0734   bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
0735                              const VarDecl *VD,
0736                              SmallVectorImpl<PartialDiagnosticAt> &Notes,
0737                              bool IsConstantInitializer) const;
0738 
0739   /// EvaluateWithSubstitution - Evaluate an expression as if from the context
0740   /// of a call to the given function with the given arguments, inside an
0741   /// unevaluated context. Returns true if the expression could be folded to a
0742   /// constant.
0743   bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
0744                                 const FunctionDecl *Callee,
0745                                 ArrayRef<const Expr*> Args,
0746                                 const Expr *This = nullptr) const;
0747 
0748   enum class ConstantExprKind {
0749     /// An integer constant expression (an array bound, enumerator, case value,
0750     /// bit-field width, or similar) or similar.
0751     Normal,
0752     /// A non-class template argument. Such a value is only used for mangling,
0753     /// not for code generation, so can refer to dllimported functions.
0754     NonClassTemplateArgument,
0755     /// A class template argument. Such a value is used for code generation.
0756     ClassTemplateArgument,
0757     /// An immediate invocation. The destruction of the end result of this
0758     /// evaluation is not part of the evaluation, but all other temporaries
0759     /// are destroyed.
0760     ImmediateInvocation,
0761   };
0762 
0763   /// Evaluate an expression that is required to be a constant expression. Does
0764   /// not check the syntactic constraints for C and C++98 constant expressions.
0765   bool EvaluateAsConstantExpr(
0766       EvalResult &Result, const ASTContext &Ctx,
0767       ConstantExprKind Kind = ConstantExprKind::Normal) const;
0768 
0769   /// If the current Expr is a pointer, this will try to statically
0770   /// determine the number of bytes available where the pointer is pointing.
0771   /// Returns true if all of the above holds and we were able to figure out the
0772   /// size, false otherwise.
0773   ///
0774   /// \param Type - How to evaluate the size of the Expr, as defined by the
0775   /// "type" parameter of __builtin_object_size
0776   bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
0777                              unsigned Type) const;
0778 
0779   /// If the current Expr is a pointer, this will try to statically
0780   /// determine the strlen of the string pointed to.
0781   /// Returns true if all of the above holds and we were able to figure out the
0782   /// strlen, false otherwise.
0783   bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
0784 
0785   bool EvaluateCharRangeAsString(std::string &Result,
0786                                  const Expr *SizeExpression,
0787                                  const Expr *PtrExpression, ASTContext &Ctx,
0788                                  EvalResult &Status) const;
0789 
0790   /// If the current Expr can be evaluated to a pointer to a null-terminated
0791   /// constant string, return the constant string (without the terminating
0792   /// null).
0793   std::optional<std::string> tryEvaluateString(ASTContext &Ctx) const;
0794 
0795   /// Enumeration used to describe the kind of Null pointer constant
0796   /// returned from \c isNullPointerConstant().
0797   enum NullPointerConstantKind {
0798     /// Expression is not a Null pointer constant.
0799     NPCK_NotNull = 0,
0800 
0801     /// Expression is a Null pointer constant built from a zero integer
0802     /// expression that is not a simple, possibly parenthesized, zero literal.
0803     /// C++ Core Issue 903 will classify these expressions as "not pointers"
0804     /// once it is adopted.
0805     /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
0806     NPCK_ZeroExpression,
0807 
0808     /// Expression is a Null pointer constant built from a literal zero.
0809     NPCK_ZeroLiteral,
0810 
0811     /// Expression is a C++11 nullptr.
0812     NPCK_CXX11_nullptr,
0813 
0814     /// Expression is a GNU-style __null constant.
0815     NPCK_GNUNull
0816   };
0817 
0818   /// Enumeration used to describe how \c isNullPointerConstant()
0819   /// should cope with value-dependent expressions.
0820   enum NullPointerConstantValueDependence {
0821     /// Specifies that the expression should never be value-dependent.
0822     NPC_NeverValueDependent = 0,
0823 
0824     /// Specifies that a value-dependent expression of integral or
0825     /// dependent type should be considered a null pointer constant.
0826     NPC_ValueDependentIsNull,
0827 
0828     /// Specifies that a value-dependent expression should be considered
0829     /// to never be a null pointer constant.
0830     NPC_ValueDependentIsNotNull
0831   };
0832 
0833   /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
0834   /// a Null pointer constant. The return value can further distinguish the
0835   /// kind of NULL pointer constant that was detected.
0836   NullPointerConstantKind isNullPointerConstant(
0837       ASTContext &Ctx,
0838       NullPointerConstantValueDependence NPC) const;
0839 
0840   /// isOBJCGCCandidate - Return true if this expression may be used in a read/
0841   /// write barrier.
0842   bool isOBJCGCCandidate(ASTContext &Ctx) const;
0843 
0844   /// Returns true if this expression is a bound member function.
0845   bool isBoundMemberFunction(ASTContext &Ctx) const;
0846 
0847   /// Given an expression of bound-member type, find the type
0848   /// of the member.  Returns null if this is an *overloaded* bound
0849   /// member expression.
0850   static QualType findBoundMemberType(const Expr *expr);
0851 
0852   /// Skip past any invisible AST nodes which might surround this
0853   /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
0854   /// but also injected CXXMemberExpr and CXXConstructExpr which represent
0855   /// implicit conversions.
0856   Expr *IgnoreUnlessSpelledInSource();
0857   const Expr *IgnoreUnlessSpelledInSource() const {
0858     return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
0859   }
0860 
0861   /// Skip past any implicit casts which might surround this expression until
0862   /// reaching a fixed point. Skips:
0863   /// * ImplicitCastExpr
0864   /// * FullExpr
0865   Expr *IgnoreImpCasts() LLVM_READONLY;
0866   const Expr *IgnoreImpCasts() const {
0867     return const_cast<Expr *>(this)->IgnoreImpCasts();
0868   }
0869 
0870   /// Skip past any casts which might surround this expression until reaching
0871   /// a fixed point. Skips:
0872   /// * CastExpr
0873   /// * FullExpr
0874   /// * MaterializeTemporaryExpr
0875   /// * SubstNonTypeTemplateParmExpr
0876   Expr *IgnoreCasts() LLVM_READONLY;
0877   const Expr *IgnoreCasts() const {
0878     return const_cast<Expr *>(this)->IgnoreCasts();
0879   }
0880 
0881   /// Skip past any implicit AST nodes which might surround this expression
0882   /// until reaching a fixed point. Skips:
0883   /// * What IgnoreImpCasts() skips
0884   /// * MaterializeTemporaryExpr
0885   /// * CXXBindTemporaryExpr
0886   Expr *IgnoreImplicit() LLVM_READONLY;
0887   const Expr *IgnoreImplicit() const {
0888     return const_cast<Expr *>(this)->IgnoreImplicit();
0889   }
0890 
0891   /// Skip past any implicit AST nodes which might surround this expression
0892   /// until reaching a fixed point. Same as IgnoreImplicit, except that it
0893   /// also skips over implicit calls to constructors and conversion functions.
0894   ///
0895   /// FIXME: Should IgnoreImplicit do this?
0896   Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
0897   const Expr *IgnoreImplicitAsWritten() const {
0898     return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
0899   }
0900 
0901   /// Skip past any parentheses which might surround this expression until
0902   /// reaching a fixed point. Skips:
0903   /// * ParenExpr
0904   /// * UnaryOperator if `UO_Extension`
0905   /// * GenericSelectionExpr if `!isResultDependent()`
0906   /// * ChooseExpr if `!isConditionDependent()`
0907   /// * ConstantExpr
0908   Expr *IgnoreParens() LLVM_READONLY;
0909   const Expr *IgnoreParens() const {
0910     return const_cast<Expr *>(this)->IgnoreParens();
0911   }
0912 
0913   /// Skip past any parentheses and implicit casts which might surround this
0914   /// expression until reaching a fixed point.
0915   /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
0916   /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
0917   /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
0918   /// * What IgnoreParens() skips
0919   /// * What IgnoreImpCasts() skips
0920   /// * MaterializeTemporaryExpr
0921   /// * SubstNonTypeTemplateParmExpr
0922   Expr *IgnoreParenImpCasts() LLVM_READONLY;
0923   const Expr *IgnoreParenImpCasts() const {
0924     return const_cast<Expr *>(this)->IgnoreParenImpCasts();
0925   }
0926 
0927   /// Skip past any parentheses and casts which might surround this expression
0928   /// until reaching a fixed point. Skips:
0929   /// * What IgnoreParens() skips
0930   /// * What IgnoreCasts() skips
0931   Expr *IgnoreParenCasts() LLVM_READONLY;
0932   const Expr *IgnoreParenCasts() const {
0933     return const_cast<Expr *>(this)->IgnoreParenCasts();
0934   }
0935 
0936   /// Skip conversion operators. If this Expr is a call to a conversion
0937   /// operator, return the argument.
0938   Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
0939   const Expr *IgnoreConversionOperatorSingleStep() const {
0940     return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
0941   }
0942 
0943   /// Skip past any parentheses and lvalue casts which might surround this
0944   /// expression until reaching a fixed point. Skips:
0945   /// * What IgnoreParens() skips
0946   /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
0947   ///   casts are skipped
0948   /// FIXME: This is intended purely as a temporary workaround for code
0949   /// that hasn't yet been rewritten to do the right thing about those
0950   /// casts, and may disappear along with the last internal use.
0951   Expr *IgnoreParenLValueCasts() LLVM_READONLY;
0952   const Expr *IgnoreParenLValueCasts() const {
0953     return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
0954   }
0955 
0956   /// Skip past any parentheses and casts which do not change the value
0957   /// (including ptr->int casts of the same size) until reaching a fixed point.
0958   /// Skips:
0959   /// * What IgnoreParens() skips
0960   /// * CastExpr which do not change the value
0961   /// * SubstNonTypeTemplateParmExpr
0962   Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
0963   const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
0964     return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
0965   }
0966 
0967   /// Skip past any parentheses and derived-to-base casts until reaching a
0968   /// fixed point. Skips:
0969   /// * What IgnoreParens() skips
0970   /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
0971   ///   CK_UncheckedDerivedToBase and CK_NoOp)
0972   Expr *IgnoreParenBaseCasts() LLVM_READONLY;
0973   const Expr *IgnoreParenBaseCasts() const {
0974     return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
0975   }
0976 
0977   /// Determine whether this expression is a default function argument.
0978   ///
0979   /// Default arguments are implicitly generated in the abstract syntax tree
0980   /// by semantic analysis for function calls, object constructions, etc. in
0981   /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
0982   /// this routine also looks through any implicit casts to determine whether
0983   /// the expression is a default argument.
0984   bool isDefaultArgument() const;
0985 
0986   /// Determine whether the result of this expression is a
0987   /// temporary object of the given class type.
0988   bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
0989 
0990   /// Whether this expression is an implicit reference to 'this' in C++.
0991   bool isImplicitCXXThis() const;
0992 
0993   static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
0994 
0995   /// For an expression of class type or pointer to class type,
0996   /// return the most derived class decl the expression is known to refer to.
0997   ///
0998   /// If this expression is a cast, this method looks through it to find the
0999   /// most derived decl that can be inferred from the expression.
1000   /// This is valid because derived-to-base conversions have undefined
1001   /// behavior if the object isn't dynamically of the derived type.
1002   const CXXRecordDecl *getBestDynamicClassType() const;
1003 
1004   /// Get the inner expression that determines the best dynamic class.
1005   /// If this is a prvalue, we guarantee that it is of the most-derived type
1006   /// for the object itself.
1007   const Expr *getBestDynamicClassTypeExpr() const;
1008 
1009   /// Walk outwards from an expression we want to bind a reference to and
1010   /// find the expression whose lifetime needs to be extended. Record
1011   /// the LHSs of comma expressions and adjustments needed along the path.
1012   const Expr *skipRValueSubobjectAdjustments(
1013       SmallVectorImpl<const Expr *> &CommaLHS,
1014       SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
1015   const Expr *skipRValueSubobjectAdjustments() const {
1016     SmallVector<const Expr *, 8> CommaLHSs;
1017     SmallVector<SubobjectAdjustment, 8> Adjustments;
1018     return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1019   }
1020 
1021   /// Checks that the two Expr's will refer to the same value as a comparison
1022   /// operand.  The caller must ensure that the values referenced by the Expr's
1023   /// are not modified between E1 and E2 or the result my be invalid.
1024   static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
1025 
1026   static bool classof(const Stmt *T) {
1027     return T->getStmtClass() >= firstExprConstant &&
1028            T->getStmtClass() <= lastExprConstant;
1029   }
1030 };
1031 // PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1032 // Expr. Verify that we got it right.
1033 static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
1034                   llvm::detail::ConstantLog2<alignof(Expr)>::value,
1035               "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1036 
1037 using ConstantExprKind = Expr::ConstantExprKind;
1038 
1039 //===----------------------------------------------------------------------===//
1040 // Wrapper Expressions.
1041 //===----------------------------------------------------------------------===//
1042 
1043 /// FullExpr - Represents a "full-expression" node.
1044 class FullExpr : public Expr {
1045 protected:
1046  Stmt *SubExpr;
1047 
1048  FullExpr(StmtClass SC, Expr *subexpr)
1049      : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1050             subexpr->getObjectKind()),
1051        SubExpr(subexpr) {
1052    setDependence(computeDependence(this));
1053  }
1054   FullExpr(StmtClass SC, EmptyShell Empty)
1055     : Expr(SC, Empty) {}
1056 public:
1057   const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1058   Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1059 
1060   /// As with any mutator of the AST, be very careful when modifying an
1061   /// existing AST to preserve its invariants.
1062   void setSubExpr(Expr *E) { SubExpr = E; }
1063 
1064   static bool classof(const Stmt *T) {
1065     return T->getStmtClass() >= firstFullExprConstant &&
1066            T->getStmtClass() <= lastFullExprConstant;
1067   }
1068 };
1069 
1070 /// Describes the kind of result that can be tail-allocated.
1071 enum class ConstantResultStorageKind { None, Int64, APValue };
1072 
1073 /// ConstantExpr - An expression that occurs in a constant context and
1074 /// optionally the result of evaluating the expression.
1075 class ConstantExpr final
1076     : public FullExpr,
1077       private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1078   static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1079                 "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1080                 "for tail-allocated storage");
1081   friend TrailingObjects;
1082   friend class ASTStmtReader;
1083   friend class ASTStmtWriter;
1084 
1085   size_t numTrailingObjects(OverloadToken<APValue>) const {
1086     return getResultStorageKind() == ConstantResultStorageKind::APValue;
1087   }
1088   size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1089     return getResultStorageKind() == ConstantResultStorageKind::Int64;
1090   }
1091 
1092   uint64_t &Int64Result() {
1093     assert(getResultStorageKind() == ConstantResultStorageKind::Int64 &&
1094            "invalid accessor");
1095     return *getTrailingObjects<uint64_t>();
1096   }
1097   const uint64_t &Int64Result() const {
1098     return const_cast<ConstantExpr *>(this)->Int64Result();
1099   }
1100   APValue &APValueResult() {
1101     assert(getResultStorageKind() == ConstantResultStorageKind::APValue &&
1102            "invalid accessor");
1103     return *getTrailingObjects<APValue>();
1104   }
1105   APValue &APValueResult() const {
1106     return const_cast<ConstantExpr *>(this)->APValueResult();
1107   }
1108 
1109   ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
1110                bool IsImmediateInvocation);
1111   ConstantExpr(EmptyShell Empty, ConstantResultStorageKind StorageKind);
1112 
1113 public:
1114   static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1115                               const APValue &Result);
1116   static ConstantExpr *
1117   Create(const ASTContext &Context, Expr *E,
1118          ConstantResultStorageKind Storage = ConstantResultStorageKind::None,
1119          bool IsImmediateInvocation = false);
1120   static ConstantExpr *CreateEmpty(const ASTContext &Context,
1121                                    ConstantResultStorageKind StorageKind);
1122 
1123   static ConstantResultStorageKind getStorageKind(const APValue &Value);
1124   static ConstantResultStorageKind getStorageKind(const Type *T,
1125                                                   const ASTContext &Context);
1126 
1127   SourceLocation getBeginLoc() const LLVM_READONLY {
1128     return SubExpr->getBeginLoc();
1129   }
1130   SourceLocation getEndLoc() const LLVM_READONLY {
1131     return SubExpr->getEndLoc();
1132   }
1133 
1134   static bool classof(const Stmt *T) {
1135     return T->getStmtClass() == ConstantExprClass;
1136   }
1137 
1138   void SetResult(APValue Value, const ASTContext &Context) {
1139     MoveIntoResult(Value, Context);
1140   }
1141   void MoveIntoResult(APValue &Value, const ASTContext &Context);
1142 
1143   APValue::ValueKind getResultAPValueKind() const {
1144     return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1145   }
1146   ConstantResultStorageKind getResultStorageKind() const {
1147     return static_cast<ConstantResultStorageKind>(ConstantExprBits.ResultKind);
1148   }
1149   bool isImmediateInvocation() const {
1150     return ConstantExprBits.IsImmediateInvocation;
1151   }
1152   bool hasAPValueResult() const {
1153     return ConstantExprBits.APValueKind != APValue::None;
1154   }
1155   APValue getAPValueResult() const;
1156   llvm::APSInt getResultAsAPSInt() const;
1157   // Iterators
1158   child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1159   const_child_range children() const {
1160     return const_child_range(&SubExpr, &SubExpr + 1);
1161   }
1162 };
1163 
1164 //===----------------------------------------------------------------------===//
1165 // Primary Expressions.
1166 //===----------------------------------------------------------------------===//
1167 
1168 /// OpaqueValueExpr - An expression referring to an opaque object of a
1169 /// fixed type and value class.  These don't correspond to concrete
1170 /// syntax; instead they're used to express operations (usually copy
1171 /// operations) on values whose source is generally obvious from
1172 /// context.
1173 class OpaqueValueExpr : public Expr {
1174   friend class ASTStmtReader;
1175   Expr *SourceExpr;
1176 
1177 public:
1178   OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1179                   ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1180       : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1181     setIsUnique(false);
1182     OpaqueValueExprBits.Loc = Loc;
1183     setDependence(computeDependence(this));
1184   }
1185 
1186   /// Given an expression which invokes a copy constructor --- i.e.  a
1187   /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1188   /// find the OpaqueValueExpr that's the source of the construction.
1189   static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1190 
1191   explicit OpaqueValueExpr(EmptyShell Empty)
1192     : Expr(OpaqueValueExprClass, Empty) {}
1193 
1194   /// Retrieve the location of this expression.
1195   SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1196 
1197   SourceLocation getBeginLoc() const LLVM_READONLY {
1198     return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1199   }
1200   SourceLocation getEndLoc() const LLVM_READONLY {
1201     return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1202   }
1203   SourceLocation getExprLoc() const LLVM_READONLY {
1204     return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1205   }
1206 
1207   child_range children() {
1208     return child_range(child_iterator(), child_iterator());
1209   }
1210 
1211   const_child_range children() const {
1212     return const_child_range(const_child_iterator(), const_child_iterator());
1213   }
1214 
1215   /// The source expression of an opaque value expression is the
1216   /// expression which originally generated the value.  This is
1217   /// provided as a convenience for analyses that don't wish to
1218   /// precisely model the execution behavior of the program.
1219   ///
1220   /// The source expression is typically set when building the
1221   /// expression which binds the opaque value expression in the first
1222   /// place.
1223   Expr *getSourceExpr() const { return SourceExpr; }
1224 
1225   void setIsUnique(bool V) {
1226     assert((!V || SourceExpr) &&
1227            "unique OVEs are expected to have source expressions");
1228     OpaqueValueExprBits.IsUnique = V;
1229   }
1230 
1231   bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1232 
1233   static bool classof(const Stmt *T) {
1234     return T->getStmtClass() == OpaqueValueExprClass;
1235   }
1236 };
1237 
1238 /// A reference to a declared variable, function, enum, etc.
1239 /// [C99 6.5.1p2]
1240 ///
1241 /// This encodes all the information about how a declaration is referenced
1242 /// within an expression.
1243 ///
1244 /// There are several optional constructs attached to DeclRefExprs only when
1245 /// they apply in order to conserve memory. These are laid out past the end of
1246 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
1247 ///
1248 ///   DeclRefExprBits.HasQualifier:
1249 ///       Specifies when this declaration reference expression has a C++
1250 ///       nested-name-specifier.
1251 ///   DeclRefExprBits.HasFoundDecl:
1252 ///       Specifies when this declaration reference expression has a record of
1253 ///       a NamedDecl (different from the referenced ValueDecl) which was found
1254 ///       during name lookup and/or overload resolution.
1255 ///   DeclRefExprBits.HasTemplateKWAndArgsInfo:
1256 ///       Specifies when this declaration reference expression has an explicit
1257 ///       C++ template keyword and/or template argument list.
1258 ///   DeclRefExprBits.RefersToEnclosingVariableOrCapture
1259 ///       Specifies when this declaration reference expression (validly)
1260 ///       refers to an enclosed local or a captured variable.
1261 class DeclRefExpr final
1262     : public Expr,
1263       private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1264                                     NamedDecl *, ASTTemplateKWAndArgsInfo,
1265                                     TemplateArgumentLoc> {
1266   friend class ASTStmtReader;
1267   friend class ASTStmtWriter;
1268   friend TrailingObjects;
1269 
1270   /// The declaration that we are referencing.
1271   ValueDecl *D;
1272 
1273   /// Provides source/type location info for the declaration name
1274   /// embedded in D.
1275   DeclarationNameLoc DNLoc;
1276 
1277   size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1278     return hasQualifier();
1279   }
1280 
1281   size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1282     return hasFoundDecl();
1283   }
1284 
1285   size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1286     return hasTemplateKWAndArgsInfo();
1287   }
1288 
1289   /// Test whether there is a distinct FoundDecl attached to the end of
1290   /// this DRE.
1291   bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1292 
1293   DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1294               SourceLocation TemplateKWLoc, ValueDecl *D,
1295               bool RefersToEnclosingVariableOrCapture,
1296               const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1297               const TemplateArgumentListInfo *TemplateArgs, QualType T,
1298               ExprValueKind VK, NonOdrUseReason NOUR);
1299 
1300   /// Construct an empty declaration reference expression.
1301   explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1302 
1303 public:
1304   DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1305               bool RefersToEnclosingVariableOrCapture, QualType T,
1306               ExprValueKind VK, SourceLocation L,
1307               const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1308               NonOdrUseReason NOUR = NOUR_None);
1309 
1310   static DeclRefExpr *
1311   Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1312          SourceLocation TemplateKWLoc, ValueDecl *D,
1313          bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1314          QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1315          const TemplateArgumentListInfo *TemplateArgs = nullptr,
1316          NonOdrUseReason NOUR = NOUR_None);
1317 
1318   static DeclRefExpr *
1319   Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1320          SourceLocation TemplateKWLoc, ValueDecl *D,
1321          bool RefersToEnclosingVariableOrCapture,
1322          const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1323          NamedDecl *FoundD = nullptr,
1324          const TemplateArgumentListInfo *TemplateArgs = nullptr,
1325          NonOdrUseReason NOUR = NOUR_None);
1326 
1327   /// Construct an empty declaration reference expression.
1328   static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1329                                   bool HasFoundDecl,
1330                                   bool HasTemplateKWAndArgsInfo,
1331                                   unsigned NumTemplateArgs);
1332 
1333   ValueDecl *getDecl() { return D; }
1334   const ValueDecl *getDecl() const { return D; }
1335   void setDecl(ValueDecl *NewD);
1336 
1337   DeclarationNameInfo getNameInfo() const {
1338     return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1339   }
1340 
1341   SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1342   void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1343   SourceLocation getBeginLoc() const LLVM_READONLY;
1344   SourceLocation getEndLoc() const LLVM_READONLY;
1345 
1346   /// Determine whether this declaration reference was preceded by a
1347   /// C++ nested-name-specifier, e.g., \c N::foo.
1348   bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1349 
1350   /// If the name was qualified, retrieves the nested-name-specifier
1351   /// that precedes the name, with source-location information.
1352   NestedNameSpecifierLoc getQualifierLoc() const {
1353     if (!hasQualifier())
1354       return NestedNameSpecifierLoc();
1355     return *getTrailingObjects<NestedNameSpecifierLoc>();
1356   }
1357 
1358   /// If the name was qualified, retrieves the nested-name-specifier
1359   /// that precedes the name. Otherwise, returns NULL.
1360   NestedNameSpecifier *getQualifier() const {
1361     return getQualifierLoc().getNestedNameSpecifier();
1362   }
1363 
1364   /// Get the NamedDecl through which this reference occurred.
1365   ///
1366   /// This Decl may be different from the ValueDecl actually referred to in the
1367   /// presence of using declarations, etc. It always returns non-NULL, and may
1368   /// simple return the ValueDecl when appropriate.
1369 
1370   NamedDecl *getFoundDecl() {
1371     return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1372   }
1373 
1374   /// Get the NamedDecl through which this reference occurred.
1375   /// See non-const variant.
1376   const NamedDecl *getFoundDecl() const {
1377     return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1378   }
1379 
1380   bool hasTemplateKWAndArgsInfo() const {
1381     return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1382   }
1383 
1384   /// Retrieve the location of the template keyword preceding
1385   /// this name, if any.
1386   SourceLocation getTemplateKeywordLoc() const {
1387     if (!hasTemplateKWAndArgsInfo())
1388       return SourceLocation();
1389     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1390   }
1391 
1392   /// Retrieve the location of the left angle bracket starting the
1393   /// explicit template argument list following the name, if any.
1394   SourceLocation getLAngleLoc() const {
1395     if (!hasTemplateKWAndArgsInfo())
1396       return SourceLocation();
1397     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1398   }
1399 
1400   /// Retrieve the location of the right angle bracket ending the
1401   /// explicit template argument list following the name, if any.
1402   SourceLocation getRAngleLoc() const {
1403     if (!hasTemplateKWAndArgsInfo())
1404       return SourceLocation();
1405     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1406   }
1407 
1408   /// Determines whether the name in this declaration reference
1409   /// was preceded by the template keyword.
1410   bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1411 
1412   /// Determines whether this declaration reference was followed by an
1413   /// explicit template argument list.
1414   bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1415 
1416   /// Copies the template arguments (if present) into the given
1417   /// structure.
1418   void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1419     if (hasExplicitTemplateArgs())
1420       getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1421           getTrailingObjects<TemplateArgumentLoc>(), List);
1422   }
1423 
1424   /// Retrieve the template arguments provided as part of this
1425   /// template-id.
1426   const TemplateArgumentLoc *getTemplateArgs() const {
1427     if (!hasExplicitTemplateArgs())
1428       return nullptr;
1429     return getTrailingObjects<TemplateArgumentLoc>();
1430   }
1431 
1432   /// Retrieve the number of template arguments provided as part of this
1433   /// template-id.
1434   unsigned getNumTemplateArgs() const {
1435     if (!hasExplicitTemplateArgs())
1436       return 0;
1437     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1438   }
1439 
1440   ArrayRef<TemplateArgumentLoc> template_arguments() const {
1441     return {getTemplateArgs(), getNumTemplateArgs()};
1442   }
1443 
1444   /// Returns true if this expression refers to a function that
1445   /// was resolved from an overloaded set having size greater than 1.
1446   bool hadMultipleCandidates() const {
1447     return DeclRefExprBits.HadMultipleCandidates;
1448   }
1449   /// Sets the flag telling whether this expression refers to
1450   /// a function that was resolved from an overloaded set having size
1451   /// greater than 1.
1452   void setHadMultipleCandidates(bool V = true) {
1453     DeclRefExprBits.HadMultipleCandidates = V;
1454   }
1455 
1456   /// Is this expression a non-odr-use reference, and if so, why?
1457   NonOdrUseReason isNonOdrUse() const {
1458     return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1459   }
1460 
1461   /// Does this DeclRefExpr refer to an enclosing local or a captured
1462   /// variable?
1463   bool refersToEnclosingVariableOrCapture() const {
1464     return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1465   }
1466 
1467   bool isImmediateEscalating() const {
1468     return DeclRefExprBits.IsImmediateEscalating;
1469   }
1470 
1471   void setIsImmediateEscalating(bool Set) {
1472     DeclRefExprBits.IsImmediateEscalating = Set;
1473   }
1474 
1475   bool isCapturedByCopyInLambdaWithExplicitObjectParameter() const {
1476     return DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter;
1477   }
1478 
1479   void setCapturedByCopyInLambdaWithExplicitObjectParameter(
1480       bool Set, const ASTContext &Context) {
1481     DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = Set;
1482     setDependence(computeDependence(this, Context));
1483   }
1484 
1485   static bool classof(const Stmt *T) {
1486     return T->getStmtClass() == DeclRefExprClass;
1487   }
1488 
1489   // Iterators
1490   child_range children() {
1491     return child_range(child_iterator(), child_iterator());
1492   }
1493 
1494   const_child_range children() const {
1495     return const_child_range(const_child_iterator(), const_child_iterator());
1496   }
1497 };
1498 
1499 class IntegerLiteral : public Expr, public APIntStorage {
1500   SourceLocation Loc;
1501 
1502   /// Construct an empty integer literal.
1503   explicit IntegerLiteral(EmptyShell Empty)
1504     : Expr(IntegerLiteralClass, Empty) { }
1505 
1506 public:
1507   // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1508   // or UnsignedLongLongTy
1509   IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1510                  SourceLocation l);
1511 
1512   /// Returns a new integer literal with value 'V' and type 'type'.
1513   /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1514   /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1515   /// \param V - the value that the returned integer literal contains.
1516   static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1517                                 QualType type, SourceLocation l);
1518   /// Returns a new empty integer literal.
1519   static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1520 
1521   SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1522   SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1523 
1524   /// Retrieve the location of the literal.
1525   SourceLocation getLocation() const { return Loc; }
1526 
1527   void setLocation(SourceLocation Location) { Loc = Location; }
1528 
1529   static bool classof(const Stmt *T) {
1530     return T->getStmtClass() == IntegerLiteralClass;
1531   }
1532 
1533   // Iterators
1534   child_range children() {
1535     return child_range(child_iterator(), child_iterator());
1536   }
1537   const_child_range children() const {
1538     return const_child_range(const_child_iterator(), const_child_iterator());
1539   }
1540 };
1541 
1542 class FixedPointLiteral : public Expr, public APIntStorage {
1543   SourceLocation Loc;
1544   unsigned Scale;
1545 
1546   /// \brief Construct an empty fixed-point literal.
1547   explicit FixedPointLiteral(EmptyShell Empty)
1548       : Expr(FixedPointLiteralClass, Empty) {}
1549 
1550  public:
1551   FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1552                     SourceLocation l, unsigned Scale);
1553 
1554   // Store the int as is without any bit shifting.
1555   static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1556                                              const llvm::APInt &V,
1557                                              QualType type, SourceLocation l,
1558                                              unsigned Scale);
1559 
1560   /// Returns an empty fixed-point literal.
1561   static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1562 
1563   SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1564   SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1565 
1566   /// \brief Retrieve the location of the literal.
1567   SourceLocation getLocation() const { return Loc; }
1568 
1569   void setLocation(SourceLocation Location) { Loc = Location; }
1570 
1571   unsigned getScale() const { return Scale; }
1572   void setScale(unsigned S) { Scale = S; }
1573 
1574   static bool classof(const Stmt *T) {
1575     return T->getStmtClass() == FixedPointLiteralClass;
1576   }
1577 
1578   std::string getValueAsString(unsigned Radix) const;
1579 
1580   // Iterators
1581   child_range children() {
1582     return child_range(child_iterator(), child_iterator());
1583   }
1584   const_child_range children() const {
1585     return const_child_range(const_child_iterator(), const_child_iterator());
1586   }
1587 };
1588 
1589 enum class CharacterLiteralKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1590 
1591 class CharacterLiteral : public Expr {
1592   unsigned Value;
1593   SourceLocation Loc;
1594 public:
1595   // type should be IntTy
1596   CharacterLiteral(unsigned value, CharacterLiteralKind kind, QualType type,
1597                    SourceLocation l)
1598       : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1599         Value(value), Loc(l) {
1600     CharacterLiteralBits.Kind = llvm::to_underlying(kind);
1601     setDependence(ExprDependence::None);
1602   }
1603 
1604   /// Construct an empty character literal.
1605   CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1606 
1607   SourceLocation getLocation() const { return Loc; }
1608   CharacterLiteralKind getKind() const {
1609     return static_cast<CharacterLiteralKind>(CharacterLiteralBits.Kind);
1610   }
1611 
1612   SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1613   SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1614 
1615   unsigned getValue() const { return Value; }
1616 
1617   void setLocation(SourceLocation Location) { Loc = Location; }
1618   void setKind(CharacterLiteralKind kind) {
1619     CharacterLiteralBits.Kind = llvm::to_underlying(kind);
1620   }
1621   void setValue(unsigned Val) { Value = Val; }
1622 
1623   static bool classof(const Stmt *T) {
1624     return T->getStmtClass() == CharacterLiteralClass;
1625   }
1626 
1627   static void print(unsigned val, CharacterLiteralKind Kind, raw_ostream &OS);
1628 
1629   // Iterators
1630   child_range children() {
1631     return child_range(child_iterator(), child_iterator());
1632   }
1633   const_child_range children() const {
1634     return const_child_range(const_child_iterator(), const_child_iterator());
1635   }
1636 };
1637 
1638 class FloatingLiteral : public Expr, private APFloatStorage {
1639   SourceLocation Loc;
1640 
1641   FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1642                   QualType Type, SourceLocation L);
1643 
1644   /// Construct an empty floating-point literal.
1645   explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1646 
1647 public:
1648   static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1649                                  bool isexact, QualType Type, SourceLocation L);
1650   static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1651 
1652   llvm::APFloat getValue() const {
1653     return APFloatStorage::getValue(getSemantics());
1654   }
1655   void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1656     assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1657     APFloatStorage::setValue(C, Val);
1658   }
1659 
1660   /// Get a raw enumeration value representing the floating-point semantics of
1661   /// this literal (32-bit IEEE, x87, ...), suitable for serialization.
1662   llvm::APFloatBase::Semantics getRawSemantics() const {
1663     return static_cast<llvm::APFloatBase::Semantics>(
1664         FloatingLiteralBits.Semantics);
1665   }
1666 
1667   /// Set the raw enumeration value representing the floating-point semantics of
1668   /// this literal (32-bit IEEE, x87, ...), suitable for serialization.
1669   void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1670     FloatingLiteralBits.Semantics = Sem;
1671   }
1672 
1673   /// Return the APFloat semantics this literal uses.
1674   const llvm::fltSemantics &getSemantics() const {
1675     return llvm::APFloatBase::EnumToSemantics(
1676         static_cast<llvm::APFloatBase::Semantics>(
1677             FloatingLiteralBits.Semantics));
1678   }
1679 
1680   /// Set the APFloat semantics this literal uses.
1681   void setSemantics(const llvm::fltSemantics &Sem) {
1682     FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1683   }
1684 
1685   bool isExact() const { return FloatingLiteralBits.IsExact; }
1686   void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1687 
1688   /// getValueAsApproximateDouble - This returns the value as an inaccurate
1689   /// double.  Note that this may cause loss of precision, but is useful for
1690   /// debugging dumps, etc.
1691   double getValueAsApproximateDouble() const;
1692 
1693   SourceLocation getLocation() const { return Loc; }
1694   void setLocation(SourceLocation L) { Loc = L; }
1695 
1696   SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1697   SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1698 
1699   static bool classof(const Stmt *T) {
1700     return T->getStmtClass() == FloatingLiteralClass;
1701   }
1702 
1703   // Iterators
1704   child_range children() {
1705     return child_range(child_iterator(), child_iterator());
1706   }
1707   const_child_range children() const {
1708     return const_child_range(const_child_iterator(), const_child_iterator());
1709   }
1710 };
1711 
1712 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1713 /// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1714 /// IntegerLiteral classes.  Instances of this class always have a Complex type
1715 /// whose element type matches the subexpression.
1716 ///
1717 class ImaginaryLiteral : public Expr {
1718   Stmt *Val;
1719 public:
1720   ImaginaryLiteral(Expr *val, QualType Ty)
1721       : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1722     setDependence(ExprDependence::None);
1723   }
1724 
1725   /// Build an empty imaginary literal.
1726   explicit ImaginaryLiteral(EmptyShell Empty)
1727     : Expr(ImaginaryLiteralClass, Empty) { }
1728 
1729   const Expr *getSubExpr() const { return cast<Expr>(Val); }
1730   Expr *getSubExpr() { return cast<Expr>(Val); }
1731   void setSubExpr(Expr *E) { Val = E; }
1732 
1733   SourceLocation getBeginLoc() const LLVM_READONLY {
1734     return Val->getBeginLoc();
1735   }
1736   SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1737 
1738   static bool classof(const Stmt *T) {
1739     return T->getStmtClass() == ImaginaryLiteralClass;
1740   }
1741 
1742   // Iterators
1743   child_range children() { return child_range(&Val, &Val+1); }
1744   const_child_range children() const {
1745     return const_child_range(&Val, &Val + 1);
1746   }
1747 };
1748 
1749 enum class StringLiteralKind {
1750   Ordinary,
1751   Wide,
1752   UTF8,
1753   UTF16,
1754   UTF32,
1755   Unevaluated,
1756   // Binary kind of string literal is used for the data coming via #embed
1757   // directive. File's binary contents is transformed to a special kind of
1758   // string literal that in some cases may be used directly as an initializer
1759   // and some features of classic string literals are not applicable to this
1760   // kind of a string literal, for example finding a particular byte's source
1761   // location for better diagnosing.
1762   Binary
1763 };
1764 
1765 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1766 /// or L"bar" (wide strings). The actual string data can be obtained with
1767 /// getBytes() and is NOT null-terminated. The length of the string data is
1768 /// determined by calling getByteLength().
1769 ///
1770 /// The C type for a string is always a ConstantArrayType. In C++, the char
1771 /// type is const qualified, in C it is not.
1772 ///
1773 /// Note that strings in C can be formed by concatenation of multiple string
1774 /// literal pptokens in translation phase #6. This keeps track of the locations
1775 /// of each of these pieces.
1776 ///
1777 /// Strings in C can also be truncated and extended by assigning into arrays,
1778 /// e.g. with constructs like:
1779 ///   char X[2] = "foobar";
1780 /// In this case, getByteLength() will return 6, but the string literal will
1781 /// have type "char[2]".
1782 class StringLiteral final
1783     : public Expr,
1784       private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1785                                     char> {
1786   friend class ASTStmtReader;
1787   friend TrailingObjects;
1788 
1789   /// StringLiteral is followed by several trailing objects. They are in order:
1790   ///
1791   /// * A single unsigned storing the length in characters of this string. The
1792   ///   length in bytes is this length times the width of a single character.
1793   ///   Always present and stored as a trailing objects because storing it in
1794   ///   StringLiteral would increase the size of StringLiteral by sizeof(void *)
1795   ///   due to alignment requirements. If you add some data to StringLiteral,
1796   ///   consider moving it inside StringLiteral.
1797   ///
1798   /// * An array of getNumConcatenated() SourceLocation, one for each of the
1799   ///   token this string is made of.
1800   ///
1801   /// * An array of getByteLength() char used to store the string data.
1802 
1803   unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1804   unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1805     return getNumConcatenated();
1806   }
1807 
1808   unsigned numTrailingObjects(OverloadToken<char>) const {
1809     return getByteLength();
1810   }
1811 
1812   char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1813   const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1814 
1815   const uint16_t *getStrDataAsUInt16() const {
1816     return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1817   }
1818 
1819   const uint32_t *getStrDataAsUInt32() const {
1820     return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1821   }
1822 
1823   /// Build a string literal.
1824   StringLiteral(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind,
1825                 bool Pascal, QualType Ty, const SourceLocation *Loc,
1826                 unsigned NumConcatenated);
1827 
1828   /// Build an empty string literal.
1829   StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1830                 unsigned CharByteWidth);
1831 
1832   /// Map a target and string kind to the appropriate character width.
1833   static unsigned mapCharByteWidth(TargetInfo const &Target,
1834                                    StringLiteralKind SK);
1835 
1836   /// Set one of the string literal token.
1837   void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1838     assert(TokNum < getNumConcatenated() && "Invalid tok number");
1839     getTrailingObjects<SourceLocation>()[TokNum] = L;
1840   }
1841 
1842 public:
1843   /// This is the "fully general" constructor that allows representation of
1844   /// strings formed from multiple concatenated tokens.
1845   static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1846                                StringLiteralKind Kind, bool Pascal, QualType Ty,
1847                                const SourceLocation *Loc,
1848                                unsigned NumConcatenated);
1849 
1850   /// Simple constructor for string literals made from one token.
1851   static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1852                                StringLiteralKind Kind, bool Pascal, QualType Ty,
1853                                SourceLocation Loc) {
1854     return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1855   }
1856 
1857   /// Construct an empty string literal.
1858   static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1859                                     unsigned NumConcatenated, unsigned Length,
1860                                     unsigned CharByteWidth);
1861 
1862   StringRef getString() const {
1863     assert((isUnevaluated() || getCharByteWidth() == 1) &&
1864            "This function is used in places that assume strings use char");
1865     return StringRef(getStrDataAsChar(), getByteLength());
1866   }
1867 
1868   /// Allow access to clients that need the byte representation, such as
1869   /// ASTWriterStmt::VisitStringLiteral().
1870   StringRef getBytes() const {
1871     // FIXME: StringRef may not be the right type to use as a result for this.
1872     return StringRef(getStrDataAsChar(), getByteLength());
1873   }
1874 
1875   void outputString(raw_ostream &OS) const;
1876 
1877   uint32_t getCodeUnit(size_t i) const {
1878     assert(i < getLength() && "out of bounds access");
1879     switch (getCharByteWidth()) {
1880     case 1:
1881       return static_cast<unsigned char>(getStrDataAsChar()[i]);
1882     case 2:
1883       return getStrDataAsUInt16()[i];
1884     case 4:
1885       return getStrDataAsUInt32()[i];
1886     }
1887     llvm_unreachable("Unsupported character width!");
1888   }
1889 
1890   // Get code unit but preserve sign info.
1891   int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const {
1892     int64_t V = getCodeUnit(I);
1893     if (isOrdinary() || isWide()) {
1894       // Ordinary and wide string literals have types that can be signed.
1895       // It is important for checking C23 constexpr initializers.
1896       unsigned Width = getCharByteWidth() * BitWidth;
1897       llvm::APInt AInt(Width, (uint64_t)V);
1898       V = AInt.getSExtValue();
1899     }
1900     return V;
1901   }
1902 
1903   unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1904   unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1905   unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1906 
1907   StringLiteralKind getKind() const {
1908     return static_cast<StringLiteralKind>(StringLiteralBits.Kind);
1909   }
1910 
1911   bool isOrdinary() const { return getKind() == StringLiteralKind::Ordinary; }
1912   bool isWide() const { return getKind() == StringLiteralKind::Wide; }
1913   bool isUTF8() const { return getKind() == StringLiteralKind::UTF8; }
1914   bool isUTF16() const { return getKind() == StringLiteralKind::UTF16; }
1915   bool isUTF32() const { return getKind() == StringLiteralKind::UTF32; }
1916   bool isUnevaluated() const { return getKind() == StringLiteralKind::Unevaluated; }
1917   bool isPascal() const { return StringLiteralBits.IsPascal; }
1918 
1919   bool containsNonAscii() const {
1920     for (auto c : getString())
1921       if (!isASCII(c))
1922         return true;
1923     return false;
1924   }
1925 
1926   bool containsNonAsciiOrNull() const {
1927     for (auto c : getString())
1928       if (!isASCII(c) || !c)
1929         return true;
1930     return false;
1931   }
1932 
1933   /// getNumConcatenated - Get the number of string literal tokens that were
1934   /// concatenated in translation phase #6 to form this string literal.
1935   unsigned getNumConcatenated() const {
1936     return StringLiteralBits.NumConcatenated;
1937   }
1938 
1939   /// Get one of the string literal token.
1940   SourceLocation getStrTokenLoc(unsigned TokNum) const {
1941     assert(TokNum < getNumConcatenated() && "Invalid tok number");
1942     return getTrailingObjects<SourceLocation>()[TokNum];
1943   }
1944 
1945   /// getLocationOfByte - Return a source location that points to the specified
1946   /// byte of this string literal.
1947   ///
1948   /// Strings are amazingly complex.  They can be formed from multiple tokens
1949   /// and can have escape sequences in them in addition to the usual trigraph
1950   /// and escaped newline business.  This routine handles this complexity.
1951   ///
1952   SourceLocation
1953   getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1954                     const LangOptions &Features, const TargetInfo &Target,
1955                     unsigned *StartToken = nullptr,
1956                     unsigned *StartTokenByteOffset = nullptr) const;
1957 
1958   typedef const SourceLocation *tokloc_iterator;
1959 
1960   tokloc_iterator tokloc_begin() const {
1961     return getTrailingObjects<SourceLocation>();
1962   }
1963 
1964   tokloc_iterator tokloc_end() const {
1965     return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1966   }
1967 
1968   SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1969   SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1970 
1971   static bool classof(const Stmt *T) {
1972     return T->getStmtClass() == StringLiteralClass;
1973   }
1974 
1975   // Iterators
1976   child_range children() {
1977     return child_range(child_iterator(), child_iterator());
1978   }
1979   const_child_range children() const {
1980     return const_child_range(const_child_iterator(), const_child_iterator());
1981   }
1982 };
1983 
1984 enum class PredefinedIdentKind {
1985   Func,
1986   Function,
1987   LFunction, // Same as Function, but as wide string.
1988   FuncDName,
1989   FuncSig,
1990   LFuncSig, // Same as FuncSig, but as wide string
1991   PrettyFunction,
1992   /// The same as PrettyFunction, except that the
1993   /// 'virtual' keyword is omitted for virtual member functions.
1994   PrettyFunctionNoVirtual
1995 };
1996 
1997 /// [C99 6.4.2.2] - A predefined identifier such as __func__.
1998 class PredefinedExpr final
1999     : public Expr,
2000       private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
2001   friend class ASTStmtReader;
2002   friend TrailingObjects;
2003 
2004   // PredefinedExpr is optionally followed by a single trailing
2005   // "Stmt *" for the predefined identifier. It is present if and only if
2006   // hasFunctionName() is true and is always a "StringLiteral *".
2007 
2008   PredefinedExpr(SourceLocation L, QualType FNTy, PredefinedIdentKind IK,
2009                  bool IsTransparent, StringLiteral *SL);
2010 
2011   explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
2012 
2013   /// True if this PredefinedExpr has storage for a function name.
2014   bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
2015 
2016   void setFunctionName(StringLiteral *SL) {
2017     assert(hasFunctionName() &&
2018            "This PredefinedExpr has no storage for a function name!");
2019     *getTrailingObjects<Stmt *>() = SL;
2020   }
2021 
2022 public:
2023   /// Create a PredefinedExpr.
2024   ///
2025   /// If IsTransparent, the PredefinedExpr is transparently handled as a
2026   /// StringLiteral.
2027   static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
2028                                 QualType FNTy, PredefinedIdentKind IK,
2029                                 bool IsTransparent, StringLiteral *SL);
2030 
2031   /// Create an empty PredefinedExpr.
2032   static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
2033                                      bool HasFunctionName);
2034 
2035   PredefinedIdentKind getIdentKind() const {
2036     return static_cast<PredefinedIdentKind>(PredefinedExprBits.Kind);
2037   }
2038 
2039   bool isTransparent() const { return PredefinedExprBits.IsTransparent; }
2040 
2041   SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
2042   void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2043 
2044   StringLiteral *getFunctionName() {
2045     return hasFunctionName()
2046                ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2047                : nullptr;
2048   }
2049 
2050   const StringLiteral *getFunctionName() const {
2051     return hasFunctionName()
2052                ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2053                : nullptr;
2054   }
2055 
2056   static StringRef getIdentKindName(PredefinedIdentKind IK);
2057   StringRef getIdentKindName() const {
2058     return getIdentKindName(getIdentKind());
2059   }
2060 
2061   static std::string ComputeName(PredefinedIdentKind IK,
2062                                  const Decl *CurrentDecl,
2063                                  bool ForceElaboratedPrinting = false);
2064 
2065   SourceLocation getBeginLoc() const { return getLocation(); }
2066   SourceLocation getEndLoc() const { return getLocation(); }
2067 
2068   static bool classof(const Stmt *T) {
2069     return T->getStmtClass() == PredefinedExprClass;
2070   }
2071 
2072   // Iterators
2073   child_range children() {
2074     return child_range(getTrailingObjects<Stmt *>(),
2075                        getTrailingObjects<Stmt *>() + hasFunctionName());
2076   }
2077 
2078   const_child_range children() const {
2079     return const_child_range(getTrailingObjects<Stmt *>(),
2080                              getTrailingObjects<Stmt *>() + hasFunctionName());
2081   }
2082 };
2083 
2084 /// This expression type represents an asterisk in an OpenACC Size-Expr, used in
2085 /// the 'tile' and 'gang' clauses. It is of 'int' type, but should not be
2086 /// evaluated.
2087 class OpenACCAsteriskSizeExpr final : public Expr {
2088   friend class ASTStmtReader;
2089   SourceLocation AsteriskLoc;
2090 
2091   OpenACCAsteriskSizeExpr(SourceLocation AsteriskLoc, QualType IntTy)
2092       : Expr(OpenACCAsteriskSizeExprClass, IntTy, VK_PRValue, OK_Ordinary),
2093         AsteriskLoc(AsteriskLoc) {}
2094 
2095   void setAsteriskLocation(SourceLocation Loc) { AsteriskLoc = Loc; }
2096 
2097 public:
2098   static OpenACCAsteriskSizeExpr *Create(const ASTContext &C,
2099                                          SourceLocation Loc);
2100   static OpenACCAsteriskSizeExpr *CreateEmpty(const ASTContext &C);
2101 
2102   SourceLocation getBeginLoc() const { return AsteriskLoc; }
2103   SourceLocation getEndLoc() const { return AsteriskLoc; }
2104   SourceLocation getLocation() const { return AsteriskLoc; }
2105 
2106   static bool classof(const Stmt *T) {
2107     return T->getStmtClass() == OpenACCAsteriskSizeExprClass;
2108   }
2109   // Iterators
2110   child_range children() {
2111     return child_range(child_iterator(), child_iterator());
2112   }
2113 
2114   const_child_range children() const {
2115     return const_child_range(const_child_iterator(), const_child_iterator());
2116   }
2117 };
2118 
2119 // This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2120 // type-id, and at CodeGen time emits a unique string representation of the
2121 // type in a way that permits us to properly encode information about the SYCL
2122 // kernels.
2123 class SYCLUniqueStableNameExpr final : public Expr {
2124   friend class ASTStmtReader;
2125   SourceLocation OpLoc, LParen, RParen;
2126   TypeSourceInfo *TypeInfo;
2127 
2128   SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
2129   SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
2130                            SourceLocation RParen, QualType ResultTy,
2131                            TypeSourceInfo *TSI);
2132 
2133   void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2134 
2135   void setLocation(SourceLocation L) { OpLoc = L; }
2136   void setLParenLocation(SourceLocation L) { LParen = L; }
2137   void setRParenLocation(SourceLocation L) { RParen = L; }
2138 
2139 public:
2140   TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
2141 
2142   const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2143 
2144   static SYCLUniqueStableNameExpr *
2145   Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2146          SourceLocation RParen, TypeSourceInfo *TSI);
2147 
2148   static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
2149 
2150   SourceLocation getBeginLoc() const { return getLocation(); }
2151   SourceLocation getEndLoc() const { return RParen; }
2152   SourceLocation getLocation() const { return OpLoc; }
2153   SourceLocation getLParenLocation() const { return LParen; }
2154   SourceLocation getRParenLocation() const { return RParen; }
2155 
2156   static bool classof(const Stmt *T) {
2157     return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2158   }
2159 
2160   // Iterators
2161   child_range children() {
2162     return child_range(child_iterator(), child_iterator());
2163   }
2164 
2165   const_child_range children() const {
2166     return const_child_range(const_child_iterator(), const_child_iterator());
2167   }
2168 
2169   // Convenience function to generate the name of the currently stored type.
2170   std::string ComputeName(ASTContext &Context) const;
2171 
2172   // Get the generated name of the type.  Note that this only works after all
2173   // kernels have been instantiated.
2174   static std::string ComputeName(ASTContext &Context, QualType Ty);
2175 };
2176 
2177 /// ParenExpr - This represents a parenthesized expression, e.g. "(1)".  This
2178 /// AST node is only formed if full location information is requested.
2179 class ParenExpr : public Expr {
2180   SourceLocation L, R;
2181   Stmt *Val;
2182 
2183 public:
2184   ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2185       : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2186              val->getObjectKind()),
2187         L(l), R(r), Val(val) {
2188     ParenExprBits.ProducedByFoldExpansion = false;
2189     setDependence(computeDependence(this));
2190   }
2191 
2192   /// Construct an empty parenthesized expression.
2193   explicit ParenExpr(EmptyShell Empty)
2194     : Expr(ParenExprClass, Empty) { }
2195 
2196   const Expr *getSubExpr() const { return cast<Expr>(Val); }
2197   Expr *getSubExpr() { return cast<Expr>(Val); }
2198   void setSubExpr(Expr *E) { Val = E; }
2199 
2200   SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
2201   SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2202 
2203   /// Get the location of the left parentheses '('.
2204   SourceLocation getLParen() const { return L; }
2205   void setLParen(SourceLocation Loc) { L = Loc; }
2206 
2207   /// Get the location of the right parentheses ')'.
2208   SourceLocation getRParen() const { return R; }
2209   void setRParen(SourceLocation Loc) { R = Loc; }
2210 
2211   static bool classof(const Stmt *T) {
2212     return T->getStmtClass() == ParenExprClass;
2213   }
2214 
2215   // Iterators
2216   child_range children() { return child_range(&Val, &Val+1); }
2217   const_child_range children() const {
2218     return const_child_range(&Val, &Val + 1);
2219   }
2220 
2221   bool isProducedByFoldExpansion() const {
2222     return ParenExprBits.ProducedByFoldExpansion != 0;
2223   }
2224   void setIsProducedByFoldExpansion(bool ProducedByFoldExpansion = true) {
2225     ParenExprBits.ProducedByFoldExpansion = ProducedByFoldExpansion;
2226   }
2227 };
2228 
2229 /// UnaryOperator - This represents the unary-expression's (except sizeof and
2230 /// alignof), the postinc/postdec operators from postfix-expression, and various
2231 /// extensions.
2232 ///
2233 /// Notes on various nodes:
2234 ///
2235 /// Real/Imag - These return the real/imag part of a complex operand.  If
2236 ///   applied to a non-complex value, the former returns its operand and the
2237 ///   later returns zero in the type of the operand.
2238 ///
2239 class UnaryOperator final
2240     : public Expr,
2241       private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2242   Stmt *Val;
2243 
2244   size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2245     return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2246   }
2247 
2248   FPOptionsOverride &getTrailingFPFeatures() {
2249     assert(UnaryOperatorBits.HasFPFeatures);
2250     return *getTrailingObjects<FPOptionsOverride>();
2251   }
2252 
2253   const FPOptionsOverride &getTrailingFPFeatures() const {
2254     assert(UnaryOperatorBits.HasFPFeatures);
2255     return *getTrailingObjects<FPOptionsOverride>();
2256   }
2257 
2258 public:
2259   typedef UnaryOperatorKind Opcode;
2260 
2261 protected:
2262   UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2263                 ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2264                 bool CanOverflow, FPOptionsOverride FPFeatures);
2265 
2266   /// Build an empty unary operator.
2267   explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2268       : Expr(UnaryOperatorClass, Empty) {
2269     UnaryOperatorBits.Opc = UO_AddrOf;
2270     UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2271   }
2272 
2273 public:
2274   static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2275 
2276   static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2277                                QualType type, ExprValueKind VK,
2278                                ExprObjectKind OK, SourceLocation l,
2279                                bool CanOverflow, FPOptionsOverride FPFeatures);
2280 
2281   Opcode getOpcode() const {
2282     return static_cast<Opcode>(UnaryOperatorBits.Opc);
2283   }
2284   void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2285 
2286   Expr *getSubExpr() const { return cast<Expr>(Val); }
2287   void setSubExpr(Expr *E) { Val = E; }
2288 
2289   /// getOperatorLoc - Return the location of the operator.
2290   SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2291   void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2292 
2293   /// Returns true if the unary operator can cause an overflow. For instance,
2294   ///   signed int i = INT_MAX; i++;
2295   ///   signed char c = CHAR_MAX; c++;
2296   /// Due to integer promotions, c++ is promoted to an int before the postfix
2297   /// increment, and the result is an int that cannot overflow. However, i++
2298   /// can overflow.
2299   bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2300   void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2301 
2302   /// Get the FP contractibility status of this operator. Only meaningful for
2303   /// operations on floating point types.
2304   bool isFPContractableWithinStatement(const LangOptions &LO) const {
2305     return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2306   }
2307 
2308   /// Get the FENV_ACCESS status of this operator. Only meaningful for
2309   /// operations on floating point types.
2310   bool isFEnvAccessOn(const LangOptions &LO) const {
2311     return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2312   }
2313 
2314   /// isPostfix - Return true if this is a postfix operation, like x++.
2315   static bool isPostfix(Opcode Op) {
2316     return Op == UO_PostInc || Op == UO_PostDec;
2317   }
2318 
2319   /// isPrefix - Return true if this is a prefix operation, like --x.
2320   static bool isPrefix(Opcode Op) {
2321     return Op == UO_PreInc || Op == UO_PreDec;
2322   }
2323 
2324   bool isPrefix() const { return isPrefix(getOpcode()); }
2325   bool isPostfix() const { return isPostfix(getOpcode()); }
2326 
2327   static bool isIncrementOp(Opcode Op) {
2328     return Op == UO_PreInc || Op == UO_PostInc;
2329   }
2330   bool isIncrementOp() const {
2331     return isIncrementOp(getOpcode());
2332   }
2333 
2334   static bool isDecrementOp(Opcode Op) {
2335     return Op == UO_PreDec || Op == UO_PostDec;
2336   }
2337   bool isDecrementOp() const {
2338     return isDecrementOp(getOpcode());
2339   }
2340 
2341   static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2342   bool isIncrementDecrementOp() const {
2343     return isIncrementDecrementOp(getOpcode());
2344   }
2345 
2346   static bool isArithmeticOp(Opcode Op) {
2347     return Op >= UO_Plus && Op <= UO_LNot;
2348   }
2349   bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2350 
2351   /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2352   /// corresponds to, e.g. "sizeof" or "[pre]++"
2353   static StringRef getOpcodeStr(Opcode Op);
2354 
2355   /// Retrieve the unary opcode that corresponds to the given
2356   /// overloaded operator.
2357   static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2358 
2359   /// Retrieve the overloaded operator kind that corresponds to
2360   /// the given unary opcode.
2361   static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2362 
2363   SourceLocation getBeginLoc() const LLVM_READONLY {
2364     return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2365   }
2366   SourceLocation getEndLoc() const LLVM_READONLY {
2367     return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2368   }
2369   SourceLocation getExprLoc() const { return getOperatorLoc(); }
2370 
2371   static bool classof(const Stmt *T) {
2372     return T->getStmtClass() == UnaryOperatorClass;
2373   }
2374 
2375   // Iterators
2376   child_range children() { return child_range(&Val, &Val+1); }
2377   const_child_range children() const {
2378     return const_child_range(&Val, &Val + 1);
2379   }
2380 
2381   /// Is FPFeatures in Trailing Storage?
2382   bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2383 
2384   /// Get FPFeatures from trailing storage.
2385   FPOptionsOverride getStoredFPFeatures() const {
2386     return getTrailingFPFeatures();
2387   }
2388 
2389   /// Get the store FPOptionsOverride or default if not stored.
2390   FPOptionsOverride getStoredFPFeaturesOrDefault() const {
2391     return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
2392   }
2393 
2394 protected:
2395   /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
2396   void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2397 
2398 public:
2399   /// Get the FP features status of this operator. Only meaningful for
2400   /// operations on floating point types.
2401   FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2402     if (UnaryOperatorBits.HasFPFeatures)
2403       return getStoredFPFeatures().applyOverrides(LO);
2404     return FPOptions::defaultWithoutTrailingStorage(LO);
2405   }
2406   FPOptionsOverride getFPOptionsOverride() const {
2407     if (UnaryOperatorBits.HasFPFeatures)
2408       return getStoredFPFeatures();
2409     return FPOptionsOverride();
2410   }
2411 
2412   friend TrailingObjects;
2413   friend class ASTNodeImporter;
2414   friend class ASTReader;
2415   friend class ASTStmtReader;
2416   friend class ASTStmtWriter;
2417 };
2418 
2419 /// Helper class for OffsetOfExpr.
2420 
2421 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
2422 class OffsetOfNode {
2423 public:
2424   /// The kind of offsetof node we have.
2425   enum Kind {
2426     /// An index into an array.
2427     Array = 0x00,
2428     /// A field.
2429     Field = 0x01,
2430     /// A field in a dependent type, known only by its name.
2431     Identifier = 0x02,
2432     /// An implicit indirection through a C++ base class, when the
2433     /// field found is in a base class.
2434     Base = 0x03
2435   };
2436 
2437 private:
2438   enum { MaskBits = 2, Mask = 0x03 };
2439 
2440   /// The source range that covers this part of the designator.
2441   SourceRange Range;
2442 
2443   /// The data describing the designator, which comes in three
2444   /// different forms, depending on the lower two bits.
2445   ///   - An unsigned index into the array of Expr*'s stored after this node
2446   ///     in memory, for [constant-expression] designators.
2447   ///   - A FieldDecl*, for references to a known field.
2448   ///   - An IdentifierInfo*, for references to a field with a given name
2449   ///     when the class type is dependent.
2450   ///   - A CXXBaseSpecifier*, for references that look at a field in a
2451   ///     base class.
2452   uintptr_t Data;
2453 
2454 public:
2455   /// Create an offsetof node that refers to an array element.
2456   OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2457                SourceLocation RBracketLoc)
2458       : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2459 
2460   /// Create an offsetof node that refers to a field.
2461   OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2462       : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2463         Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2464 
2465   /// Create an offsetof node that refers to an identifier.
2466   OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2467                SourceLocation NameLoc)
2468       : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2469         Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2470 
2471   /// Create an offsetof node that refers into a C++ base class.
2472   explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2473       : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2474 
2475   /// Determine what kind of offsetof node this is.
2476   Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2477 
2478   /// For an array element node, returns the index into the array
2479   /// of expressions.
2480   unsigned getArrayExprIndex() const {
2481     assert(getKind() == Array);
2482     return Data >> 2;
2483   }
2484 
2485   /// For a field offsetof node, returns the field.
2486   FieldDecl *getField() const {
2487     assert(getKind() == Field);
2488     return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2489   }
2490 
2491   /// For a field or identifier offsetof node, returns the name of
2492   /// the field.
2493   IdentifierInfo *getFieldName() const;
2494 
2495   /// For a base class node, returns the base specifier.
2496   CXXBaseSpecifier *getBase() const {
2497     assert(getKind() == Base);
2498     return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2499   }
2500 
2501   /// Retrieve the source range that covers this offsetof node.
2502   ///
2503   /// For an array element node, the source range contains the locations of
2504   /// the square brackets. For a field or identifier node, the source range
2505   /// contains the location of the period (if there is one) and the
2506   /// identifier.
2507   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2508   SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2509   SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2510 };
2511 
2512 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2513 /// offsetof(record-type, member-designator). For example, given:
2514 /// @code
2515 /// struct S {
2516 ///   float f;
2517 ///   double d;
2518 /// };
2519 /// struct T {
2520 ///   int i;
2521 ///   struct S s[10];
2522 /// };
2523 /// @endcode
2524 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2525 
2526 class OffsetOfExpr final
2527     : public Expr,
2528       private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2529   SourceLocation OperatorLoc, RParenLoc;
2530   // Base type;
2531   TypeSourceInfo *TSInfo;
2532   // Number of sub-components (i.e. instances of OffsetOfNode).
2533   unsigned NumComps;
2534   // Number of sub-expressions (i.e. array subscript expressions).
2535   unsigned NumExprs;
2536 
2537   size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2538     return NumComps;
2539   }
2540 
2541   OffsetOfExpr(const ASTContext &C, QualType type,
2542                SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2543                ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2544                SourceLocation RParenLoc);
2545 
2546   explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2547     : Expr(OffsetOfExprClass, EmptyShell()),
2548       TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2549 
2550 public:
2551 
2552   static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2553                               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2554                               ArrayRef<OffsetOfNode> comps,
2555                               ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2556 
2557   static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2558                                    unsigned NumComps, unsigned NumExprs);
2559 
2560   /// getOperatorLoc - Return the location of the operator.
2561   SourceLocation getOperatorLoc() const { return OperatorLoc; }
2562   void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2563 
2564   /// Return the location of the right parentheses.
2565   SourceLocation getRParenLoc() const { return RParenLoc; }
2566   void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2567 
2568   TypeSourceInfo *getTypeSourceInfo() const {
2569     return TSInfo;
2570   }
2571   void setTypeSourceInfo(TypeSourceInfo *tsi) {
2572     TSInfo = tsi;
2573   }
2574 
2575   const OffsetOfNode &getComponent(unsigned Idx) const {
2576     assert(Idx < NumComps && "Subscript out of range");
2577     return getTrailingObjects<OffsetOfNode>()[Idx];
2578   }
2579 
2580   void setComponent(unsigned Idx, OffsetOfNode ON) {
2581     assert(Idx < NumComps && "Subscript out of range");
2582     getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2583   }
2584 
2585   unsigned getNumComponents() const {
2586     return NumComps;
2587   }
2588 
2589   Expr* getIndexExpr(unsigned Idx) {
2590     assert(Idx < NumExprs && "Subscript out of range");
2591     return getTrailingObjects<Expr *>()[Idx];
2592   }
2593 
2594   const Expr *getIndexExpr(unsigned Idx) const {
2595     assert(Idx < NumExprs && "Subscript out of range");
2596     return getTrailingObjects<Expr *>()[Idx];
2597   }
2598 
2599   void setIndexExpr(unsigned Idx, Expr* E) {
2600     assert(Idx < NumComps && "Subscript out of range");
2601     getTrailingObjects<Expr *>()[Idx] = E;
2602   }
2603 
2604   unsigned getNumExpressions() const {
2605     return NumExprs;
2606   }
2607 
2608   SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2609   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2610 
2611   static bool classof(const Stmt *T) {
2612     return T->getStmtClass() == OffsetOfExprClass;
2613   }
2614 
2615   // Iterators
2616   child_range children() {
2617     Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2618     return child_range(begin, begin + NumExprs);
2619   }
2620   const_child_range children() const {
2621     Stmt *const *begin =
2622         reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2623     return const_child_range(begin, begin + NumExprs);
2624   }
2625   friend TrailingObjects;
2626 };
2627 
2628 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2629 /// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
2630 /// vec_step (OpenCL 1.1 6.11.12).
2631 class UnaryExprOrTypeTraitExpr : public Expr {
2632   union {
2633     TypeSourceInfo *Ty;
2634     Stmt *Ex;
2635   } Argument;
2636   SourceLocation OpLoc, RParenLoc;
2637 
2638 public:
2639   UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2640                            QualType resultType, SourceLocation op,
2641                            SourceLocation rp)
2642       : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2643              OK_Ordinary),
2644         OpLoc(op), RParenLoc(rp) {
2645     assert(ExprKind <= UETT_Last && "invalid enum value!");
2646     UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2647     assert(static_cast<unsigned>(ExprKind) ==
2648                UnaryExprOrTypeTraitExprBits.Kind &&
2649            "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2650     UnaryExprOrTypeTraitExprBits.IsType = true;
2651     Argument.Ty = TInfo;
2652     setDependence(computeDependence(this));
2653   }
2654 
2655   UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2656                            QualType resultType, SourceLocation op,
2657                            SourceLocation rp);
2658 
2659   /// Construct an empty sizeof/alignof expression.
2660   explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2661     : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2662 
2663   UnaryExprOrTypeTrait getKind() const {
2664     return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2665   }
2666   void setKind(UnaryExprOrTypeTrait K) {
2667     assert(K <= UETT_Last && "invalid enum value!");
2668     UnaryExprOrTypeTraitExprBits.Kind = K;
2669     assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2670            "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2671   }
2672 
2673   bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2674   QualType getArgumentType() const {
2675     return getArgumentTypeInfo()->getType();
2676   }
2677   TypeSourceInfo *getArgumentTypeInfo() const {
2678     assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2679     return Argument.Ty;
2680   }
2681   Expr *getArgumentExpr() {
2682     assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2683     return static_cast<Expr*>(Argument.Ex);
2684   }
2685   const Expr *getArgumentExpr() const {
2686     return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2687   }
2688 
2689   void setArgument(Expr *E) {
2690     Argument.Ex = E;
2691     UnaryExprOrTypeTraitExprBits.IsType = false;
2692   }
2693   void setArgument(TypeSourceInfo *TInfo) {
2694     Argument.Ty = TInfo;
2695     UnaryExprOrTypeTraitExprBits.IsType = true;
2696   }
2697 
2698   /// Gets the argument type, or the type of the argument expression, whichever
2699   /// is appropriate.
2700   QualType getTypeOfArgument() const {
2701     return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2702   }
2703 
2704   SourceLocation getOperatorLoc() const { return OpLoc; }
2705   void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2706 
2707   SourceLocation getRParenLoc() const { return RParenLoc; }
2708   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2709 
2710   SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2711   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2712 
2713   static bool classof(const Stmt *T) {
2714     return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2715   }
2716 
2717   // Iterators
2718   child_range children();
2719   const_child_range children() const;
2720 };
2721 
2722 //===----------------------------------------------------------------------===//
2723 // Postfix Operators.
2724 //===----------------------------------------------------------------------===//
2725 
2726 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2727 class ArraySubscriptExpr : public Expr {
2728   enum { LHS, RHS, END_EXPR };
2729   Stmt *SubExprs[END_EXPR];
2730 
2731   bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2732 
2733 public:
2734   ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2735                      ExprObjectKind OK, SourceLocation rbracketloc)
2736       : Expr(ArraySubscriptExprClass, t, VK, OK) {
2737     SubExprs[LHS] = lhs;
2738     SubExprs[RHS] = rhs;
2739     ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2740     setDependence(computeDependence(this));
2741   }
2742 
2743   /// Create an empty array subscript expression.
2744   explicit ArraySubscriptExpr(EmptyShell Shell)
2745     : Expr(ArraySubscriptExprClass, Shell) { }
2746 
2747   /// An array access can be written A[4] or 4[A] (both are equivalent).
2748   /// - getBase() and getIdx() always present the normalized view: A[4].
2749   ///    In this case getBase() returns "A" and getIdx() returns "4".
2750   /// - getLHS() and getRHS() present the syntactic view. e.g. for
2751   ///    4[A] getLHS() returns "4".
2752   /// Note: Because vector element access is also written A[4] we must
2753   /// predicate the format conversion in getBase and getIdx only on the
2754   /// the type of the RHS, as it is possible for the LHS to be a vector of
2755   /// integer type
2756   Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2757   const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2758   void setLHS(Expr *E) { SubExprs[LHS] = E; }
2759 
2760   Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2761   const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2762   void setRHS(Expr *E) { SubExprs[RHS] = E; }
2763 
2764   Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2765   const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2766 
2767   Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2768   const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2769 
2770   SourceLocation getBeginLoc() const LLVM_READONLY {
2771     return getLHS()->getBeginLoc();
2772   }
2773   SourceLocation getEndLoc() const { return getRBracketLoc(); }
2774 
2775   SourceLocation getRBracketLoc() const {
2776     return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2777   }
2778   void setRBracketLoc(SourceLocation L) {
2779     ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2780   }
2781 
2782   SourceLocation getExprLoc() const LLVM_READONLY {
2783     return getBase()->getExprLoc();
2784   }
2785 
2786   static bool classof(const Stmt *T) {
2787     return T->getStmtClass() == ArraySubscriptExprClass;
2788   }
2789 
2790   // Iterators
2791   child_range children() {
2792     return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2793   }
2794   const_child_range children() const {
2795     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2796   }
2797 };
2798 
2799 /// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2800 /// extension.
2801 /// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2802 /// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2803 /// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2804 /// exist during the initial construction of the AST.
2805 class MatrixSubscriptExpr : public Expr {
2806   enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2807   Stmt *SubExprs[END_EXPR];
2808 
2809 public:
2810   MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2811                       SourceLocation RBracketLoc)
2812       : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2813              OK_MatrixComponent) {
2814     SubExprs[BASE] = Base;
2815     SubExprs[ROW_IDX] = RowIdx;
2816     SubExprs[COLUMN_IDX] = ColumnIdx;
2817     ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2818     setDependence(computeDependence(this));
2819   }
2820 
2821   /// Create an empty matrix subscript expression.
2822   explicit MatrixSubscriptExpr(EmptyShell Shell)
2823       : Expr(MatrixSubscriptExprClass, Shell) {}
2824 
2825   bool isIncomplete() const {
2826     bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2827     assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2828            "expressions without column index must be marked as incomplete");
2829     return IsIncomplete;
2830   }
2831   Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
2832   const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
2833   void setBase(Expr *E) { SubExprs[BASE] = E; }
2834 
2835   Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
2836   const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
2837   void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2838 
2839   Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
2840   const Expr *getColumnIdx() const {
2841     assert(!isIncomplete() &&
2842            "cannot get the column index of an incomplete expression");
2843     return cast<Expr>(SubExprs[COLUMN_IDX]);
2844   }
2845   void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2846 
2847   SourceLocation getBeginLoc() const LLVM_READONLY {
2848     return getBase()->getBeginLoc();
2849   }
2850 
2851   SourceLocation getEndLoc() const { return getRBracketLoc(); }
2852 
2853   SourceLocation getExprLoc() const LLVM_READONLY {
2854     return getBase()->getExprLoc();
2855   }
2856 
2857   SourceLocation getRBracketLoc() const {
2858     return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2859   }
2860   void setRBracketLoc(SourceLocation L) {
2861     ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2862   }
2863 
2864   static bool classof(const Stmt *T) {
2865     return T->getStmtClass() == MatrixSubscriptExprClass;
2866   }
2867 
2868   // Iterators
2869   child_range children() {
2870     return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2871   }
2872   const_child_range children() const {
2873     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2874   }
2875 };
2876 
2877 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2878 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2879 /// while its subclasses may represent alternative syntax that (semantically)
2880 /// results in a function call. For example, CXXOperatorCallExpr is
2881 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2882 /// "str1 + str2" to resolve to a function call.
2883 class CallExpr : public Expr {
2884   enum { FN = 0, PREARGS_START = 1 };
2885 
2886   /// The number of arguments in the call expression.
2887   unsigned NumArgs;
2888 
2889   /// The location of the right parentheses. This has a different meaning for
2890   /// the derived classes of CallExpr.
2891   SourceLocation RParenLoc;
2892 
2893   // CallExpr store some data in trailing objects. However since CallExpr
2894   // is used a base of other expression classes we cannot use
2895   // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2896   // and casts.
2897   //
2898   // The trailing objects are in order:
2899   //
2900   // * A single "Stmt *" for the callee expression.
2901   //
2902   // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2903   //
2904   // * An array of getNumArgs() "Stmt *" for the argument expressions.
2905   //
2906   // * An optional of type FPOptionsOverride.
2907   //
2908   // Note that we store the offset in bytes from the this pointer to the start
2909   // of the trailing objects. It would be perfectly possible to compute it
2910   // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2911   // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2912   // compute this once and then load the offset from the bit-fields of Stmt,
2913   // instead of re-computing the offset each time the trailing objects are
2914   // accessed.
2915 
2916   /// Return a pointer to the start of the trailing array of "Stmt *".
2917   Stmt **getTrailingStmts() {
2918     return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2919                                      CallExprBits.OffsetToTrailingObjects);
2920   }
2921   Stmt *const *getTrailingStmts() const {
2922     return const_cast<CallExpr *>(this)->getTrailingStmts();
2923   }
2924 
2925   /// Map a statement class to the appropriate offset in bytes from the
2926   /// this pointer to the trailing objects.
2927   static unsigned offsetToTrailingObjects(StmtClass SC);
2928 
2929   unsigned getSizeOfTrailingStmts() const {
2930     return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2931   }
2932 
2933   size_t getOffsetOfTrailingFPFeatures() const {
2934     assert(hasStoredFPFeatures());
2935     return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2936   }
2937 
2938 public:
2939   enum class ADLCallKind : bool { NotADL, UsesADL };
2940   static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2941   static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2942 
2943 protected:
2944   /// Build a call expression, assuming that appropriate storage has been
2945   /// allocated for the trailing objects.
2946   CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2947            ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2948            SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2949            unsigned MinNumArgs, ADLCallKind UsesADL);
2950 
2951   /// Build an empty call expression, for deserialization.
2952   CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2953            bool hasFPFeatures, EmptyShell Empty);
2954 
2955   /// Return the size in bytes needed for the trailing objects.
2956   /// Used by the derived classes to allocate the right amount of storage.
2957   static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2958                                         bool HasFPFeatures) {
2959     return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2960            HasFPFeatures * sizeof(FPOptionsOverride);
2961   }
2962 
2963   Stmt *getPreArg(unsigned I) {
2964     assert(I < getNumPreArgs() && "Prearg access out of range!");
2965     return getTrailingStmts()[PREARGS_START + I];
2966   }
2967   const Stmt *getPreArg(unsigned I) const {
2968     assert(I < getNumPreArgs() && "Prearg access out of range!");
2969     return getTrailingStmts()[PREARGS_START + I];
2970   }
2971   void setPreArg(unsigned I, Stmt *PreArg) {
2972     assert(I < getNumPreArgs() && "Prearg access out of range!");
2973     getTrailingStmts()[PREARGS_START + I] = PreArg;
2974   }
2975 
2976   unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2977 
2978   /// Return a pointer to the trailing FPOptions
2979   FPOptionsOverride *getTrailingFPFeatures() {
2980     assert(hasStoredFPFeatures());
2981     return reinterpret_cast<FPOptionsOverride *>(
2982         reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2983         getSizeOfTrailingStmts());
2984   }
2985   const FPOptionsOverride *getTrailingFPFeatures() const {
2986     assert(hasStoredFPFeatures());
2987     return reinterpret_cast<const FPOptionsOverride *>(
2988         reinterpret_cast<const char *>(this) +
2989         CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2990   }
2991 
2992 public:
2993   /// Create a call expression.
2994   /// \param Fn     The callee expression,
2995   /// \param Args   The argument array,
2996   /// \param Ty     The type of the call expression (which is *not* the return
2997   ///               type in general),
2998   /// \param VK     The value kind of the call expression (lvalue, rvalue, ...),
2999   /// \param RParenLoc  The location of the right parenthesis in the call
3000   ///                   expression.
3001   /// \param FPFeatures Floating-point features associated with the call,
3002   /// \param MinNumArgs Specifies the minimum number of arguments. The actual
3003   ///                   number of arguments will be the greater of Args.size()
3004   ///                   and MinNumArgs. This is used in a few places to allocate
3005   ///                   enough storage for the default arguments.
3006   /// \param UsesADL    Specifies whether the callee was found through
3007   ///                   argument-dependent lookup.
3008   ///
3009   /// Note that you can use CreateTemporary if you need a temporary call
3010   /// expression on the stack.
3011   static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
3012                           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
3013                           SourceLocation RParenLoc,
3014                           FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
3015                           ADLCallKind UsesADL = NotADL);
3016 
3017   /// Create a temporary call expression with no arguments in the memory
3018   /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
3019   /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
3020   ///
3021   /// \code{.cpp}
3022   ///   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
3023   ///   CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
3024   /// \endcode
3025   static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
3026                                    ExprValueKind VK, SourceLocation RParenLoc,
3027                                    ADLCallKind UsesADL = NotADL);
3028 
3029   /// Create an empty call expression, for deserialization.
3030   static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
3031                                bool HasFPFeatures, EmptyShell Empty);
3032 
3033   Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
3034   const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
3035   void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
3036 
3037   ADLCallKind getADLCallKind() const {
3038     return static_cast<ADLCallKind>(CallExprBits.UsesADL);
3039   }
3040   void setADLCallKind(ADLCallKind V = UsesADL) {
3041     CallExprBits.UsesADL = static_cast<bool>(V);
3042   }
3043   bool usesADL() const { return getADLCallKind() == UsesADL; }
3044 
3045   bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
3046 
3047   bool isCoroElideSafe() const { return CallExprBits.IsCoroElideSafe; }
3048   void setCoroElideSafe(bool V = true) { CallExprBits.IsCoroElideSafe = V; }
3049 
3050   Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
3051   const Decl *getCalleeDecl() const {
3052     return getCallee()->getReferencedDeclOfCallee();
3053   }
3054 
3055   /// If the callee is a FunctionDecl, return it. Otherwise return null.
3056   FunctionDecl *getDirectCallee() {
3057     return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
3058   }
3059   const FunctionDecl *getDirectCallee() const {
3060     return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
3061   }
3062 
3063   /// getNumArgs - Return the number of actual arguments to this call.
3064   unsigned getNumArgs() const { return NumArgs; }
3065 
3066   /// Retrieve the call arguments.
3067   Expr **getArgs() {
3068     return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
3069                                      getNumPreArgs());
3070   }
3071   const Expr *const *getArgs() const {
3072     return reinterpret_cast<const Expr *const *>(
3073         getTrailingStmts() + PREARGS_START + getNumPreArgs());
3074   }
3075 
3076   /// getArg - Return the specified argument.
3077   Expr *getArg(unsigned Arg) {
3078     assert(Arg < getNumArgs() && "Arg access out of range!");
3079     return getArgs()[Arg];
3080   }
3081   const Expr *getArg(unsigned Arg) const {
3082     assert(Arg < getNumArgs() && "Arg access out of range!");
3083     return getArgs()[Arg];
3084   }
3085 
3086   /// setArg - Set the specified argument.
3087   /// ! the dependence bits might be stale after calling this setter, it is
3088   /// *caller*'s responsibility to recompute them by calling
3089   /// computeDependence().
3090   void setArg(unsigned Arg, Expr *ArgExpr) {
3091     assert(Arg < getNumArgs() && "Arg access out of range!");
3092     getArgs()[Arg] = ArgExpr;
3093   }
3094 
3095   /// Compute and set dependence bits.
3096   void computeDependence() {
3097     setDependence(clang::computeDependence(
3098         this, llvm::ArrayRef(
3099                   reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3100                   getNumPreArgs())));
3101   }
3102 
3103   /// Reduce the number of arguments in this call expression. This is used for
3104   /// example during error recovery to drop extra arguments. There is no way
3105   /// to perform the opposite because: 1.) We don't track how much storage
3106   /// we have for the argument array 2.) This would potentially require growing
3107   /// the argument array, something we cannot support since the arguments are
3108   /// stored in a trailing array.
3109   void shrinkNumArgs(unsigned NewNumArgs) {
3110     assert((NewNumArgs <= getNumArgs()) &&
3111            "shrinkNumArgs cannot increase the number of arguments!");
3112     NumArgs = NewNumArgs;
3113   }
3114 
3115   /// Bluntly set a new number of arguments without doing any checks whatsoever.
3116   /// Only used during construction of a CallExpr in a few places in Sema.
3117   /// FIXME: Find a way to remove it.
3118   void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3119 
3120   typedef ExprIterator arg_iterator;
3121   typedef ConstExprIterator const_arg_iterator;
3122   typedef llvm::iterator_range<arg_iterator> arg_range;
3123   typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3124 
3125   arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3126   const_arg_range arguments() const {
3127     return const_arg_range(arg_begin(), arg_end());
3128   }
3129 
3130   arg_iterator arg_begin() {
3131     return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3132   }
3133   arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3134 
3135   const_arg_iterator arg_begin() const {
3136     return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3137   }
3138   const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3139 
3140   /// This method provides fast access to all the subexpressions of
3141   /// a CallExpr without going through the slower virtual child_iterator
3142   /// interface.  This provides efficient reverse iteration of the
3143   /// subexpressions.  This is currently used for CFG construction.
3144   ArrayRef<Stmt *> getRawSubExprs() {
3145     return llvm::ArrayRef(getTrailingStmts(),
3146                           PREARGS_START + getNumPreArgs() + getNumArgs());
3147   }
3148 
3149   /// Get FPOptionsOverride from trailing storage.
3150   FPOptionsOverride getStoredFPFeatures() const {
3151     assert(hasStoredFPFeatures());
3152     return *getTrailingFPFeatures();
3153   }
3154   /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3155   void setStoredFPFeatures(FPOptionsOverride F) {
3156     assert(hasStoredFPFeatures());
3157     *getTrailingFPFeatures() = F;
3158   }
3159 
3160   /// Get the store FPOptionsOverride or default if not stored.
3161   FPOptionsOverride getStoredFPFeaturesOrDefault() const {
3162     return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
3163   }
3164 
3165   /// Get the FP features status of this operator. Only meaningful for
3166   /// operations on floating point types.
3167   FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3168     if (hasStoredFPFeatures())
3169       return getStoredFPFeatures().applyOverrides(LO);
3170     return FPOptions::defaultWithoutTrailingStorage(LO);
3171   }
3172 
3173   FPOptionsOverride getFPFeatures() const {
3174     if (hasStoredFPFeatures())
3175       return getStoredFPFeatures();
3176     return FPOptionsOverride();
3177   }
3178 
3179   /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3180   /// of the callee. If not, return 0.
3181   unsigned getBuiltinCallee() const;
3182 
3183   /// Returns \c true if this is a call to a builtin which does not
3184   /// evaluate side-effects within its arguments.
3185   bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3186 
3187   /// getCallReturnType - Get the return type of the call expr. This is not
3188   /// always the type of the expr itself, if the return type is a reference
3189   /// type.
3190   QualType getCallReturnType(const ASTContext &Ctx) const;
3191 
3192   /// Returns the WarnUnusedResultAttr that is either declared on the called
3193   /// function, or its return type declaration, together with a NamedDecl that
3194   /// refers to the declaration the attribute is attached onto.
3195   std::pair<const NamedDecl *, const Attr *>
3196   getUnusedResultAttr(const ASTContext &Ctx) const;
3197 
3198   /// Returns true if this call expression should warn on unused results.
3199   bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3200     return getUnusedResultAttr(Ctx).second != nullptr;
3201   }
3202 
3203   SourceLocation getRParenLoc() const { return RParenLoc; }
3204   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3205 
3206   SourceLocation getBeginLoc() const LLVM_READONLY;
3207   SourceLocation getEndLoc() const LLVM_READONLY;
3208 
3209   /// Return true if this is a call to __assume() or __builtin_assume() with
3210   /// a non-value-dependent constant parameter evaluating as false.
3211   bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3212 
3213   /// Used by Sema to implement MSVC-compatible delayed name lookup.
3214   /// (Usually Exprs themselves should set dependence).
3215   void markDependentForPostponedNameLookup() {
3216     setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3217   }
3218 
3219   bool isCallToStdMove() const;
3220 
3221   static bool classof(const Stmt *T) {
3222     return T->getStmtClass() >= firstCallExprConstant &&
3223            T->getStmtClass() <= lastCallExprConstant;
3224   }
3225 
3226   // Iterators
3227   child_range children() {
3228     return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3229                                                getNumPreArgs() + getNumArgs());
3230   }
3231 
3232   const_child_range children() const {
3233     return const_child_range(getTrailingStmts(),
3234                              getTrailingStmts() + PREARGS_START +
3235                                  getNumPreArgs() + getNumArgs());
3236   }
3237 };
3238 
3239 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
3240 ///
3241 class MemberExpr final
3242     : public Expr,
3243       private llvm::TrailingObjects<MemberExpr, NestedNameSpecifierLoc,
3244                                     DeclAccessPair, ASTTemplateKWAndArgsInfo,
3245                                     TemplateArgumentLoc> {
3246   friend class ASTReader;
3247   friend class ASTStmtReader;
3248   friend class ASTStmtWriter;
3249   friend TrailingObjects;
3250 
3251   /// Base - the expression for the base pointer or structure references.  In
3252   /// X.F, this is "X".
3253   Stmt *Base;
3254 
3255   /// MemberDecl - This is the decl being referenced by the field/member name.
3256   /// In X.F, this is the decl referenced by F.
3257   ValueDecl *MemberDecl;
3258 
3259   /// MemberDNLoc - Provides source/type location info for the
3260   /// declaration name embedded in MemberDecl.
3261   DeclarationNameLoc MemberDNLoc;
3262 
3263   /// MemberLoc - This is the location of the member name.
3264   SourceLocation MemberLoc;
3265 
3266   size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
3267     return hasQualifier();
3268   }
3269 
3270   size_t numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3271     return hasFoundDecl();
3272   }
3273 
3274   size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3275     return hasTemplateKWAndArgsInfo();
3276   }
3277 
3278   bool hasFoundDecl() const { return MemberExprBits.HasFoundDecl; }
3279 
3280   bool hasTemplateKWAndArgsInfo() const {
3281     return MemberExprBits.HasTemplateKWAndArgsInfo;
3282   }
3283 
3284   MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3285              NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3286              ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
3287              const DeclarationNameInfo &NameInfo,
3288              const TemplateArgumentListInfo *TemplateArgs, QualType T,
3289              ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR);
3290   MemberExpr(EmptyShell Empty)
3291       : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3292 
3293 public:
3294   static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3295                             SourceLocation OperatorLoc,
3296                             NestedNameSpecifierLoc QualifierLoc,
3297                             SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3298                             DeclAccessPair FoundDecl,
3299                             DeclarationNameInfo MemberNameInfo,
3300                             const TemplateArgumentListInfo *TemplateArgs,
3301                             QualType T, ExprValueKind VK, ExprObjectKind OK,
3302                             NonOdrUseReason NOUR);
3303 
3304   /// Create an implicit MemberExpr, with no location, qualifier, template
3305   /// arguments, and so on. Suitable only for non-static member access.
3306   static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3307                                     bool IsArrow, ValueDecl *MemberDecl,
3308                                     QualType T, ExprValueKind VK,
3309                                     ExprObjectKind OK) {
3310     return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3311                   SourceLocation(), MemberDecl,
3312                   DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3313                   DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3314   }
3315 
3316   static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3317                                  bool HasFoundDecl,
3318                                  bool HasTemplateKWAndArgsInfo,
3319                                  unsigned NumTemplateArgs);
3320 
3321   void setBase(Expr *E) { Base = E; }
3322   Expr *getBase() const { return cast<Expr>(Base); }
3323 
3324   /// Retrieve the member declaration to which this expression refers.
3325   ///
3326   /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3327   /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3328   ValueDecl *getMemberDecl() const { return MemberDecl; }
3329   void setMemberDecl(ValueDecl *D);
3330 
3331   /// Retrieves the declaration found by lookup.
3332   DeclAccessPair getFoundDecl() const {
3333     if (!hasFoundDecl())
3334       return DeclAccessPair::make(getMemberDecl(),
3335                                   getMemberDecl()->getAccess());
3336     return *getTrailingObjects<DeclAccessPair>();
3337   }
3338 
3339   /// Determines whether this member expression actually had
3340   /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3341   /// x->Base::foo.
3342   bool hasQualifier() const { return MemberExprBits.HasQualifier; }
3343 
3344   /// If the member name was qualified, retrieves the
3345   /// nested-name-specifier that precedes the member name, with source-location
3346   /// information.
3347   NestedNameSpecifierLoc getQualifierLoc() const {
3348     if (!hasQualifier())
3349       return NestedNameSpecifierLoc();
3350     return *getTrailingObjects<NestedNameSpecifierLoc>();
3351   }
3352 
3353   /// If the member name was qualified, retrieves the
3354   /// nested-name-specifier that precedes the member name. Otherwise, returns
3355   /// NULL.
3356   NestedNameSpecifier *getQualifier() const {
3357     return getQualifierLoc().getNestedNameSpecifier();
3358   }
3359 
3360   /// Retrieve the location of the template keyword preceding
3361   /// the member name, if any.
3362   SourceLocation getTemplateKeywordLoc() const {
3363     if (!hasTemplateKWAndArgsInfo())
3364       return SourceLocation();
3365     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3366   }
3367 
3368   /// Retrieve the location of the left angle bracket starting the
3369   /// explicit template argument list following the member name, if any.
3370   SourceLocation getLAngleLoc() const {
3371     if (!hasTemplateKWAndArgsInfo())
3372       return SourceLocation();
3373     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3374   }
3375 
3376   /// Retrieve the location of the right angle bracket ending the
3377   /// explicit template argument list following the member name, if any.
3378   SourceLocation getRAngleLoc() const {
3379     if (!hasTemplateKWAndArgsInfo())
3380       return SourceLocation();
3381     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3382   }
3383 
3384   /// Determines whether the member name was preceded by the template keyword.
3385   bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3386 
3387   /// Determines whether the member name was followed by an
3388   /// explicit template argument list.
3389   bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3390 
3391   /// Copies the template arguments (if present) into the given
3392   /// structure.
3393   void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3394     if (hasExplicitTemplateArgs())
3395       getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3396           getTrailingObjects<TemplateArgumentLoc>(), List);
3397   }
3398 
3399   /// Retrieve the template arguments provided as part of this
3400   /// template-id.
3401   const TemplateArgumentLoc *getTemplateArgs() const {
3402     if (!hasExplicitTemplateArgs())
3403       return nullptr;
3404 
3405     return getTrailingObjects<TemplateArgumentLoc>();
3406   }
3407 
3408   /// Retrieve the number of template arguments provided as part of this
3409   /// template-id.
3410   unsigned getNumTemplateArgs() const {
3411     if (!hasExplicitTemplateArgs())
3412       return 0;
3413 
3414     return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3415   }
3416 
3417   ArrayRef<TemplateArgumentLoc> template_arguments() const {
3418     return {getTemplateArgs(), getNumTemplateArgs()};
3419   }
3420 
3421   /// Retrieve the member declaration name info.
3422   DeclarationNameInfo getMemberNameInfo() const {
3423     return DeclarationNameInfo(MemberDecl->getDeclName(),
3424                                MemberLoc, MemberDNLoc);
3425   }
3426 
3427   SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3428 
3429   bool isArrow() const { return MemberExprBits.IsArrow; }
3430   void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3431 
3432   /// getMemberLoc - Return the location of the "member", in X->F, it is the
3433   /// location of 'F'.
3434   SourceLocation getMemberLoc() const { return MemberLoc; }
3435   void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3436 
3437   SourceLocation getBeginLoc() const LLVM_READONLY;
3438   SourceLocation getEndLoc() const LLVM_READONLY;
3439 
3440   SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3441 
3442   /// Determine whether the base of this explicit is implicit.
3443   bool isImplicitAccess() const {
3444     return getBase() && getBase()->isImplicitCXXThis();
3445   }
3446 
3447   /// Returns true if this member expression refers to a method that
3448   /// was resolved from an overloaded set having size greater than 1.
3449   bool hadMultipleCandidates() const {
3450     return MemberExprBits.HadMultipleCandidates;
3451   }
3452   /// Sets the flag telling whether this expression refers to
3453   /// a method that was resolved from an overloaded set having size
3454   /// greater than 1.
3455   void setHadMultipleCandidates(bool V = true) {
3456     MemberExprBits.HadMultipleCandidates = V;
3457   }
3458 
3459   /// Returns true if virtual dispatch is performed.
3460   /// If the member access is fully qualified, (i.e. X::f()), virtual
3461   /// dispatching is not performed. In -fapple-kext mode qualified
3462   /// calls to virtual method will still go through the vtable.
3463   bool performsVirtualDispatch(const LangOptions &LO) const {
3464     return LO.AppleKext || !hasQualifier();
3465   }
3466 
3467   /// Is this expression a non-odr-use reference, and if so, why?
3468   /// This is only meaningful if the named member is a static member.
3469   NonOdrUseReason isNonOdrUse() const {
3470     return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3471   }
3472 
3473   static bool classof(const Stmt *T) {
3474     return T->getStmtClass() == MemberExprClass;
3475   }
3476 
3477   // Iterators
3478   child_range children() { return child_range(&Base, &Base+1); }
3479   const_child_range children() const {
3480     return const_child_range(&Base, &Base + 1);
3481   }
3482 };
3483 
3484 /// CompoundLiteralExpr - [C99 6.5.2.5]
3485 ///
3486 class CompoundLiteralExpr : public Expr {
3487   /// LParenLoc - If non-null, this is the location of the left paren in a
3488   /// compound literal like "(int){4}".  This can be null if this is a
3489   /// synthesized compound expression.
3490   SourceLocation LParenLoc;
3491 
3492   /// The type as written.  This can be an incomplete array type, in
3493   /// which case the actual expression type will be different.
3494   /// The int part of the pair stores whether this expr is file scope.
3495   llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3496   Stmt *Init;
3497 public:
3498   CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3499                       QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3500       : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3501         LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3502     setDependence(computeDependence(this));
3503   }
3504 
3505   /// Construct an empty compound literal.
3506   explicit CompoundLiteralExpr(EmptyShell Empty)
3507     : Expr(CompoundLiteralExprClass, Empty) { }
3508 
3509   const Expr *getInitializer() const { return cast<Expr>(Init); }
3510   Expr *getInitializer() { return cast<Expr>(Init); }
3511   void setInitializer(Expr *E) { Init = E; }
3512 
3513   bool isFileScope() const { return TInfoAndScope.getInt(); }
3514   void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3515 
3516   SourceLocation getLParenLoc() const { return LParenLoc; }
3517   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3518 
3519   TypeSourceInfo *getTypeSourceInfo() const {
3520     return TInfoAndScope.getPointer();
3521   }
3522   void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3523     TInfoAndScope.setPointer(tinfo);
3524   }
3525 
3526   SourceLocation getBeginLoc() const LLVM_READONLY {
3527     // FIXME: Init should never be null.
3528     if (!Init)
3529       return SourceLocation();
3530     if (LParenLoc.isInvalid())
3531       return Init->getBeginLoc();
3532     return LParenLoc;
3533   }
3534   SourceLocation getEndLoc() const LLVM_READONLY {
3535     // FIXME: Init should never be null.
3536     if (!Init)
3537       return SourceLocation();
3538     return Init->getEndLoc();
3539   }
3540 
3541   static bool classof(const Stmt *T) {
3542     return T->getStmtClass() == CompoundLiteralExprClass;
3543   }
3544 
3545   // Iterators
3546   child_range children() { return child_range(&Init, &Init+1); }
3547   const_child_range children() const {
3548     return const_child_range(&Init, &Init + 1);
3549   }
3550 };
3551 
3552 /// CastExpr - Base class for type casts, including both implicit
3553 /// casts (ImplicitCastExpr) and explicit casts that have some
3554 /// representation in the source code (ExplicitCastExpr's derived
3555 /// classes).
3556 class CastExpr : public Expr {
3557   Stmt *Op;
3558 
3559   bool CastConsistency() const;
3560 
3561   const CXXBaseSpecifier * const *path_buffer() const {
3562     return const_cast<CastExpr*>(this)->path_buffer();
3563   }
3564   CXXBaseSpecifier **path_buffer();
3565 
3566   friend class ASTStmtReader;
3567 
3568 protected:
3569   CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3570            Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3571       : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3572     CastExprBits.Kind = kind;
3573     CastExprBits.PartOfExplicitCast = false;
3574     CastExprBits.BasePathSize = BasePathSize;
3575     assert((CastExprBits.BasePathSize == BasePathSize) &&
3576            "BasePathSize overflow!");
3577     assert(CastConsistency());
3578     CastExprBits.HasFPFeatures = HasFPFeatures;
3579   }
3580 
3581   /// Construct an empty cast.
3582   CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3583            bool HasFPFeatures)
3584       : Expr(SC, Empty) {
3585     CastExprBits.PartOfExplicitCast = false;
3586     CastExprBits.BasePathSize = BasePathSize;
3587     CastExprBits.HasFPFeatures = HasFPFeatures;
3588     assert((CastExprBits.BasePathSize == BasePathSize) &&
3589            "BasePathSize overflow!");
3590   }
3591 
3592   /// Return a pointer to the trailing FPOptions.
3593   /// \pre hasStoredFPFeatures() == true
3594   FPOptionsOverride *getTrailingFPFeatures();
3595   const FPOptionsOverride *getTrailingFPFeatures() const {
3596     return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3597   }
3598 
3599 public:
3600   CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3601   void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3602 
3603   static const char *getCastKindName(CastKind CK);
3604   const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3605 
3606   Expr *getSubExpr() { return cast<Expr>(Op); }
3607   const Expr *getSubExpr() const { return cast<Expr>(Op); }
3608   void setSubExpr(Expr *E) { Op = E; }
3609 
3610   /// Retrieve the cast subexpression as it was written in the source
3611   /// code, looking through any implicit casts or other intermediate nodes
3612   /// introduced by semantic analysis.
3613   Expr *getSubExprAsWritten();
3614   const Expr *getSubExprAsWritten() const {
3615     return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3616   }
3617 
3618   /// If this cast applies a user-defined conversion, retrieve the conversion
3619   /// function that it invokes.
3620   NamedDecl *getConversionFunction() const;
3621 
3622   typedef CXXBaseSpecifier **path_iterator;
3623   typedef const CXXBaseSpecifier *const *path_const_iterator;
3624   bool path_empty() const { return path_size() == 0; }
3625   unsigned path_size() const { return CastExprBits.BasePathSize; }
3626   path_iterator path_begin() { return path_buffer(); }
3627   path_iterator path_end() { return path_buffer() + path_size(); }
3628   path_const_iterator path_begin() const { return path_buffer(); }
3629   path_const_iterator path_end() const { return path_buffer() + path_size(); }
3630 
3631   /// Path through the class hierarchy taken by casts between base and derived
3632   /// classes (see implementation of `CastConsistency()` for a full list of
3633   /// cast kinds that have a path).
3634   ///
3635   /// For each derived-to-base edge in the path, the path contains a
3636   /// `CXXBaseSpecifier` for the base class of that edge; the entries are
3637   /// ordered from derived class to base class.
3638   ///
3639   /// For example, given classes `Base`, `Intermediate : public Base` and
3640   /// `Derived : public Intermediate`, the path for a cast from `Derived *` to
3641   /// `Base *` contains two entries: One for `Intermediate`, and one for `Base`,
3642   /// in that order.
3643   llvm::iterator_range<path_iterator> path() {
3644     return llvm::make_range(path_begin(), path_end());
3645   }
3646   llvm::iterator_range<path_const_iterator> path() const {
3647     return llvm::make_range(path_begin(), path_end());
3648   }
3649 
3650   const FieldDecl *getTargetUnionField() const {
3651     assert(getCastKind() == CK_ToUnion);
3652     return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3653   }
3654 
3655   bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3656 
3657   /// Get FPOptionsOverride from trailing storage.
3658   FPOptionsOverride getStoredFPFeatures() const {
3659     assert(hasStoredFPFeatures());
3660     return *getTrailingFPFeatures();
3661   }
3662 
3663   /// Get the store FPOptionsOverride or default if not stored.
3664   FPOptionsOverride getStoredFPFeaturesOrDefault() const {
3665     return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
3666   }
3667 
3668   /// Get the FP features status of this operation. Only meaningful for
3669   /// operations on floating point types.
3670   FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3671     if (hasStoredFPFeatures())
3672       return getStoredFPFeatures().applyOverrides(LO);
3673     return FPOptions::defaultWithoutTrailingStorage(LO);
3674   }
3675 
3676   FPOptionsOverride getFPFeatures() const {
3677     if (hasStoredFPFeatures())
3678       return getStoredFPFeatures();
3679     return FPOptionsOverride();
3680   }
3681 
3682   /// Return
3683   //  True : if this conversion changes the volatile-ness of a gl-value.
3684   //         Qualification conversions on gl-values currently use CK_NoOp, but
3685   //         it's important to recognize volatile-changing conversions in
3686   //         clients code generation that normally eagerly peephole loads. Note
3687   //         that the query is answering for this specific node; Sema may
3688   //         produce multiple cast nodes for any particular conversion sequence.
3689   //  False : Otherwise.
3690   bool changesVolatileQualification() const {
3691     return (isGLValue() && (getType().isVolatileQualified() !=
3692                             getSubExpr()->getType().isVolatileQualified()));
3693   }
3694 
3695   static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3696                                                        QualType opType);
3697   static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3698                                                        QualType opType);
3699 
3700   static bool classof(const Stmt *T) {
3701     return T->getStmtClass() >= firstCastExprConstant &&
3702            T->getStmtClass() <= lastCastExprConstant;
3703   }
3704 
3705   // Iterators
3706   child_range children() { return child_range(&Op, &Op+1); }
3707   const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3708 };
3709 
3710 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
3711 /// conversions, which have no direct representation in the original
3712 /// source code. For example: converting T[]->T*, void f()->void
3713 /// (*f)(), float->double, short->int, etc.
3714 ///
3715 /// In C, implicit casts always produce rvalues. However, in C++, an
3716 /// implicit cast whose result is being bound to a reference will be
3717 /// an lvalue or xvalue. For example:
3718 ///
3719 /// @code
3720 /// class Base { };
3721 /// class Derived : public Base { };
3722 /// Derived &&ref();
3723 /// void f(Derived d) {
3724 ///   Base& b = d; // initializer is an ImplicitCastExpr
3725 ///                // to an lvalue of type Base
3726 ///   Base&& r = ref(); // initializer is an ImplicitCastExpr
3727 ///                     // to an xvalue of type Base
3728 /// }
3729 /// @endcode
3730 class ImplicitCastExpr final
3731     : public CastExpr,
3732       private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3733                                     FPOptionsOverride> {
3734 
3735   ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3736                    unsigned BasePathLength, FPOptionsOverride FPO,
3737                    ExprValueKind VK)
3738       : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3739                  FPO.requiresTrailingStorage()) {
3740     setDependence(computeDependence(this));
3741     if (hasStoredFPFeatures())
3742       *getTrailingFPFeatures() = FPO;
3743   }
3744 
3745   /// Construct an empty implicit cast.
3746   explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3747                             bool HasFPFeatures)
3748       : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3749 
3750   unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3751     return path_size();
3752   }
3753 
3754 public:
3755   enum OnStack_t { OnStack };
3756   ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3757                    ExprValueKind VK, FPOptionsOverride FPO)
3758       : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3759                  FPO.requiresTrailingStorage()) {
3760     if (hasStoredFPFeatures())
3761       *getTrailingFPFeatures() = FPO;
3762   }
3763 
3764   bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3765   void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3766     CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3767   }
3768 
3769   static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3770                                   CastKind Kind, Expr *Operand,
3771                                   const CXXCastPath *BasePath,
3772                                   ExprValueKind Cat, FPOptionsOverride FPO);
3773 
3774   static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3775                                        unsigned PathSize, bool HasFPFeatures);
3776 
3777   SourceLocation getBeginLoc() const LLVM_READONLY {
3778     return getSubExpr()->getBeginLoc();
3779   }
3780   SourceLocation getEndLoc() const LLVM_READONLY {
3781     return getSubExpr()->getEndLoc();
3782   }
3783 
3784   static bool classof(const Stmt *T) {
3785     return T->getStmtClass() == ImplicitCastExprClass;
3786   }
3787 
3788   friend TrailingObjects;
3789   friend class CastExpr;
3790 };
3791 
3792 /// ExplicitCastExpr - An explicit cast written in the source
3793 /// code.
3794 ///
3795 /// This class is effectively an abstract class, because it provides
3796 /// the basic representation of an explicitly-written cast without
3797 /// specifying which kind of cast (C cast, functional cast, static
3798 /// cast, etc.) was written; specific derived classes represent the
3799 /// particular style of cast and its location information.
3800 ///
3801 /// Unlike implicit casts, explicit cast nodes have two different
3802 /// types: the type that was written into the source code, and the
3803 /// actual type of the expression as determined by semantic
3804 /// analysis. These types may differ slightly. For example, in C++ one
3805 /// can cast to a reference type, which indicates that the resulting
3806 /// expression will be an lvalue or xvalue. The reference type, however,
3807 /// will not be used as the type of the expression.
3808 class ExplicitCastExpr : public CastExpr {
3809   /// TInfo - Source type info for the (written) type
3810   /// this expression is casting to.
3811   TypeSourceInfo *TInfo;
3812 
3813 protected:
3814   ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3815                    CastKind kind, Expr *op, unsigned PathSize,
3816                    bool HasFPFeatures, TypeSourceInfo *writtenTy)
3817       : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3818         TInfo(writtenTy) {
3819     setDependence(computeDependence(this));
3820   }
3821 
3822   /// Construct an empty explicit cast.
3823   ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3824                    bool HasFPFeatures)
3825       : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3826 
3827 public:
3828   /// getTypeInfoAsWritten - Returns the type source info for the type
3829   /// that this expression is casting to.
3830   TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3831   void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3832 
3833   /// getTypeAsWritten - Returns the type that this expression is
3834   /// casting to, as written in the source code.
3835   QualType getTypeAsWritten() const { return TInfo->getType(); }
3836 
3837   static bool classof(const Stmt *T) {
3838      return T->getStmtClass() >= firstExplicitCastExprConstant &&
3839             T->getStmtClass() <= lastExplicitCastExprConstant;
3840   }
3841 };
3842 
3843 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3844 /// cast in C++ (C++ [expr.cast]), which uses the syntax
3845 /// (Type)expr. For example: @c (int)f.
3846 class CStyleCastExpr final
3847     : public ExplicitCastExpr,
3848       private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3849                                     FPOptionsOverride> {
3850   SourceLocation LPLoc; // the location of the left paren
3851   SourceLocation RPLoc; // the location of the right paren
3852 
3853   CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3854                  unsigned PathSize, FPOptionsOverride FPO,
3855                  TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3856       : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3857                          FPO.requiresTrailingStorage(), writtenTy),
3858         LPLoc(l), RPLoc(r) {
3859     if (hasStoredFPFeatures())
3860       *getTrailingFPFeatures() = FPO;
3861   }
3862 
3863   /// Construct an empty C-style explicit cast.
3864   explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3865                           bool HasFPFeatures)
3866       : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3867 
3868   unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3869     return path_size();
3870   }
3871 
3872 public:
3873   static CStyleCastExpr *
3874   Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3875          Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3876          TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3877 
3878   static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3879                                      unsigned PathSize, bool HasFPFeatures);
3880 
3881   SourceLocation getLParenLoc() const { return LPLoc; }
3882   void setLParenLoc(SourceLocation L) { LPLoc = L; }
3883 
3884   SourceLocation getRParenLoc() const { return RPLoc; }
3885   void setRParenLoc(SourceLocation L) { RPLoc = L; }
3886 
3887   SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3888   SourceLocation getEndLoc() const LLVM_READONLY {
3889     return getSubExpr()->getEndLoc();
3890   }
3891 
3892   static bool classof(const Stmt *T) {
3893     return T->getStmtClass() == CStyleCastExprClass;
3894   }
3895 
3896   friend TrailingObjects;
3897   friend class CastExpr;
3898 };
3899 
3900 /// A builtin binary operation expression such as "x + y" or "x <= y".
3901 ///
3902 /// This expression node kind describes a builtin binary operation,
3903 /// such as "x + y" for integer values "x" and "y". The operands will
3904 /// already have been converted to appropriate types (e.g., by
3905 /// performing promotions or conversions).
3906 ///
3907 /// In C++, where operators may be overloaded, a different kind of
3908 /// expression node (CXXOperatorCallExpr) is used to express the
3909 /// invocation of an overloaded operator with operator syntax. Within
3910 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3911 /// used to store an expression "x + y" depends on the subexpressions
3912 /// for x and y. If neither x or y is type-dependent, and the "+"
3913 /// operator resolves to a built-in operation, BinaryOperator will be
3914 /// used to express the computation (x and y may still be
3915 /// value-dependent). If either x or y is type-dependent, or if the
3916 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3917 /// be used to express the computation.
3918 class BinaryOperator : public Expr {
3919   enum { LHS, RHS, END_EXPR };
3920   Stmt *SubExprs[END_EXPR];
3921 
3922 public:
3923   typedef BinaryOperatorKind Opcode;
3924 
3925 protected:
3926   size_t offsetOfTrailingStorage() const;
3927 
3928   /// Return a pointer to the trailing FPOptions
3929   FPOptionsOverride *getTrailingFPFeatures() {
3930     assert(BinaryOperatorBits.HasFPFeatures);
3931     return reinterpret_cast<FPOptionsOverride *>(
3932         reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3933   }
3934   const FPOptionsOverride *getTrailingFPFeatures() const {
3935     assert(BinaryOperatorBits.HasFPFeatures);
3936     return reinterpret_cast<const FPOptionsOverride *>(
3937         reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3938   }
3939 
3940   /// Build a binary operator, assuming that appropriate storage has been
3941   /// allocated for the trailing objects when needed.
3942   BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3943                  QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3944                  SourceLocation opLoc, FPOptionsOverride FPFeatures);
3945 
3946   /// Construct an empty binary operator.
3947   explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3948     BinaryOperatorBits.Opc = BO_Comma;
3949     BinaryOperatorBits.ExcludedOverflowPattern = false;
3950   }
3951 
3952 public:
3953   static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3954 
3955   static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3956                                 Opcode opc, QualType ResTy, ExprValueKind VK,
3957                                 ExprObjectKind OK, SourceLocation opLoc,
3958                                 FPOptionsOverride FPFeatures);
3959   SourceLocation getExprLoc() const { return getOperatorLoc(); }
3960   SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3961   void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3962 
3963   Opcode getOpcode() const {
3964     return static_cast<Opcode>(BinaryOperatorBits.Opc);
3965   }
3966   void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3967 
3968   Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3969   void setLHS(Expr *E) { SubExprs[LHS] = E; }
3970   Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3971   void setRHS(Expr *E) { SubExprs[RHS] = E; }
3972 
3973   SourceLocation getBeginLoc() const LLVM_READONLY {
3974     return getLHS()->getBeginLoc();
3975   }
3976   SourceLocation getEndLoc() const LLVM_READONLY {
3977     return getRHS()->getEndLoc();
3978   }
3979 
3980   /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3981   /// corresponds to, e.g. "<<=".
3982   static StringRef getOpcodeStr(Opcode Op);
3983 
3984   StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3985 
3986   /// Retrieve the binary opcode that corresponds to the given
3987   /// overloaded operator.
3988   static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3989 
3990   /// Retrieve the overloaded operator kind that corresponds to
3991   /// the given binary opcode.
3992   static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3993 
3994   /// predicates to categorize the respective opcodes.
3995   static bool isPtrMemOp(Opcode Opc) {
3996     return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3997   }
3998   bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3999 
4000   static bool isMultiplicativeOp(Opcode Opc) {
4001     return Opc >= BO_Mul && Opc <= BO_Rem;
4002   }
4003   bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
4004   static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
4005   bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
4006   static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
4007   bool isShiftOp() const { return isShiftOp(getOpcode()); }
4008 
4009   static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
4010   bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
4011 
4012   static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
4013   bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
4014 
4015   static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
4016   bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
4017 
4018   static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
4019   bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
4020 
4021   static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
4022   bool isCommaOp() const { return isCommaOp(getOpcode()); }
4023 
4024   static Opcode negateComparisonOp(Opcode Opc) {
4025     switch (Opc) {
4026     default:
4027       llvm_unreachable("Not a comparison operator.");
4028     case BO_LT: return BO_GE;
4029     case BO_GT: return BO_LE;
4030     case BO_LE: return BO_GT;
4031     case BO_GE: return BO_LT;
4032     case BO_EQ: return BO_NE;
4033     case BO_NE: return BO_EQ;
4034     }
4035   }
4036 
4037   static Opcode reverseComparisonOp(Opcode Opc) {
4038     switch (Opc) {
4039     default:
4040       llvm_unreachable("Not a comparison operator.");
4041     case BO_LT: return BO_GT;
4042     case BO_GT: return BO_LT;
4043     case BO_LE: return BO_GE;
4044     case BO_GE: return BO_LE;
4045     case BO_EQ:
4046     case BO_NE:
4047       return Opc;
4048     }
4049   }
4050 
4051   static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
4052   bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
4053 
4054   static bool isAssignmentOp(Opcode Opc) {
4055     return Opc >= BO_Assign && Opc <= BO_OrAssign;
4056   }
4057   bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
4058 
4059   static bool isCompoundAssignmentOp(Opcode Opc) {
4060     return Opc > BO_Assign && Opc <= BO_OrAssign;
4061   }
4062   bool isCompoundAssignmentOp() const {
4063     return isCompoundAssignmentOp(getOpcode());
4064   }
4065   static Opcode getOpForCompoundAssignment(Opcode Opc) {
4066     assert(isCompoundAssignmentOp(Opc));
4067     if (Opc >= BO_AndAssign)
4068       return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
4069     else
4070       return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
4071   }
4072 
4073   static bool isShiftAssignOp(Opcode Opc) {
4074     return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
4075   }
4076   bool isShiftAssignOp() const {
4077     return isShiftAssignOp(getOpcode());
4078   }
4079 
4080   /// Return true if a binary operator using the specified opcode and operands
4081   /// would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
4082   /// integer to a pointer.
4083   static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
4084                                                const Expr *LHS,
4085                                                const Expr *RHS);
4086 
4087   static bool classof(const Stmt *S) {
4088     return S->getStmtClass() >= firstBinaryOperatorConstant &&
4089            S->getStmtClass() <= lastBinaryOperatorConstant;
4090   }
4091 
4092   // Iterators
4093   child_range children() {
4094     return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4095   }
4096   const_child_range children() const {
4097     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4098   }
4099 
4100   /// Set and fetch the bit that shows whether FPFeatures needs to be
4101   /// allocated in Trailing Storage
4102   void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
4103   bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
4104 
4105   /// Set and get the bit that informs arithmetic overflow sanitizers whether
4106   /// or not they should exclude certain BinaryOperators from instrumentation
4107   void setExcludedOverflowPattern(bool B) {
4108     BinaryOperatorBits.ExcludedOverflowPattern = B;
4109   }
4110   bool hasExcludedOverflowPattern() const {
4111     return BinaryOperatorBits.ExcludedOverflowPattern;
4112   }
4113 
4114   /// Get FPFeatures from trailing storage
4115   FPOptionsOverride getStoredFPFeatures() const {
4116     assert(hasStoredFPFeatures());
4117     return *getTrailingFPFeatures();
4118   }
4119   /// Set FPFeatures in trailing storage, used only by Serialization
4120   void setStoredFPFeatures(FPOptionsOverride F) {
4121     assert(BinaryOperatorBits.HasFPFeatures);
4122     *getTrailingFPFeatures() = F;
4123   }
4124   /// Get the store FPOptionsOverride or default if not stored.
4125   FPOptionsOverride getStoredFPFeaturesOrDefault() const {
4126     return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
4127   }
4128 
4129   /// Get the FP features status of this operator. Only meaningful for
4130   /// operations on floating point types.
4131   FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
4132     if (BinaryOperatorBits.HasFPFeatures)
4133       return getStoredFPFeatures().applyOverrides(LO);
4134     return FPOptions::defaultWithoutTrailingStorage(LO);
4135   }
4136 
4137   // This is used in ASTImporter
4138   FPOptionsOverride getFPFeatures() const {
4139     if (BinaryOperatorBits.HasFPFeatures)
4140       return getStoredFPFeatures();
4141     return FPOptionsOverride();
4142   }
4143 
4144   /// Get the FP contractibility status of this operator. Only meaningful for
4145   /// operations on floating point types.
4146   bool isFPContractableWithinStatement(const LangOptions &LO) const {
4147     return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4148   }
4149 
4150   /// Get the FENV_ACCESS status of this operator. Only meaningful for
4151   /// operations on floating point types.
4152   bool isFEnvAccessOn(const LangOptions &LO) const {
4153     return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4154   }
4155 
4156 protected:
4157   BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4158                  QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
4159                  SourceLocation opLoc, FPOptionsOverride FPFeatures,
4160                  bool dead2);
4161 
4162   /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4163   BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4164     BinaryOperatorBits.Opc = BO_MulAssign;
4165   }
4166 
4167   /// Return the size in bytes needed for the trailing objects.
4168   /// Used to allocate the right amount of storage.
4169   static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4170     return HasFPFeatures * sizeof(FPOptionsOverride);
4171   }
4172 };
4173 
4174 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4175 /// track of the type the operation is performed in.  Due to the semantics of
4176 /// these operators, the operands are promoted, the arithmetic performed, an
4177 /// implicit conversion back to the result type done, then the assignment takes
4178 /// place.  This captures the intermediate type which the computation is done
4179 /// in.
4180 class CompoundAssignOperator : public BinaryOperator {
4181   QualType ComputationLHSType;
4182   QualType ComputationResultType;
4183 
4184   /// Construct an empty CompoundAssignOperator.
4185   explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4186                                   bool hasFPFeatures)
4187       : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4188 
4189 protected:
4190   CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
4191                          QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4192                          SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4193                          QualType CompLHSType, QualType CompResultType)
4194       : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4195                        true),
4196         ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4197     assert(isCompoundAssignmentOp() &&
4198            "Only should be used for compound assignments");
4199   }
4200 
4201 public:
4202   static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
4203                                              bool hasFPFeatures);
4204 
4205   static CompoundAssignOperator *
4206   Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4207          ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4208          FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4209          QualType CompResultType = QualType());
4210 
4211   // The two computation types are the type the LHS is converted
4212   // to for the computation and the type of the result; the two are
4213   // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4214   QualType getComputationLHSType() const { return ComputationLHSType; }
4215   void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4216 
4217   QualType getComputationResultType() const { return ComputationResultType; }
4218   void setComputationResultType(QualType T) { ComputationResultType = T; }
4219 
4220   static bool classof(const Stmt *S) {
4221     return S->getStmtClass() == CompoundAssignOperatorClass;
4222   }
4223 };
4224 
4225 inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4226   assert(BinaryOperatorBits.HasFPFeatures);
4227   return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4228                                            : sizeof(BinaryOperator);
4229 }
4230 
4231 /// AbstractConditionalOperator - An abstract base class for
4232 /// ConditionalOperator and BinaryConditionalOperator.
4233 class AbstractConditionalOperator : public Expr {
4234   SourceLocation QuestionLoc, ColonLoc;
4235   friend class ASTStmtReader;
4236 
4237 protected:
4238   AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4239                               ExprObjectKind OK, SourceLocation qloc,
4240                               SourceLocation cloc)
4241       : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4242 
4243   AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4244     : Expr(SC, Empty) { }
4245 
4246 public:
4247   /// getCond - Return the expression representing the condition for
4248   ///   the ?: operator.
4249   Expr *getCond() const;
4250 
4251   /// getTrueExpr - Return the subexpression representing the value of
4252   ///   the expression if the condition evaluates to true.
4253   Expr *getTrueExpr() const;
4254 
4255   /// getFalseExpr - Return the subexpression representing the value of
4256   ///   the expression if the condition evaluates to false.  This is
4257   ///   the same as getRHS.
4258   Expr *getFalseExpr() const;
4259 
4260   SourceLocation getQuestionLoc() const { return QuestionLoc; }
4261   SourceLocation getColonLoc() const { return ColonLoc; }
4262 
4263   static bool classof(const Stmt *T) {
4264     return T->getStmtClass() == ConditionalOperatorClass ||
4265            T->getStmtClass() == BinaryConditionalOperatorClass;
4266   }
4267 };
4268 
4269 /// ConditionalOperator - The ?: ternary operator.  The GNU "missing
4270 /// middle" extension is a BinaryConditionalOperator.
4271 class ConditionalOperator : public AbstractConditionalOperator {
4272   enum { COND, LHS, RHS, END_EXPR };
4273   Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4274 
4275   friend class ASTStmtReader;
4276 public:
4277   ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4278                       SourceLocation CLoc, Expr *rhs, QualType t,
4279                       ExprValueKind VK, ExprObjectKind OK)
4280       : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4281                                     CLoc) {
4282     SubExprs[COND] = cond;
4283     SubExprs[LHS] = lhs;
4284     SubExprs[RHS] = rhs;
4285     setDependence(computeDependence(this));
4286   }
4287 
4288   /// Build an empty conditional operator.
4289   explicit ConditionalOperator(EmptyShell Empty)
4290     : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4291 
4292   /// getCond - Return the expression representing the condition for
4293   ///   the ?: operator.
4294   Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4295 
4296   /// getTrueExpr - Return the subexpression representing the value of
4297   ///   the expression if the condition evaluates to true.
4298   Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4299 
4300   /// getFalseExpr - Return the subexpression representing the value of
4301   ///   the expression if the condition evaluates to false.  This is
4302   ///   the same as getRHS.
4303   Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4304 
4305   Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4306   Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4307 
4308   SourceLocation getBeginLoc() const LLVM_READONLY {
4309     return getCond()->getBeginLoc();
4310   }
4311   SourceLocation getEndLoc() const LLVM_READONLY {
4312     return getRHS()->getEndLoc();
4313   }
4314 
4315   static bool classof(const Stmt *T) {
4316     return T->getStmtClass() == ConditionalOperatorClass;
4317   }
4318 
4319   // Iterators
4320   child_range children() {
4321     return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4322   }
4323   const_child_range children() const {
4324     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4325   }
4326 };
4327 
4328 /// BinaryConditionalOperator - The GNU extension to the conditional
4329 /// operator which allows the middle operand to be omitted.
4330 ///
4331 /// This is a different expression kind on the assumption that almost
4332 /// every client ends up needing to know that these are different.
4333 class BinaryConditionalOperator : public AbstractConditionalOperator {
4334   enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4335 
4336   /// - the common condition/left-hand-side expression, which will be
4337   ///   evaluated as the opaque value
4338   /// - the condition, expressed in terms of the opaque value
4339   /// - the left-hand-side, expressed in terms of the opaque value
4340   /// - the right-hand-side
4341   Stmt *SubExprs[NUM_SUBEXPRS];
4342   OpaqueValueExpr *OpaqueValue;
4343 
4344   friend class ASTStmtReader;
4345 public:
4346   BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4347                             Expr *cond, Expr *lhs, Expr *rhs,
4348                             SourceLocation qloc, SourceLocation cloc,
4349                             QualType t, ExprValueKind VK, ExprObjectKind OK)
4350       : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4351                                     qloc, cloc),
4352         OpaqueValue(opaqueValue) {
4353     SubExprs[COMMON] = common;
4354     SubExprs[COND] = cond;
4355     SubExprs[LHS] = lhs;
4356     SubExprs[RHS] = rhs;
4357     assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4358     setDependence(computeDependence(this));
4359   }
4360 
4361   /// Build an empty conditional operator.
4362   explicit BinaryConditionalOperator(EmptyShell Empty)
4363     : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4364 
4365   /// getCommon - Return the common expression, written to the
4366   ///   left of the condition.  The opaque value will be bound to the
4367   ///   result of this expression.
4368   Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4369 
4370   /// getOpaqueValue - Return the opaque value placeholder.
4371   OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4372 
4373   /// getCond - Return the condition expression; this is defined
4374   ///   in terms of the opaque value.
4375   Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4376 
4377   /// getTrueExpr - Return the subexpression which will be
4378   ///   evaluated if the condition evaluates to true;  this is defined
4379   ///   in terms of the opaque value.
4380   Expr *getTrueExpr() const {
4381     return cast<Expr>(SubExprs[LHS]);
4382   }
4383 
4384   /// getFalseExpr - Return the subexpression which will be
4385   ///   evaluated if the condition evaluates to false; this is
4386   ///   defined in terms of the opaque value.
4387   Expr *getFalseExpr() const {
4388     return cast<Expr>(SubExprs[RHS]);
4389   }
4390 
4391   SourceLocation getBeginLoc() const LLVM_READONLY {
4392     return getCommon()->getBeginLoc();
4393   }
4394   SourceLocation getEndLoc() const LLVM_READONLY {
4395     return getFalseExpr()->getEndLoc();
4396   }
4397 
4398   static bool classof(const Stmt *T) {
4399     return T->getStmtClass() == BinaryConditionalOperatorClass;
4400   }
4401 
4402   // Iterators
4403   child_range children() {
4404     return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4405   }
4406   const_child_range children() const {
4407     return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4408   }
4409 };
4410 
4411 inline Expr *AbstractConditionalOperator::getCond() const {
4412   if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4413     return co->getCond();
4414   return cast<BinaryConditionalOperator>(this)->getCond();
4415 }
4416 
4417 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4418   if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4419     return co->getTrueExpr();
4420   return cast<BinaryConditionalOperator>(this)->getTrueExpr();
4421 }
4422 
4423 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4424   if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4425     return co->getFalseExpr();
4426   return cast<BinaryConditionalOperator>(this)->getFalseExpr();
4427 }
4428 
4429 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
4430 class AddrLabelExpr : public Expr {
4431   SourceLocation AmpAmpLoc, LabelLoc;
4432   LabelDecl *Label;
4433 public:
4434   AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4435                 QualType t)
4436       : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
4437         LabelLoc(LLoc), Label(L) {
4438     setDependence(ExprDependence::None);
4439   }
4440 
4441   /// Build an empty address of a label expression.
4442   explicit AddrLabelExpr(EmptyShell Empty)
4443     : Expr(AddrLabelExprClass, Empty) { }
4444 
4445   SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
4446   void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
4447   SourceLocation getLabelLoc() const { return LabelLoc; }
4448   void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4449 
4450   SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
4451   SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4452 
4453   LabelDecl *getLabel() const { return Label; }
4454   void setLabel(LabelDecl *L) { Label = L; }
4455 
4456   static bool classof(const Stmt *T) {
4457     return T->getStmtClass() == AddrLabelExprClass;
4458   }
4459 
4460   // Iterators
4461   child_range children() {
4462     return child_range(child_iterator(), child_iterator());
4463   }
4464   const_child_range children() const {
4465     return const_child_range(const_child_iterator(), const_child_iterator());
4466   }
4467 };
4468 
4469 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4470 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4471 /// takes the value of the last subexpression.
4472 ///
4473 /// A StmtExpr is always an r-value; values "returned" out of a
4474 /// StmtExpr will be copied.
4475 class StmtExpr : public Expr {
4476   Stmt *SubStmt;
4477   SourceLocation LParenLoc, RParenLoc;
4478 public:
4479   StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4480            SourceLocation RParenLoc, unsigned TemplateDepth)
4481       : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
4482         LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4483     setDependence(computeDependence(this, TemplateDepth));
4484     // FIXME: A templated statement expression should have an associated
4485     // DeclContext so that nested declarations always have a dependent context.
4486     StmtExprBits.TemplateDepth = TemplateDepth;
4487   }
4488 
4489   /// Build an empty statement expression.
4490   explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4491 
4492   CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
4493   const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
4494   void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4495 
4496   SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
4497   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4498 
4499   SourceLocation getLParenLoc() const { return LParenLoc; }
4500   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
4501   SourceLocation getRParenLoc() const { return RParenLoc; }
4502   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4503 
4504   unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4505 
4506   static bool classof(const Stmt *T) {
4507     return T->getStmtClass() == StmtExprClass;
4508   }
4509 
4510   // Iterators
4511   child_range children() { return child_range(&SubStmt, &SubStmt+1); }
4512   const_child_range children() const {
4513     return const_child_range(&SubStmt, &SubStmt + 1);
4514   }
4515 };
4516 
4517 /// ShuffleVectorExpr - clang-specific builtin-in function
4518 /// __builtin_shufflevector.
4519 /// This AST node represents a operator that does a constant
4520 /// shuffle, similar to LLVM's shufflevector instruction. It takes
4521 /// two vectors and a variable number of constant indices,
4522 /// and returns the appropriately shuffled vector.
4523 class ShuffleVectorExpr : public Expr {
4524   SourceLocation BuiltinLoc, RParenLoc;
4525 
4526   // SubExprs - the list of values passed to the __builtin_shufflevector
4527   // function. The first two are vectors, and the rest are constant
4528   // indices.  The number of values in this list is always
4529   // 2+the number of indices in the vector type.
4530   Stmt **SubExprs;
4531   unsigned NumExprs;
4532 
4533 public:
4534   ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4535                     SourceLocation BLoc, SourceLocation RP);
4536 
4537   /// Build an empty vector-shuffle expression.
4538   explicit ShuffleVectorExpr(EmptyShell Empty)
4539     : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4540 
4541   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4542   void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4543 
4544   SourceLocation getRParenLoc() const { return RParenLoc; }
4545   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4546 
4547   SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4548   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4549 
4550   static bool classof(const Stmt *T) {
4551     return T->getStmtClass() == ShuffleVectorExprClass;
4552   }
4553 
4554   /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
4555   /// constant expression, the actual arguments passed in, and the function
4556   /// pointers.
4557   unsigned getNumSubExprs() const { return NumExprs; }
4558 
4559   /// Retrieve the array of expressions.
4560   Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4561 
4562   /// getExpr - Return the Expr at the specified index.
4563   Expr *getExpr(unsigned Index) {
4564     assert((Index < NumExprs) && "Arg access out of range!");
4565     return cast<Expr>(SubExprs[Index]);
4566   }
4567   const Expr *getExpr(unsigned Index) const {
4568     assert((Index < NumExprs) && "Arg access out of range!");
4569     return cast<Expr>(SubExprs[Index]);
4570   }
4571 
4572   void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4573 
4574   llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4575     assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4576     return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4577   }
4578 
4579   // Iterators
4580   child_range children() {
4581     return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4582   }
4583   const_child_range children() const {
4584     return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4585   }
4586 };
4587 
4588 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4589 /// This AST node provides support for converting a vector type to another
4590 /// vector type of the same arity.
4591 class ConvertVectorExpr : public Expr {
4592 private:
4593   Stmt *SrcExpr;
4594   TypeSourceInfo *TInfo;
4595   SourceLocation BuiltinLoc, RParenLoc;
4596 
4597   friend class ASTReader;
4598   friend class ASTStmtReader;
4599   explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4600 
4601 public:
4602   ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4603                     ExprValueKind VK, ExprObjectKind OK,
4604                     SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4605       : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4606         TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4607     setDependence(computeDependence(this));
4608   }
4609 
4610   /// getSrcExpr - Return the Expr to be converted.
4611   Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4612 
4613   /// getTypeSourceInfo - Return the destination type.
4614   TypeSourceInfo *getTypeSourceInfo() const {
4615     return TInfo;
4616   }
4617   void setTypeSourceInfo(TypeSourceInfo *ti) {
4618     TInfo = ti;
4619   }
4620 
4621   /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4622   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4623 
4624   /// getRParenLoc - Return the location of final right parenthesis.
4625   SourceLocation getRParenLoc() const { return RParenLoc; }
4626 
4627   SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4628   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4629 
4630   static bool classof(const Stmt *T) {
4631     return T->getStmtClass() == ConvertVectorExprClass;
4632   }
4633 
4634   // Iterators
4635   child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4636   const_child_range children() const {
4637     return const_child_range(&SrcExpr, &SrcExpr + 1);
4638   }
4639 };
4640 
4641 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4642 /// This AST node is similar to the conditional operator (?:) in C, with
4643 /// the following exceptions:
4644 /// - the test expression must be a integer constant expression.
4645 /// - the expression returned acts like the chosen subexpression in every
4646 ///   visible way: the type is the same as that of the chosen subexpression,
4647 ///   and all predicates (whether it's an l-value, whether it's an integer
4648 ///   constant expression, etc.) return the same result as for the chosen
4649 ///   sub-expression.
4650 class ChooseExpr : public Expr {
4651   enum { COND, LHS, RHS, END_EXPR };
4652   Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4653   SourceLocation BuiltinLoc, RParenLoc;
4654   bool CondIsTrue;
4655 public:
4656   ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4657              ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4658              bool condIsTrue)
4659       : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4660         CondIsTrue(condIsTrue) {
4661     SubExprs[COND] = cond;
4662     SubExprs[LHS] = lhs;
4663     SubExprs[RHS] = rhs;
4664 
4665     setDependence(computeDependence(this));
4666   }
4667 
4668   /// Build an empty __builtin_choose_expr.
4669   explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4670 
4671   /// isConditionTrue - Return whether the condition is true (i.e. not
4672   /// equal to zero).
4673   bool isConditionTrue() const {
4674     assert(!isConditionDependent() &&
4675            "Dependent condition isn't true or false");
4676     return CondIsTrue;
4677   }
4678   void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4679 
4680   bool isConditionDependent() const {
4681     return getCond()->isTypeDependent() || getCond()->isValueDependent();
4682   }
4683 
4684   /// getChosenSubExpr - Return the subexpression chosen according to the
4685   /// condition.
4686   Expr *getChosenSubExpr() const {
4687     return isConditionTrue() ? getLHS() : getRHS();
4688   }
4689 
4690   Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4691   void setCond(Expr *E) { SubExprs[COND] = E; }
4692   Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4693   void setLHS(Expr *E) { SubExprs[LHS] = E; }
4694   Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4695   void setRHS(Expr *E) { SubExprs[RHS] = E; }
4696 
4697   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4698   void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4699 
4700   SourceLocation getRParenLoc() const { return RParenLoc; }
4701   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4702 
4703   SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4704   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4705 
4706   static bool classof(const Stmt *T) {
4707     return T->getStmtClass() == ChooseExprClass;
4708   }
4709 
4710   // Iterators
4711   child_range children() {
4712     return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4713   }
4714   const_child_range children() const {
4715     return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4716   }
4717 };
4718 
4719 /// GNUNullExpr - Implements the GNU __null extension, which is a name
4720 /// for a null pointer constant that has integral type (e.g., int or
4721 /// long) and is the same size and alignment as a pointer. The __null
4722 /// extension is typically only used by system headers, which define
4723 /// NULL as __null in C++ rather than using 0 (which is an integer
4724 /// that may not match the size of a pointer).
4725 class GNUNullExpr : public Expr {
4726   /// TokenLoc - The location of the __null keyword.
4727   SourceLocation TokenLoc;
4728 
4729 public:
4730   GNUNullExpr(QualType Ty, SourceLocation Loc)
4731       : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
4732     setDependence(ExprDependence::None);
4733   }
4734 
4735   /// Build an empty GNU __null expression.
4736   explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4737 
4738   /// getTokenLocation - The location of the __null token.
4739   SourceLocation getTokenLocation() const { return TokenLoc; }
4740   void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4741 
4742   SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
4743   SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4744 
4745   static bool classof(const Stmt *T) {
4746     return T->getStmtClass() == GNUNullExprClass;
4747   }
4748 
4749   // Iterators
4750   child_range children() {
4751     return child_range(child_iterator(), child_iterator());
4752   }
4753   const_child_range children() const {
4754     return const_child_range(const_child_iterator(), const_child_iterator());
4755   }
4756 };
4757 
4758 /// Represents a call to the builtin function \c __builtin_va_arg.
4759 class VAArgExpr : public Expr {
4760   Stmt *Val;
4761   llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4762   SourceLocation BuiltinLoc, RParenLoc;
4763 public:
4764   VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4765             SourceLocation RPLoc, QualType t, bool IsMS)
4766       : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
4767         TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4768     setDependence(computeDependence(this));
4769   }
4770 
4771   /// Create an empty __builtin_va_arg expression.
4772   explicit VAArgExpr(EmptyShell Empty)
4773       : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4774 
4775   const Expr *getSubExpr() const { return cast<Expr>(Val); }
4776   Expr *getSubExpr() { return cast<Expr>(Val); }
4777   void setSubExpr(Expr *E) { Val = E; }
4778 
4779   /// Returns whether this is really a Win64 ABI va_arg expression.
4780   bool isMicrosoftABI() const { return TInfo.getInt(); }
4781   void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4782 
4783   TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4784   void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4785 
4786   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4787   void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4788 
4789   SourceLocation getRParenLoc() const { return RParenLoc; }
4790   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4791 
4792   SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4793   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4794 
4795   static bool classof(const Stmt *T) {
4796     return T->getStmtClass() == VAArgExprClass;
4797   }
4798 
4799   // Iterators
4800   child_range children() { return child_range(&Val, &Val+1); }
4801   const_child_range children() const {
4802     return const_child_range(&Val, &Val + 1);
4803   }
4804 };
4805 
4806 enum class SourceLocIdentKind {
4807   Function,
4808   FuncSig,
4809   File,
4810   FileName,
4811   Line,
4812   Column,
4813   SourceLocStruct
4814 };
4815 
4816 /// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4817 /// __builtin_FUNCTION(), __builtin_FUNCSIG(), __builtin_FILE(),
4818 /// __builtin_FILE_NAME() or __builtin_source_location().
4819 class SourceLocExpr final : public Expr {
4820   SourceLocation BuiltinLoc, RParenLoc;
4821   DeclContext *ParentContext;
4822 
4823 public:
4824   SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Type,
4825                 QualType ResultTy, SourceLocation BLoc,
4826                 SourceLocation RParenLoc, DeclContext *Context);
4827 
4828   /// Build an empty call expression.
4829   explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4830 
4831   /// Return the result of evaluating this SourceLocExpr in the specified
4832   /// (and possibly null) default argument or initialization context.
4833   APValue EvaluateInContext(const ASTContext &Ctx,
4834                             const Expr *DefaultExpr) const;
4835 
4836   /// Return a string representing the name of the specific builtin function.
4837   StringRef getBuiltinStr() const;
4838 
4839   SourceLocIdentKind getIdentKind() const {
4840     return static_cast<SourceLocIdentKind>(SourceLocExprBits.Kind);
4841   }
4842 
4843   bool isIntType() const {
4844     switch (getIdentKind()) {
4845     case SourceLocIdentKind::File:
4846     case SourceLocIdentKind::FileName:
4847     case SourceLocIdentKind::Function:
4848     case SourceLocIdentKind::FuncSig:
4849     case SourceLocIdentKind::SourceLocStruct:
4850       return false;
4851     case SourceLocIdentKind::Line:
4852     case SourceLocIdentKind::Column:
4853       return true;
4854     }
4855     llvm_unreachable("unknown source location expression kind");
4856   }
4857 
4858   /// If the SourceLocExpr has been resolved return the subexpression
4859   /// representing the resolved value. Otherwise return null.
4860   const DeclContext *getParentContext() const { return ParentContext; }
4861   DeclContext *getParentContext() { return ParentContext; }
4862 
4863   SourceLocation getLocation() const { return BuiltinLoc; }
4864   SourceLocation getBeginLoc() const { return BuiltinLoc; }
4865   SourceLocation getEndLoc() const { return RParenLoc; }
4866 
4867   child_range children() {
4868     return child_range(child_iterator(), child_iterator());
4869   }
4870 
4871   const_child_range children() const {
4872     return const_child_range(child_iterator(), child_iterator());
4873   }
4874 
4875   static bool classof(const Stmt *T) {
4876     return T->getStmtClass() == SourceLocExprClass;
4877   }
4878 
4879   static bool MayBeDependent(SourceLocIdentKind Kind) {
4880     switch (Kind) {
4881     case SourceLocIdentKind::Function:
4882     case SourceLocIdentKind::FuncSig:
4883     case SourceLocIdentKind::SourceLocStruct:
4884       return true;
4885     default:
4886       return false;
4887     }
4888   }
4889 
4890 private:
4891   friend class ASTStmtReader;
4892 };
4893 
4894 /// Stores data related to a single #embed directive.
4895 struct EmbedDataStorage {
4896   StringLiteral *BinaryData;
4897   size_t getDataElementCount() const { return BinaryData->getByteLength(); }
4898 };
4899 
4900 /// Represents a reference to #emded data. By default, this references the whole
4901 /// range. Otherwise it represents a subrange of data imported by #embed
4902 /// directive. Needed to handle nested initializer lists with #embed directives.
4903 /// Example:
4904 ///  struct S {
4905 ///    int x, y;
4906 ///  };
4907 ///
4908 ///  struct T {
4909 ///    int x[2];
4910 ///    struct S s
4911 ///  };
4912 ///
4913 ///  struct T t[] = {
4914 ///  #embed "data" // data contains 10 elements;
4915 ///  };
4916 ///
4917 /// The resulting semantic form of initializer list will contain (EE stands
4918 /// for EmbedExpr):
4919 ///  { {EE(first two data elements), {EE(3rd element), EE(4th element) }},
4920 ///  { {EE(5th and 6th element), {EE(7th element), EE(8th element) }},
4921 ///  { {EE(9th and 10th element), { zeroinitializer }}}
4922 ///
4923 /// EmbedExpr inside of a semantic initializer list and referencing more than
4924 /// one element can only appear for arrays of scalars.
4925 class EmbedExpr final : public Expr {
4926   SourceLocation EmbedKeywordLoc;
4927   IntegerLiteral *FakeChildNode = nullptr;
4928   const ASTContext *Ctx = nullptr;
4929   EmbedDataStorage *Data;
4930   unsigned Begin = 0;
4931   unsigned NumOfElements;
4932 
4933 public:
4934   EmbedExpr(const ASTContext &Ctx, SourceLocation Loc, EmbedDataStorage *Data,
4935             unsigned Begin, unsigned NumOfElements);
4936   explicit EmbedExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4937 
4938   SourceLocation getLocation() const { return EmbedKeywordLoc; }
4939   SourceLocation getBeginLoc() const { return EmbedKeywordLoc; }
4940   SourceLocation getEndLoc() const { return EmbedKeywordLoc; }
4941 
4942   StringLiteral *getDataStringLiteral() const { return Data->BinaryData; }
4943   EmbedDataStorage *getData() const { return Data; }
4944 
4945   unsigned getStartingElementPos() const { return Begin; }
4946   size_t getDataElementCount() const { return NumOfElements; }
4947 
4948   // Allows accessing every byte of EmbedExpr data and iterating over it.
4949   // An Iterator knows the EmbedExpr that it refers to, and an offset value
4950   // within the data.
4951   // Dereferencing an Iterator results in construction of IntegerLiteral AST
4952   // node filled with byte of data of the corresponding EmbedExpr within offset
4953   // that the Iterator currently has.
4954   template <bool Const>
4955   class ChildElementIter
4956       : public llvm::iterator_facade_base<
4957             ChildElementIter<Const>, std::random_access_iterator_tag,
4958             std::conditional_t<Const, const IntegerLiteral *,
4959                                IntegerLiteral *>> {
4960     friend class EmbedExpr;
4961 
4962     EmbedExpr *EExpr = nullptr;
4963     unsigned long long CurOffset = ULLONG_MAX;
4964     using BaseTy = typename ChildElementIter::iterator_facade_base;
4965 
4966     ChildElementIter(EmbedExpr *E) : EExpr(E) {
4967       if (E)
4968         CurOffset = E->getStartingElementPos();
4969     }
4970 
4971   public:
4972     ChildElementIter() : CurOffset(ULLONG_MAX) {}
4973     typename BaseTy::reference operator*() const {
4974       assert(EExpr && CurOffset != ULLONG_MAX &&
4975              "trying to dereference an invalid iterator");
4976       IntegerLiteral *N = EExpr->FakeChildNode;
4977       N->setValue(*EExpr->Ctx,
4978                   llvm::APInt(N->getValue().getBitWidth(),
4979                               EExpr->Data->BinaryData->getCodeUnit(CurOffset),
4980                               N->getType()->isSignedIntegerType()));
4981       // We want to return a reference to the fake child node in the
4982       // EmbedExpr, not the local variable N.
4983       return const_cast<typename BaseTy::reference>(EExpr->FakeChildNode);
4984     }
4985     typename BaseTy::pointer operator->() const { return **this; }
4986     using BaseTy::operator++;
4987     ChildElementIter &operator++() {
4988       assert(EExpr && "trying to increment an invalid iterator");
4989       assert(CurOffset != ULLONG_MAX &&
4990              "Already at the end of what we can iterate over");
4991       if (++CurOffset >=
4992           EExpr->getDataElementCount() + EExpr->getStartingElementPos()) {
4993         CurOffset = ULLONG_MAX;
4994         EExpr = nullptr;
4995       }
4996       return *this;
4997     }
4998     bool operator==(ChildElementIter Other) const {
4999       return (EExpr == Other.EExpr && CurOffset == Other.CurOffset);
5000     }
5001   }; // class ChildElementIter
5002 
5003 public:
5004   using fake_child_range = llvm::iterator_range<ChildElementIter<false>>;
5005   using const_fake_child_range = llvm::iterator_range<ChildElementIter<true>>;
5006 
5007   fake_child_range underlying_data_elements() {
5008     return fake_child_range(ChildElementIter<false>(this),
5009                             ChildElementIter<false>());
5010   }
5011 
5012   const_fake_child_range underlying_data_elements() const {
5013     return const_fake_child_range(
5014         ChildElementIter<true>(const_cast<EmbedExpr *>(this)),
5015         ChildElementIter<true>());
5016   }
5017 
5018   child_range children() {
5019     return child_range(child_iterator(), child_iterator());
5020   }
5021 
5022   const_child_range children() const {
5023     return const_child_range(const_child_iterator(), const_child_iterator());
5024   }
5025 
5026   static bool classof(const Stmt *T) {
5027     return T->getStmtClass() == EmbedExprClass;
5028   }
5029 
5030   ChildElementIter<false> begin() { return ChildElementIter<false>(this); }
5031 
5032   ChildElementIter<true> begin() const {
5033     return ChildElementIter<true>(const_cast<EmbedExpr *>(this));
5034   }
5035 
5036   template <typename Call, typename... Targs>
5037   bool doForEachDataElement(Call &&C, unsigned &StartingIndexInArray,
5038                             Targs &&...Fargs) const {
5039     for (auto It : underlying_data_elements()) {
5040       if (!std::invoke(std::forward<Call>(C), const_cast<IntegerLiteral *>(It),
5041                        StartingIndexInArray, std::forward<Targs>(Fargs)...))
5042         return false;
5043       StartingIndexInArray++;
5044     }
5045     return true;
5046   }
5047 
5048 private:
5049   friend class ASTStmtReader;
5050 };
5051 
5052 /// Describes an C or C++ initializer list.
5053 ///
5054 /// InitListExpr describes an initializer list, which can be used to
5055 /// initialize objects of different types, including
5056 /// struct/class/union types, arrays, and vectors. For example:
5057 ///
5058 /// @code
5059 /// struct foo x = { 1, { 2, 3 } };
5060 /// @endcode
5061 ///
5062 /// Prior to semantic analysis, an initializer list will represent the
5063 /// initializer list as written by the user, but will have the
5064 /// placeholder type "void". This initializer list is called the
5065 /// syntactic form of the initializer, and may contain C99 designated
5066 /// initializers (represented as DesignatedInitExprs), initializations
5067 /// of subobject members without explicit braces, and so on. Clients
5068 /// interested in the original syntax of the initializer list should
5069 /// use the syntactic form of the initializer list.
5070 ///
5071 /// After semantic analysis, the initializer list will represent the
5072 /// semantic form of the initializer, where the initializations of all
5073 /// subobjects are made explicit with nested InitListExpr nodes and
5074 /// C99 designators have been eliminated by placing the designated
5075 /// initializations into the subobject they initialize. Additionally,
5076 /// any "holes" in the initialization, where no initializer has been
5077 /// specified for a particular subobject, will be replaced with
5078 /// implicitly-generated ImplicitValueInitExpr expressions that
5079 /// value-initialize the subobjects. Note, however, that the
5080 /// initializer lists may still have fewer initializers than there are
5081 /// elements to initialize within the object.
5082 ///
5083 /// After semantic analysis has completed, given an initializer list,
5084 /// method isSemanticForm() returns true if and only if this is the
5085 /// semantic form of the initializer list (note: the same AST node
5086 /// may at the same time be the syntactic form).
5087 /// Given the semantic form of the initializer list, one can retrieve
5088 /// the syntactic form of that initializer list (when different)
5089 /// using method getSyntacticForm(); the method returns null if applied
5090 /// to a initializer list which is already in syntactic form.
5091 /// Similarly, given the syntactic form (i.e., an initializer list such
5092 /// that isSemanticForm() returns false), one can retrieve the semantic
5093 /// form using method getSemanticForm().
5094 /// Since many initializer lists have the same syntactic and semantic forms,
5095 /// getSyntacticForm() may return NULL, indicating that the current
5096 /// semantic initializer list also serves as its syntactic form.
5097 class InitListExpr : public Expr {
5098   // FIXME: Eliminate this vector in favor of ASTContext allocation
5099   typedef ASTVector<Stmt *> InitExprsTy;
5100   InitExprsTy InitExprs;
5101   SourceLocation LBraceLoc, RBraceLoc;
5102 
5103   /// The alternative form of the initializer list (if it exists).
5104   /// The int part of the pair stores whether this initializer list is
5105   /// in semantic form. If not null, the pointer points to:
5106   ///   - the syntactic form, if this is in semantic form;
5107   ///   - the semantic form, if this is in syntactic form.
5108   llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
5109 
5110   /// Either:
5111   ///  If this initializer list initializes an array with more elements than
5112   ///  there are initializers in the list, specifies an expression to be used
5113   ///  for value initialization of the rest of the elements.
5114   /// Or
5115   ///  If this initializer list initializes a union, specifies which
5116   ///  field within the union will be initialized.
5117   llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
5118 
5119 public:
5120   InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
5121                ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
5122 
5123   /// Build an empty initializer list.
5124   explicit InitListExpr(EmptyShell Empty)
5125     : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
5126 
5127   unsigned getNumInits() const { return InitExprs.size(); }
5128 
5129   /// Retrieve the set of initializers.
5130   Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
5131 
5132   /// Retrieve the set of initializers.
5133   Expr * const *getInits() const {
5134     return reinterpret_cast<Expr * const *>(InitExprs.data());
5135   }
5136 
5137   ArrayRef<Expr *> inits() { return llvm::ArrayRef(getInits(), getNumInits()); }
5138 
5139   ArrayRef<Expr *> inits() const {
5140     return llvm::ArrayRef(getInits(), getNumInits());
5141   }
5142 
5143   const Expr *getInit(unsigned Init) const {
5144     assert(Init < getNumInits() && "Initializer access out of range!");
5145     return cast_or_null<Expr>(InitExprs[Init]);
5146   }
5147 
5148   Expr *getInit(unsigned Init) {
5149     assert(Init < getNumInits() && "Initializer access out of range!");
5150     return cast_or_null<Expr>(InitExprs[Init]);
5151   }
5152 
5153   void setInit(unsigned Init, Expr *expr) {
5154     assert(Init < getNumInits() && "Initializer access out of range!");
5155     InitExprs[Init] = expr;
5156 
5157     if (expr)
5158       setDependence(getDependence() | expr->getDependence());
5159   }
5160 
5161   /// Mark the semantic form of the InitListExpr as error when the semantic
5162   /// analysis fails.
5163   void markError() {
5164     assert(isSemanticForm());
5165     setDependence(getDependence() | ExprDependence::ErrorDependent);
5166   }
5167 
5168   /// Reserve space for some number of initializers.
5169   void reserveInits(const ASTContext &C, unsigned NumInits);
5170 
5171   /// Specify the number of initializers
5172   ///
5173   /// If there are more than @p NumInits initializers, the remaining
5174   /// initializers will be destroyed. If there are fewer than @p
5175   /// NumInits initializers, NULL expressions will be added for the
5176   /// unknown initializers.
5177   void resizeInits(const ASTContext &Context, unsigned NumInits);
5178 
5179   /// Updates the initializer at index @p Init with the new
5180   /// expression @p expr, and returns the old expression at that
5181   /// location.
5182   ///
5183   /// When @p Init is out of range for this initializer list, the
5184   /// initializer list will be extended with NULL expressions to
5185   /// accommodate the new entry.
5186   Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
5187 
5188   /// If this initializer list initializes an array with more elements
5189   /// than there are initializers in the list, specifies an expression to be
5190   /// used for value initialization of the rest of the elements.
5191   Expr *getArrayFiller() {
5192     return dyn_cast_if_present<Expr *>(ArrayFillerOrUnionFieldInit);
5193   }
5194   const Expr *getArrayFiller() const {
5195     return const_cast<InitListExpr *>(this)->getArrayFiller();
5196   }
5197   void setArrayFiller(Expr *filler);
5198 
5199   /// Return true if this is an array initializer and its array "filler"
5200   /// has been set.
5201   bool hasArrayFiller() const { return getArrayFiller(); }
5202 
5203   /// Determine whether this initializer list contains a designated initializer.
5204   bool hasDesignatedInit() const {
5205     return std::any_of(begin(), end(), [](const Stmt *S) {
5206       return isa<DesignatedInitExpr>(S);
5207     });
5208   }
5209 
5210   /// If this initializes a union, specifies which field in the
5211   /// union to initialize.
5212   ///
5213   /// Typically, this field is the first named field within the
5214   /// union. However, a designated initializer can specify the
5215   /// initialization of a different field within the union.
5216   FieldDecl *getInitializedFieldInUnion() {
5217     return dyn_cast_if_present<FieldDecl *>(ArrayFillerOrUnionFieldInit);
5218   }
5219   const FieldDecl *getInitializedFieldInUnion() const {
5220     return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
5221   }
5222   void setInitializedFieldInUnion(FieldDecl *FD) {
5223     assert((FD == nullptr
5224             || getInitializedFieldInUnion() == nullptr
5225             || getInitializedFieldInUnion() == FD)
5226            && "Only one field of a union may be initialized at a time!");
5227     ArrayFillerOrUnionFieldInit = FD;
5228   }
5229 
5230   // Explicit InitListExpr's originate from source code (and have valid source
5231   // locations). Implicit InitListExpr's are created by the semantic analyzer.
5232   // FIXME: This is wrong; InitListExprs created by semantic analysis have
5233   // valid source locations too!
5234   bool isExplicit() const {
5235     return LBraceLoc.isValid() && RBraceLoc.isValid();
5236   }
5237 
5238   /// Is this an initializer for an array of characters, initialized by a string
5239   /// literal or an @encode?
5240   bool isStringLiteralInit() const;
5241 
5242   /// Is this a transparent initializer list (that is, an InitListExpr that is
5243   /// purely syntactic, and whose semantics are that of the sole contained
5244   /// initializer)?
5245   bool isTransparent() const;
5246 
5247   /// Is this the zero initializer {0} in a language which considers it
5248   /// idiomatic?
5249   bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
5250 
5251   SourceLocation getLBraceLoc() const { return LBraceLoc; }
5252   void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
5253   SourceLocation getRBraceLoc() const { return RBraceLoc; }
5254   void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
5255 
5256   bool isSemanticForm() const { return AltForm.getInt(); }
5257   InitListExpr *getSemanticForm() const {
5258     return isSemanticForm() ? nullptr : AltForm.getPointer();
5259   }
5260   bool isSyntacticForm() const {
5261     return !AltForm.getInt() || !AltForm.getPointer();
5262   }
5263   InitListExpr *getSyntacticForm() const {
5264     return isSemanticForm() ? AltForm.getPointer() : nullptr;
5265   }
5266 
5267   void setSyntacticForm(InitListExpr *Init) {
5268     AltForm.setPointer(Init);
5269     AltForm.setInt(true);
5270     Init->AltForm.setPointer(this);
5271     Init->AltForm.setInt(false);
5272   }
5273 
5274   bool hadArrayRangeDesignator() const {
5275     return InitListExprBits.HadArrayRangeDesignator != 0;
5276   }
5277   void sawArrayRangeDesignator(bool ARD = true) {
5278     InitListExprBits.HadArrayRangeDesignator = ARD;
5279   }
5280 
5281   SourceLocation getBeginLoc() const LLVM_READONLY;
5282   SourceLocation getEndLoc() const LLVM_READONLY;
5283 
5284   static bool classof(const Stmt *T) {
5285     return T->getStmtClass() == InitListExprClass;
5286   }
5287 
5288   // Iterators
5289   child_range children() {
5290     const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
5291     return child_range(cast_away_const(CCR.begin()),
5292                        cast_away_const(CCR.end()));
5293   }
5294 
5295   const_child_range children() const {
5296     // FIXME: This does not include the array filler expression.
5297     if (InitExprs.empty())
5298       return const_child_range(const_child_iterator(), const_child_iterator());
5299     return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
5300   }
5301 
5302   typedef InitExprsTy::iterator iterator;
5303   typedef InitExprsTy::const_iterator const_iterator;
5304   typedef InitExprsTy::reverse_iterator reverse_iterator;
5305   typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
5306 
5307   iterator begin() { return InitExprs.begin(); }
5308   const_iterator begin() const { return InitExprs.begin(); }
5309   iterator end() { return InitExprs.end(); }
5310   const_iterator end() const { return InitExprs.end(); }
5311   reverse_iterator rbegin() { return InitExprs.rbegin(); }
5312   const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
5313   reverse_iterator rend() { return InitExprs.rend(); }
5314   const_reverse_iterator rend() const { return InitExprs.rend(); }
5315 
5316   friend class ASTStmtReader;
5317   friend class ASTStmtWriter;
5318 };
5319 
5320 /// Represents a C99 designated initializer expression.
5321 ///
5322 /// A designated initializer expression (C99 6.7.8) contains one or
5323 /// more designators (which can be field designators, array
5324 /// designators, or GNU array-range designators) followed by an
5325 /// expression that initializes the field or element(s) that the
5326 /// designators refer to. For example, given:
5327 ///
5328 /// @code
5329 /// struct point {
5330 ///   double x;
5331 ///   double y;
5332 /// };
5333 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
5334 /// @endcode
5335 ///
5336 /// The InitListExpr contains three DesignatedInitExprs, the first of
5337 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
5338 /// designators, one array designator for @c [2] followed by one field
5339 /// designator for @c .y. The initialization expression will be 1.0.
5340 class DesignatedInitExpr final
5341     : public Expr,
5342       private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
5343 public:
5344   /// Forward declaration of the Designator class.
5345   class Designator;
5346 
5347 private:
5348   /// The location of the '=' or ':' prior to the actual initializer
5349   /// expression.
5350   SourceLocation EqualOrColonLoc;
5351 
5352   /// Whether this designated initializer used the GNU deprecated
5353   /// syntax rather than the C99 '=' syntax.
5354   LLVM_PREFERRED_TYPE(bool)
5355   unsigned GNUSyntax : 1;
5356 
5357   /// The number of designators in this initializer expression.
5358   unsigned NumDesignators : 15;
5359 
5360   /// The number of subexpressions of this initializer expression,
5361   /// which contains both the initializer and any additional
5362   /// expressions used by array and array-range designators.
5363   unsigned NumSubExprs : 16;
5364 
5365   /// The designators in this designated initialization
5366   /// expression.
5367   Designator *Designators;
5368 
5369   DesignatedInitExpr(const ASTContext &C, QualType Ty,
5370                      llvm::ArrayRef<Designator> Designators,
5371                      SourceLocation EqualOrColonLoc, bool GNUSyntax,
5372                      ArrayRef<Expr *> IndexExprs, Expr *Init);
5373 
5374   explicit DesignatedInitExpr(unsigned NumSubExprs)
5375     : Expr(DesignatedInitExprClass, EmptyShell()),
5376       NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
5377 
5378 public:
5379   /// Represents a single C99 designator.
5380   ///
5381   /// @todo This class is infuriatingly similar to clang::Designator,
5382   /// but minor differences (storing indices vs. storing pointers)
5383   /// keep us from reusing it. Try harder, later, to rectify these
5384   /// differences.
5385   class Designator {
5386     /// A field designator, e.g., ".x".
5387     struct FieldDesignatorInfo {
5388       /// Refers to the field that is being initialized. The low bit
5389       /// of this field determines whether this is actually a pointer
5390       /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
5391       /// initially constructed, a field designator will store an
5392       /// IdentifierInfo*. After semantic analysis has resolved that
5393       /// name, the field designator will instead store a FieldDecl*.
5394       uintptr_t NameOrField;
5395 
5396       /// The location of the '.' in the designated initializer.
5397       SourceLocation DotLoc;
5398 
5399       /// The location of the field name in the designated initializer.
5400       SourceLocation FieldLoc;
5401 
5402       FieldDesignatorInfo(const IdentifierInfo *II, SourceLocation DotLoc,
5403                           SourceLocation FieldLoc)
5404           : NameOrField(reinterpret_cast<uintptr_t>(II) | 0x1), DotLoc(DotLoc),
5405             FieldLoc(FieldLoc) {}
5406     };
5407 
5408     /// An array or GNU array-range designator, e.g., "[9]" or "[10...15]".
5409     struct ArrayOrRangeDesignatorInfo {
5410       /// Location of the first index expression within the designated
5411       /// initializer expression's list of subexpressions.
5412       unsigned Index;
5413 
5414       /// The location of the '[' starting the array range designator.
5415       SourceLocation LBracketLoc;
5416 
5417       /// The location of the ellipsis separating the start and end
5418       /// indices. Only valid for GNU array-range designators.
5419       SourceLocation EllipsisLoc;
5420 
5421       /// The location of the ']' terminating the array range designator.
5422       SourceLocation RBracketLoc;
5423 
5424       ArrayOrRangeDesignatorInfo(unsigned Index, SourceLocation LBracketLoc,
5425                                  SourceLocation RBracketLoc)
5426           : Index(Index), LBracketLoc(LBracketLoc), RBracketLoc(RBracketLoc) {}
5427 
5428       ArrayOrRangeDesignatorInfo(unsigned Index,
5429                                  SourceLocation LBracketLoc,
5430                                  SourceLocation EllipsisLoc,
5431                                  SourceLocation RBracketLoc)
5432           : Index(Index), LBracketLoc(LBracketLoc), EllipsisLoc(EllipsisLoc),
5433             RBracketLoc(RBracketLoc) {}
5434     };
5435 
5436     /// The kind of designator this describes.
5437     enum DesignatorKind {
5438       FieldDesignator,
5439       ArrayDesignator,
5440       ArrayRangeDesignator
5441     };
5442 
5443     DesignatorKind Kind;
5444 
5445     union {
5446       /// A field designator, e.g., ".x".
5447       struct FieldDesignatorInfo FieldInfo;
5448 
5449       /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5450       struct ArrayOrRangeDesignatorInfo ArrayOrRangeInfo;
5451     };
5452 
5453     Designator(DesignatorKind Kind) : Kind(Kind) {}
5454 
5455   public:
5456     Designator() {}
5457 
5458     bool isFieldDesignator() const { return Kind == FieldDesignator; }
5459     bool isArrayDesignator() const { return Kind == ArrayDesignator; }
5460     bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
5461 
5462     //===------------------------------------------------------------------===//
5463     // FieldDesignatorInfo
5464 
5465     /// Creates a field designator.
5466     static Designator CreateFieldDesignator(const IdentifierInfo *FieldName,
5467                                             SourceLocation DotLoc,
5468                                             SourceLocation FieldLoc) {
5469       Designator D(FieldDesignator);
5470       new (&D.FieldInfo) FieldDesignatorInfo(FieldName, DotLoc, FieldLoc);
5471       return D;
5472     }
5473 
5474     const IdentifierInfo *getFieldName() const;
5475 
5476     FieldDecl *getFieldDecl() const {
5477       assert(isFieldDesignator() && "Only valid on a field designator");
5478       if (FieldInfo.NameOrField & 0x01)
5479         return nullptr;
5480       return reinterpret_cast<FieldDecl *>(FieldInfo.NameOrField);
5481     }
5482 
5483     void setFieldDecl(FieldDecl *FD) {
5484       assert(isFieldDesignator() && "Only valid on a field designator");
5485       FieldInfo.NameOrField = reinterpret_cast<uintptr_t>(FD);
5486     }
5487 
5488     SourceLocation getDotLoc() const {
5489       assert(isFieldDesignator() && "Only valid on a field designator");
5490       return FieldInfo.DotLoc;
5491     }
5492 
5493     SourceLocation getFieldLoc() const {
5494       assert(isFieldDesignator() && "Only valid on a field designator");
5495       return FieldInfo.FieldLoc;
5496     }
5497 
5498     //===------------------------------------------------------------------===//
5499     // ArrayOrRangeDesignator
5500 
5501     /// Creates an array designator.
5502     static Designator CreateArrayDesignator(unsigned Index,
5503                                             SourceLocation LBracketLoc,
5504                                             SourceLocation RBracketLoc) {
5505       Designator D(ArrayDesignator);
5506       new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc,
5507                                                            RBracketLoc);
5508       return D;
5509     }
5510 
5511     /// Creates a GNU array-range designator.
5512     static Designator CreateArrayRangeDesignator(unsigned Index,
5513                                                  SourceLocation LBracketLoc,
5514                                                  SourceLocation EllipsisLoc,
5515                                                  SourceLocation RBracketLoc) {
5516       Designator D(ArrayRangeDesignator);
5517       new (&D.ArrayOrRangeInfo) ArrayOrRangeDesignatorInfo(Index, LBracketLoc,
5518                                                            EllipsisLoc,
5519                                                            RBracketLoc);
5520       return D;
5521     }
5522 
5523     unsigned getArrayIndex() const {
5524       assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5525              "Only valid on an array or array-range designator");
5526       return ArrayOrRangeInfo.Index;
5527     }
5528 
5529     SourceLocation getLBracketLoc() const {
5530       assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5531              "Only valid on an array or array-range designator");
5532       return ArrayOrRangeInfo.LBracketLoc;
5533     }
5534 
5535     SourceLocation getEllipsisLoc() const {
5536       assert(isArrayRangeDesignator() &&
5537              "Only valid on an array-range designator");
5538       return ArrayOrRangeInfo.EllipsisLoc;
5539     }
5540 
5541     SourceLocation getRBracketLoc() const {
5542       assert((isArrayDesignator() || isArrayRangeDesignator()) &&
5543              "Only valid on an array or array-range designator");
5544       return ArrayOrRangeInfo.RBracketLoc;
5545     }
5546 
5547     SourceLocation getBeginLoc() const LLVM_READONLY {
5548       if (isFieldDesignator())
5549         return getDotLoc().isInvalid() ? getFieldLoc() : getDotLoc();
5550       return getLBracketLoc();
5551     }
5552 
5553     SourceLocation getEndLoc() const LLVM_READONLY {
5554       return isFieldDesignator() ? getFieldLoc() : getRBracketLoc();
5555     }
5556 
5557     SourceRange getSourceRange() const LLVM_READONLY {
5558       return SourceRange(getBeginLoc(), getEndLoc());
5559     }
5560   };
5561 
5562   static DesignatedInitExpr *Create(const ASTContext &C,
5563                                     llvm::ArrayRef<Designator> Designators,
5564                                     ArrayRef<Expr*> IndexExprs,
5565                                     SourceLocation EqualOrColonLoc,
5566                                     bool GNUSyntax, Expr *Init);
5567 
5568   static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
5569                                          unsigned NumIndexExprs);
5570 
5571   /// Returns the number of designators in this initializer.
5572   unsigned size() const { return NumDesignators; }
5573 
5574   // Iterator access to the designators.
5575   llvm::MutableArrayRef<Designator> designators() {
5576     return {Designators, NumDesignators};
5577   }
5578 
5579   llvm::ArrayRef<Designator> designators() const {
5580     return {Designators, NumDesignators};
5581   }
5582 
5583   Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
5584   const Designator *getDesignator(unsigned Idx) const {
5585     return &designators()[Idx];
5586   }
5587 
5588   void setDesignators(const ASTContext &C, const Designator *Desigs,
5589                       unsigned NumDesigs);
5590 
5591   Expr *getArrayIndex(const Designator &D) const;
5592   Expr *getArrayRangeStart(const Designator &D) const;
5593   Expr *getArrayRangeEnd(const Designator &D) const;
5594 
5595   /// Retrieve the location of the '=' that precedes the
5596   /// initializer value itself, if present.
5597   SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
5598   void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
5599 
5600   /// Whether this designated initializer should result in direct-initialization
5601   /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
5602   bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
5603 
5604   /// Determines whether this designated initializer used the
5605   /// deprecated GNU syntax for designated initializers.
5606   bool usesGNUSyntax() const { return GNUSyntax; }
5607   void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
5608 
5609   /// Retrieve the initializer value.
5610   Expr *getInit() const {
5611     return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
5612   }
5613 
5614   void setInit(Expr *init) {
5615     *child_begin() = init;
5616   }
5617 
5618   /// Retrieve the total number of subexpressions in this
5619   /// designated initializer expression, including the actual
5620   /// initialized value and any expressions that occur within array
5621   /// and array-range designators.
5622   unsigned getNumSubExprs() const { return NumSubExprs; }
5623 
5624   Expr *getSubExpr(unsigned Idx) const {
5625     assert(Idx < NumSubExprs && "Subscript out of range");
5626     return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
5627   }
5628 
5629   void setSubExpr(unsigned Idx, Expr *E) {
5630     assert(Idx < NumSubExprs && "Subscript out of range");
5631     getTrailingObjects<Stmt *>()[Idx] = E;
5632   }
5633 
5634   /// Replaces the designator at index @p Idx with the series
5635   /// of designators in [First, Last).
5636   void ExpandDesignator(const ASTContext &C, unsigned Idx,
5637                         const Designator *First, const Designator *Last);
5638 
5639   SourceRange getDesignatorsSourceRange() const;
5640 
5641   SourceLocation getBeginLoc() const LLVM_READONLY;
5642   SourceLocation getEndLoc() const LLVM_READONLY;
5643 
5644   static bool classof(const Stmt *T) {
5645     return T->getStmtClass() == DesignatedInitExprClass;
5646   }
5647 
5648   // Iterators
5649   child_range children() {
5650     Stmt **begin = getTrailingObjects<Stmt *>();
5651     return child_range(begin, begin + NumSubExprs);
5652   }
5653   const_child_range children() const {
5654     Stmt * const *begin = getTrailingObjects<Stmt *>();
5655     return const_child_range(begin, begin + NumSubExprs);
5656   }
5657 
5658   friend TrailingObjects;
5659 };
5660 
5661 /// Represents a place-holder for an object not to be initialized by
5662 /// anything.
5663 ///
5664 /// This only makes sense when it appears as part of an updater of a
5665 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
5666 /// initializes a big object, and the NoInitExpr's mark the spots within the
5667 /// big object not to be overwritten by the updater.
5668 ///
5669 /// \see DesignatedInitUpdateExpr
5670 class NoInitExpr : public Expr {
5671 public:
5672   explicit NoInitExpr(QualType ty)
5673       : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5674     setDependence(computeDependence(this));
5675   }
5676 
5677   explicit NoInitExpr(EmptyShell Empty)
5678     : Expr(NoInitExprClass, Empty) { }
5679 
5680   static bool classof(const Stmt *T) {
5681     return T->getStmtClass() == NoInitExprClass;
5682   }
5683 
5684   SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5685   SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5686 
5687   // Iterators
5688   child_range children() {
5689     return child_range(child_iterator(), child_iterator());
5690   }
5691   const_child_range children() const {
5692     return const_child_range(const_child_iterator(), const_child_iterator());
5693   }
5694 };
5695 
5696 // In cases like:
5697 //   struct Q { int a, b, c; };
5698 //   Q *getQ();
5699 //   void foo() {
5700 //     struct A { Q q; } a = { *getQ(), .q.b = 3 };
5701 //   }
5702 //
5703 // We will have an InitListExpr for a, with type A, and then a
5704 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
5705 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
5706 //
5707 class DesignatedInitUpdateExpr : public Expr {
5708   // BaseAndUpdaterExprs[0] is the base expression;
5709   // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
5710   Stmt *BaseAndUpdaterExprs[2];
5711 
5712 public:
5713   DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
5714                            Expr *baseExprs, SourceLocation rBraceLoc);
5715 
5716   explicit DesignatedInitUpdateExpr(EmptyShell Empty)
5717     : Expr(DesignatedInitUpdateExprClass, Empty) { }
5718 
5719   SourceLocation getBeginLoc() const LLVM_READONLY;
5720   SourceLocation getEndLoc() const LLVM_READONLY;
5721 
5722   static bool classof(const Stmt *T) {
5723     return T->getStmtClass() == DesignatedInitUpdateExprClass;
5724   }
5725 
5726   Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
5727   void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
5728 
5729   InitListExpr *getUpdater() const {
5730     return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
5731   }
5732   void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
5733 
5734   // Iterators
5735   // children = the base and the updater
5736   child_range children() {
5737     return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
5738   }
5739   const_child_range children() const {
5740     return const_child_range(&BaseAndUpdaterExprs[0],
5741                              &BaseAndUpdaterExprs[0] + 2);
5742   }
5743 };
5744 
5745 /// Represents a loop initializing the elements of an array.
5746 ///
5747 /// The need to initialize the elements of an array occurs in a number of
5748 /// contexts:
5749 ///
5750 ///  * in the implicit copy/move constructor for a class with an array member
5751 ///  * when a lambda-expression captures an array by value
5752 ///  * when a decomposition declaration decomposes an array
5753 ///
5754 /// There are two subexpressions: a common expression (the source array)
5755 /// that is evaluated once up-front, and a per-element initializer that
5756 /// runs once for each array element.
5757 ///
5758 /// Within the per-element initializer, the common expression may be referenced
5759 /// via an OpaqueValueExpr, and the current index may be obtained via an
5760 /// ArrayInitIndexExpr.
5761 class ArrayInitLoopExpr : public Expr {
5762   Stmt *SubExprs[2];
5763 
5764   explicit ArrayInitLoopExpr(EmptyShell Empty)
5765       : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
5766 
5767 public:
5768   explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
5769       : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
5770         SubExprs{CommonInit, ElementInit} {
5771     setDependence(computeDependence(this));
5772   }
5773 
5774   /// Get the common subexpression shared by all initializations (the source
5775   /// array).
5776   OpaqueValueExpr *getCommonExpr() const {
5777     return cast<OpaqueValueExpr>(SubExprs[0]);
5778   }
5779 
5780   /// Get the initializer to use for each array element.
5781   Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
5782 
5783   llvm::APInt getArraySize() const {
5784     return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
5785         ->getSize();
5786   }
5787 
5788   static bool classof(const Stmt *S) {
5789     return S->getStmtClass() == ArrayInitLoopExprClass;
5790   }
5791 
5792   SourceLocation getBeginLoc() const LLVM_READONLY {
5793     return getCommonExpr()->getBeginLoc();
5794   }
5795   SourceLocation getEndLoc() const LLVM_READONLY {
5796     return getCommonExpr()->getEndLoc();
5797   }
5798 
5799   child_range children() {
5800     return child_range(SubExprs, SubExprs + 2);
5801   }
5802   const_child_range children() const {
5803     return const_child_range(SubExprs, SubExprs + 2);
5804   }
5805 
5806   friend class ASTReader;
5807   friend class ASTStmtReader;
5808   friend class ASTStmtWriter;
5809 };
5810 
5811 /// Represents the index of the current element of an array being
5812 /// initialized by an ArrayInitLoopExpr. This can only appear within the
5813 /// subexpression of an ArrayInitLoopExpr.
5814 class ArrayInitIndexExpr : public Expr {
5815   explicit ArrayInitIndexExpr(EmptyShell Empty)
5816       : Expr(ArrayInitIndexExprClass, Empty) {}
5817 
5818 public:
5819   explicit ArrayInitIndexExpr(QualType T)
5820       : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
5821     setDependence(ExprDependence::None);
5822   }
5823 
5824   static bool classof(const Stmt *S) {
5825     return S->getStmtClass() == ArrayInitIndexExprClass;
5826   }
5827 
5828   SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5829   SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5830 
5831   child_range children() {
5832     return child_range(child_iterator(), child_iterator());
5833   }
5834   const_child_range children() const {
5835     return const_child_range(const_child_iterator(), const_child_iterator());
5836   }
5837 
5838   friend class ASTReader;
5839   friend class ASTStmtReader;
5840 };
5841 
5842 /// Represents an implicitly-generated value initialization of
5843 /// an object of a given type.
5844 ///
5845 /// Implicit value initializations occur within semantic initializer
5846 /// list expressions (InitListExpr) as placeholders for subobject
5847 /// initializations not explicitly specified by the user.
5848 ///
5849 /// \see InitListExpr
5850 class ImplicitValueInitExpr : public Expr {
5851 public:
5852   explicit ImplicitValueInitExpr(QualType ty)
5853       : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5854     setDependence(computeDependence(this));
5855   }
5856 
5857   /// Construct an empty implicit value initialization.
5858   explicit ImplicitValueInitExpr(EmptyShell Empty)
5859     : Expr(ImplicitValueInitExprClass, Empty) { }
5860 
5861   static bool classof(const Stmt *T) {
5862     return T->getStmtClass() == ImplicitValueInitExprClass;
5863   }
5864 
5865   SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5866   SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5867 
5868   // Iterators
5869   child_range children() {
5870     return child_range(child_iterator(), child_iterator());
5871   }
5872   const_child_range children() const {
5873     return const_child_range(const_child_iterator(), const_child_iterator());
5874   }
5875 };
5876 
5877 class ParenListExpr final
5878     : public Expr,
5879       private llvm::TrailingObjects<ParenListExpr, Stmt *> {
5880   friend class ASTStmtReader;
5881   friend TrailingObjects;
5882 
5883   /// The location of the left and right parentheses.
5884   SourceLocation LParenLoc, RParenLoc;
5885 
5886   /// Build a paren list.
5887   ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5888                 SourceLocation RParenLoc);
5889 
5890   /// Build an empty paren list.
5891   ParenListExpr(EmptyShell Empty, unsigned NumExprs);
5892 
5893 public:
5894   /// Create a paren list.
5895   static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
5896                                ArrayRef<Expr *> Exprs,
5897                                SourceLocation RParenLoc);
5898 
5899   /// Create an empty paren list.
5900   static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
5901 
5902   /// Return the number of expressions in this paren list.
5903   unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
5904 
5905   Expr *getExpr(unsigned Init) {
5906     assert(Init < getNumExprs() && "Initializer access out of range!");
5907     return getExprs()[Init];
5908   }
5909 
5910   const Expr *getExpr(unsigned Init) const {
5911     return const_cast<ParenListExpr *>(this)->getExpr(Init);
5912   }
5913 
5914   Expr **getExprs() {
5915     return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
5916   }
5917 
5918   ArrayRef<Expr *> exprs() { return llvm::ArrayRef(getExprs(), getNumExprs()); }
5919 
5920   SourceLocation getLParenLoc() const { return LParenLoc; }
5921   SourceLocation getRParenLoc() const { return RParenLoc; }
5922   SourceLocation getBeginLoc() const { return getLParenLoc(); }
5923   SourceLocation getEndLoc() const { return getRParenLoc(); }
5924 
5925   static bool classof(const Stmt *T) {
5926     return T->getStmtClass() == ParenListExprClass;
5927   }
5928 
5929   // Iterators
5930   child_range children() {
5931     return child_range(getTrailingObjects<Stmt *>(),
5932                        getTrailingObjects<Stmt *>() + getNumExprs());
5933   }
5934   const_child_range children() const {
5935     return const_child_range(getTrailingObjects<Stmt *>(),
5936                              getTrailingObjects<Stmt *>() + getNumExprs());
5937   }
5938 };
5939 
5940 /// Represents a C11 generic selection.
5941 ///
5942 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
5943 /// expression, followed by one or more generic associations.  Each generic
5944 /// association specifies a type name and an expression, or "default" and an
5945 /// expression (in which case it is known as a default generic association).
5946 /// The type and value of the generic selection are identical to those of its
5947 /// result expression, which is defined as the expression in the generic
5948 /// association with a type name that is compatible with the type of the
5949 /// controlling expression, or the expression in the default generic association
5950 /// if no types are compatible.  For example:
5951 ///
5952 /// @code
5953 /// _Generic(X, double: 1, float: 2, default: 3)
5954 /// @endcode
5955 ///
5956 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
5957 /// or 3 if "hello".
5958 ///
5959 /// As an extension, generic selections are allowed in C++, where the following
5960 /// additional semantics apply:
5961 ///
5962 /// Any generic selection whose controlling expression is type-dependent or
5963 /// which names a dependent type in its association list is result-dependent,
5964 /// which means that the choice of result expression is dependent.
5965 /// Result-dependent generic associations are both type- and value-dependent.
5966 ///
5967 /// We also allow an extended form in both C and C++ where the controlling
5968 /// predicate for the selection expression is a type rather than an expression.
5969 /// This type argument form does not perform any conversions for the
5970 /// controlling type, which makes it suitable for use with qualified type
5971 /// associations, which is not possible with the expression form.
5972 class GenericSelectionExpr final
5973     : public Expr,
5974       private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
5975                                     TypeSourceInfo *> {
5976   friend class ASTStmtReader;
5977   friend class ASTStmtWriter;
5978   friend TrailingObjects;
5979 
5980   /// The number of association expressions and the index of the result
5981   /// expression in the case where the generic selection expression is not
5982   /// result-dependent. The result index is equal to ResultDependentIndex
5983   /// if and only if the generic selection expression is result-dependent.
5984   unsigned NumAssocs : 15;
5985   unsigned ResultIndex : 15; // NB: ResultDependentIndex is tied to this width.
5986   LLVM_PREFERRED_TYPE(bool)
5987   unsigned IsExprPredicate : 1;
5988   enum : unsigned {
5989     ResultDependentIndex = 0x7FFF
5990   };
5991 
5992   unsigned getIndexOfControllingExpression() const {
5993     // If controlled by an expression, the first offset into the Stmt *
5994     // trailing array is the controlling expression, the associated expressions
5995     // follow this.
5996     assert(isExprPredicate() && "Asking for the controlling expression of a "
5997                                 "selection expr predicated by a type");
5998     return 0;
5999   }
6000 
6001   unsigned getIndexOfControllingType() const {
6002     // If controlled by a type, the first offset into the TypeSourceInfo *
6003     // trailing array is the controlling type, the associated types follow this.
6004     assert(isTypePredicate() && "Asking for the controlling type of a "
6005                                  "selection expr predicated by an expression");
6006     return 0;
6007   }
6008 
6009   unsigned getIndexOfStartOfAssociatedExprs() const {
6010     // If the predicate is a type, then the associated expressions are the only
6011     // Stmt * in the trailing array, otherwise we need to offset past the
6012     // predicate expression.
6013     return (int)isExprPredicate();
6014   }
6015 
6016   unsigned getIndexOfStartOfAssociatedTypes() const {
6017     // If the predicate is a type, then the associated types follow it in the
6018     // trailing array. Otherwise, the associated types are the only
6019     // TypeSourceInfo * in the trailing array.
6020     return (int)isTypePredicate();
6021   }
6022 
6023 
6024   /// The location of the "default" and of the right parenthesis.
6025   SourceLocation DefaultLoc, RParenLoc;
6026 
6027   // GenericSelectionExpr is followed by several trailing objects.
6028   // They are (in order):
6029   //
6030   // * A single Stmt * for the controlling expression or a TypeSourceInfo * for
6031   //   the controlling type, depending on the result of isTypePredicate() or
6032   //   isExprPredicate().
6033   // * An array of getNumAssocs() Stmt * for the association expressions.
6034   // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
6035   //   association expressions.
6036   unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
6037     // Add one to account for the controlling expression; the remainder
6038     // are the associated expressions.
6039     return getNumAssocs() + (int)isExprPredicate();
6040   }
6041 
6042   unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
6043     // Add one to account for the controlling type predicate, the remainder
6044     // are the associated types.
6045     return getNumAssocs() + (int)isTypePredicate();
6046   }
6047 
6048   template <bool Const> class AssociationIteratorTy;
6049   /// Bundle together an association expression and its TypeSourceInfo.
6050   /// The Const template parameter is for the const and non-const versions
6051   /// of AssociationTy.
6052   template <bool Const> class AssociationTy {
6053     friend class GenericSelectionExpr;
6054     template <bool OtherConst> friend class AssociationIteratorTy;
6055     using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
6056     using TSIPtrTy =
6057         std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
6058     ExprPtrTy E;
6059     TSIPtrTy TSI;
6060     bool Selected;
6061     AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
6062         : E(E), TSI(TSI), Selected(Selected) {}
6063 
6064   public:
6065     ExprPtrTy getAssociationExpr() const { return E; }
6066     TSIPtrTy getTypeSourceInfo() const { return TSI; }
6067     QualType getType() const { return TSI ? TSI->getType() : QualType(); }
6068     bool isSelected() const { return Selected; }
6069     AssociationTy *operator->() { return this; }
6070     const AssociationTy *operator->() const { return this; }
6071   }; // class AssociationTy
6072 
6073   /// Iterator over const and non-const Association objects. The Association
6074   /// objects are created on the fly when the iterator is dereferenced.
6075   /// This abstract over how exactly the association expressions and the
6076   /// corresponding TypeSourceInfo * are stored.
6077   template <bool Const>
6078   class AssociationIteratorTy
6079       : public llvm::iterator_facade_base<
6080             AssociationIteratorTy<Const>, std::input_iterator_tag,
6081             AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
6082             AssociationTy<Const>> {
6083     friend class GenericSelectionExpr;
6084     // FIXME: This iterator could conceptually be a random access iterator, and
6085     // it would be nice if we could strengthen the iterator category someday.
6086     // However this iterator does not satisfy two requirements of forward
6087     // iterators:
6088     // a) reference = T& or reference = const T&
6089     // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
6090     //    if *It1 and *It2 are bound to the same objects.
6091     // An alternative design approach was discussed during review;
6092     // store an Association object inside the iterator, and return a reference
6093     // to it when dereferenced. This idea was discarded because of nasty
6094     // lifetime issues:
6095     //    AssociationIterator It = ...;
6096     //    const Association &Assoc = *It++; // Oops, Assoc is dangling.
6097     using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
6098     using StmtPtrPtrTy =
6099         std::conditional_t<Const, const Stmt *const *, Stmt **>;
6100     using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
6101                                            TypeSourceInfo **>;
6102     StmtPtrPtrTy E = nullptr;
6103     TSIPtrPtrTy TSI; // Kept in sync with E.
6104     unsigned Offset = 0, SelectedOffset = 0;
6105     AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
6106                           unsigned SelectedOffset)
6107         : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
6108 
6109   public:
6110     AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
6111     typename BaseTy::reference operator*() const {
6112       return AssociationTy<Const>(cast<Expr>(*E), *TSI,
6113                                   Offset == SelectedOffset);
6114     }
6115     typename BaseTy::pointer operator->() const { return **this; }
6116     using BaseTy::operator++;
6117     AssociationIteratorTy &operator++() {
6118       ++E;
6119       ++TSI;
6120       ++Offset;
6121       return *this;
6122     }
6123     bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
6124   }; // class AssociationIterator
6125 
6126   /// Build a non-result-dependent generic selection expression accepting an
6127   /// expression predicate.
6128   GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6129                        Expr *ControllingExpr,
6130                        ArrayRef<TypeSourceInfo *> AssocTypes,
6131                        ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6132                        SourceLocation RParenLoc,
6133                        bool ContainsUnexpandedParameterPack,
6134                        unsigned ResultIndex);
6135 
6136   /// Build a result-dependent generic selection expression accepting an
6137   /// expression predicate.
6138   GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6139                        Expr *ControllingExpr,
6140                        ArrayRef<TypeSourceInfo *> AssocTypes,
6141                        ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6142                        SourceLocation RParenLoc,
6143                        bool ContainsUnexpandedParameterPack);
6144 
6145   /// Build a non-result-dependent generic selection expression accepting a
6146   /// type predicate.
6147   GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6148                        TypeSourceInfo *ControllingType,
6149                        ArrayRef<TypeSourceInfo *> AssocTypes,
6150                        ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6151                        SourceLocation RParenLoc,
6152                        bool ContainsUnexpandedParameterPack,
6153                        unsigned ResultIndex);
6154 
6155   /// Build a result-dependent generic selection expression accepting a type
6156   /// predicate.
6157   GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
6158                        TypeSourceInfo *ControllingType,
6159                        ArrayRef<TypeSourceInfo *> AssocTypes,
6160                        ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6161                        SourceLocation RParenLoc,
6162                        bool ContainsUnexpandedParameterPack);
6163 
6164   /// Build an empty generic selection expression for deserialization.
6165   explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
6166 
6167 public:
6168   /// Create a non-result-dependent generic selection expression accepting an
6169   /// expression predicate.
6170   static GenericSelectionExpr *
6171   Create(const ASTContext &Context, SourceLocation GenericLoc,
6172          Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
6173          ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6174          SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
6175          unsigned ResultIndex);
6176 
6177   /// Create a result-dependent generic selection expression accepting an
6178   /// expression predicate.
6179   static GenericSelectionExpr *
6180   Create(const ASTContext &Context, SourceLocation GenericLoc,
6181          Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
6182          ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6183          SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
6184 
6185   /// Create a non-result-dependent generic selection expression accepting a
6186   /// type predicate.
6187   static GenericSelectionExpr *
6188   Create(const ASTContext &Context, SourceLocation GenericLoc,
6189          TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
6190          ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6191          SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
6192          unsigned ResultIndex);
6193 
6194   /// Create a result-dependent generic selection expression accepting a type
6195   /// predicate
6196   static GenericSelectionExpr *
6197   Create(const ASTContext &Context, SourceLocation GenericLoc,
6198          TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
6199          ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
6200          SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
6201 
6202   /// Create an empty generic selection expression for deserialization.
6203   static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
6204                                            unsigned NumAssocs);
6205 
6206   using Association = AssociationTy<false>;
6207   using ConstAssociation = AssociationTy<true>;
6208   using AssociationIterator = AssociationIteratorTy<false>;
6209   using ConstAssociationIterator = AssociationIteratorTy<true>;
6210   using association_range = llvm::iterator_range<AssociationIterator>;
6211   using const_association_range =
6212       llvm::iterator_range<ConstAssociationIterator>;
6213 
6214   /// The number of association expressions.
6215   unsigned getNumAssocs() const { return NumAssocs; }
6216 
6217   /// The zero-based index of the result expression's generic association in
6218   /// the generic selection's association list.  Defined only if the
6219   /// generic selection is not result-dependent.
6220   unsigned getResultIndex() const {
6221     assert(!isResultDependent() &&
6222            "Generic selection is result-dependent but getResultIndex called!");
6223     return ResultIndex;
6224   }
6225 
6226   /// Whether this generic selection is result-dependent.
6227   bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
6228 
6229   /// Whether this generic selection uses an expression as its controlling
6230   /// argument.
6231   bool isExprPredicate() const { return IsExprPredicate; }
6232   /// Whether this generic selection uses a type as its controlling argument.
6233   bool isTypePredicate() const { return !IsExprPredicate; }
6234 
6235   /// Return the controlling expression of this generic selection expression.
6236   /// Only valid to call if the selection expression used an expression as its
6237   /// controlling argument.
6238   Expr *getControllingExpr() {
6239     return cast<Expr>(
6240         getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]);
6241   }
6242   const Expr *getControllingExpr() const {
6243     return cast<Expr>(
6244         getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()]);
6245   }
6246 
6247   /// Return the controlling type of this generic selection expression. Only
6248   /// valid to call if the selection expression used a type as its controlling
6249   /// argument.
6250   TypeSourceInfo *getControllingType() {
6251     return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()];
6252   }
6253   const TypeSourceInfo* getControllingType() const {
6254     return getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()];
6255   }
6256 
6257   /// Return the result expression of this controlling expression. Defined if
6258   /// and only if the generic selection expression is not result-dependent.
6259   Expr *getResultExpr() {
6260     return cast<Expr>(
6261         getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6262                                      getResultIndex()]);
6263   }
6264   const Expr *getResultExpr() const {
6265     return cast<Expr>(
6266         getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6267                                      getResultIndex()]);
6268   }
6269 
6270   ArrayRef<Expr *> getAssocExprs() const {
6271     return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
6272                                             getIndexOfStartOfAssociatedExprs()),
6273             NumAssocs};
6274   }
6275   ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
6276     return {getTrailingObjects<TypeSourceInfo *>() +
6277                 getIndexOfStartOfAssociatedTypes(),
6278             NumAssocs};
6279   }
6280 
6281   /// Return the Ith association expression with its TypeSourceInfo,
6282   /// bundled together in GenericSelectionExpr::(Const)Association.
6283   Association getAssociation(unsigned I) {
6284     assert(I < getNumAssocs() &&
6285            "Out-of-range index in GenericSelectionExpr::getAssociation!");
6286     return Association(
6287         cast<Expr>(
6288             getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6289                                          I]),
6290         getTrailingObjects<
6291             TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I],
6292         !isResultDependent() && (getResultIndex() == I));
6293   }
6294   ConstAssociation getAssociation(unsigned I) const {
6295     assert(I < getNumAssocs() &&
6296            "Out-of-range index in GenericSelectionExpr::getAssociation!");
6297     return ConstAssociation(
6298         cast<Expr>(
6299             getTrailingObjects<Stmt *>()[getIndexOfStartOfAssociatedExprs() +
6300                                          I]),
6301         getTrailingObjects<
6302             TypeSourceInfo *>()[getIndexOfStartOfAssociatedTypes() + I],
6303         !isResultDependent() && (getResultIndex() == I));
6304   }
6305 
6306   association_range associations() {
6307     AssociationIterator Begin(getTrailingObjects<Stmt *>() +
6308                                   getIndexOfStartOfAssociatedExprs(),
6309                               getTrailingObjects<TypeSourceInfo *>() +
6310                                   getIndexOfStartOfAssociatedTypes(),
6311                               /*Offset=*/0, ResultIndex);
6312     AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
6313                             /*Offset=*/NumAssocs, ResultIndex);
6314     return llvm::make_range(Begin, End);
6315   }
6316 
6317   const_association_range associations() const {
6318     ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
6319                                        getIndexOfStartOfAssociatedExprs(),
6320                                    getTrailingObjects<TypeSourceInfo *>() +
6321                                        getIndexOfStartOfAssociatedTypes(),
6322                                    /*Offset=*/0, ResultIndex);
6323     ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
6324                                  /*Offset=*/NumAssocs, ResultIndex);
6325     return llvm::make_range(Begin, End);
6326   }
6327 
6328   SourceLocation getGenericLoc() const {
6329     return GenericSelectionExprBits.GenericLoc;
6330   }
6331   SourceLocation getDefaultLoc() const { return DefaultLoc; }
6332   SourceLocation getRParenLoc() const { return RParenLoc; }
6333   SourceLocation getBeginLoc() const { return getGenericLoc(); }
6334   SourceLocation getEndLoc() const { return getRParenLoc(); }
6335 
6336   static bool classof(const Stmt *T) {
6337     return T->getStmtClass() == GenericSelectionExprClass;
6338   }
6339 
6340   child_range children() {
6341     return child_range(getTrailingObjects<Stmt *>(),
6342                        getTrailingObjects<Stmt *>() +
6343                            numTrailingObjects(OverloadToken<Stmt *>()));
6344   }
6345   const_child_range children() const {
6346     return const_child_range(getTrailingObjects<Stmt *>(),
6347                              getTrailingObjects<Stmt *>() +
6348                                  numTrailingObjects(OverloadToken<Stmt *>()));
6349   }
6350 };
6351 
6352 //===----------------------------------------------------------------------===//
6353 // Clang Extensions
6354 //===----------------------------------------------------------------------===//
6355 
6356 /// ExtVectorElementExpr - This represents access to specific elements of a
6357 /// vector, and may occur on the left hand side or right hand side.  For example
6358 /// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
6359 ///
6360 /// Note that the base may have either vector or pointer to vector type, just
6361 /// like a struct field reference.
6362 ///
6363 class ExtVectorElementExpr : public Expr {
6364   Stmt *Base;
6365   IdentifierInfo *Accessor;
6366   SourceLocation AccessorLoc;
6367 public:
6368   ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
6369                        IdentifierInfo &accessor, SourceLocation loc)
6370       : Expr(ExtVectorElementExprClass, ty, VK,
6371              (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
6372         Base(base), Accessor(&accessor), AccessorLoc(loc) {
6373     setDependence(computeDependence(this));
6374   }
6375 
6376   /// Build an empty vector element expression.
6377   explicit ExtVectorElementExpr(EmptyShell Empty)
6378     : Expr(ExtVectorElementExprClass, Empty) { }
6379 
6380   const Expr *getBase() const { return cast<Expr>(Base); }
6381   Expr *getBase() { return cast<Expr>(Base); }
6382   void setBase(Expr *E) { Base = E; }
6383 
6384   IdentifierInfo &getAccessor() const { return *Accessor; }
6385   void setAccessor(IdentifierInfo *II) { Accessor = II; }
6386 
6387   SourceLocation getAccessorLoc() const { return AccessorLoc; }
6388   void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
6389 
6390   /// getNumElements - Get the number of components being selected.
6391   unsigned getNumElements() const;
6392 
6393   /// containsDuplicateElements - Return true if any element access is
6394   /// repeated.
6395   bool containsDuplicateElements() const;
6396 
6397   /// getEncodedElementAccess - Encode the elements accessed into an llvm
6398   /// aggregate Constant of ConstantInt(s).
6399   void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
6400 
6401   SourceLocation getBeginLoc() const LLVM_READONLY {
6402     return getBase()->getBeginLoc();
6403   }
6404   SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
6405 
6406   /// isArrow - Return true if the base expression is a pointer to vector,
6407   /// return false if the base expression is a vector.
6408   bool isArrow() const;
6409 
6410   static bool classof(const Stmt *T) {
6411     return T->getStmtClass() == ExtVectorElementExprClass;
6412   }
6413 
6414   // Iterators
6415   child_range children() { return child_range(&Base, &Base+1); }
6416   const_child_range children() const {
6417     return const_child_range(&Base, &Base + 1);
6418   }
6419 };
6420 
6421 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
6422 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
6423 class BlockExpr : public Expr {
6424 protected:
6425   BlockDecl *TheBlock;
6426 public:
6427   BlockExpr(BlockDecl *BD, QualType ty, bool ContainsUnexpandedParameterPack)
6428       : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
6429     setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
6430   }
6431 
6432   /// Build an empty block expression.
6433   explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
6434 
6435   const BlockDecl *getBlockDecl() const { return TheBlock; }
6436   BlockDecl *getBlockDecl() { return TheBlock; }
6437   void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
6438 
6439   // Convenience functions for probing the underlying BlockDecl.
6440   SourceLocation getCaretLocation() const;
6441   const Stmt *getBody() const;
6442   Stmt *getBody();
6443 
6444   SourceLocation getBeginLoc() const LLVM_READONLY {
6445     return getCaretLocation();
6446   }
6447   SourceLocation getEndLoc() const LLVM_READONLY {
6448     return getBody()->getEndLoc();
6449   }
6450 
6451   /// getFunctionType - Return the underlying function type for this block.
6452   const FunctionProtoType *getFunctionType() const;
6453 
6454   static bool classof(const Stmt *T) {
6455     return T->getStmtClass() == BlockExprClass;
6456   }
6457 
6458   // Iterators
6459   child_range children() {
6460     return child_range(child_iterator(), child_iterator());
6461   }
6462   const_child_range children() const {
6463     return const_child_range(const_child_iterator(), const_child_iterator());
6464   }
6465 };
6466 
6467 /// Copy initialization expr of a __block variable and a boolean flag that
6468 /// indicates whether the expression can throw.
6469 struct BlockVarCopyInit {
6470   BlockVarCopyInit() = default;
6471   BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
6472       : ExprAndFlag(CopyExpr, CanThrow) {}
6473   void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
6474     ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
6475   }
6476   Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
6477   bool canThrow() const { return ExprAndFlag.getInt(); }
6478   llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
6479 };
6480 
6481 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
6482 /// This AST node provides support for reinterpreting a type to another
6483 /// type of the same size.
6484 class AsTypeExpr : public Expr {
6485 private:
6486   Stmt *SrcExpr;
6487   SourceLocation BuiltinLoc, RParenLoc;
6488 
6489   friend class ASTReader;
6490   friend class ASTStmtReader;
6491   explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
6492 
6493 public:
6494   AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
6495              ExprObjectKind OK, SourceLocation BuiltinLoc,
6496              SourceLocation RParenLoc)
6497       : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
6498         BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
6499     setDependence(computeDependence(this));
6500   }
6501 
6502   /// getSrcExpr - Return the Expr to be converted.
6503   Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
6504 
6505   /// getBuiltinLoc - Return the location of the __builtin_astype token.
6506   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6507 
6508   /// getRParenLoc - Return the location of final right parenthesis.
6509   SourceLocation getRParenLoc() const { return RParenLoc; }
6510 
6511   SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6512   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6513 
6514   static bool classof(const Stmt *T) {
6515     return T->getStmtClass() == AsTypeExprClass;
6516   }
6517 
6518   // Iterators
6519   child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
6520   const_child_range children() const {
6521     return const_child_range(&SrcExpr, &SrcExpr + 1);
6522   }
6523 };
6524 
6525 /// PseudoObjectExpr - An expression which accesses a pseudo-object
6526 /// l-value.  A pseudo-object is an abstract object, accesses to which
6527 /// are translated to calls.  The pseudo-object expression has a
6528 /// syntactic form, which shows how the expression was actually
6529 /// written in the source code, and a semantic form, which is a series
6530 /// of expressions to be executed in order which detail how the
6531 /// operation is actually evaluated.  Optionally, one of the semantic
6532 /// forms may also provide a result value for the expression.
6533 ///
6534 /// If any of the semantic-form expressions is an OpaqueValueExpr,
6535 /// that OVE is required to have a source expression, and it is bound
6536 /// to the result of that source expression.  Such OVEs may appear
6537 /// only in subsequent semantic-form expressions and as
6538 /// sub-expressions of the syntactic form.
6539 ///
6540 /// PseudoObjectExpr should be used only when an operation can be
6541 /// usefully described in terms of fairly simple rewrite rules on
6542 /// objects and functions that are meant to be used by end-developers.
6543 /// For example, under the Itanium ABI, dynamic casts are implemented
6544 /// as a call to a runtime function called __dynamic_cast; using this
6545 /// class to describe that would be inappropriate because that call is
6546 /// not really part of the user-visible semantics, and instead the
6547 /// cast is properly reflected in the AST and IR-generation has been
6548 /// taught to generate the call as necessary.  In contrast, an
6549 /// Objective-C property access is semantically defined to be
6550 /// equivalent to a particular message send, and this is very much
6551 /// part of the user model.  The name of this class encourages this
6552 /// modelling design.
6553 class PseudoObjectExpr final
6554     : public Expr,
6555       private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
6556   // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
6557   // Always at least two, because the first sub-expression is the
6558   // syntactic form.
6559 
6560   // PseudoObjectExprBits.ResultIndex - The index of the
6561   // sub-expression holding the result.  0 means the result is void,
6562   // which is unambiguous because it's the index of the syntactic
6563   // form.  Note that this is therefore 1 higher than the value passed
6564   // in to Create, which is an index within the semantic forms.
6565   // Note also that ASTStmtWriter assumes this encoding.
6566 
6567   Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
6568   const Expr * const *getSubExprsBuffer() const {
6569     return getTrailingObjects<Expr *>();
6570   }
6571 
6572   PseudoObjectExpr(QualType type, ExprValueKind VK,
6573                    Expr *syntactic, ArrayRef<Expr*> semantic,
6574                    unsigned resultIndex);
6575 
6576   PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
6577 
6578   unsigned getNumSubExprs() const {
6579     return PseudoObjectExprBits.NumSubExprs;
6580   }
6581 
6582 public:
6583   /// NoResult - A value for the result index indicating that there is
6584   /// no semantic result.
6585   enum : unsigned { NoResult = ~0U };
6586 
6587   static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
6588                                   ArrayRef<Expr*> semantic,
6589                                   unsigned resultIndex);
6590 
6591   static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
6592                                   unsigned numSemanticExprs);
6593 
6594   /// Return the syntactic form of this expression, i.e. the
6595   /// expression it actually looks like.  Likely to be expressed in
6596   /// terms of OpaqueValueExprs bound in the semantic form.
6597   Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
6598   const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
6599 
6600   /// Return the index of the result-bearing expression into the semantics
6601   /// expressions, or PseudoObjectExpr::NoResult if there is none.
6602   unsigned getResultExprIndex() const {
6603     if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
6604     return PseudoObjectExprBits.ResultIndex - 1;
6605   }
6606 
6607   /// Return the result-bearing expression, or null if there is none.
6608   Expr *getResultExpr() {
6609     if (PseudoObjectExprBits.ResultIndex == 0)
6610       return nullptr;
6611     return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
6612   }
6613   const Expr *getResultExpr() const {
6614     return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
6615   }
6616 
6617   unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
6618 
6619   typedef Expr * const *semantics_iterator;
6620   typedef const Expr * const *const_semantics_iterator;
6621   semantics_iterator semantics_begin() {
6622     return getSubExprsBuffer() + 1;
6623   }
6624   const_semantics_iterator semantics_begin() const {
6625     return getSubExprsBuffer() + 1;
6626   }
6627   semantics_iterator semantics_end() {
6628     return getSubExprsBuffer() + getNumSubExprs();
6629   }
6630   const_semantics_iterator semantics_end() const {
6631     return getSubExprsBuffer() + getNumSubExprs();
6632   }
6633 
6634   ArrayRef<Expr*> semantics() {
6635     return ArrayRef(semantics_begin(), semantics_end());
6636   }
6637   ArrayRef<const Expr*> semantics() const {
6638     return ArrayRef(semantics_begin(), semantics_end());
6639   }
6640 
6641   Expr *getSemanticExpr(unsigned index) {
6642     assert(index + 1 < getNumSubExprs());
6643     return getSubExprsBuffer()[index + 1];
6644   }
6645   const Expr *getSemanticExpr(unsigned index) const {
6646     return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
6647   }
6648 
6649   SourceLocation getExprLoc() const LLVM_READONLY {
6650     return getSyntacticForm()->getExprLoc();
6651   }
6652 
6653   SourceLocation getBeginLoc() const LLVM_READONLY {
6654     return getSyntacticForm()->getBeginLoc();
6655   }
6656   SourceLocation getEndLoc() const LLVM_READONLY {
6657     return getSyntacticForm()->getEndLoc();
6658   }
6659 
6660   child_range children() {
6661     const_child_range CCR =
6662         const_cast<const PseudoObjectExpr *>(this)->children();
6663     return child_range(cast_away_const(CCR.begin()),
6664                        cast_away_const(CCR.end()));
6665   }
6666   const_child_range children() const {
6667     Stmt *const *cs = const_cast<Stmt *const *>(
6668         reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
6669     return const_child_range(cs, cs + getNumSubExprs());
6670   }
6671 
6672   static bool classof(const Stmt *T) {
6673     return T->getStmtClass() == PseudoObjectExprClass;
6674   }
6675 
6676   friend TrailingObjects;
6677   friend class ASTStmtReader;
6678 };
6679 
6680 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
6681 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
6682 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
6683 /// and corresponding __opencl_atomic_* for OpenCL 2.0.
6684 /// All of these instructions take one primary pointer, at least one memory
6685 /// order. The instructions for which getScopeModel returns non-null value
6686 /// take one synch scope.
6687 class AtomicExpr : public Expr {
6688 public:
6689   enum AtomicOp {
6690 #define BUILTIN(ID, TYPE, ATTRS)
6691 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
6692 #include "clang/Basic/Builtins.inc"
6693     // Avoid trailing comma
6694     BI_First = 0
6695   };
6696 
6697 private:
6698   /// Location of sub-expressions.
6699   /// The location of Scope sub-expression is NumSubExprs - 1, which is
6700   /// not fixed, therefore is not defined in enum.
6701   enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
6702   Stmt *SubExprs[END_EXPR + 1];
6703   unsigned NumSubExprs;
6704   SourceLocation BuiltinLoc, RParenLoc;
6705   AtomicOp Op;
6706 
6707   friend class ASTStmtReader;
6708 public:
6709   AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
6710              AtomicOp op, SourceLocation RP);
6711 
6712   /// Determine the number of arguments the specified atomic builtin
6713   /// should have.
6714   static unsigned getNumSubExprs(AtomicOp Op);
6715 
6716   /// Build an empty AtomicExpr.
6717   explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
6718 
6719   Expr *getPtr() const {
6720     return cast<Expr>(SubExprs[PTR]);
6721   }
6722   Expr *getOrder() const {
6723     return cast<Expr>(SubExprs[ORDER]);
6724   }
6725   Expr *getScope() const {
6726     assert(getScopeModel() && "No scope");
6727     return cast<Expr>(SubExprs[NumSubExprs - 1]);
6728   }
6729   Expr *getVal1() const {
6730     if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
6731       return cast<Expr>(SubExprs[ORDER]);
6732     assert(NumSubExprs > VAL1);
6733     return cast<Expr>(SubExprs[VAL1]);
6734   }
6735   Expr *getOrderFail() const {
6736     assert(NumSubExprs > ORDER_FAIL);
6737     return cast<Expr>(SubExprs[ORDER_FAIL]);
6738   }
6739   Expr *getVal2() const {
6740     if (Op == AO__atomic_exchange || Op == AO__scoped_atomic_exchange)
6741       return cast<Expr>(SubExprs[ORDER_FAIL]);
6742     assert(NumSubExprs > VAL2);
6743     return cast<Expr>(SubExprs[VAL2]);
6744   }
6745   Expr *getWeak() const {
6746     assert(NumSubExprs > WEAK);
6747     return cast<Expr>(SubExprs[WEAK]);
6748   }
6749   QualType getValueType() const;
6750 
6751   AtomicOp getOp() const { return Op; }
6752   StringRef getOpAsString() const {
6753     switch (Op) {
6754 #define BUILTIN(ID, TYPE, ATTRS)
6755 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS)                                        \
6756   case AO##ID:                                                                 \
6757     return #ID;
6758 #include "clang/Basic/Builtins.inc"
6759     }
6760     llvm_unreachable("not an atomic operator?");
6761   }
6762   unsigned getNumSubExprs() const { return NumSubExprs; }
6763 
6764   Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
6765   const Expr * const *getSubExprs() const {
6766     return reinterpret_cast<Expr * const *>(SubExprs);
6767   }
6768 
6769   bool isVolatile() const {
6770     return getPtr()->getType()->getPointeeType().isVolatileQualified();
6771   }
6772 
6773   bool isCmpXChg() const {
6774     return getOp() == AO__c11_atomic_compare_exchange_strong ||
6775            getOp() == AO__c11_atomic_compare_exchange_weak ||
6776            getOp() == AO__hip_atomic_compare_exchange_strong ||
6777            getOp() == AO__opencl_atomic_compare_exchange_strong ||
6778            getOp() == AO__opencl_atomic_compare_exchange_weak ||
6779            getOp() == AO__hip_atomic_compare_exchange_weak ||
6780            getOp() == AO__atomic_compare_exchange ||
6781            getOp() == AO__atomic_compare_exchange_n ||
6782            getOp() == AO__scoped_atomic_compare_exchange ||
6783            getOp() == AO__scoped_atomic_compare_exchange_n;
6784   }
6785 
6786   bool isOpenCL() const {
6787     return getOp() >= AO__opencl_atomic_compare_exchange_strong &&
6788            getOp() <= AO__opencl_atomic_store;
6789   }
6790 
6791   bool isHIP() const {
6792     return Op >= AO__hip_atomic_compare_exchange_strong &&
6793            Op <= AO__hip_atomic_store;
6794   }
6795 
6796   /// Return true if atomics operations targeting allocations in private memory
6797   /// are undefined.
6798   bool threadPrivateMemoryAtomicsAreUndefined() const {
6799     return isOpenCL() || isHIP();
6800   }
6801 
6802   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6803   SourceLocation getRParenLoc() const { return RParenLoc; }
6804 
6805   SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6806   SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6807 
6808   static bool classof(const Stmt *T) {
6809     return T->getStmtClass() == AtomicExprClass;
6810   }
6811 
6812   // Iterators
6813   child_range children() {
6814     return child_range(SubExprs, SubExprs+NumSubExprs);
6815   }
6816   const_child_range children() const {
6817     return const_child_range(SubExprs, SubExprs + NumSubExprs);
6818   }
6819 
6820   /// Get atomic scope model for the atomic op code.
6821   /// \return empty atomic scope model if the atomic op code does not have
6822   ///   scope operand.
6823   static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
6824     // FIXME: Allow grouping of builtins to be able to only check >= and <=
6825     if (Op >= AO__opencl_atomic_compare_exchange_strong &&
6826         Op <= AO__opencl_atomic_store && Op != AO__opencl_atomic_init)
6827       return AtomicScopeModel::create(AtomicScopeModelKind::OpenCL);
6828     if (Op >= AO__hip_atomic_compare_exchange_strong &&
6829         Op <= AO__hip_atomic_store)
6830       return AtomicScopeModel::create(AtomicScopeModelKind::HIP);
6831     if (Op >= AO__scoped_atomic_add_fetch && Op <= AO__scoped_atomic_xor_fetch)
6832       return AtomicScopeModel::create(AtomicScopeModelKind::Generic);
6833     return AtomicScopeModel::create(AtomicScopeModelKind::None);
6834   }
6835 
6836   /// Get atomic scope model.
6837   /// \return empty atomic scope model if this atomic expression does not have
6838   ///   scope operand.
6839   std::unique_ptr<AtomicScopeModel> getScopeModel() const {
6840     return getScopeModel(getOp());
6841   }
6842 };
6843 
6844 /// TypoExpr - Internal placeholder for expressions where typo correction
6845 /// still needs to be performed and/or an error diagnostic emitted.
6846 class TypoExpr : public Expr {
6847   // The location for the typo name.
6848   SourceLocation TypoLoc;
6849 
6850 public:
6851   TypoExpr(QualType T, SourceLocation TypoLoc)
6852       : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) {
6853     assert(T->isDependentType() && "TypoExpr given a non-dependent type");
6854     setDependence(ExprDependence::TypeValueInstantiation |
6855                   ExprDependence::Error);
6856   }
6857 
6858   child_range children() {
6859     return child_range(child_iterator(), child_iterator());
6860   }
6861   const_child_range children() const {
6862     return const_child_range(const_child_iterator(), const_child_iterator());
6863   }
6864 
6865   SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; }
6866   SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; }
6867 
6868   static bool classof(const Stmt *T) {
6869     return T->getStmtClass() == TypoExprClass;
6870   }
6871 
6872 };
6873 
6874 /// This class represents BOTH the OpenMP Array Section and OpenACC 'subarray',
6875 /// with a boolean differentiator.
6876 /// OpenMP 5.0 [2.1.5, Array Sections].
6877 /// To specify an array section in an OpenMP construct, array subscript
6878 /// expressions are extended with the following syntax:
6879 /// \code
6880 /// [ lower-bound : length : stride ]
6881 /// [ lower-bound : length : ]
6882 /// [ lower-bound : length ]
6883 /// [ lower-bound : : stride ]
6884 /// [ lower-bound : : ]
6885 /// [ lower-bound : ]
6886 /// [ : length : stride ]
6887 /// [ : length : ]
6888 /// [ : length ]
6889 /// [ : : stride ]
6890 /// [ : : ]
6891 /// [ : ]
6892 /// \endcode
6893 /// The array section must be a subset of the original array.
6894 /// Array sections are allowed on multidimensional arrays. Base language array
6895 /// subscript expressions can be used to specify length-one dimensions of
6896 /// multidimensional array sections.
6897 /// Each of the lower-bound, length, and stride expressions if specified must be
6898 /// an integral type expressions of the base language. When evaluated
6899 /// they represent a set of integer values as follows:
6900 /// \code
6901 /// { lower-bound, lower-bound + stride, lower-bound + 2 * stride,... ,
6902 /// lower-bound + ((length - 1) * stride) }
6903 /// \endcode
6904 /// The lower-bound and length must evaluate to non-negative integers.
6905 /// The stride must evaluate to a positive integer.
6906 /// When the size of the array dimension is not known, the length must be
6907 /// specified explicitly.
6908 /// When the stride is absent it defaults to 1.
6909 /// When the length is absent it defaults to ⌈(size − lower-bound)/stride⌉,
6910 /// where size is the size of the array dimension. When the lower-bound is
6911 /// absent it defaults to 0.
6912 ///
6913 ///
6914 /// OpenACC 3.3 [2.7.1 Data Specification in Data Clauses]
6915 /// In C and C++, a subarray is an array name followed by an extended array
6916 /// range specification in brackets, with start and length, such as
6917 ///
6918 /// AA[2:n]
6919 ///
6920 /// If the lower bound is missing, zero is used. If the length is missing and
6921 /// the array has known size, the size of the array is used; otherwise the
6922 /// length is required. The subarray AA[2:n] means elements AA[2], AA[3], . . .
6923 /// , AA[2+n-1]. In C and C++, a two dimensional array may be declared in at
6924 /// least four ways:
6925 ///
6926 /// -Statically-sized array: float AA[100][200];
6927 /// -Pointer to statically sized rows: typedef float row[200]; row* BB;
6928 /// -Statically-sized array of pointers: float* CC[200];
6929 /// -Pointer to pointers: float** DD;
6930 ///
6931 /// Each dimension may be statically sized, or a pointer to dynamically
6932 /// allocated memory. Each of these may be included in a data clause using
6933 /// subarray notation to specify a rectangular array:
6934 ///
6935 /// -AA[2:n][0:200]
6936 /// -BB[2:n][0:m]
6937 /// -CC[2:n][0:m]
6938 /// -DD[2:n][0:m]
6939 ///
6940 /// Multidimensional rectangular subarrays in C and C++ may be specified for any
6941 /// array with any combination of statically-sized or dynamically-allocated
6942 /// dimensions. For statically sized dimensions, all dimensions except the first
6943 /// must specify the whole extent to preserve the contiguous data restriction,
6944 /// discussed below. For dynamically allocated dimensions, the implementation
6945 /// will allocate pointers in device memory corresponding to the pointers in
6946 /// local memory and will fill in those pointers as appropriate.
6947 ///
6948 /// In Fortran, a subarray is an array name followed by a comma-separated list
6949 /// of range specifications in parentheses, with lower and upper bound
6950 /// subscripts, such as
6951 ///
6952 /// arr(1:high,low:100)
6953 ///
6954 /// If either the lower or upper bounds are missing, the declared or allocated
6955 /// bounds of the array, if known, are used. All dimensions except the last must
6956 /// specify the whole extent, to preserve the contiguous data restriction,
6957 /// discussed below.
6958 ///
6959 /// Restrictions
6960 ///
6961 /// -In Fortran, the upper bound for the last dimension of an assumed-size dummy
6962 /// array must be specified.
6963 ///
6964 /// -In C and C++, the length for dynamically allocated dimensions of an array
6965 /// must be explicitly specified.
6966 ///
6967 /// -In C and C++, modifying pointers in pointer arrays during the data
6968 /// lifetime, either on the host or on the device, may result in undefined
6969 /// behavior.
6970 ///
6971 /// -If a subarray  appears in a data clause, the implementation may choose to
6972 /// allocate memory for only that subarray on the accelerator.
6973 ///
6974 /// -In Fortran, array pointers may appear, but pointer association is not
6975 /// preserved in device memory.
6976 ///
6977 /// -Any array or subarray in a data clause, including Fortran array pointers,
6978 /// must be a contiguous section of memory, except for dynamic multidimensional
6979 /// C arrays.
6980 ///
6981 /// -In C and C++, if a variable or array of composite type appears, all the
6982 /// data members of the struct or class are allocated and copied, as
6983 /// appropriate. If a composite member is a pointer type, the data addressed by
6984 /// that pointer are not implicitly copied.
6985 ///
6986 /// -In Fortran, if a variable or array of composite type appears, all the
6987 /// members of that derived type are allocated and copied, as appropriate. If
6988 /// any member has the allocatable or pointer attribute, the data accessed
6989 /// through that member are not copied.
6990 ///
6991 /// -If an expression is used in a subscript or subarray expression in a clause
6992 /// on a data construct, the same value is used when copying data at the end of
6993 /// the data region, even if the values of variables in the expression change
6994 /// during the data region.
6995 class ArraySectionExpr : public Expr {
6996   friend class ASTStmtReader;
6997   friend class ASTStmtWriter;
6998 
6999 public:
7000   enum ArraySectionType { OMPArraySection, OpenACCArraySection };
7001 
7002 private:
7003   enum {
7004     BASE,
7005     LOWER_BOUND,
7006     LENGTH,
7007     STRIDE,
7008     END_EXPR,
7009     OPENACC_END_EXPR = STRIDE
7010   };
7011 
7012   ArraySectionType ASType = OMPArraySection;
7013   Stmt *SubExprs[END_EXPR] = {nullptr};
7014   SourceLocation ColonLocFirst;
7015   SourceLocation ColonLocSecond;
7016   SourceLocation RBracketLoc;
7017 
7018 public:
7019   // Constructor for OMP array sections, which include a 'stride'.
7020   ArraySectionExpr(Expr *Base, Expr *LowerBound, Expr *Length, Expr *Stride,
7021                    QualType Type, ExprValueKind VK, ExprObjectKind OK,
7022                    SourceLocation ColonLocFirst, SourceLocation ColonLocSecond,
7023                    SourceLocation RBracketLoc)
7024       : Expr(ArraySectionExprClass, Type, VK, OK), ASType(OMPArraySection),
7025         ColonLocFirst(ColonLocFirst), ColonLocSecond(ColonLocSecond),
7026         RBracketLoc(RBracketLoc) {
7027     setBase(Base);
7028     setLowerBound(LowerBound);
7029     setLength(Length);
7030     setStride(Stride);
7031     setDependence(computeDependence(this));
7032   }
7033 
7034   // Constructor for OpenACC sub-arrays, which do not permit a 'stride'.
7035   ArraySectionExpr(Expr *Base, Expr *LowerBound, Expr *Length, QualType Type,
7036                    ExprValueKind VK, ExprObjectKind OK, SourceLocation ColonLoc,
7037                    SourceLocation RBracketLoc)
7038       : Expr(ArraySectionExprClass, Type, VK, OK), ASType(OpenACCArraySection),
7039         ColonLocFirst(ColonLoc), RBracketLoc(RBracketLoc) {
7040     setBase(Base);
7041     setLowerBound(LowerBound);
7042     setLength(Length);
7043     setDependence(computeDependence(this));
7044   }
7045 
7046   /// Create an empty array section expression.
7047   explicit ArraySectionExpr(EmptyShell Shell)
7048       : Expr(ArraySectionExprClass, Shell) {}
7049 
7050   /// Return original type of the base expression for array section.
7051   static QualType getBaseOriginalType(const Expr *Base);
7052 
7053   static bool classof(const Stmt *T) {
7054     return T->getStmtClass() == ArraySectionExprClass;
7055   }
7056 
7057   bool isOMPArraySection() const { return ASType == OMPArraySection; }
7058   bool isOpenACCArraySection() const { return ASType == OpenACCArraySection; }
7059 
7060   /// Get base of the array section.
7061   Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
7062   const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
7063 
7064   /// Get lower bound of array section.
7065   Expr *getLowerBound() { return cast_or_null<Expr>(SubExprs[LOWER_BOUND]); }
7066   const Expr *getLowerBound() const {
7067     return cast_or_null<Expr>(SubExprs[LOWER_BOUND]);
7068   }
7069 
7070   /// Get length of array section.
7071   Expr *getLength() { return cast_or_null<Expr>(SubExprs[LENGTH]); }
7072   const Expr *getLength() const { return cast_or_null<Expr>(SubExprs[LENGTH]); }
7073 
7074   /// Get stride of array section.
7075   Expr *getStride() {
7076     assert(ASType != OpenACCArraySection &&
7077            "Stride not valid in OpenACC subarrays");
7078     return cast_or_null<Expr>(SubExprs[STRIDE]);
7079   }
7080 
7081   const Expr *getStride() const {
7082     assert(ASType != OpenACCArraySection &&
7083            "Stride not valid in OpenACC subarrays");
7084     return cast_or_null<Expr>(SubExprs[STRIDE]);
7085   }
7086 
7087   SourceLocation getBeginLoc() const LLVM_READONLY {
7088     return getBase()->getBeginLoc();
7089   }
7090   SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
7091 
7092   SourceLocation getColonLocFirst() const { return ColonLocFirst; }
7093   SourceLocation getColonLocSecond() const {
7094     assert(ASType != OpenACCArraySection &&
7095            "second colon for stride not valid in OpenACC subarrays");
7096     return ColonLocSecond;
7097   }
7098   SourceLocation getRBracketLoc() const { return RBracketLoc; }
7099 
7100   SourceLocation getExprLoc() const LLVM_READONLY {
7101     return getBase()->getExprLoc();
7102   }
7103 
7104   child_range children() {
7105     return child_range(
7106         &SubExprs[BASE],
7107         &SubExprs[ASType == OMPArraySection ? END_EXPR : OPENACC_END_EXPR]);
7108   }
7109 
7110   const_child_range children() const {
7111     return const_child_range(
7112         &SubExprs[BASE],
7113         &SubExprs[ASType == OMPArraySection ? END_EXPR : OPENACC_END_EXPR]);
7114   }
7115 
7116 private:
7117   /// Set base of the array section.
7118   void setBase(Expr *E) { SubExprs[BASE] = E; }
7119 
7120   /// Set lower bound of the array section.
7121   void setLowerBound(Expr *E) { SubExprs[LOWER_BOUND] = E; }
7122 
7123   /// Set length of the array section.
7124   void setLength(Expr *E) { SubExprs[LENGTH] = E; }
7125 
7126   /// Set length of the array section.
7127   void setStride(Expr *E) {
7128     assert(ASType != OpenACCArraySection &&
7129            "Stride not valid in OpenACC subarrays");
7130     SubExprs[STRIDE] = E;
7131   }
7132 
7133   void setColonLocFirst(SourceLocation L) { ColonLocFirst = L; }
7134 
7135   void setColonLocSecond(SourceLocation L) {
7136     assert(ASType != OpenACCArraySection &&
7137            "second colon for stride not valid in OpenACC subarrays");
7138     ColonLocSecond = L;
7139   }
7140   void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
7141 };
7142 
7143 /// This class represents temporary values used to represent inout and out
7144 /// arguments in HLSL. From the callee perspective these parameters are more or
7145 /// less __restrict__ T&. They are guaranteed to not alias any memory. inout
7146 /// parameters are initialized by the caller, and out parameters are references
7147 /// to uninitialized memory.
7148 ///
7149 /// In the caller, the argument expression creates a temporary in local memory
7150 /// and the address of the temporary is passed into the callee. There may be
7151 /// implicit conversion sequences to initialize the temporary, and on expiration
7152 /// of the temporary an inverse conversion sequence is applied as a write-back
7153 /// conversion to the source l-value.
7154 ///
7155 /// This AST node has three sub-expressions:
7156 ///  - An OpaqueValueExpr with a source that is the argument lvalue expression.
7157 ///  - An OpaqueValueExpr with a source that is an implicit conversion
7158 ///    sequence from the source lvalue to the argument type.
7159 ///  - An expression that assigns the second expression into the first,
7160 ///    performing any necessary conversions.
7161 class HLSLOutArgExpr : public Expr {
7162   friend class ASTStmtReader;
7163 
7164   enum {
7165     BaseLValue,
7166     CastedTemporary,
7167     WritebackCast,
7168     NumSubExprs,
7169   };
7170 
7171   Stmt *SubExprs[NumSubExprs];
7172   bool IsInOut;
7173 
7174   HLSLOutArgExpr(QualType Ty, OpaqueValueExpr *B, OpaqueValueExpr *OpV,
7175                  Expr *WB, bool IsInOut)
7176       : Expr(HLSLOutArgExprClass, Ty, VK_LValue, OK_Ordinary),
7177         IsInOut(IsInOut) {
7178     SubExprs[BaseLValue] = B;
7179     SubExprs[CastedTemporary] = OpV;
7180     SubExprs[WritebackCast] = WB;
7181     assert(!Ty->isDependentType() && "HLSLOutArgExpr given a dependent type!");
7182   }
7183 
7184   explicit HLSLOutArgExpr(EmptyShell Shell)
7185       : Expr(HLSLOutArgExprClass, Shell) {}
7186 
7187 public:
7188   static HLSLOutArgExpr *Create(const ASTContext &C, QualType Ty,
7189                                 OpaqueValueExpr *Base, OpaqueValueExpr *OpV,
7190                                 Expr *WB, bool IsInOut);
7191   static HLSLOutArgExpr *CreateEmpty(const ASTContext &Ctx);
7192 
7193   const OpaqueValueExpr *getOpaqueArgLValue() const {
7194     return cast<OpaqueValueExpr>(SubExprs[BaseLValue]);
7195   }
7196   OpaqueValueExpr *getOpaqueArgLValue() {
7197     return cast<OpaqueValueExpr>(SubExprs[BaseLValue]);
7198   }
7199 
7200   /// Return the l-value expression that was written as the argument
7201   /// in source.  Everything else here is implicitly generated.
7202   const Expr *getArgLValue() const {
7203     return getOpaqueArgLValue()->getSourceExpr();
7204   }
7205   Expr *getArgLValue() { return getOpaqueArgLValue()->getSourceExpr(); }
7206 
7207   const Expr *getWritebackCast() const {
7208     return cast<Expr>(SubExprs[WritebackCast]);
7209   }
7210   Expr *getWritebackCast() { return cast<Expr>(SubExprs[WritebackCast]); }
7211 
7212   const OpaqueValueExpr *getCastedTemporary() const {
7213     return cast<OpaqueValueExpr>(SubExprs[CastedTemporary]);
7214   }
7215   OpaqueValueExpr *getCastedTemporary() {
7216     return cast<OpaqueValueExpr>(SubExprs[CastedTemporary]);
7217   }
7218 
7219   /// returns true if the parameter is inout and false if the parameter is out.
7220   bool isInOut() const { return IsInOut; }
7221 
7222   SourceLocation getBeginLoc() const LLVM_READONLY {
7223     return SubExprs[BaseLValue]->getBeginLoc();
7224   }
7225 
7226   SourceLocation getEndLoc() const LLVM_READONLY {
7227     return SubExprs[BaseLValue]->getEndLoc();
7228   }
7229 
7230   static bool classof(const Stmt *T) {
7231     return T->getStmtClass() == HLSLOutArgExprClass;
7232   }
7233 
7234   // Iterators
7235   child_range children() {
7236     return child_range(&SubExprs[BaseLValue], &SubExprs[NumSubExprs]);
7237   }
7238 };
7239 
7240 /// Frontend produces RecoveryExprs on semantic errors that prevent creating
7241 /// other well-formed expressions. E.g. when type-checking of a binary operator
7242 /// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
7243 /// to produce a recovery expression storing left and right operands.
7244 ///
7245 /// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
7246 /// preserve expressions in AST that would otherwise be dropped. It captures
7247 /// subexpressions of some expression that we could not construct and source
7248 /// range covered by the expression.
7249 ///
7250 /// By default, RecoveryExpr uses dependence-bits to take advantage of existing
7251 /// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
7252 /// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
7253 /// addition to that, clang does not report most errors on dependent
7254 /// expressions, so we get rid of bogus errors for free. However, note that
7255 /// unlike other dependent expressions, RecoveryExpr can be produced in
7256 /// non-template contexts.
7257 ///
7258 /// We will preserve the type in RecoveryExpr when the type is known, e.g.
7259 /// preserving the return type for a broken non-overloaded function call, a
7260 /// overloaded call where all candidates have the same return type. In this
7261 /// case, the expression is not type-dependent (unless the known type is itself
7262 /// dependent)
7263 ///
7264 /// One can also reliably suppress all bogus errors on expressions containing
7265 /// recovery expressions by examining results of Expr::containsErrors().
7266 class RecoveryExpr final : public Expr,
7267                            private llvm::TrailingObjects<RecoveryExpr, Expr *> {
7268 public:
7269   static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
7270                               SourceLocation BeginLoc, SourceLocation EndLoc,
7271                               ArrayRef<Expr *> SubExprs);
7272   static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
7273 
7274   ArrayRef<Expr *> subExpressions() {
7275     auto *B = getTrailingObjects<Expr *>();
7276     return llvm::ArrayRef(B, B + NumExprs);
7277   }
7278 
7279   ArrayRef<const Expr *> subExpressions() const {
7280     return const_cast<RecoveryExpr *>(this)->subExpressions();
7281   }
7282 
7283   child_range children() {
7284     Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
7285     return child_range(B, B + NumExprs);
7286   }
7287 
7288   SourceLocation getBeginLoc() const { return BeginLoc; }
7289   SourceLocation getEndLoc() const { return EndLoc; }
7290 
7291   static bool classof(const Stmt *T) {
7292     return T->getStmtClass() == RecoveryExprClass;
7293   }
7294 
7295 private:
7296   RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
7297                SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
7298   RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
7299       : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
7300 
7301   size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
7302 
7303   SourceLocation BeginLoc, EndLoc;
7304   unsigned NumExprs;
7305   friend TrailingObjects;
7306   friend class ASTStmtReader;
7307   friend class ASTStmtWriter;
7308 };
7309 
7310 } // end namespace clang
7311 
7312 #endif // LLVM_CLANG_AST_EXPR_H