Index: head/contrib/llvm/tools/clang/include/clang/AST/Expr.h =================================================================== --- head/contrib/llvm/tools/clang/include/clang/AST/Expr.h (revision 327929) +++ head/contrib/llvm/tools/clang/include/clang/AST/Expr.h (revision 327930) @@ -1,5195 +1,5202 @@ //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Expr interface and subclasses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_EXPR_H #define LLVM_CLANG_AST_EXPR_H #include "clang/AST/APValue.h" #include "clang/AST/ASTVector.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclAccessPair.h" #include "clang/AST/OperationKinds.h" #include "clang/AST/Stmt.h" #include "clang/AST/TemplateBase.h" #include "clang/AST/Type.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TypeTraits.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/AtomicOrdering.h" #include "llvm/Support/Compiler.h" namespace clang { class APValue; class ASTContext; class BlockDecl; class CXXBaseSpecifier; class CXXMemberCallExpr; class CXXOperatorCallExpr; class CastExpr; class Decl; class IdentifierInfo; class MaterializeTemporaryExpr; class NamedDecl; class ObjCPropertyRefExpr; class OpaqueValueExpr; class ParmVarDecl; class StringLiteral; class TargetInfo; class ValueDecl; /// \brief A simple array of base specifiers. typedef SmallVector CXXCastPath; /// \brief An adjustment to be made to the temporary created when emitting a /// reference binding, which accesses a particular subobject of that temporary. struct SubobjectAdjustment { enum { DerivedToBaseAdjustment, FieldAdjustment, MemberPointerAdjustment } Kind; struct DTB { const CastExpr *BasePath; const CXXRecordDecl *DerivedClass; }; struct P { const MemberPointerType *MPT; Expr *RHS; }; union { struct DTB DerivedToBase; FieldDecl *Field; struct P Ptr; }; SubobjectAdjustment(const CastExpr *BasePath, const CXXRecordDecl *DerivedClass) : Kind(DerivedToBaseAdjustment) { DerivedToBase.BasePath = BasePath; DerivedToBase.DerivedClass = DerivedClass; } SubobjectAdjustment(FieldDecl *Field) : Kind(FieldAdjustment) { this->Field = Field; } SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS) : Kind(MemberPointerAdjustment) { this->Ptr.MPT = MPT; this->Ptr.RHS = RHS; } }; /// Expr - This represents one expression. Note that Expr's are subclasses of /// Stmt. This allows an expression to be transparently used any place a Stmt /// is required. /// class Expr : public Stmt { QualType TR; protected: Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack) : Stmt(SC) { ExprBits.TypeDependent = TD; ExprBits.ValueDependent = VD; ExprBits.InstantiationDependent = ID; ExprBits.ValueKind = VK; ExprBits.ObjectKind = OK; assert(ExprBits.ObjectKind == OK && "truncated kind"); ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; setType(T); } /// \brief Construct an empty expression. explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { } public: QualType getType() const { return TR; } void setType(QualType t) { // In C++, the type of an expression is always adjusted so that it // will not have reference type (C++ [expr]p6). Use // QualType::getNonReferenceType() to retrieve the non-reference // type. Additionally, inspect Expr::isLvalue to determine whether // an expression that is adjusted in this manner should be // considered an lvalue. assert((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type"); TR = t; } /// isValueDependent - Determines whether this expression is /// value-dependent (C++ [temp.dep.constexpr]). For example, the /// array bound of "Chars" in the following example is /// value-dependent. /// @code /// template struct meta_string; /// @endcode bool isValueDependent() const { return ExprBits.ValueDependent; } /// \brief Set whether this expression is value-dependent or not. void setValueDependent(bool VD) { ExprBits.ValueDependent = VD; } /// isTypeDependent - Determines whether this expression is /// type-dependent (C++ [temp.dep.expr]), which means that its type /// could change from one template instantiation to the next. For /// example, the expressions "x" and "x + y" are type-dependent in /// the following code, but "y" is not type-dependent: /// @code /// template /// void add(T x, int y) { /// x + y; /// } /// @endcode bool isTypeDependent() const { return ExprBits.TypeDependent; } /// \brief Set whether this expression is type-dependent or not. void setTypeDependent(bool TD) { ExprBits.TypeDependent = TD; } /// \brief Whether this expression is instantiation-dependent, meaning that /// it depends in some way on a template parameter, even if neither its type /// nor (constant) value can change due to the template instantiation. /// /// In the following example, the expression \c sizeof(sizeof(T() + T())) is /// instantiation-dependent (since it involves a template parameter \c T), but /// is neither type- nor value-dependent, since the type of the inner /// \c sizeof is known (\c std::size_t) and therefore the size of the outer /// \c sizeof is known. /// /// \code /// template /// void f(T x, T y) { /// sizeof(sizeof(T() + T()); /// } /// \endcode /// bool isInstantiationDependent() const { return ExprBits.InstantiationDependent; } /// \brief Set whether this expression is instantiation-dependent or not. void setInstantiationDependent(bool ID) { ExprBits.InstantiationDependent = ID; } /// \brief Whether this expression contains an unexpanded parameter /// pack (for C++11 variadic templates). /// /// Given the following function template: /// /// \code /// template /// void forward(const F &f, Types &&...args) { /// f(static_cast(args)...); /// } /// \endcode /// /// The expressions \c args and \c static_cast(args) both /// contain parameter packs. bool containsUnexpandedParameterPack() const { return ExprBits.ContainsUnexpandedParameterPack; } /// \brief Set the bit that describes whether this expression /// contains an unexpanded parameter pack. void setContainsUnexpandedParameterPack(bool PP = true) { ExprBits.ContainsUnexpandedParameterPack = PP; } /// getExprLoc - Return the preferred location for the arrow when diagnosing /// a problem with a generic expression. SourceLocation getExprLoc() const LLVM_READONLY; /// isUnusedResultAWarning - Return true if this immediate expression should /// be warned about if the result is unused. If so, fill in expr, location, /// and ranges with expr to warn on and source locations/ranges appropriate /// for a warning. bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const; /// isLValue - True if this expression is an "l-value" according to /// the rules of the current language. C and C++ give somewhat /// different rules for this concept, but in general, the result of /// an l-value expression identifies a specific object whereas the /// result of an r-value expression is a value detached from any /// specific storage. /// /// C++11 divides the concept of "r-value" into pure r-values /// ("pr-values") and so-called expiring values ("x-values"), which /// identify specific objects that can be safely cannibalized for /// their resources. This is an unfortunate abuse of terminology on /// the part of the C++ committee. In Clang, when we say "r-value", /// we generally mean a pr-value. bool isLValue() const { return getValueKind() == VK_LValue; } bool isRValue() const { return getValueKind() == VK_RValue; } bool isXValue() const { return getValueKind() == VK_XValue; } bool isGLValue() const { return getValueKind() != VK_RValue; } enum LValueClassification { LV_Valid, LV_NotObjectType, LV_IncompleteVoidType, LV_DuplicateVectorComponents, LV_InvalidExpression, LV_InvalidMessageExpression, LV_MemberFunction, LV_SubObjCPropertySetting, LV_ClassTemporary, LV_ArrayTemporary }; /// Reasons why an expression might not be an l-value. LValueClassification ClassifyLValue(ASTContext &Ctx) const; enum isModifiableLvalueResult { MLV_Valid, MLV_NotObjectType, MLV_IncompleteVoidType, MLV_DuplicateVectorComponents, MLV_InvalidExpression, MLV_LValueCast, // Specialized form of MLV_InvalidExpression. MLV_IncompleteType, MLV_ConstQualified, MLV_ConstAddrSpace, MLV_ArrayType, MLV_NoSetterProperty, MLV_MemberFunction, MLV_SubObjCPropertySetting, MLV_InvalidMessageExpression, MLV_ClassTemporary, MLV_ArrayTemporary }; /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, /// does not have an incomplete type, does not have a const-qualified type, /// and if it is a structure or union, does not have any member (including, /// recursively, any member or element of all contained aggregates or unions) /// with a const-qualified type. /// /// \param Loc [in,out] - A source location which *may* be filled /// in with the location of the expression making this a /// non-modifiable lvalue, if specified. isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const; /// \brief The return type of classify(). Represents the C++11 expression /// taxonomy. class Classification { public: /// \brief The various classification results. Most of these mean prvalue. enum Kinds { CL_LValue, CL_XValue, CL_Function, // Functions cannot be lvalues in C. CL_Void, // Void cannot be an lvalue in C. CL_AddressableVoid, // Void expression whose address can be taken in C. CL_DuplicateVectorComponents, // A vector shuffle with dupes. CL_MemberFunction, // An expression referring to a member function CL_SubObjCPropertySetting, CL_ClassTemporary, // A temporary of class type, or subobject thereof. CL_ArrayTemporary, // A temporary of array type. CL_ObjCMessageRValue, // ObjC message is an rvalue CL_PRValue // A prvalue for any other reason, of any other type }; /// \brief The results of modification testing. enum ModifiableType { CM_Untested, // testModifiable was false. CM_Modifiable, CM_RValue, // Not modifiable because it's an rvalue CM_Function, // Not modifiable because it's a function; C++ only CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext CM_NoSetterProperty,// Implicit assignment to ObjC property without setter CM_ConstQualified, CM_ConstAddrSpace, CM_ArrayType, CM_IncompleteType }; private: friend class Expr; unsigned short Kind; unsigned short Modifiable; explicit Classification(Kinds k, ModifiableType m) : Kind(k), Modifiable(m) {} public: Classification() {} Kinds getKind() const { return static_cast(Kind); } ModifiableType getModifiable() const { assert(Modifiable != CM_Untested && "Did not test for modifiability."); return static_cast(Modifiable); } bool isLValue() const { return Kind == CL_LValue; } bool isXValue() const { return Kind == CL_XValue; } bool isGLValue() const { return Kind <= CL_XValue; } bool isPRValue() const { return Kind >= CL_Function; } bool isRValue() const { return Kind >= CL_XValue; } bool isModifiable() const { return getModifiable() == CM_Modifiable; } /// \brief Create a simple, modifiably lvalue static Classification makeSimpleLValue() { return Classification(CL_LValue, CM_Modifiable); } }; /// \brief Classify - Classify this expression according to the C++11 /// expression taxonomy. /// /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the /// old lvalue vs rvalue. This function determines the type of expression this /// is. There are three expression types: /// - lvalues are classical lvalues as in C++03. /// - prvalues are equivalent to rvalues in C++03. /// - xvalues are expressions yielding unnamed rvalue references, e.g. a /// function returning an rvalue reference. /// lvalues and xvalues are collectively referred to as glvalues, while /// prvalues and xvalues together form rvalues. Classification Classify(ASTContext &Ctx) const { return ClassifyImpl(Ctx, nullptr); } /// \brief ClassifyModifiable - Classify this expression according to the /// C++11 expression taxonomy, and see if it is valid on the left side /// of an assignment. /// /// This function extends classify in that it also tests whether the /// expression is modifiable (C99 6.3.2.1p1). /// \param Loc A source location that might be filled with a relevant location /// if the expression is not modifiable. Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{ return ClassifyImpl(Ctx, &Loc); } /// getValueKindForType - Given a formal return or parameter type, /// give its value kind. static ExprValueKind getValueKindForType(QualType T) { if (const ReferenceType *RT = T->getAs()) return (isa(RT) ? VK_LValue : (RT->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue)); return VK_RValue; } /// getValueKind - The value kind that this expression produces. ExprValueKind getValueKind() const { return static_cast(ExprBits.ValueKind); } /// getObjectKind - The object kind that this expression produces. /// Object kinds are meaningful only for expressions that yield an /// l-value or x-value. ExprObjectKind getObjectKind() const { return static_cast(ExprBits.ObjectKind); } bool isOrdinaryOrBitFieldObject() const { ExprObjectKind OK = getObjectKind(); return (OK == OK_Ordinary || OK == OK_BitField); } /// setValueKind - Set the value kind produced by this expression. void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; } /// setObjectKind - Set the object kind produced by this expression. void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; } private: Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const; public: /// \brief Returns true if this expression is a gl-value that /// potentially refers to a bit-field. /// /// In C++, whether a gl-value refers to a bitfield is essentially /// an aspect of the value-kind type system. bool refersToBitField() const { return getObjectKind() == OK_BitField; } /// \brief If this expression refers to a bit-field, retrieve the /// declaration of that bit-field. /// /// Note that this returns a non-null pointer in subtly different /// places than refersToBitField returns true. In particular, this can /// return a non-null pointer even for r-values loaded from /// bit-fields, but it will return null for a conditional bit-field. FieldDecl *getSourceBitField(); const FieldDecl *getSourceBitField() const { return const_cast(this)->getSourceBitField(); } Decl *getReferencedDeclOfCallee(); const Decl *getReferencedDeclOfCallee() const { return const_cast(this)->getReferencedDeclOfCallee(); } /// \brief If this expression is an l-value for an Objective C /// property, find the underlying property reference expression. const ObjCPropertyRefExpr *getObjCProperty() const; /// \brief Check if this expression is the ObjC 'self' implicit parameter. bool isObjCSelfExpr() const; /// \brief Returns whether this expression refers to a vector element. bool refersToVectorElement() const; /// \brief Returns whether this expression refers to a global register /// variable. bool refersToGlobalRegisterVar() const; /// \brief Returns whether this expression has a placeholder type. bool hasPlaceholderType() const { return getType()->isPlaceholderType(); } /// \brief Returns whether this expression has a specific placeholder type. bool hasPlaceholderType(BuiltinType::Kind K) const { assert(BuiltinType::isPlaceholderTypeKind(K)); if (const BuiltinType *BT = dyn_cast(getType())) return BT->getKind() == K; return false; } /// isKnownToHaveBooleanValue - Return true if this is an integer expression /// that is known to return 0 or 1. This happens for _Bool/bool expressions /// but also int expressions which are produced by things like comparisons in /// C. bool isKnownToHaveBooleanValue() const; /// isIntegerConstantExpr - Return true if this expression is a valid integer /// constant expression, and, if so, return its value in Result. If not a /// valid i-c-e, return false and fill in Loc (if specified) with the location /// of the invalid expression. /// /// Note: This does not perform the implicit conversions required by C++11 /// [expr.const]p5. bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc = nullptr, bool isEvaluated = true) const; bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr) const; /// isCXX98IntegralConstantExpr - Return true if this expression is an /// integral constant expression in C++98. Can only be used in C++. bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const; /// isCXX11ConstantExpr - Return true if this expression is a constant /// expression in C++11. Can only be used in C++. /// /// Note: This does not perform the implicit conversions required by C++11 /// [expr.const]p5. bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr, SourceLocation *Loc = nullptr) const; /// isPotentialConstantExpr - Return true if this function's definition /// might be usable in a constant expression in C++11, if it were marked /// constexpr. Return false if the function can never produce a constant /// expression, along with diagnostics describing why not. static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt> &Diags); /// isPotentialConstantExprUnevaluted - Return true if this expression might /// be usable in a constant expression in C++11 in an unevaluated context, if /// it were in function FD marked constexpr. Return false if the function can /// never produce a constant expression, along with diagnostics describing /// why not. static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt> &Diags); /// isConstantInitializer - Returns true if this expression can be emitted to /// IR as a constant, and thus can be used as a constant initializer in C. /// If this expression is not constant and Culprit is non-null, /// it is used to store the address of first non constant expr. bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit = nullptr) const; /// EvalStatus is a struct with detailed info about an evaluation in progress. struct EvalStatus { /// \brief Whether the evaluated expression has side effects. /// For example, (f() && 0) can be folded, but it still has side effects. bool HasSideEffects; /// \brief Whether the evaluation hit undefined behavior. /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior. /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB. bool HasUndefinedBehavior; /// Diag - If this is non-null, it will be filled in with a stack of notes /// indicating why evaluation failed (or why it failed to produce a constant /// expression). /// If the expression is unfoldable, the notes will indicate why it's not /// foldable. If the expression is foldable, but not a constant expression, /// the notes will describes why it isn't a constant expression. If the /// expression *is* a constant expression, no notes will be produced. SmallVectorImpl *Diag; EvalStatus() : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {} // hasSideEffects - Return true if the evaluated expression has // side effects. bool hasSideEffects() const { return HasSideEffects; } }; /// EvalResult is a struct with detailed info about an evaluated expression. struct EvalResult : EvalStatus { /// Val - This is the value the expression can be folded to. APValue Val; // isGlobalLValue - Return true if the evaluated lvalue expression // is global. bool isGlobalLValue() const; }; /// EvaluateAsRValue - Return true if this is a constant which we can fold to /// an rvalue using any crazy technique (that has nothing to do with language /// standards) that we want to, even if the expression has side-effects. If /// this function returns true, it returns the folded constant in Result. If /// the expression is a glvalue, an lvalue-to-rvalue conversion will be /// applied. bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const; /// EvaluateAsBooleanCondition - Return true if this is a constant /// which we we can fold and convert to a boolean condition using /// any crazy technique that we want to, even if the expression has /// side-effects. bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const; enum SideEffectsKind { SE_NoSideEffects, ///< Strictly evaluate the expression. SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not ///< arbitrary unmodeled side effects. SE_AllowSideEffects ///< Allow any unmodeled side effect. }; /// EvaluateAsInt - Return true if this is a constant which we can fold and /// convert to an integer, using any crazy technique that we want to. bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; /// EvaluateAsFloat - Return true if this is a constant which we can fold and /// convert to a floating point value, using any crazy technique that we /// want to. bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be /// constant folded without side-effects, but discard the result. bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects = SE_NoSideEffects) const; /// HasSideEffects - This routine returns true for all those expressions /// which have any effect other than producing a value. Example is a function /// call, volatile variable read, or throwing an exception. If /// IncludePossibleEffects is false, this call treats certain expressions with /// potential side effects (such as function call-like expressions, /// instantiation-dependent expressions, or invocations from a macro) as not /// having side effects. bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects = true) const; /// \brief Determine whether this expression involves a call to any function /// that is not trivial. bool hasNonTrivialCall(const ASTContext &Ctx) const; /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded /// integer. This must be called on an expression that constant folds to an /// integer. llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl *Diag = nullptr) const; void EvaluateForOverflow(const ASTContext &Ctx) const; /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an /// lvalue with link time known address, with no side-effects. bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const; /// EvaluateAsInitializer - Evaluate an expression as if it were the /// initializer of the given declaration. Returns true if the initializer /// can be folded to a constant, and produces any relevant notes. In C++11, /// notes will be produced if the expression is not a constant expression. bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl &Notes) const; /// EvaluateWithSubstitution - Evaluate an expression as if from the context /// of a call to the given function with the given arguments, inside an /// unevaluated context. Returns true if the expression could be folded to a /// constant. bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef Args, const Expr *This = nullptr) const; /// \brief If the current Expr is a pointer, this will try to statically /// determine the number of bytes available where the pointer is pointing. /// Returns true if all of the above holds and we were able to figure out the /// size, false otherwise. /// /// \param Type - How to evaluate the size of the Expr, as defined by the /// "type" parameter of __builtin_object_size bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const; /// \brief Enumeration used to describe the kind of Null pointer constant /// returned from \c isNullPointerConstant(). enum NullPointerConstantKind { /// \brief Expression is not a Null pointer constant. NPCK_NotNull = 0, /// \brief Expression is a Null pointer constant built from a zero integer /// expression that is not a simple, possibly parenthesized, zero literal. /// C++ Core Issue 903 will classify these expressions as "not pointers" /// once it is adopted. /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 NPCK_ZeroExpression, /// \brief Expression is a Null pointer constant built from a literal zero. NPCK_ZeroLiteral, /// \brief Expression is a C++11 nullptr. NPCK_CXX11_nullptr, /// \brief Expression is a GNU-style __null constant. NPCK_GNUNull }; /// \brief Enumeration used to describe how \c isNullPointerConstant() /// should cope with value-dependent expressions. enum NullPointerConstantValueDependence { /// \brief Specifies that the expression should never be value-dependent. NPC_NeverValueDependent = 0, /// \brief Specifies that a value-dependent expression of integral or /// dependent type should be considered a null pointer constant. NPC_ValueDependentIsNull, /// \brief Specifies that a value-dependent expression should be considered /// to never be a null pointer constant. NPC_ValueDependentIsNotNull }; /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to /// a Null pointer constant. The return value can further distinguish the /// kind of NULL pointer constant that was detected. NullPointerConstantKind isNullPointerConstant( ASTContext &Ctx, NullPointerConstantValueDependence NPC) const; /// isOBJCGCCandidate - Return true if this expression may be used in a read/ /// write barrier. bool isOBJCGCCandidate(ASTContext &Ctx) const; /// \brief Returns true if this expression is a bound member function. bool isBoundMemberFunction(ASTContext &Ctx) const; /// \brief Given an expression of bound-member type, find the type /// of the member. Returns null if this is an *overloaded* bound /// member expression. static QualType findBoundMemberType(const Expr *expr); /// IgnoreImpCasts - Skip past any implicit casts which might /// surround this expression. Only skips ImplicitCastExprs. Expr *IgnoreImpCasts() LLVM_READONLY; /// IgnoreImplicit - Skip past any implicit AST nodes which might /// surround this expression. Expr *IgnoreImplicit() LLVM_READONLY { return cast(Stmt::IgnoreImplicit()); } const Expr *IgnoreImplicit() const LLVM_READONLY { return const_cast(this)->IgnoreImplicit(); } /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return /// its subexpression. If that subexpression is also a ParenExpr, /// then this method recursively returns its subexpression, and so forth. /// Otherwise, the method returns the current Expr. Expr *IgnoreParens() LLVM_READONLY; /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr /// or CastExprs, returning their operand. Expr *IgnoreParenCasts() LLVM_READONLY; /// Ignore casts. Strip off any CastExprs, returning their operand. Expr *IgnoreCasts() LLVM_READONLY; /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off /// any ParenExpr or ImplicitCastExprs, returning their operand. Expr *IgnoreParenImpCasts() LLVM_READONLY; /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a /// call to a conversion operator, return the argument. Expr *IgnoreConversionOperator() LLVM_READONLY; const Expr *IgnoreConversionOperator() const LLVM_READONLY { return const_cast(this)->IgnoreConversionOperator(); } const Expr *IgnoreParenImpCasts() const LLVM_READONLY { return const_cast(this)->IgnoreParenImpCasts(); } /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and /// CastExprs that represent lvalue casts, returning their operand. Expr *IgnoreParenLValueCasts() LLVM_READONLY; const Expr *IgnoreParenLValueCasts() const LLVM_READONLY { return const_cast(this)->IgnoreParenLValueCasts(); } /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the /// value (including ptr->int casts of the same size). Strip off any /// ParenExpr or CastExprs, returning their operand. Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY; /// Ignore parentheses and derived-to-base casts. Expr *ignoreParenBaseCasts() LLVM_READONLY; const Expr *ignoreParenBaseCasts() const LLVM_READONLY { return const_cast(this)->ignoreParenBaseCasts(); } /// \brief Determine whether this expression is a default function argument. /// /// Default arguments are implicitly generated in the abstract syntax tree /// by semantic analysis for function calls, object constructions, etc. in /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes; /// this routine also looks through any implicit casts to determine whether /// the expression is a default argument. bool isDefaultArgument() const; /// \brief Determine whether the result of this expression is a /// temporary object of the given class type. bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const; /// \brief Whether this expression is an implicit reference to 'this' in C++. bool isImplicitCXXThis() const; const Expr *IgnoreImpCasts() const LLVM_READONLY { return const_cast(this)->IgnoreImpCasts(); } const Expr *IgnoreParens() const LLVM_READONLY { return const_cast(this)->IgnoreParens(); } const Expr *IgnoreParenCasts() const LLVM_READONLY { return const_cast(this)->IgnoreParenCasts(); } /// Strip off casts, but keep parentheses. const Expr *IgnoreCasts() const LLVM_READONLY { return const_cast(this)->IgnoreCasts(); } const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY { return const_cast(this)->IgnoreParenNoopCasts(Ctx); } static bool hasAnyTypeDependentArguments(ArrayRef Exprs); /// \brief For an expression of class type or pointer to class type, /// return the most derived class decl the expression is known to refer to. /// /// If this expression is a cast, this method looks through it to find the /// most derived decl that can be inferred from the expression. /// This is valid because derived-to-base conversions have undefined /// behavior if the object isn't dynamically of the derived type. const CXXRecordDecl *getBestDynamicClassType() const; /// \brief Get the inner expression that determines the best dynamic class. /// If this is a prvalue, we guarantee that it is of the most-derived type /// for the object itself. const Expr *getBestDynamicClassTypeExpr() const; /// Walk outwards from an expression we want to bind a reference to and /// find the expression whose lifetime needs to be extended. Record /// the LHSs of comma expressions and adjustments needed along the path. const Expr *skipRValueSubobjectAdjustments( SmallVectorImpl &CommaLHS, SmallVectorImpl &Adjustments) const; const Expr *skipRValueSubobjectAdjustments() const { SmallVector CommaLHSs; SmallVector Adjustments; return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); } static bool classof(const Stmt *T) { return T->getStmtClass() >= firstExprConstant && T->getStmtClass() <= lastExprConstant; } }; //===----------------------------------------------------------------------===// // Primary Expressions. //===----------------------------------------------------------------------===// /// OpaqueValueExpr - An expression referring to an opaque object of a /// fixed type and value class. These don't correspond to concrete /// syntax; instead they're used to express operations (usually copy /// operations) on values whose source is generally obvious from /// context. class OpaqueValueExpr : public Expr { friend class ASTStmtReader; Expr *SourceExpr; SourceLocation Loc; public: OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr) : Expr(OpaqueValueExprClass, T, VK, OK, T->isDependentType() || (SourceExpr && SourceExpr->isTypeDependent()), T->isDependentType() || (SourceExpr && SourceExpr->isValueDependent()), T->isInstantiationDependentType() || (SourceExpr && SourceExpr->isInstantiationDependent()), false), SourceExpr(SourceExpr), Loc(Loc) { } /// Given an expression which invokes a copy constructor --- i.e. a /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups --- /// find the OpaqueValueExpr that's the source of the construction. static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr); explicit OpaqueValueExpr(EmptyShell Empty) : Expr(OpaqueValueExprClass, Empty) { } /// \brief Retrieve the location of this expression. SourceLocation getLocation() const { return Loc; } SourceLocation getLocStart() const LLVM_READONLY { return SourceExpr ? SourceExpr->getLocStart() : Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return SourceExpr ? SourceExpr->getLocEnd() : Loc; } SourceLocation getExprLoc() const LLVM_READONLY { if (SourceExpr) return SourceExpr->getExprLoc(); return Loc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } /// The source expression of an opaque value expression is the /// expression which originally generated the value. This is /// provided as a convenience for analyses that don't wish to /// precisely model the execution behavior of the program. /// /// The source expression is typically set when building the /// expression which binds the opaque value expression in the first /// place. Expr *getSourceExpr() const { return SourceExpr; } static bool classof(const Stmt *T) { return T->getStmtClass() == OpaqueValueExprClass; } }; /// \brief A reference to a declared variable, function, enum, etc. /// [C99 6.5.1p2] /// /// This encodes all the information about how a declaration is referenced /// within an expression. /// /// There are several optional constructs attached to DeclRefExprs only when /// they apply in order to conserve memory. These are laid out past the end of /// the object, and flags in the DeclRefExprBitfield track whether they exist: /// /// DeclRefExprBits.HasQualifier: /// Specifies when this declaration reference expression has a C++ /// nested-name-specifier. /// DeclRefExprBits.HasFoundDecl: /// Specifies when this declaration reference expression has a record of /// a NamedDecl (different from the referenced ValueDecl) which was found /// during name lookup and/or overload resolution. /// DeclRefExprBits.HasTemplateKWAndArgsInfo: /// Specifies when this declaration reference expression has an explicit /// C++ template keyword and/or template argument list. /// DeclRefExprBits.RefersToEnclosingVariableOrCapture /// Specifies when this declaration reference expression (validly) /// refers to an enclosed local or a captured variable. class DeclRefExpr final : public Expr, private llvm::TrailingObjects { /// \brief The declaration that we are referencing. ValueDecl *D; /// \brief The location of the declaration name itself. SourceLocation Loc; /// \brief Provides source/type location info for the declaration name /// embedded in D. DeclarationNameLoc DNLoc; size_t numTrailingObjects(OverloadToken) const { return hasQualifier() ? 1 : 0; } size_t numTrailingObjects(OverloadToken) const { return hasFoundDecl() ? 1 : 0; } size_t numTrailingObjects(OverloadToken) const { return hasTemplateKWAndArgsInfo() ? 1 : 0; } /// \brief Test whether there is a distinct FoundDecl attached to the end of /// this DRE. bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; } DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnlosingVariableOrCapture, const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK); /// \brief Construct an empty declaration reference expression. explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) { } /// \brief Computes the type- and value-dependence flags for this /// declaration reference expression. void computeDependence(const ASTContext &C); public: DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T, ExprValueKind VK, SourceLocation L, const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), D(D), Loc(L), DNLoc(LocInfo) { DeclRefExprBits.HasQualifier = 0; DeclRefExprBits.HasTemplateKWAndArgsInfo = 0; DeclRefExprBits.HasFoundDecl = 0; DeclRefExprBits.HadMultipleCandidates = 0; DeclRefExprBits.RefersToEnclosingVariableOrCapture = RefersToEnclosingVariableOrCapture; computeDependence(D->getASTContext()); } static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr); static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr); /// \brief Construct an empty declaration reference expression. static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs); ValueDecl *getDecl() { return D; } const ValueDecl *getDecl() const { return D; } void setDecl(ValueDecl *NewD) { D = NewD; } DeclarationNameInfo getNameInfo() const { return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc); } SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; /// \brief Determine whether this declaration reference was preceded by a /// C++ nested-name-specifier, e.g., \c N::foo. bool hasQualifier() const { return DeclRefExprBits.HasQualifier; } /// \brief If the name was qualified, retrieves the nested-name-specifier /// that precedes the name, with source-location information. NestedNameSpecifierLoc getQualifierLoc() const { if (!hasQualifier()) return NestedNameSpecifierLoc(); return *getTrailingObjects(); } /// \brief If the name was qualified, retrieves the nested-name-specifier /// that precedes the name. Otherwise, returns NULL. NestedNameSpecifier *getQualifier() const { return getQualifierLoc().getNestedNameSpecifier(); } /// \brief Get the NamedDecl through which this reference occurred. /// /// This Decl may be different from the ValueDecl actually referred to in the /// presence of using declarations, etc. It always returns non-NULL, and may /// simple return the ValueDecl when appropriate. NamedDecl *getFoundDecl() { return hasFoundDecl() ? *getTrailingObjects() : D; } /// \brief Get the NamedDecl through which this reference occurred. /// See non-const variant. const NamedDecl *getFoundDecl() const { return hasFoundDecl() ? *getTrailingObjects() : D; } bool hasTemplateKWAndArgsInfo() const { return DeclRefExprBits.HasTemplateKWAndArgsInfo; } /// \brief Retrieve the location of the template keyword preceding /// this name, if any. SourceLocation getTemplateKeywordLoc() const { if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); return getTrailingObjects()->TemplateKWLoc; } /// \brief Retrieve the location of the left angle bracket starting the /// explicit template argument list following the name, if any. SourceLocation getLAngleLoc() const { if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); return getTrailingObjects()->LAngleLoc; } /// \brief Retrieve the location of the right angle bracket ending the /// explicit template argument list following the name, if any. SourceLocation getRAngleLoc() const { if (!hasTemplateKWAndArgsInfo()) return SourceLocation(); return getTrailingObjects()->RAngleLoc; } /// \brief Determines whether the name in this declaration reference /// was preceded by the template keyword. bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } /// \brief Determines whether this declaration reference was followed by an /// explicit template argument list. bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { if (hasExplicitTemplateArgs()) getTrailingObjects()->copyInto( getTrailingObjects(), List); } /// \brief Retrieve the template arguments provided as part of this /// template-id. const TemplateArgumentLoc *getTemplateArgs() const { if (!hasExplicitTemplateArgs()) return nullptr; return getTrailingObjects(); } /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { if (!hasExplicitTemplateArgs()) return 0; return getTrailingObjects()->NumTemplateArgs; } ArrayRef template_arguments() const { return {getTemplateArgs(), getNumTemplateArgs()}; } /// \brief Returns true if this expression refers to a function that /// was resolved from an overloaded set having size greater than 1. bool hadMultipleCandidates() const { return DeclRefExprBits.HadMultipleCandidates; } /// \brief Sets the flag telling whether this expression refers to /// a function that was resolved from an overloaded set having size /// greater than 1. void setHadMultipleCandidates(bool V = true) { DeclRefExprBits.HadMultipleCandidates = V; } /// \brief Does this DeclRefExpr refer to an enclosing local or a captured /// variable? bool refersToEnclosingVariableOrCapture() const { return DeclRefExprBits.RefersToEnclosingVariableOrCapture; } static bool classof(const Stmt *T) { return T->getStmtClass() == DeclRefExprClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } friend TrailingObjects; friend class ASTStmtReader; friend class ASTStmtWriter; }; /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__. class PredefinedExpr : public Expr { public: enum IdentType { Func, Function, LFunction, // Same as Function, but as wide string. FuncDName, FuncSig, PrettyFunction, /// \brief The same as PrettyFunction, except that the /// 'virtual' keyword is omitted for virtual member functions. PrettyFunctionNoVirtual }; private: SourceLocation Loc; IdentType Type; Stmt *FnName; public: PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT, StringLiteral *SL); /// \brief Construct an empty predefined expression. explicit PredefinedExpr(EmptyShell Empty) : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {} IdentType getIdentType() const { return Type; } SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } StringLiteral *getFunctionName(); const StringLiteral *getFunctionName() const { return const_cast(this)->getFunctionName(); } static StringRef getIdentTypeName(IdentType IT); static std::string ComputeName(IdentType IT, const Decl *CurrentDecl); SourceLocation getLocStart() const LLVM_READONLY { return Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } static bool classof(const Stmt *T) { return T->getStmtClass() == PredefinedExprClass; } // Iterators child_range children() { return child_range(&FnName, &FnName + 1); } const_child_range children() const { return const_child_range(&FnName, &FnName + 1); } friend class ASTStmtReader; }; /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without /// leaking memory. /// /// For large floats/integers, APFloat/APInt will allocate memory from the heap /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with /// the APFloat/APInt values will never get freed. APNumericStorage uses /// ASTContext's allocator for memory allocation. class APNumericStorage { union { uint64_t VAL; ///< Used to store the <= 64 bits integer value. uint64_t *pVal; ///< Used to store the >64 bits integer value. }; unsigned BitWidth; bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; } APNumericStorage(const APNumericStorage &) = delete; void operator=(const APNumericStorage &) = delete; protected: APNumericStorage() : VAL(0), BitWidth(0) { } llvm::APInt getIntValue() const { unsigned NumWords = llvm::APInt::getNumWords(BitWidth); if (NumWords > 1) return llvm::APInt(BitWidth, NumWords, pVal); else return llvm::APInt(BitWidth, VAL); } void setIntValue(const ASTContext &C, const llvm::APInt &Val); }; class APIntStorage : private APNumericStorage { public: llvm::APInt getValue() const { return getIntValue(); } void setValue(const ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); } }; class APFloatStorage : private APNumericStorage { public: llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const { return llvm::APFloat(Semantics, getIntValue()); } void setValue(const ASTContext &C, const llvm::APFloat &Val) { setIntValue(C, Val.bitcastToAPInt()); } }; class IntegerLiteral : public Expr, public APIntStorage { SourceLocation Loc; /// \brief Construct an empty integer literal. explicit IntegerLiteral(EmptyShell Empty) : Expr(IntegerLiteralClass, Empty) { } public: // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy, // or UnsignedLongLongTy IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l); /// \brief Returns a new integer literal with value 'V' and type 'type'. /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy, /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V /// \param V - the value that the returned integer literal contains. static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l); /// \brief Returns a new empty integer literal. static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty); SourceLocation getLocStart() const LLVM_READONLY { return Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } /// \brief Retrieve the location of the literal. SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation Location) { Loc = Location; } static bool classof(const Stmt *T) { return T->getStmtClass() == IntegerLiteralClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; class CharacterLiteral : public Expr { public: enum CharacterKind { Ascii, Wide, UTF8, UTF16, UTF32 }; private: unsigned Value; SourceLocation Loc; public: // type should be IntTy CharacterLiteral(unsigned value, CharacterKind kind, QualType type, SourceLocation l) : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false, false, false), Value(value), Loc(l) { CharacterLiteralBits.Kind = kind; } /// \brief Construct an empty character literal. CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { } SourceLocation getLocation() const { return Loc; } CharacterKind getKind() const { return static_cast(CharacterLiteralBits.Kind); } SourceLocation getLocStart() const LLVM_READONLY { return Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } unsigned getValue() const { return Value; } void setLocation(SourceLocation Location) { Loc = Location; } void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; } void setValue(unsigned Val) { Value = Val; } static bool classof(const Stmt *T) { return T->getStmtClass() == CharacterLiteralClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; class FloatingLiteral : public Expr, private APFloatStorage { SourceLocation Loc; FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L); /// \brief Construct an empty floating-point literal. explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty); public: static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L); static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty); llvm::APFloat getValue() const { return APFloatStorage::getValue(getSemantics()); } void setValue(const ASTContext &C, const llvm::APFloat &Val) { assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"); APFloatStorage::setValue(C, Val); } /// Get a raw enumeration value representing the floating-point semantics of /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. APFloatSemantics getRawSemantics() const { return static_cast(FloatingLiteralBits.Semantics); } /// Set the raw enumeration value representing the floating-point semantics of /// this literal (32-bit IEEE, x87, ...), suitable for serialisation. void setRawSemantics(APFloatSemantics Sem) { FloatingLiteralBits.Semantics = Sem; } /// Return the APFloat semantics this literal uses. const llvm::fltSemantics &getSemantics() const; /// Set the APFloat semantics this literal uses. void setSemantics(const llvm::fltSemantics &Sem); bool isExact() const { return FloatingLiteralBits.IsExact; } void setExact(bool E) { FloatingLiteralBits.IsExact = E; } /// getValueAsApproximateDouble - This returns the value as an inaccurate /// double. Note that this may cause loss of precision, but is useful for /// debugging dumps, etc. double getValueAsApproximateDouble() const; SourceLocation getLocation() const { return Loc; } void setLocation(SourceLocation L) { Loc = L; } SourceLocation getLocStart() const LLVM_READONLY { return Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return Loc; } static bool classof(const Stmt *T) { return T->getStmtClass() == FloatingLiteralClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// ImaginaryLiteral - We support imaginary integer and floating point literals, /// like "1.0i". We represent these as a wrapper around FloatingLiteral and /// IntegerLiteral classes. Instances of this class always have a Complex type /// whose element type matches the subexpression. /// class ImaginaryLiteral : public Expr { Stmt *Val; public: ImaginaryLiteral(Expr *val, QualType Ty) : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false, false, false), Val(val) {} /// \brief Build an empty imaginary literal. explicit ImaginaryLiteral(EmptyShell Empty) : Expr(ImaginaryLiteralClass, Empty) { } const Expr *getSubExpr() const { return cast(Val); } Expr *getSubExpr() { return cast(Val); } void setSubExpr(Expr *E) { Val = E; } SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ImaginaryLiteralClass; } // Iterators child_range children() { return child_range(&Val, &Val+1); } const_child_range children() const { return const_child_range(&Val, &Val + 1); } }; /// StringLiteral - This represents a string literal expression, e.g. "foo" /// or L"bar" (wide strings). The actual string is returned by getBytes() /// is NOT null-terminated, and the length of the string is determined by /// calling getByteLength(). The C type for a string is always a /// ConstantArrayType. In C++, the char type is const qualified, in C it is /// not. /// /// Note that strings in C can be formed by concatenation of multiple string /// literal pptokens in translation phase #6. This keeps track of the locations /// of each of these pieces. /// /// Strings in C can also be truncated and extended by assigning into arrays, /// e.g. with constructs like: /// char X[2] = "foobar"; /// In this case, getByteLength() will return 6, but the string literal will /// have type "char[2]". class StringLiteral : public Expr { public: enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 }; private: friend class ASTStmtReader; union { const char *asChar; const uint16_t *asUInt16; const uint32_t *asUInt32; } StrData; unsigned Length; unsigned CharByteWidth : 4; unsigned Kind : 3; unsigned IsPascal : 1; unsigned NumConcatenated; SourceLocation TokLocs[1]; StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false, false) {} static int mapCharByteWidth(TargetInfo const &target,StringKind k); public: /// This is the "fully general" constructor that allows representation of /// strings formed from multiple concatenated tokens. static StringLiteral *Create(const ASTContext &C, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumStrs); /// Simple constructor for string literals made from one token. static StringLiteral *Create(const ASTContext &C, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, SourceLocation Loc) { return Create(C, Str, Kind, Pascal, Ty, &Loc, 1); } /// \brief Construct an empty string literal. static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs); StringRef getString() const { assert(CharByteWidth==1 && "This function is used in places that assume strings use char"); return StringRef(StrData.asChar, getByteLength()); } /// Allow access to clients that need the byte representation, such as /// ASTWriterStmt::VisitStringLiteral(). StringRef getBytes() const { // FIXME: StringRef may not be the right type to use as a result for this. if (CharByteWidth == 1) return StringRef(StrData.asChar, getByteLength()); if (CharByteWidth == 4) return StringRef(reinterpret_cast(StrData.asUInt32), getByteLength()); assert(CharByteWidth == 2 && "unsupported CharByteWidth"); return StringRef(reinterpret_cast(StrData.asUInt16), getByteLength()); } void outputString(raw_ostream &OS) const; uint32_t getCodeUnit(size_t i) const { assert(i < Length && "out of bounds access"); if (CharByteWidth == 1) return static_cast(StrData.asChar[i]); if (CharByteWidth == 4) return StrData.asUInt32[i]; assert(CharByteWidth == 2 && "unsupported CharByteWidth"); return StrData.asUInt16[i]; } unsigned getByteLength() const { return CharByteWidth*Length; } unsigned getLength() const { return Length; } unsigned getCharByteWidth() const { return CharByteWidth; } /// \brief Sets the string data to the given string data. void setString(const ASTContext &C, StringRef Str, StringKind Kind, bool IsPascal); StringKind getKind() const { return static_cast(Kind); } bool isAscii() const { return Kind == Ascii; } bool isWide() const { return Kind == Wide; } bool isUTF8() const { return Kind == UTF8; } bool isUTF16() const { return Kind == UTF16; } bool isUTF32() const { return Kind == UTF32; } bool isPascal() const { return IsPascal; } bool containsNonAsciiOrNull() const { StringRef Str = getString(); for (unsigned i = 0, e = Str.size(); i != e; ++i) if (!isASCII(Str[i]) || !Str[i]) return true; return false; } /// getNumConcatenated - Get the number of string literal tokens that were /// concatenated in translation phase #6 to form this string literal. unsigned getNumConcatenated() const { return NumConcatenated; } SourceLocation getStrTokenLoc(unsigned TokNum) const { assert(TokNum < NumConcatenated && "Invalid tok number"); return TokLocs[TokNum]; } void setStrTokenLoc(unsigned TokNum, SourceLocation L) { assert(TokNum < NumConcatenated && "Invalid tok number"); TokLocs[TokNum] = L; } /// getLocationOfByte - Return a source location that points to the specified /// byte of this string literal. /// /// Strings are amazingly complex. They can be formed from multiple tokens /// and can have escape sequences in them in addition to the usual trigraph /// and escaped newline business. This routine handles this complexity. /// SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken = nullptr, unsigned *StartTokenByteOffset = nullptr) const; typedef const SourceLocation *tokloc_iterator; tokloc_iterator tokloc_begin() const { return TokLocs; } tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; } SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; } SourceLocation getLocEnd() const LLVM_READONLY { return TokLocs[NumConcatenated - 1]; } static bool classof(const Stmt *T) { return T->getStmtClass() == StringLiteralClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This /// AST node is only formed if full location information is requested. class ParenExpr : public Expr { SourceLocation L, R; Stmt *Val; public: ParenExpr(SourceLocation l, SourceLocation r, Expr *val) : Expr(ParenExprClass, val->getType(), val->getValueKind(), val->getObjectKind(), val->isTypeDependent(), val->isValueDependent(), val->isInstantiationDependent(), val->containsUnexpandedParameterPack()), L(l), R(r), Val(val) {} /// \brief Construct an empty parenthesized expression. explicit ParenExpr(EmptyShell Empty) : Expr(ParenExprClass, Empty) { } const Expr *getSubExpr() const { return cast(Val); } Expr *getSubExpr() { return cast(Val); } void setSubExpr(Expr *E) { Val = E; } SourceLocation getLocStart() const LLVM_READONLY { return L; } SourceLocation getLocEnd() const LLVM_READONLY { return R; } /// \brief Get the location of the left parentheses '('. SourceLocation getLParen() const { return L; } void setLParen(SourceLocation Loc) { L = Loc; } /// \brief Get the location of the right parentheses ')'. SourceLocation getRParen() const { return R; } void setRParen(SourceLocation Loc) { R = Loc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ParenExprClass; } // Iterators child_range children() { return child_range(&Val, &Val+1); } const_child_range children() const { return const_child_range(&Val, &Val + 1); } }; /// UnaryOperator - This represents the unary-expression's (except sizeof and /// alignof), the postinc/postdec operators from postfix-expression, and various /// extensions. /// /// Notes on various nodes: /// /// Real/Imag - These return the real/imag part of a complex operand. If /// applied to a non-complex value, the former returns its operand and the /// later returns zero in the type of the operand. /// class UnaryOperator : public Expr { public: typedef UnaryOperatorKind Opcode; private: unsigned Opc : 5; SourceLocation Loc; Stmt *Val; public: UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l) : Expr(UnaryOperatorClass, type, VK, OK, input->isTypeDependent() || type->isDependentType(), input->isValueDependent(), (input->isInstantiationDependent() || type->isInstantiationDependentType()), input->containsUnexpandedParameterPack()), Opc(opc), Loc(l), Val(input) {} /// \brief Build an empty unary operator. explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { } Opcode getOpcode() const { return static_cast(Opc); } void setOpcode(Opcode O) { Opc = O; } Expr *getSubExpr() const { return cast(Val); } void setSubExpr(Expr *E) { Val = E; } /// getOperatorLoc - Return the location of the operator. SourceLocation getOperatorLoc() const { return Loc; } void setOperatorLoc(SourceLocation L) { Loc = L; } /// isPostfix - Return true if this is a postfix operation, like x++. static bool isPostfix(Opcode Op) { return Op == UO_PostInc || Op == UO_PostDec; } /// isPrefix - Return true if this is a prefix operation, like --x. static bool isPrefix(Opcode Op) { return Op == UO_PreInc || Op == UO_PreDec; } bool isPrefix() const { return isPrefix(getOpcode()); } bool isPostfix() const { return isPostfix(getOpcode()); } static bool isIncrementOp(Opcode Op) { return Op == UO_PreInc || Op == UO_PostInc; } bool isIncrementOp() const { return isIncrementOp(getOpcode()); } static bool isDecrementOp(Opcode Op) { return Op == UO_PreDec || Op == UO_PostDec; } bool isDecrementOp() const { return isDecrementOp(getOpcode()); } static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; } bool isIncrementDecrementOp() const { return isIncrementDecrementOp(getOpcode()); } static bool isArithmeticOp(Opcode Op) { return Op >= UO_Plus && Op <= UO_LNot; } bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); } /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "sizeof" or "[pre]++" static StringRef getOpcodeStr(Opcode Op); /// \brief Retrieve the unary opcode that corresponds to the given /// overloaded operator. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix); /// \brief Retrieve the overloaded operator kind that corresponds to /// the given unary opcode. static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); SourceLocation getLocStart() const LLVM_READONLY { return isPostfix() ? Val->getLocStart() : Loc; } SourceLocation getLocEnd() const LLVM_READONLY { return isPostfix() ? Loc : Val->getLocEnd(); } SourceLocation getExprLoc() const LLVM_READONLY { return Loc; } static bool classof(const Stmt *T) { return T->getStmtClass() == UnaryOperatorClass; } // Iterators child_range children() { return child_range(&Val, &Val+1); } const_child_range children() const { return const_child_range(&Val, &Val + 1); } }; /// Helper class for OffsetOfExpr. // __builtin_offsetof(type, identifier(.identifier|[expr])*) class OffsetOfNode { public: /// \brief The kind of offsetof node we have. enum Kind { /// \brief An index into an array. Array = 0x00, /// \brief A field. Field = 0x01, /// \brief A field in a dependent type, known only by its name. Identifier = 0x02, /// \brief An implicit indirection through a C++ base class, when the /// field found is in a base class. Base = 0x03 }; private: enum { MaskBits = 2, Mask = 0x03 }; /// \brief The source range that covers this part of the designator. SourceRange Range; /// \brief The data describing the designator, which comes in three /// different forms, depending on the lower two bits. /// - An unsigned index into the array of Expr*'s stored after this node /// in memory, for [constant-expression] designators. /// - A FieldDecl*, for references to a known field. /// - An IdentifierInfo*, for references to a field with a given name /// when the class type is dependent. /// - A CXXBaseSpecifier*, for references that look at a field in a /// base class. uintptr_t Data; public: /// \brief Create an offsetof node that refers to an array element. OffsetOfNode(SourceLocation LBracketLoc, unsigned Index, SourceLocation RBracketLoc) : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {} /// \brief Create an offsetof node that refers to a field. OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc) : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), Data(reinterpret_cast(Field) | OffsetOfNode::Field) {} /// \brief Create an offsetof node that refers to an identifier. OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name, SourceLocation NameLoc) : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc), Data(reinterpret_cast(Name) | Identifier) {} /// \brief Create an offsetof node that refers into a C++ base class. explicit OffsetOfNode(const CXXBaseSpecifier *Base) : Range(), Data(reinterpret_cast(Base) | OffsetOfNode::Base) {} /// \brief Determine what kind of offsetof node this is. Kind getKind() const { return static_cast(Data & Mask); } /// \brief For an array element node, returns the index into the array /// of expressions. unsigned getArrayExprIndex() const { assert(getKind() == Array); return Data >> 2; } /// \brief For a field offsetof node, returns the field. FieldDecl *getField() const { assert(getKind() == Field); return reinterpret_cast(Data & ~(uintptr_t)Mask); } /// \brief For a field or identifier offsetof node, returns the name of /// the field. IdentifierInfo *getFieldName() const; /// \brief For a base class node, returns the base specifier. CXXBaseSpecifier *getBase() const { assert(getKind() == Base); return reinterpret_cast(Data & ~(uintptr_t)Mask); } /// \brief Retrieve the source range that covers this offsetof node. /// /// For an array element node, the source range contains the locations of /// the square brackets. For a field or identifier node, the source range /// contains the location of the period (if there is one) and the /// identifier. SourceRange getSourceRange() const LLVM_READONLY { return Range; } SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); } SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); } }; /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form /// offsetof(record-type, member-designator). For example, given: /// @code /// struct S { /// float f; /// double d; /// }; /// struct T { /// int i; /// struct S s[10]; /// }; /// @endcode /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d). class OffsetOfExpr final : public Expr, private llvm::TrailingObjects { SourceLocation OperatorLoc, RParenLoc; // Base type; TypeSourceInfo *TSInfo; // Number of sub-components (i.e. instances of OffsetOfNode). unsigned NumComps; // Number of sub-expressions (i.e. array subscript expressions). unsigned NumExprs; size_t numTrailingObjects(OverloadToken) const { return NumComps; } OffsetOfExpr(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef comps, ArrayRef exprs, SourceLocation RParenLoc); explicit OffsetOfExpr(unsigned numComps, unsigned numExprs) : Expr(OffsetOfExprClass, EmptyShell()), TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {} public: static OffsetOfExpr *Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef comps, ArrayRef exprs, SourceLocation RParenLoc); static OffsetOfExpr *CreateEmpty(const ASTContext &C, unsigned NumComps, unsigned NumExprs); /// getOperatorLoc - Return the location of the operator. SourceLocation getOperatorLoc() const { return OperatorLoc; } void setOperatorLoc(SourceLocation L) { OperatorLoc = L; } /// \brief Return the location of the right parentheses. SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation R) { RParenLoc = R; } TypeSourceInfo *getTypeSourceInfo() const { return TSInfo; } void setTypeSourceInfo(TypeSourceInfo *tsi) { TSInfo = tsi; } const OffsetOfNode &getComponent(unsigned Idx) const { assert(Idx < NumComps && "Subscript out of range"); return getTrailingObjects()[Idx]; } void setComponent(unsigned Idx, OffsetOfNode ON) { assert(Idx < NumComps && "Subscript out of range"); getTrailingObjects()[Idx] = ON; } unsigned getNumComponents() const { return NumComps; } Expr* getIndexExpr(unsigned Idx) { assert(Idx < NumExprs && "Subscript out of range"); return getTrailingObjects()[Idx]; } const Expr *getIndexExpr(unsigned Idx) const { assert(Idx < NumExprs && "Subscript out of range"); return getTrailingObjects()[Idx]; } void setIndexExpr(unsigned Idx, Expr* E) { assert(Idx < NumComps && "Subscript out of range"); getTrailingObjects()[Idx] = E; } unsigned getNumExpressions() const { return NumExprs; } SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == OffsetOfExprClass; } // Iterators child_range children() { Stmt **begin = reinterpret_cast(getTrailingObjects()); return child_range(begin, begin + NumExprs); } const_child_range children() const { Stmt *const *begin = reinterpret_cast(getTrailingObjects()); return const_child_range(begin, begin + NumExprs); } friend TrailingObjects; }; /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and /// vec_step (OpenCL 1.1 6.11.12). class UnaryExprOrTypeTraitExpr : public Expr { union { TypeSourceInfo *Ty; Stmt *Ex; } Argument; SourceLocation OpLoc, RParenLoc; public: UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, QualType resultType, SourceLocation op, SourceLocation rp) : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, false, // Never type-dependent (C++ [temp.dep.expr]p3). // Value-dependent if the argument is type-dependent. TInfo->getType()->isDependentType(), TInfo->getType()->isInstantiationDependentType(), TInfo->getType()->containsUnexpandedParameterPack()), OpLoc(op), RParenLoc(rp) { UnaryExprOrTypeTraitExprBits.Kind = ExprKind; UnaryExprOrTypeTraitExprBits.IsType = true; Argument.Ty = TInfo; } UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType, SourceLocation op, SourceLocation rp); /// \brief Construct an empty sizeof/alignof expression. explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty) : Expr(UnaryExprOrTypeTraitExprClass, Empty) { } UnaryExprOrTypeTrait getKind() const { return static_cast(UnaryExprOrTypeTraitExprBits.Kind); } void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;} bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; } QualType getArgumentType() const { return getArgumentTypeInfo()->getType(); } TypeSourceInfo *getArgumentTypeInfo() const { assert(isArgumentType() && "calling getArgumentType() when arg is expr"); return Argument.Ty; } Expr *getArgumentExpr() { assert(!isArgumentType() && "calling getArgumentExpr() when arg is type"); return static_cast(Argument.Ex); } const Expr *getArgumentExpr() const { return const_cast(this)->getArgumentExpr(); } void setArgument(Expr *E) { Argument.Ex = E; UnaryExprOrTypeTraitExprBits.IsType = false; } void setArgument(TypeSourceInfo *TInfo) { Argument.Ty = TInfo; UnaryExprOrTypeTraitExprBits.IsType = true; } /// Gets the argument type, or the type of the argument expression, whichever /// is appropriate. QualType getTypeOfArgument() const { return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType(); } SourceLocation getOperatorLoc() const { return OpLoc; } void setOperatorLoc(SourceLocation L) { OpLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == UnaryExprOrTypeTraitExprClass; } // Iterators child_range children(); const_child_range children() const; }; //===----------------------------------------------------------------------===// // Postfix Operators. //===----------------------------------------------------------------------===// /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting. class ArraySubscriptExpr : public Expr { enum { LHS, RHS, END_EXPR=2 }; Stmt* SubExprs[END_EXPR]; SourceLocation RBracketLoc; public: ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK, ExprObjectKind OK, SourceLocation rbracketloc) : Expr(ArraySubscriptExprClass, t, VK, OK, lhs->isTypeDependent() || rhs->isTypeDependent(), lhs->isValueDependent() || rhs->isValueDependent(), (lhs->isInstantiationDependent() || rhs->isInstantiationDependent()), (lhs->containsUnexpandedParameterPack() || rhs->containsUnexpandedParameterPack())), RBracketLoc(rbracketloc) { SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; } /// \brief Create an empty array subscript expression. explicit ArraySubscriptExpr(EmptyShell Shell) : Expr(ArraySubscriptExprClass, Shell) { } /// An array access can be written A[4] or 4[A] (both are equivalent). /// - getBase() and getIdx() always present the normalized view: A[4]. /// In this case getBase() returns "A" and getIdx() returns "4". /// - getLHS() and getRHS() present the syntactic view. e.g. for /// 4[A] getLHS() returns "4". /// Note: Because vector element access is also written A[4] we must /// predicate the format conversion in getBase and getIdx only on the /// the type of the RHS, as it is possible for the LHS to be a vector of /// integer type Expr *getLHS() { return cast(SubExprs[LHS]); } const Expr *getLHS() const { return cast(SubExprs[LHS]); } void setLHS(Expr *E) { SubExprs[LHS] = E; } Expr *getRHS() { return cast(SubExprs[RHS]); } const Expr *getRHS() const { return cast(SubExprs[RHS]); } void setRHS(Expr *E) { SubExprs[RHS] = E; } Expr *getBase() { return cast(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); } const Expr *getBase() const { return cast(getRHS()->getType()->isIntegerType() ? getLHS():getRHS()); } Expr *getIdx() { return cast(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); } const Expr *getIdx() const { return cast(getRHS()->getType()->isIntegerType() ? getRHS():getLHS()); } SourceLocation getLocStart() const LLVM_READONLY { return getLHS()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; } SourceLocation getRBracketLoc() const { return RBracketLoc; } void setRBracketLoc(SourceLocation L) { RBracketLoc = L; } SourceLocation getExprLoc() const LLVM_READONLY { return getBase()->getExprLoc(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ArraySubscriptExprClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } }; /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]). /// CallExpr itself represents a normal function call, e.g., "f(x, 2)", /// while its subclasses may represent alternative syntax that (semantically) /// results in a function call. For example, CXXOperatorCallExpr is /// a subclass for overloaded operator calls that use operator syntax, e.g., /// "str1 + str2" to resolve to a function call. class CallExpr : public Expr { enum { FN=0, PREARGS_START=1 }; Stmt **SubExprs; unsigned NumArgs; SourceLocation RParenLoc; void updateDependenciesFromArg(Expr *Arg); protected: // These versions of the constructor are for derived classes. CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef preargs, ArrayRef args, QualType t, ExprValueKind VK, SourceLocation rparenloc); CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef args, QualType t, ExprValueKind VK, SourceLocation rparenloc); CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty); Stmt *getPreArg(unsigned i) { assert(i < getNumPreArgs() && "Prearg access out of range!"); return SubExprs[PREARGS_START+i]; } const Stmt *getPreArg(unsigned i) const { assert(i < getNumPreArgs() && "Prearg access out of range!"); return SubExprs[PREARGS_START+i]; } void setPreArg(unsigned i, Stmt *PreArg) { assert(i < getNumPreArgs() && "Prearg access out of range!"); SubExprs[PREARGS_START+i] = PreArg; } unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; } public: CallExpr(const ASTContext& C, Expr *fn, ArrayRef args, QualType t, ExprValueKind VK, SourceLocation rparenloc); /// \brief Build an empty call expression. CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty); const Expr *getCallee() const { return cast(SubExprs[FN]); } Expr *getCallee() { return cast(SubExprs[FN]); } void setCallee(Expr *F) { SubExprs[FN] = F; } Decl *getCalleeDecl(); const Decl *getCalleeDecl() const { return const_cast(this)->getCalleeDecl(); } /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0. FunctionDecl *getDirectCallee(); const FunctionDecl *getDirectCallee() const { return const_cast(this)->getDirectCallee(); } /// getNumArgs - Return the number of actual arguments to this call. /// unsigned getNumArgs() const { return NumArgs; } /// \brief Retrieve the call arguments. Expr **getArgs() { return reinterpret_cast(SubExprs+getNumPreArgs()+PREARGS_START); } const Expr *const *getArgs() const { return reinterpret_cast(SubExprs + getNumPreArgs() + PREARGS_START); } /// getArg - Return the specified argument. Expr *getArg(unsigned Arg) { assert(Arg < NumArgs && "Arg access out of range!"); return cast_or_null(SubExprs[Arg + getNumPreArgs() + PREARGS_START]); } const Expr *getArg(unsigned Arg) const { assert(Arg < NumArgs && "Arg access out of range!"); return cast_or_null(SubExprs[Arg + getNumPreArgs() + PREARGS_START]); } /// setArg - Set the specified argument. void setArg(unsigned Arg, Expr *ArgExpr) { assert(Arg < NumArgs && "Arg access out of range!"); SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr; } /// setNumArgs - This changes the number of arguments present in this call. /// Any orphaned expressions are deleted by this, and any new operands are set /// to null. void setNumArgs(const ASTContext& C, unsigned NumArgs); typedef ExprIterator arg_iterator; typedef ConstExprIterator const_arg_iterator; typedef llvm::iterator_range arg_range; typedef llvm::iterator_range arg_const_range; arg_range arguments() { return arg_range(arg_begin(), arg_end()); } arg_const_range arguments() const { return arg_const_range(arg_begin(), arg_end()); } arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); } arg_iterator arg_end() { return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); } const_arg_iterator arg_begin() const { return SubExprs+PREARGS_START+getNumPreArgs(); } const_arg_iterator arg_end() const { return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs(); } /// This method provides fast access to all the subexpressions of /// a CallExpr without going through the slower virtual child_iterator /// interface. This provides efficient reverse iteration of the /// subexpressions. This is currently used for CFG construction. ArrayRef getRawSubExprs() { return llvm::makeArrayRef(SubExprs, getNumPreArgs() + PREARGS_START + getNumArgs()); } /// getNumCommas - Return the number of commas that must have been present in /// this function call. unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; } /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID /// of the callee. If not, return 0. unsigned getBuiltinCallee() const; /// \brief Returns \c true if this is a call to a builtin which does not /// evaluate side-effects within its arguments. bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const; /// getCallReturnType - Get the return type of the call expr. This is not /// always the type of the expr itself, if the return type is a reference /// type. QualType getCallReturnType(const ASTContext &Ctx) const; SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() >= firstCallExprConstant && T->getStmtClass() <= lastCallExprConstant; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs + getNumPreArgs() + PREARGS_START); } }; /// Extra data stored in some MemberExpr objects. struct MemberExprNameQualifier { /// \brief The nested-name-specifier that qualifies the name, including /// source-location information. NestedNameSpecifierLoc QualifierLoc; /// \brief The DeclAccessPair through which the MemberDecl was found due to /// name qualifiers. DeclAccessPair FoundDecl; }; /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F. /// class MemberExpr final : public Expr, private llvm::TrailingObjects { /// Base - the expression for the base pointer or structure references. In /// X.F, this is "X". Stmt *Base; /// MemberDecl - This is the decl being referenced by the field/member name. /// In X.F, this is the decl referenced by F. ValueDecl *MemberDecl; /// MemberDNLoc - Provides source/type location info for the /// declaration name embedded in MemberDecl. DeclarationNameLoc MemberDNLoc; /// MemberLoc - This is the location of the member name. SourceLocation MemberLoc; /// This is the location of the -> or . in the expression. SourceLocation OperatorLoc; /// IsArrow - True if this is "X->F", false if this is "X.F". bool IsArrow : 1; /// \brief True if this member expression used a nested-name-specifier to /// refer to the member, e.g., "x->Base::f", or found its member via a using /// declaration. When true, a MemberExprNameQualifier /// structure is allocated immediately after the MemberExpr. bool HasQualifierOrFoundDecl : 1; /// \brief True if this member expression specified a template keyword /// and/or a template argument list explicitly, e.g., x->f, /// x->template f, x->template f. /// When true, an ASTTemplateKWAndArgsInfo structure and its /// TemplateArguments (if any) are present. bool HasTemplateKWAndArgsInfo : 1; /// \brief True if this member expression refers to a method that /// was resolved from an overloaded set having size greater than 1. bool HadMultipleCandidates : 1; size_t numTrailingObjects(OverloadToken) const { return HasQualifierOrFoundDecl ? 1 : 0; } size_t numTrailingObjects(OverloadToken) const { return HasTemplateKWAndArgsInfo ? 1 : 0; } public: MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc, ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo, QualType ty, ExprValueKind VK, ExprObjectKind OK) : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(), base->isValueDependent(), base->isInstantiationDependent(), base->containsUnexpandedParameterPack()), Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc), IsArrow(isarrow), HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) { assert(memberdecl->getDeclName() == NameInfo.getName()); } // NOTE: this constructor should be used only when it is known that // the member name can not provide additional syntactic info // (i.e., source locations for C++ operator names or type source info // for constructors, destructors and conversion operators). MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc, ValueDecl *memberdecl, SourceLocation l, QualType ty, ExprValueKind VK, ExprObjectKind OK) : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(), base->isValueDependent(), base->isInstantiationDependent(), base->containsUnexpandedParameterPack()), Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l), OperatorLoc(operatorloc), IsArrow(isarrow), HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {} static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *memberdecl, DeclAccessPair founddecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *targs, QualType ty, ExprValueKind VK, ExprObjectKind OK); void setBase(Expr *E) { Base = E; } Expr *getBase() const { return cast(Base); } /// \brief Retrieve the member declaration to which this expression refers. /// /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for /// static data members), a CXXMethodDecl, or an EnumConstantDecl. ValueDecl *getMemberDecl() const { return MemberDecl; } void setMemberDecl(ValueDecl *D) { MemberDecl = D; } /// \brief Retrieves the declaration found by lookup. DeclAccessPair getFoundDecl() const { if (!HasQualifierOrFoundDecl) return DeclAccessPair::make(getMemberDecl(), getMemberDecl()->getAccess()); return getTrailingObjects()->FoundDecl; } /// \brief Determines whether this member expression actually had /// a C++ nested-name-specifier prior to the name of the member, e.g., /// x->Base::foo. bool hasQualifier() const { return getQualifier() != nullptr; } /// \brief If the member name was qualified, retrieves the /// nested-name-specifier that precedes the member name, with source-location /// information. NestedNameSpecifierLoc getQualifierLoc() const { if (!HasQualifierOrFoundDecl) return NestedNameSpecifierLoc(); return getTrailingObjects()->QualifierLoc; } /// \brief If the member name was qualified, retrieves the /// nested-name-specifier that precedes the member name. Otherwise, returns /// NULL. NestedNameSpecifier *getQualifier() const { return getQualifierLoc().getNestedNameSpecifier(); } /// \brief Retrieve the location of the template keyword preceding /// the member name, if any. SourceLocation getTemplateKeywordLoc() const { if (!HasTemplateKWAndArgsInfo) return SourceLocation(); return getTrailingObjects()->TemplateKWLoc; } /// \brief Retrieve the location of the left angle bracket starting the /// explicit template argument list following the member name, if any. SourceLocation getLAngleLoc() const { if (!HasTemplateKWAndArgsInfo) return SourceLocation(); return getTrailingObjects()->LAngleLoc; } /// \brief Retrieve the location of the right angle bracket ending the /// explicit template argument list following the member name, if any. SourceLocation getRAngleLoc() const { if (!HasTemplateKWAndArgsInfo) return SourceLocation(); return getTrailingObjects()->RAngleLoc; } /// Determines whether the member name was preceded by the template keyword. bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } /// \brief Determines whether the member name was followed by an /// explicit template argument list. bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); } /// \brief Copies the template arguments (if present) into the given /// structure. void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const { if (hasExplicitTemplateArgs()) getTrailingObjects()->copyInto( getTrailingObjects(), List); } /// \brief Retrieve the template arguments provided as part of this /// template-id. const TemplateArgumentLoc *getTemplateArgs() const { if (!hasExplicitTemplateArgs()) return nullptr; return getTrailingObjects(); } /// \brief Retrieve the number of template arguments provided as part of this /// template-id. unsigned getNumTemplateArgs() const { if (!hasExplicitTemplateArgs()) return 0; return getTrailingObjects()->NumTemplateArgs; } ArrayRef template_arguments() const { return {getTemplateArgs(), getNumTemplateArgs()}; } /// \brief Retrieve the member declaration name info. DeclarationNameInfo getMemberNameInfo() const { return DeclarationNameInfo(MemberDecl->getDeclName(), MemberLoc, MemberDNLoc); } SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; } bool isArrow() const { return IsArrow; } void setArrow(bool A) { IsArrow = A; } /// getMemberLoc - Return the location of the "member", in X->F, it is the /// location of 'F'. SourceLocation getMemberLoc() const { return MemberLoc; } void setMemberLoc(SourceLocation L) { MemberLoc = L; } SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; } /// \brief Determine whether the base of this explicit is implicit. bool isImplicitAccess() const { return getBase() && getBase()->isImplicitCXXThis(); } /// \brief Returns true if this member expression refers to a method that /// was resolved from an overloaded set having size greater than 1. bool hadMultipleCandidates() const { return HadMultipleCandidates; } /// \brief Sets the flag telling whether this expression refers to /// a method that was resolved from an overloaded set having size /// greater than 1. void setHadMultipleCandidates(bool V = true) { HadMultipleCandidates = V; } /// \brief Returns true if virtual dispatch is performed. /// If the member access is fully qualified, (i.e. X::f()), virtual /// dispatching is not performed. In -fapple-kext mode qualified /// calls to virtual method will still go through the vtable. bool performsVirtualDispatch(const LangOptions &LO) const { return LO.AppleKext || !hasQualifier(); } static bool classof(const Stmt *T) { return T->getStmtClass() == MemberExprClass; } // Iterators child_range children() { return child_range(&Base, &Base+1); } const_child_range children() const { return const_child_range(&Base, &Base + 1); } friend TrailingObjects; friend class ASTReader; friend class ASTStmtWriter; }; /// CompoundLiteralExpr - [C99 6.5.2.5] /// class CompoundLiteralExpr : public Expr { /// LParenLoc - If non-null, this is the location of the left paren in a /// compound literal like "(int){4}". This can be null if this is a /// synthesized compound expression. SourceLocation LParenLoc; /// The type as written. This can be an incomplete array type, in /// which case the actual expression type will be different. /// The int part of the pair stores whether this expr is file scope. llvm::PointerIntPair TInfoAndScope; Stmt *Init; public: CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo, QualType T, ExprValueKind VK, Expr *init, bool fileScope) : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary, tinfo->getType()->isDependentType(), init->isValueDependent(), (init->isInstantiationDependent() || tinfo->getType()->isInstantiationDependentType()), init->containsUnexpandedParameterPack()), LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {} /// \brief Construct an empty compound literal. explicit CompoundLiteralExpr(EmptyShell Empty) : Expr(CompoundLiteralExprClass, Empty) { } const Expr *getInitializer() const { return cast(Init); } Expr *getInitializer() { return cast(Init); } void setInitializer(Expr *E) { Init = E; } bool isFileScope() const { return TInfoAndScope.getInt(); } void setFileScope(bool FS) { TInfoAndScope.setInt(FS); } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } TypeSourceInfo *getTypeSourceInfo() const { return TInfoAndScope.getPointer(); } void setTypeSourceInfo(TypeSourceInfo *tinfo) { TInfoAndScope.setPointer(tinfo); } SourceLocation getLocStart() const LLVM_READONLY { // FIXME: Init should never be null. if (!Init) return SourceLocation(); if (LParenLoc.isInvalid()) return Init->getLocStart(); return LParenLoc; } SourceLocation getLocEnd() const LLVM_READONLY { // FIXME: Init should never be null. if (!Init) return SourceLocation(); return Init->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CompoundLiteralExprClass; } // Iterators child_range children() { return child_range(&Init, &Init+1); } const_child_range children() const { return const_child_range(&Init, &Init + 1); } }; /// CastExpr - Base class for type casts, including both implicit /// casts (ImplicitCastExpr) and explicit casts that have some /// representation in the source code (ExplicitCastExpr's derived /// classes). class CastExpr : public Expr { private: Stmt *Op; bool CastConsistency() const; const CXXBaseSpecifier * const *path_buffer() const { return const_cast(this)->path_buffer(); } CXXBaseSpecifier **path_buffer(); void setBasePathSize(unsigned basePathSize) { CastExprBits.BasePathSize = basePathSize; assert(CastExprBits.BasePathSize == basePathSize && "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!"); } protected: CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, Expr *op, unsigned BasePathSize) : Expr(SC, ty, VK, OK_Ordinary, // Cast expressions are type-dependent if the type is // dependent (C++ [temp.dep.expr]p3). ty->isDependentType(), // Cast expressions are value-dependent if the type is // dependent or if the subexpression is value-dependent. ty->isDependentType() || (op && op->isValueDependent()), (ty->isInstantiationDependentType() || (op && op->isInstantiationDependent())), // An implicit cast expression doesn't (lexically) contain an // unexpanded pack, even if its target type does. ((SC != ImplicitCastExprClass && ty->containsUnexpandedParameterPack()) || (op && op->containsUnexpandedParameterPack()))), Op(op) { assert(kind != CK_Invalid && "creating cast with invalid cast kind"); CastExprBits.Kind = kind; setBasePathSize(BasePathSize); assert(CastConsistency()); } /// \brief Construct an empty cast. CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize) : Expr(SC, Empty) { setBasePathSize(BasePathSize); } public: CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; } void setCastKind(CastKind K) { CastExprBits.Kind = K; } const char *getCastKindName() const; Expr *getSubExpr() { return cast(Op); } const Expr *getSubExpr() const { return cast(Op); } void setSubExpr(Expr *E) { Op = E; } /// \brief Retrieve the cast subexpression as it was written in the source /// code, looking through any implicit casts or other intermediate nodes /// introduced by semantic analysis. Expr *getSubExprAsWritten(); const Expr *getSubExprAsWritten() const { return const_cast(this)->getSubExprAsWritten(); } typedef CXXBaseSpecifier **path_iterator; typedef const CXXBaseSpecifier * const *path_const_iterator; bool path_empty() const { return CastExprBits.BasePathSize == 0; } unsigned path_size() const { return CastExprBits.BasePathSize; } path_iterator path_begin() { return path_buffer(); } path_iterator path_end() { return path_buffer() + path_size(); } path_const_iterator path_begin() const { return path_buffer(); } path_const_iterator path_end() const { return path_buffer() + path_size(); } static bool classof(const Stmt *T) { return T->getStmtClass() >= firstCastExprConstant && T->getStmtClass() <= lastCastExprConstant; } // Iterators child_range children() { return child_range(&Op, &Op+1); } const_child_range children() const { return const_child_range(&Op, &Op + 1); } }; /// ImplicitCastExpr - Allows us to explicitly represent implicit type /// conversions, which have no direct representation in the original /// source code. For example: converting T[]->T*, void f()->void /// (*f)(), float->double, short->int, etc. /// /// In C, implicit casts always produce rvalues. However, in C++, an /// implicit cast whose result is being bound to a reference will be /// an lvalue or xvalue. For example: /// /// @code /// class Base { }; /// class Derived : public Base { }; /// Derived &&ref(); /// void f(Derived d) { /// Base& b = d; // initializer is an ImplicitCastExpr /// // to an lvalue of type Base /// Base&& r = ref(); // initializer is an ImplicitCastExpr /// // to an xvalue of type Base /// } /// @endcode class ImplicitCastExpr final : public CastExpr, private llvm::TrailingObjects { private: ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, unsigned BasePathLength, ExprValueKind VK) : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { } /// \brief Construct an empty implicit cast. explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize) : CastExpr(ImplicitCastExprClass, Shell, PathSize) { } public: enum OnStack_t { OnStack }; ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op, ExprValueKind VK) : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) { } static ImplicitCastExpr *Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat); static ImplicitCastExpr *CreateEmpty(const ASTContext &Context, unsigned PathSize); SourceLocation getLocStart() const LLVM_READONLY { return getSubExpr()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getSubExpr()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ImplicitCastExprClass; } friend TrailingObjects; friend class CastExpr; }; inline Expr *Expr::IgnoreImpCasts() { Expr *e = this; while (ImplicitCastExpr *ice = dyn_cast(e)) e = ice->getSubExpr(); return e; } /// ExplicitCastExpr - An explicit cast written in the source /// code. /// /// This class is effectively an abstract class, because it provides /// the basic representation of an explicitly-written cast without /// specifying which kind of cast (C cast, functional cast, static /// cast, etc.) was written; specific derived classes represent the /// particular style of cast and its location information. /// /// Unlike implicit casts, explicit cast nodes have two different /// types: the type that was written into the source code, and the /// actual type of the expression as determined by semantic /// analysis. These types may differ slightly. For example, in C++ one /// can cast to a reference type, which indicates that the resulting /// expression will be an lvalue or xvalue. The reference type, however, /// will not be used as the type of the expression. class ExplicitCastExpr : public CastExpr { /// TInfo - Source type info for the (written) type /// this expression is casting to. TypeSourceInfo *TInfo; protected: ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK, CastKind kind, Expr *op, unsigned PathSize, TypeSourceInfo *writtenTy) : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {} /// \brief Construct an empty explicit cast. ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize) : CastExpr(SC, Shell, PathSize) { } public: /// getTypeInfoAsWritten - Returns the type source info for the type /// that this expression is casting to. TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; } void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; } /// getTypeAsWritten - Returns the type that this expression is /// casting to, as written in the source code. QualType getTypeAsWritten() const { return TInfo->getType(); } static bool classof(const Stmt *T) { return T->getStmtClass() >= firstExplicitCastExprConstant && T->getStmtClass() <= lastExplicitCastExprConstant; } }; /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style /// cast in C++ (C++ [expr.cast]), which uses the syntax /// (Type)expr. For example: @c (int)f. class CStyleCastExpr final : public ExplicitCastExpr, private llvm::TrailingObjects { SourceLocation LPLoc; // the location of the left paren SourceLocation RPLoc; // the location of the right paren CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op, unsigned PathSize, TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r) : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize, writtenTy), LPLoc(l), RPLoc(r) {} /// \brief Construct an empty C-style explicit cast. explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize) : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { } public: static CStyleCastExpr *Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R); static CStyleCastExpr *CreateEmpty(const ASTContext &Context, unsigned PathSize); SourceLocation getLParenLoc() const { return LPLoc; } void setLParenLoc(SourceLocation L) { LPLoc = L; } SourceLocation getRParenLoc() const { return RPLoc; } void setRParenLoc(SourceLocation L) { RPLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return getSubExpr()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == CStyleCastExprClass; } friend TrailingObjects; friend class CastExpr; }; /// \brief A builtin binary operation expression such as "x + y" or "x <= y". /// /// This expression node kind describes a builtin binary operation, /// such as "x + y" for integer values "x" and "y". The operands will /// already have been converted to appropriate types (e.g., by /// performing promotions or conversions). /// /// In C++, where operators may be overloaded, a different kind of /// expression node (CXXOperatorCallExpr) is used to express the /// invocation of an overloaded operator with operator syntax. Within /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is /// used to store an expression "x + y" depends on the subexpressions /// for x and y. If neither x or y is type-dependent, and the "+" /// operator resolves to a built-in operation, BinaryOperator will be /// used to express the computation (x and y may still be /// value-dependent). If either x or y is type-dependent, or if the /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will /// be used to express the computation. class BinaryOperator : public Expr { public: typedef BinaryOperatorKind Opcode; private: unsigned Opc : 6; // This is only meaningful for operations on floating point types and 0 // otherwise. unsigned FPFeatures : 2; SourceLocation OpLoc; enum { LHS, RHS, END_EXPR }; Stmt* SubExprs[END_EXPR]; public: BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptions FPFeatures) : Expr(BinaryOperatorClass, ResTy, VK, OK, lhs->isTypeDependent() || rhs->isTypeDependent(), lhs->isValueDependent() || rhs->isValueDependent(), (lhs->isInstantiationDependent() || rhs->isInstantiationDependent()), (lhs->containsUnexpandedParameterPack() || rhs->containsUnexpandedParameterPack())), Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) { SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; assert(!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments"); } /// \brief Construct an empty binary operator. explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { } SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; } SourceLocation getOperatorLoc() const { return OpLoc; } void setOperatorLoc(SourceLocation L) { OpLoc = L; } Opcode getOpcode() const { return static_cast(Opc); } void setOpcode(Opcode O) { Opc = O; } Expr *getLHS() const { return cast(SubExprs[LHS]); } void setLHS(Expr *E) { SubExprs[LHS] = E; } Expr *getRHS() const { return cast(SubExprs[RHS]); } void setRHS(Expr *E) { SubExprs[RHS] = E; } SourceLocation getLocStart() const LLVM_READONLY { return getLHS()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getRHS()->getLocEnd(); } /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "<<=". static StringRef getOpcodeStr(Opcode Op); StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); } /// \brief Retrieve the binary opcode that corresponds to the given /// overloaded operator. static Opcode getOverloadedOpcode(OverloadedOperatorKind OO); /// \brief Retrieve the overloaded operator kind that corresponds to /// the given binary opcode. static OverloadedOperatorKind getOverloadedOperator(Opcode Opc); /// predicates to categorize the respective opcodes. bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; } static bool isMultiplicativeOp(Opcode Opc) { return Opc >= BO_Mul && Opc <= BO_Rem; } bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); } static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; } bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); } static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; } bool isShiftOp() const { return isShiftOp(getOpcode()); } static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; } bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); } static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; } bool isRelationalOp() const { return isRelationalOp(getOpcode()); } static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; } bool isEqualityOp() const { return isEqualityOp(getOpcode()); } static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; } bool isComparisonOp() const { return isComparisonOp(getOpcode()); } static Opcode negateComparisonOp(Opcode Opc) { switch (Opc) { default: llvm_unreachable("Not a comparsion operator."); case BO_LT: return BO_GE; case BO_GT: return BO_LE; case BO_LE: return BO_GT; case BO_GE: return BO_LT; case BO_EQ: return BO_NE; case BO_NE: return BO_EQ; } } static Opcode reverseComparisonOp(Opcode Opc) { switch (Opc) { default: llvm_unreachable("Not a comparsion operator."); case BO_LT: return BO_GT; case BO_GT: return BO_LT; case BO_LE: return BO_GE; case BO_GE: return BO_LE; case BO_EQ: case BO_NE: return Opc; } } static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; } bool isLogicalOp() const { return isLogicalOp(getOpcode()); } static bool isAssignmentOp(Opcode Opc) { return Opc >= BO_Assign && Opc <= BO_OrAssign; } bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); } static bool isCompoundAssignmentOp(Opcode Opc) { return Opc > BO_Assign && Opc <= BO_OrAssign; } bool isCompoundAssignmentOp() const { return isCompoundAssignmentOp(getOpcode()); } static Opcode getOpForCompoundAssignment(Opcode Opc) { assert(isCompoundAssignmentOp(Opc)); if (Opc >= BO_AndAssign) return Opcode(unsigned(Opc) - BO_AndAssign + BO_And); else return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul); } static bool isShiftAssignOp(Opcode Opc) { return Opc == BO_ShlAssign || Opc == BO_ShrAssign; } bool isShiftAssignOp() const { return isShiftAssignOp(getOpcode()); } static bool classof(const Stmt *S) { return S->getStmtClass() >= firstBinaryOperatorConstant && S->getStmtClass() <= lastBinaryOperatorConstant; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } // Set the FP contractability status of this operator. Only meaningful for // operations on floating point types. void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); } FPOptions getFPFeatures() const { return FPOptions(FPFeatures); } // Get the FP contractability status of this operator. Only meaningful for // operations on floating point types. bool isFPContractableWithinStatement() const { return FPOptions(FPFeatures).allowFPContractWithinStatement(); } protected: BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptions FPFeatures, bool dead2) : Expr(CompoundAssignOperatorClass, ResTy, VK, OK, lhs->isTypeDependent() || rhs->isTypeDependent(), lhs->isValueDependent() || rhs->isValueDependent(), (lhs->isInstantiationDependent() || rhs->isInstantiationDependent()), (lhs->containsUnexpandedParameterPack() || rhs->containsUnexpandedParameterPack())), Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) { SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; } BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty), Opc(BO_MulAssign) { } }; /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep /// track of the type the operation is performed in. Due to the semantics of /// these operators, the operands are promoted, the arithmetic performed, an /// implicit conversion back to the result type done, then the assignment takes /// place. This captures the intermediate type which the computation is done /// in. class CompoundAssignOperator : public BinaryOperator { QualType ComputationLHSType; QualType ComputationResultType; public: CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType, ExprValueKind VK, ExprObjectKind OK, QualType CompLHSType, QualType CompResultType, SourceLocation OpLoc, FPOptions FPFeatures) : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures, true), ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) { assert(isCompoundAssignmentOp() && "Only should be used for compound assignments"); } /// \brief Build an empty compound assignment operator expression. explicit CompoundAssignOperator(EmptyShell Empty) : BinaryOperator(CompoundAssignOperatorClass, Empty) { } // The two computation types are the type the LHS is converted // to for the computation and the type of the result; the two are // distinct in a few cases (specifically, int+=ptr and ptr-=ptr). QualType getComputationLHSType() const { return ComputationLHSType; } void setComputationLHSType(QualType T) { ComputationLHSType = T; } QualType getComputationResultType() const { return ComputationResultType; } void setComputationResultType(QualType T) { ComputationResultType = T; } static bool classof(const Stmt *S) { return S->getStmtClass() == CompoundAssignOperatorClass; } }; /// AbstractConditionalOperator - An abstract base class for /// ConditionalOperator and BinaryConditionalOperator. class AbstractConditionalOperator : public Expr { SourceLocation QuestionLoc, ColonLoc; friend class ASTStmtReader; protected: AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK, bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack, SourceLocation qloc, SourceLocation cloc) : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack), QuestionLoc(qloc), ColonLoc(cloc) {} AbstractConditionalOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) { } public: // getCond - Return the expression representing the condition for // the ?: operator. Expr *getCond() const; // getTrueExpr - Return the subexpression representing the value of // the expression if the condition evaluates to true. Expr *getTrueExpr() const; // getFalseExpr - Return the subexpression representing the value of // the expression if the condition evaluates to false. This is // the same as getRHS. Expr *getFalseExpr() const; SourceLocation getQuestionLoc() const { return QuestionLoc; } SourceLocation getColonLoc() const { return ColonLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ConditionalOperatorClass || T->getStmtClass() == BinaryConditionalOperatorClass; } }; /// ConditionalOperator - The ?: ternary operator. The GNU "missing /// middle" extension is a BinaryConditionalOperator. class ConditionalOperator : public AbstractConditionalOperator { enum { COND, LHS, RHS, END_EXPR }; Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. friend class ASTStmtReader; public: ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs, SourceLocation CLoc, Expr *rhs, QualType t, ExprValueKind VK, ExprObjectKind OK) : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, // FIXME: the type of the conditional operator doesn't // depend on the type of the conditional, but the standard // seems to imply that it could. File a bug! (lhs->isTypeDependent() || rhs->isTypeDependent()), (cond->isValueDependent() || lhs->isValueDependent() || rhs->isValueDependent()), (cond->isInstantiationDependent() || lhs->isInstantiationDependent() || rhs->isInstantiationDependent()), (cond->containsUnexpandedParameterPack() || lhs->containsUnexpandedParameterPack() || rhs->containsUnexpandedParameterPack()), QLoc, CLoc) { SubExprs[COND] = cond; SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; } /// \brief Build an empty conditional operator. explicit ConditionalOperator(EmptyShell Empty) : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { } // getCond - Return the expression representing the condition for // the ?: operator. Expr *getCond() const { return cast(SubExprs[COND]); } // getTrueExpr - Return the subexpression representing the value of // the expression if the condition evaluates to true. Expr *getTrueExpr() const { return cast(SubExprs[LHS]); } // getFalseExpr - Return the subexpression representing the value of // the expression if the condition evaluates to false. This is // the same as getRHS. Expr *getFalseExpr() const { return cast(SubExprs[RHS]); } Expr *getLHS() const { return cast(SubExprs[LHS]); } Expr *getRHS() const { return cast(SubExprs[RHS]); } SourceLocation getLocStart() const LLVM_READONLY { return getCond()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getRHS()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == ConditionalOperatorClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } }; /// BinaryConditionalOperator - The GNU extension to the conditional /// operator which allows the middle operand to be omitted. /// /// This is a different expression kind on the assumption that almost /// every client ends up needing to know that these are different. class BinaryConditionalOperator : public AbstractConditionalOperator { enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS }; /// - the common condition/left-hand-side expression, which will be /// evaluated as the opaque value /// - the condition, expressed in terms of the opaque value /// - the left-hand-side, expressed in terms of the opaque value /// - the right-hand-side Stmt *SubExprs[NUM_SUBEXPRS]; OpaqueValueExpr *OpaqueValue; friend class ASTStmtReader; public: BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue, Expr *cond, Expr *lhs, Expr *rhs, SourceLocation qloc, SourceLocation cloc, QualType t, ExprValueKind VK, ExprObjectKind OK) : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK, (common->isTypeDependent() || rhs->isTypeDependent()), (common->isValueDependent() || rhs->isValueDependent()), (common->isInstantiationDependent() || rhs->isInstantiationDependent()), (common->containsUnexpandedParameterPack() || rhs->containsUnexpandedParameterPack()), qloc, cloc), OpaqueValue(opaqueValue) { SubExprs[COMMON] = common; SubExprs[COND] = cond; SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value"); } /// \brief Build an empty conditional operator. explicit BinaryConditionalOperator(EmptyShell Empty) : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { } /// \brief getCommon - Return the common expression, written to the /// left of the condition. The opaque value will be bound to the /// result of this expression. Expr *getCommon() const { return cast(SubExprs[COMMON]); } /// \brief getOpaqueValue - Return the opaque value placeholder. OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; } /// \brief getCond - Return the condition expression; this is defined /// in terms of the opaque value. Expr *getCond() const { return cast(SubExprs[COND]); } /// \brief getTrueExpr - Return the subexpression which will be /// evaluated if the condition evaluates to true; this is defined /// in terms of the opaque value. Expr *getTrueExpr() const { return cast(SubExprs[LHS]); } /// \brief getFalseExpr - Return the subexpression which will be /// evaluated if the condnition evaluates to false; this is /// defined in terms of the opaque value. Expr *getFalseExpr() const { return cast(SubExprs[RHS]); } SourceLocation getLocStart() const LLVM_READONLY { return getCommon()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getFalseExpr()->getLocEnd(); } static bool classof(const Stmt *T) { return T->getStmtClass() == BinaryConditionalOperatorClass; } // Iterators child_range children() { return child_range(SubExprs, SubExprs + NUM_SUBEXPRS); } const_child_range children() const { return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS); } }; inline Expr *AbstractConditionalOperator::getCond() const { if (const ConditionalOperator *co = dyn_cast(this)) return co->getCond(); return cast(this)->getCond(); } inline Expr *AbstractConditionalOperator::getTrueExpr() const { if (const ConditionalOperator *co = dyn_cast(this)) return co->getTrueExpr(); return cast(this)->getTrueExpr(); } inline Expr *AbstractConditionalOperator::getFalseExpr() const { if (const ConditionalOperator *co = dyn_cast(this)) return co->getFalseExpr(); return cast(this)->getFalseExpr(); } /// AddrLabelExpr - The GNU address of label extension, representing &&label. class AddrLabelExpr : public Expr { SourceLocation AmpAmpLoc, LabelLoc; LabelDecl *Label; public: AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L, QualType t) : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false, false), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {} /// \brief Build an empty address of a label expression. explicit AddrLabelExpr(EmptyShell Empty) : Expr(AddrLabelExprClass, Empty) { } SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; } void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; } SourceLocation getLabelLoc() const { return LabelLoc; } void setLabelLoc(SourceLocation L) { LabelLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; } LabelDecl *getLabel() const { return Label; } void setLabel(LabelDecl *L) { Label = L; } static bool classof(const Stmt *T) { return T->getStmtClass() == AddrLabelExprClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}). /// The StmtExpr contains a single CompoundStmt node, which it evaluates and /// takes the value of the last subexpression. /// /// A StmtExpr is always an r-value; values "returned" out of a /// StmtExpr will be copied. class StmtExpr : public Expr { Stmt *SubStmt; SourceLocation LParenLoc, RParenLoc; public: // FIXME: Does type-dependence need to be computed differently? // FIXME: Do we need to compute instantiation instantiation-dependence for // statements? (ugh!) StmtExpr(CompoundStmt *substmt, QualType T, SourceLocation lp, SourceLocation rp) : Expr(StmtExprClass, T, VK_RValue, OK_Ordinary, T->isDependentType(), false, false, false), SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { } /// \brief Build an empty statement expression. explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { } CompoundStmt *getSubStmt() { return cast(SubStmt); } const CompoundStmt *getSubStmt() const { return cast(SubStmt); } void setSubStmt(CompoundStmt *S) { SubStmt = S; } SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } SourceLocation getLParenLoc() const { return LParenLoc; } void setLParenLoc(SourceLocation L) { LParenLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } static bool classof(const Stmt *T) { return T->getStmtClass() == StmtExprClass; } // Iterators child_range children() { return child_range(&SubStmt, &SubStmt+1); } const_child_range children() const { return const_child_range(&SubStmt, &SubStmt + 1); } }; /// ShuffleVectorExpr - clang-specific builtin-in function /// __builtin_shufflevector. /// This AST node represents a operator that does a constant /// shuffle, similar to LLVM's shufflevector instruction. It takes /// two vectors and a variable number of constant indices, /// and returns the appropriately shuffled vector. class ShuffleVectorExpr : public Expr { SourceLocation BuiltinLoc, RParenLoc; // SubExprs - the list of values passed to the __builtin_shufflevector // function. The first two are vectors, and the rest are constant // indices. The number of values in this list is always // 2+the number of indices in the vector type. Stmt **SubExprs; unsigned NumExprs; public: ShuffleVectorExpr(const ASTContext &C, ArrayRef args, QualType Type, SourceLocation BLoc, SourceLocation RP); /// \brief Build an empty vector-shuffle expression. explicit ShuffleVectorExpr(EmptyShell Empty) : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { } SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ShuffleVectorExprClass; } /// getNumSubExprs - Return the size of the SubExprs array. This includes the /// constant expression, the actual arguments passed in, and the function /// pointers. unsigned getNumSubExprs() const { return NumExprs; } /// \brief Retrieve the array of expressions. Expr **getSubExprs() { return reinterpret_cast(SubExprs); } /// getExpr - Return the Expr at the specified index. Expr *getExpr(unsigned Index) { assert((Index < NumExprs) && "Arg access out of range!"); return cast(SubExprs[Index]); } const Expr *getExpr(unsigned Index) const { assert((Index < NumExprs) && "Arg access out of range!"); return cast(SubExprs[Index]); } void setExprs(const ASTContext &C, ArrayRef Exprs); llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const { assert((N < NumExprs - 2) && "Shuffle idx out of range!"); return getExpr(N+2)->EvaluateKnownConstInt(Ctx); } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+NumExprs); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs); } }; /// ConvertVectorExpr - Clang builtin function __builtin_convertvector /// This AST node provides support for converting a vector type to another /// vector type of the same arity. class ConvertVectorExpr : public Expr { private: Stmt *SrcExpr; TypeSourceInfo *TInfo; SourceLocation BuiltinLoc, RParenLoc; friend class ASTReader; friend class ASTStmtReader; explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} public: ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc) : Expr(ConvertVectorExprClass, DstType, VK, OK, DstType->isDependentType(), DstType->isDependentType() || SrcExpr->isValueDependent(), (DstType->isInstantiationDependentType() || SrcExpr->isInstantiationDependent()), (DstType->containsUnexpandedParameterPack() || SrcExpr->containsUnexpandedParameterPack())), SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} /// getSrcExpr - Return the Expr to be converted. Expr *getSrcExpr() const { return cast(SrcExpr); } /// getTypeSourceInfo - Return the destination type. TypeSourceInfo *getTypeSourceInfo() const { return TInfo; } void setTypeSourceInfo(TypeSourceInfo *ti) { TInfo = ti; } /// getBuiltinLoc - Return the location of the __builtin_convertvector token. SourceLocation getBuiltinLoc() const { return BuiltinLoc; } /// getRParenLoc - Return the location of final right parenthesis. SourceLocation getRParenLoc() const { return RParenLoc; } SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ConvertVectorExprClass; } // Iterators child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } const_child_range children() const { return const_child_range(&SrcExpr, &SrcExpr + 1); } }; /// ChooseExpr - GNU builtin-in function __builtin_choose_expr. /// This AST node is similar to the conditional operator (?:) in C, with /// the following exceptions: /// - the test expression must be a integer constant expression. /// - the expression returned acts like the chosen subexpression in every /// visible way: the type is the same as that of the chosen subexpression, /// and all predicates (whether it's an l-value, whether it's an integer /// constant expression, etc.) return the same result as for the chosen /// sub-expression. class ChooseExpr : public Expr { enum { COND, LHS, RHS, END_EXPR }; Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides. SourceLocation BuiltinLoc, RParenLoc; bool CondIsTrue; public: ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK, ExprObjectKind OK, SourceLocation RP, bool condIsTrue, bool TypeDependent, bool ValueDependent) : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent, (cond->isInstantiationDependent() || lhs->isInstantiationDependent() || rhs->isInstantiationDependent()), (cond->containsUnexpandedParameterPack() || lhs->containsUnexpandedParameterPack() || rhs->containsUnexpandedParameterPack())), BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) { SubExprs[COND] = cond; SubExprs[LHS] = lhs; SubExprs[RHS] = rhs; } /// \brief Build an empty __builtin_choose_expr. explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { } /// isConditionTrue - Return whether the condition is true (i.e. not /// equal to zero). bool isConditionTrue() const { assert(!isConditionDependent() && "Dependent condition isn't true or false"); return CondIsTrue; } void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; } bool isConditionDependent() const { return getCond()->isTypeDependent() || getCond()->isValueDependent(); } /// getChosenSubExpr - Return the subexpression chosen according to the /// condition. Expr *getChosenSubExpr() const { return isConditionTrue() ? getLHS() : getRHS(); } Expr *getCond() const { return cast(SubExprs[COND]); } void setCond(Expr *E) { SubExprs[COND] = E; } Expr *getLHS() const { return cast(SubExprs[LHS]); } void setLHS(Expr *E) { SubExprs[LHS] = E; } Expr *getRHS() const { return cast(SubExprs[RHS]); } void setRHS(Expr *E) { SubExprs[RHS] = E; } SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ChooseExprClass; } // Iterators child_range children() { return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR); } const_child_range children() const { return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR); } }; /// GNUNullExpr - Implements the GNU __null extension, which is a name /// for a null pointer constant that has integral type (e.g., int or /// long) and is the same size and alignment as a pointer. The __null /// extension is typically only used by system headers, which define /// NULL as __null in C++ rather than using 0 (which is an integer /// that may not match the size of a pointer). class GNUNullExpr : public Expr { /// TokenLoc - The location of the __null keyword. SourceLocation TokenLoc; public: GNUNullExpr(QualType Ty, SourceLocation Loc) : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false, false), TokenLoc(Loc) { } /// \brief Build an empty GNU __null expression. explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { } /// getTokenLocation - The location of the __null token. SourceLocation getTokenLocation() const { return TokenLoc; } void setTokenLocation(SourceLocation L) { TokenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GNUNullExprClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// Represents a call to the builtin function \c __builtin_va_arg. class VAArgExpr : public Expr { Stmt *Val; llvm::PointerIntPair TInfo; SourceLocation BuiltinLoc, RParenLoc; public: VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo, SourceLocation RPLoc, QualType t, bool IsMS) : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(), false, (TInfo->getType()->isInstantiationDependentType() || e->isInstantiationDependent()), (TInfo->getType()->containsUnexpandedParameterPack() || e->containsUnexpandedParameterPack())), Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {} /// Create an empty __builtin_va_arg expression. explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {} const Expr *getSubExpr() const { return cast(Val); } Expr *getSubExpr() { return cast(Val); } void setSubExpr(Expr *E) { Val = E; } /// Returns whether this is really a Win64 ABI va_arg expression. bool isMicrosoftABI() const { return TInfo.getInt(); } void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); } TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); } void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); } SourceLocation getBuiltinLoc() const { return BuiltinLoc; } void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; } SourceLocation getRParenLoc() const { return RParenLoc; } void setRParenLoc(SourceLocation L) { RParenLoc = L; } SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == VAArgExprClass; } // Iterators child_range children() { return child_range(&Val, &Val+1); } const_child_range children() const { return const_child_range(&Val, &Val + 1); } }; /// @brief Describes an C or C++ initializer list. /// /// InitListExpr describes an initializer list, which can be used to /// initialize objects of different types, including /// struct/class/union types, arrays, and vectors. For example: /// /// @code /// struct foo x = { 1, { 2, 3 } }; /// @endcode /// /// Prior to semantic analysis, an initializer list will represent the /// initializer list as written by the user, but will have the /// placeholder type "void". This initializer list is called the /// syntactic form of the initializer, and may contain C99 designated /// initializers (represented as DesignatedInitExprs), initializations /// of subobject members without explicit braces, and so on. Clients /// interested in the original syntax of the initializer list should /// use the syntactic form of the initializer list. /// /// After semantic analysis, the initializer list will represent the /// semantic form of the initializer, where the initializations of all /// subobjects are made explicit with nested InitListExpr nodes and /// C99 designators have been eliminated by placing the designated /// initializations into the subobject they initialize. Additionally, /// any "holes" in the initialization, where no initializer has been /// specified for a particular subobject, will be replaced with /// implicitly-generated ImplicitValueInitExpr expressions that /// value-initialize the subobjects. Note, however, that the /// initializer lists may still have fewer initializers than there are /// elements to initialize within the object. /// /// After semantic analysis has completed, given an initializer list, /// method isSemanticForm() returns true if and only if this is the /// semantic form of the initializer list (note: the same AST node /// may at the same time be the syntactic form). /// Given the semantic form of the initializer list, one can retrieve /// the syntactic form of that initializer list (when different) /// using method getSyntacticForm(); the method returns null if applied /// to a initializer list which is already in syntactic form. /// Similarly, given the syntactic form (i.e., an initializer list such /// that isSemanticForm() returns false), one can retrieve the semantic /// form using method getSemanticForm(). /// Since many initializer lists have the same syntactic and semantic forms, /// getSyntacticForm() may return NULL, indicating that the current /// semantic initializer list also serves as its syntactic form. class InitListExpr : public Expr { // FIXME: Eliminate this vector in favor of ASTContext allocation typedef ASTVector InitExprsTy; InitExprsTy InitExprs; SourceLocation LBraceLoc, RBraceLoc; /// The alternative form of the initializer list (if it exists). /// The int part of the pair stores whether this initializer list is /// in semantic form. If not null, the pointer points to: /// - the syntactic form, if this is in semantic form; /// - the semantic form, if this is in syntactic form. llvm::PointerIntPair AltForm; /// \brief Either: /// If this initializer list initializes an array with more elements than /// there are initializers in the list, specifies an expression to be used /// for value initialization of the rest of the elements. /// Or /// If this initializer list initializes a union, specifies which /// field within the union will be initialized. llvm::PointerUnion ArrayFillerOrUnionFieldInit; public: InitListExpr(const ASTContext &C, SourceLocation lbraceloc, ArrayRef initExprs, SourceLocation rbraceloc); /// \brief Build an empty initializer list. explicit InitListExpr(EmptyShell Empty) : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { } unsigned getNumInits() const { return InitExprs.size(); } /// \brief Retrieve the set of initializers. Expr **getInits() { return reinterpret_cast(InitExprs.data()); } /// \brief Retrieve the set of initializers. Expr * const *getInits() const { return reinterpret_cast(InitExprs.data()); } ArrayRef inits() { return llvm::makeArrayRef(getInits(), getNumInits()); } ArrayRef inits() const { return llvm::makeArrayRef(getInits(), getNumInits()); } const Expr *getInit(unsigned Init) const { assert(Init < getNumInits() && "Initializer access out of range!"); return cast_or_null(InitExprs[Init]); } Expr *getInit(unsigned Init) { assert(Init < getNumInits() && "Initializer access out of range!"); return cast_or_null(InitExprs[Init]); } void setInit(unsigned Init, Expr *expr) { assert(Init < getNumInits() && "Initializer access out of range!"); InitExprs[Init] = expr; if (expr) { ExprBits.TypeDependent |= expr->isTypeDependent(); ExprBits.ValueDependent |= expr->isValueDependent(); ExprBits.InstantiationDependent |= expr->isInstantiationDependent(); ExprBits.ContainsUnexpandedParameterPack |= expr->containsUnexpandedParameterPack(); } } /// \brief Reserve space for some number of initializers. void reserveInits(const ASTContext &C, unsigned NumInits); /// @brief Specify the number of initializers /// /// If there are more than @p NumInits initializers, the remaining /// initializers will be destroyed. If there are fewer than @p /// NumInits initializers, NULL expressions will be added for the /// unknown initializers. void resizeInits(const ASTContext &Context, unsigned NumInits); /// @brief Updates the initializer at index @p Init with the new /// expression @p expr, and returns the old expression at that /// location. /// /// When @p Init is out of range for this initializer list, the /// initializer list will be extended with NULL expressions to /// accommodate the new entry. Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr); /// \brief If this initializer list initializes an array with more elements /// than there are initializers in the list, specifies an expression to be /// used for value initialization of the rest of the elements. Expr *getArrayFiller() { return ArrayFillerOrUnionFieldInit.dyn_cast(); } const Expr *getArrayFiller() const { return const_cast(this)->getArrayFiller(); } void setArrayFiller(Expr *filler); /// \brief Return true if this is an array initializer and its array "filler" /// has been set. bool hasArrayFiller() const { return getArrayFiller(); } /// \brief If this initializes a union, specifies which field in the /// union to initialize. /// /// Typically, this field is the first named field within the /// union. However, a designated initializer can specify the /// initialization of a different field within the union. FieldDecl *getInitializedFieldInUnion() { return ArrayFillerOrUnionFieldInit.dyn_cast(); } const FieldDecl *getInitializedFieldInUnion() const { return const_cast(this)->getInitializedFieldInUnion(); } void setInitializedFieldInUnion(FieldDecl *FD) { assert((FD == nullptr || getInitializedFieldInUnion() == nullptr || getInitializedFieldInUnion() == FD) && "Only one field of a union may be initialized at a time!"); ArrayFillerOrUnionFieldInit = FD; } // Explicit InitListExpr's originate from source code (and have valid source // locations). Implicit InitListExpr's are created by the semantic analyzer. bool isExplicit() const { return LBraceLoc.isValid() && RBraceLoc.isValid(); } // Is this an initializer for an array of characters, initialized by a string // literal or an @encode? bool isStringLiteralInit() const; /// Is this a transparent initializer list (that is, an InitListExpr that is /// purely syntactic, and whose semantics are that of the sole contained /// initializer)? bool isTransparent() const; + /// Is this the zero initializer {0} in a language which considers it + /// idiomatic? + bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; + SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } SourceLocation getRBraceLoc() const { return RBraceLoc; } void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; } bool isSemanticForm() const { return AltForm.getInt(); } InitListExpr *getSemanticForm() const { return isSemanticForm() ? nullptr : AltForm.getPointer(); + } + bool isSyntacticForm() const { + return !AltForm.getInt() || !AltForm.getPointer(); } InitListExpr *getSyntacticForm() const { return isSemanticForm() ? AltForm.getPointer() : nullptr; } void setSyntacticForm(InitListExpr *Init) { AltForm.setPointer(Init); AltForm.setInt(true); Init->AltForm.setPointer(this); Init->AltForm.setInt(false); } bool hadArrayRangeDesignator() const { return InitListExprBits.HadArrayRangeDesignator != 0; } void sawArrayRangeDesignator(bool ARD = true) { InitListExprBits.HadArrayRangeDesignator = ARD; } SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == InitListExprClass; } // Iterators child_range children() { const_child_range CCR = const_cast(this)->children(); return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end())); } const_child_range children() const { // FIXME: This does not include the array filler expression. if (InitExprs.empty()) return const_child_range(const_child_iterator(), const_child_iterator()); return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size()); } typedef InitExprsTy::iterator iterator; typedef InitExprsTy::const_iterator const_iterator; typedef InitExprsTy::reverse_iterator reverse_iterator; typedef InitExprsTy::const_reverse_iterator const_reverse_iterator; iterator begin() { return InitExprs.begin(); } const_iterator begin() const { return InitExprs.begin(); } iterator end() { return InitExprs.end(); } const_iterator end() const { return InitExprs.end(); } reverse_iterator rbegin() { return InitExprs.rbegin(); } const_reverse_iterator rbegin() const { return InitExprs.rbegin(); } reverse_iterator rend() { return InitExprs.rend(); } const_reverse_iterator rend() const { return InitExprs.rend(); } friend class ASTStmtReader; friend class ASTStmtWriter; }; /// @brief Represents a C99 designated initializer expression. /// /// A designated initializer expression (C99 6.7.8) contains one or /// more designators (which can be field designators, array /// designators, or GNU array-range designators) followed by an /// expression that initializes the field or element(s) that the /// designators refer to. For example, given: /// /// @code /// struct point { /// double x; /// double y; /// }; /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; /// @endcode /// /// The InitListExpr contains three DesignatedInitExprs, the first of /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two /// designators, one array designator for @c [2] followed by one field /// designator for @c .y. The initialization expression will be 1.0. class DesignatedInitExpr final : public Expr, private llvm::TrailingObjects { public: /// \brief Forward declaration of the Designator class. class Designator; private: /// The location of the '=' or ':' prior to the actual initializer /// expression. SourceLocation EqualOrColonLoc; /// Whether this designated initializer used the GNU deprecated /// syntax rather than the C99 '=' syntax. unsigned GNUSyntax : 1; /// The number of designators in this initializer expression. unsigned NumDesignators : 15; /// The number of subexpressions of this initializer expression, /// which contains both the initializer and any additional /// expressions used by array and array-range designators. unsigned NumSubExprs : 16; /// \brief The designators in this designated initialization /// expression. Designator *Designators; DesignatedInitExpr(const ASTContext &C, QualType Ty, llvm::ArrayRef Designators, SourceLocation EqualOrColonLoc, bool GNUSyntax, ArrayRef IndexExprs, Expr *Init); explicit DesignatedInitExpr(unsigned NumSubExprs) : Expr(DesignatedInitExprClass, EmptyShell()), NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { } public: /// A field designator, e.g., ".x". struct FieldDesignator { /// Refers to the field that is being initialized. The low bit /// of this field determines whether this is actually a pointer /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When /// initially constructed, a field designator will store an /// IdentifierInfo*. After semantic analysis has resolved that /// name, the field designator will instead store a FieldDecl*. uintptr_t NameOrField; /// The location of the '.' in the designated initializer. unsigned DotLoc; /// The location of the field name in the designated initializer. unsigned FieldLoc; }; /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". struct ArrayOrRangeDesignator { /// Location of the first index expression within the designated /// initializer expression's list of subexpressions. unsigned Index; /// The location of the '[' starting the array range designator. unsigned LBracketLoc; /// The location of the ellipsis separating the start and end /// indices. Only valid for GNU array-range designators. unsigned EllipsisLoc; /// The location of the ']' terminating the array range designator. unsigned RBracketLoc; }; /// @brief Represents a single C99 designator. /// /// @todo This class is infuriatingly similar to clang::Designator, /// but minor differences (storing indices vs. storing pointers) /// keep us from reusing it. Try harder, later, to rectify these /// differences. class Designator { /// @brief The kind of designator this describes. enum { FieldDesignator, ArrayDesignator, ArrayRangeDesignator } Kind; union { /// A field designator, e.g., ".x". struct FieldDesignator Field; /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]". struct ArrayOrRangeDesignator ArrayOrRange; }; friend class DesignatedInitExpr; public: Designator() {} /// @brief Initializes a field designator. Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc) : Kind(FieldDesignator) { Field.NameOrField = reinterpret_cast(FieldName) | 0x01; Field.DotLoc = DotLoc.getRawEncoding(); Field.FieldLoc = FieldLoc.getRawEncoding(); } /// @brief Initializes an array designator. Designator(unsigned Index, SourceLocation LBracketLoc, SourceLocation RBracketLoc) : Kind(ArrayDesignator) { ArrayOrRange.Index = Index; ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding(); ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); } /// @brief Initializes a GNU array-range designator. Designator(unsigned Index, SourceLocation LBracketLoc, SourceLocation EllipsisLoc, SourceLocation RBracketLoc) : Kind(ArrayRangeDesignator) { ArrayOrRange.Index = Index; ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding(); ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding(); ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding(); } bool isFieldDesignator() const { return Kind == FieldDesignator; } bool isArrayDesignator() const { return Kind == ArrayDesignator; } bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; } IdentifierInfo *getFieldName() const; FieldDecl *getField() const { assert(Kind == FieldDesignator && "Only valid on a field designator"); if (Field.NameOrField & 0x01) return nullptr; else return reinterpret_cast(Field.NameOrField); } void setField(FieldDecl *FD) { assert(Kind == FieldDesignator && "Only valid on a field designator"); Field.NameOrField = reinterpret_cast(FD); } SourceLocation getDotLoc() const { assert(Kind == FieldDesignator && "Only valid on a field designator"); return SourceLocation::getFromRawEncoding(Field.DotLoc); } SourceLocation getFieldLoc() const { assert(Kind == FieldDesignator && "Only valid on a field designator"); return SourceLocation::getFromRawEncoding(Field.FieldLoc); } SourceLocation getLBracketLoc() const { assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator"); return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc); } SourceLocation getRBracketLoc() const { assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator"); return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc); } SourceLocation getEllipsisLoc() const { assert(Kind == ArrayRangeDesignator && "Only valid on an array-range designator"); return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc); } unsigned getFirstExprIndex() const { assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) && "Only valid on an array or array-range designator"); return ArrayOrRange.Index; } SourceLocation getLocStart() const LLVM_READONLY { if (Kind == FieldDesignator) return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc(); else return getLBracketLoc(); } SourceLocation getLocEnd() const LLVM_READONLY { return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc(); } SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(getLocStart(), getLocEnd()); } }; static DesignatedInitExpr *Create(const ASTContext &C, llvm::ArrayRef Designators, ArrayRef IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init); static DesignatedInitExpr *CreateEmpty(const ASTContext &C, unsigned NumIndexExprs); /// @brief Returns the number of designators in this initializer. unsigned size() const { return NumDesignators; } // Iterator access to the designators. llvm::MutableArrayRef designators() { return {Designators, NumDesignators}; } llvm::ArrayRef designators() const { return {Designators, NumDesignators}; } Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; } const Designator *getDesignator(unsigned Idx) const { return &designators()[Idx]; } void setDesignators(const ASTContext &C, const Designator *Desigs, unsigned NumDesigs); Expr *getArrayIndex(const Designator &D) const; Expr *getArrayRangeStart(const Designator &D) const; Expr *getArrayRangeEnd(const Designator &D) const; /// @brief Retrieve the location of the '=' that precedes the /// initializer value itself, if present. SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; } void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; } /// @brief Determines whether this designated initializer used the /// deprecated GNU syntax for designated initializers. bool usesGNUSyntax() const { return GNUSyntax; } void setGNUSyntax(bool GNU) { GNUSyntax = GNU; } /// @brief Retrieve the initializer value. Expr *getInit() const { return cast(*const_cast(this)->child_begin()); } void setInit(Expr *init) { *child_begin() = init; } /// \brief Retrieve the total number of subexpressions in this /// designated initializer expression, including the actual /// initialized value and any expressions that occur within array /// and array-range designators. unsigned getNumSubExprs() const { return NumSubExprs; } Expr *getSubExpr(unsigned Idx) const { assert(Idx < NumSubExprs && "Subscript out of range"); return cast(getTrailingObjects()[Idx]); } void setSubExpr(unsigned Idx, Expr *E) { assert(Idx < NumSubExprs && "Subscript out of range"); getTrailingObjects()[Idx] = E; } /// \brief Replaces the designator at index @p Idx with the series /// of designators in [First, Last). void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last); SourceRange getDesignatorsSourceRange() const; SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == DesignatedInitExprClass; } // Iterators child_range children() { Stmt **begin = getTrailingObjects(); return child_range(begin, begin + NumSubExprs); } const_child_range children() const { Stmt * const *begin = getTrailingObjects(); return const_child_range(begin, begin + NumSubExprs); } friend TrailingObjects; }; /// \brief Represents a place-holder for an object not to be initialized by /// anything. /// /// This only makes sense when it appears as part of an updater of a /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE /// initializes a big object, and the NoInitExpr's mark the spots within the /// big object not to be overwritten by the updater. /// /// \see DesignatedInitUpdateExpr class NoInitExpr : public Expr { public: explicit NoInitExpr(QualType ty) : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary, false, false, ty->isInstantiationDependentType(), false) { } explicit NoInitExpr(EmptyShell Empty) : Expr(NoInitExprClass, Empty) { } static bool classof(const Stmt *T) { return T->getStmtClass() == NoInitExprClass; } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; // In cases like: // struct Q { int a, b, c; }; // Q *getQ(); // void foo() { // struct A { Q q; } a = { *getQ(), .q.b = 3 }; // } // // We will have an InitListExpr for a, with type A, and then a // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3" // class DesignatedInitUpdateExpr : public Expr { // BaseAndUpdaterExprs[0] is the base expression; // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base. Stmt *BaseAndUpdaterExprs[2]; public: DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExprs, SourceLocation rBraceLoc); explicit DesignatedInitUpdateExpr(EmptyShell Empty) : Expr(DesignatedInitUpdateExprClass, Empty) { } SourceLocation getLocStart() const LLVM_READONLY; SourceLocation getLocEnd() const LLVM_READONLY; static bool classof(const Stmt *T) { return T->getStmtClass() == DesignatedInitUpdateExprClass; } Expr *getBase() const { return cast(BaseAndUpdaterExprs[0]); } void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; } InitListExpr *getUpdater() const { return cast(BaseAndUpdaterExprs[1]); } void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; } // Iterators // children = the base and the updater child_range children() { return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); } const_child_range children() const { return const_child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2); } }; /// \brief Represents a loop initializing the elements of an array. /// /// The need to initialize the elements of an array occurs in a number of /// contexts: /// /// * in the implicit copy/move constructor for a class with an array member /// * when a lambda-expression captures an array by value /// * when a decomposition declaration decomposes an array /// /// There are two subexpressions: a common expression (the source array) /// that is evaluated once up-front, and a per-element initializer that /// runs once for each array element. /// /// Within the per-element initializer, the common expression may be referenced /// via an OpaqueValueExpr, and the current index may be obtained via an /// ArrayInitIndexExpr. class ArrayInitLoopExpr : public Expr { Stmt *SubExprs[2]; explicit ArrayInitLoopExpr(EmptyShell Empty) : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {} public: explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit) : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false, CommonInit->isValueDependent() || ElementInit->isValueDependent(), T->isInstantiationDependentType(), CommonInit->containsUnexpandedParameterPack() || ElementInit->containsUnexpandedParameterPack()), SubExprs{CommonInit, ElementInit} {} /// Get the common subexpression shared by all initializations (the source /// array). OpaqueValueExpr *getCommonExpr() const { return cast(SubExprs[0]); } /// Get the initializer to use for each array element. Expr *getSubExpr() const { return cast(SubExprs[1]); } llvm::APInt getArraySize() const { return cast(getType()->castAsArrayTypeUnsafe()) ->getSize(); } static bool classof(const Stmt *S) { return S->getStmtClass() == ArrayInitLoopExprClass; } SourceLocation getLocStart() const LLVM_READONLY { return getCommonExpr()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getCommonExpr()->getLocEnd(); } child_range children() { return child_range(SubExprs, SubExprs + 2); } const_child_range children() const { return const_child_range(SubExprs, SubExprs + 2); } friend class ASTReader; friend class ASTStmtReader; friend class ASTStmtWriter; }; /// \brief Represents the index of the current element of an array being /// initialized by an ArrayInitLoopExpr. This can only appear within the /// subexpression of an ArrayInitLoopExpr. class ArrayInitIndexExpr : public Expr { explicit ArrayInitIndexExpr(EmptyShell Empty) : Expr(ArrayInitIndexExprClass, Empty) {} public: explicit ArrayInitIndexExpr(QualType T) : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary, false, false, false, false) {} static bool classof(const Stmt *S) { return S->getStmtClass() == ArrayInitIndexExprClass; } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } friend class ASTReader; friend class ASTStmtReader; }; /// \brief Represents an implicitly-generated value initialization of /// an object of a given type. /// /// Implicit value initializations occur within semantic initializer /// list expressions (InitListExpr) as placeholders for subobject /// initializations not explicitly specified by the user. /// /// \see InitListExpr class ImplicitValueInitExpr : public Expr { public: explicit ImplicitValueInitExpr(QualType ty) : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary, false, false, ty->isInstantiationDependentType(), false) { } /// \brief Construct an empty implicit value initialization. explicit ImplicitValueInitExpr(EmptyShell Empty) : Expr(ImplicitValueInitExprClass, Empty) { } static bool classof(const Stmt *T) { return T->getStmtClass() == ImplicitValueInitExprClass; } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; class ParenListExpr : public Expr { Stmt **Exprs; unsigned NumExprs; SourceLocation LParenLoc, RParenLoc; public: ParenListExpr(const ASTContext& C, SourceLocation lparenloc, ArrayRef exprs, SourceLocation rparenloc); /// \brief Build an empty paren list. explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { } unsigned getNumExprs() const { return NumExprs; } const Expr* getExpr(unsigned Init) const { assert(Init < getNumExprs() && "Initializer access out of range!"); return cast_or_null(Exprs[Init]); } Expr* getExpr(unsigned Init) { assert(Init < getNumExprs() && "Initializer access out of range!"); return cast_or_null(Exprs[Init]); } Expr **getExprs() { return reinterpret_cast(Exprs); } ArrayRef exprs() { return llvm::makeArrayRef(getExprs(), getNumExprs()); } SourceLocation getLParenLoc() const { return LParenLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == ParenListExprClass; } // Iterators child_range children() { return child_range(&Exprs[0], &Exprs[0]+NumExprs); } const_child_range children() const { return const_child_range(&Exprs[0], &Exprs[0] + NumExprs); } friend class ASTStmtReader; friend class ASTStmtWriter; }; /// \brief Represents a C11 generic selection. /// /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling /// expression, followed by one or more generic associations. Each generic /// association specifies a type name and an expression, or "default" and an /// expression (in which case it is known as a default generic association). /// The type and value of the generic selection are identical to those of its /// result expression, which is defined as the expression in the generic /// association with a type name that is compatible with the type of the /// controlling expression, or the expression in the default generic association /// if no types are compatible. For example: /// /// @code /// _Generic(X, double: 1, float: 2, default: 3) /// @endcode /// /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f /// or 3 if "hello". /// /// As an extension, generic selections are allowed in C++, where the following /// additional semantics apply: /// /// Any generic selection whose controlling expression is type-dependent or /// which names a dependent type in its association list is result-dependent, /// which means that the choice of result expression is dependent. /// Result-dependent generic associations are both type- and value-dependent. class GenericSelectionExpr : public Expr { enum { CONTROLLING, END_EXPR }; TypeSourceInfo **AssocTypes; Stmt **SubExprs; unsigned NumAssocs, ResultIndex; SourceLocation GenericLoc, DefaultLoc, RParenLoc; public: GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex); /// This constructor is used in the result-dependent case. GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack); explicit GenericSelectionExpr(EmptyShell Empty) : Expr(GenericSelectionExprClass, Empty) { } unsigned getNumAssocs() const { return NumAssocs; } SourceLocation getGenericLoc() const { return GenericLoc; } SourceLocation getDefaultLoc() const { return DefaultLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } const Expr *getAssocExpr(unsigned i) const { return cast(SubExprs[END_EXPR+i]); } Expr *getAssocExpr(unsigned i) { return cast(SubExprs[END_EXPR+i]); } ArrayRef getAssocExprs() const { return NumAssocs ? llvm::makeArrayRef( &reinterpret_cast(SubExprs)[END_EXPR], NumAssocs) : None; } const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const { return AssocTypes[i]; } TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; } ArrayRef getAssocTypeSourceInfos() const { return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : None; } QualType getAssocType(unsigned i) const { if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i)) return TS->getType(); else return QualType(); } const Expr *getControllingExpr() const { return cast(SubExprs[CONTROLLING]); } Expr *getControllingExpr() { return cast(SubExprs[CONTROLLING]); } /// Whether this generic selection is result-dependent. bool isResultDependent() const { return ResultIndex == -1U; } /// The zero-based index of the result expression's generic association in /// the generic selection's association list. Defined only if the /// generic selection is not result-dependent. unsigned getResultIndex() const { assert(!isResultDependent() && "Generic selection is result-dependent"); return ResultIndex; } /// The generic selection's result expression. Defined only if the /// generic selection is not result-dependent. const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); } Expr *getResultExpr() { return getAssocExpr(getResultIndex()); } SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == GenericSelectionExprClass; } child_range children() { return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs); } const_child_range children() const { return const_child_range(SubExprs, SubExprs + END_EXPR + NumAssocs); } friend class ASTStmtReader; }; //===----------------------------------------------------------------------===// // Clang Extensions //===----------------------------------------------------------------------===// /// ExtVectorElementExpr - This represents access to specific elements of a /// vector, and may occur on the left hand side or right hand side. For example /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector. /// /// Note that the base may have either vector or pointer to vector type, just /// like a struct field reference. /// class ExtVectorElementExpr : public Expr { Stmt *Base; IdentifierInfo *Accessor; SourceLocation AccessorLoc; public: ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base, IdentifierInfo &accessor, SourceLocation loc) : Expr(ExtVectorElementExprClass, ty, VK, (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent), base->isTypeDependent(), base->isValueDependent(), base->isInstantiationDependent(), base->containsUnexpandedParameterPack()), Base(base), Accessor(&accessor), AccessorLoc(loc) {} /// \brief Build an empty vector element expression. explicit ExtVectorElementExpr(EmptyShell Empty) : Expr(ExtVectorElementExprClass, Empty) { } const Expr *getBase() const { return cast(Base); } Expr *getBase() { return cast(Base); } void setBase(Expr *E) { Base = E; } IdentifierInfo &getAccessor() const { return *Accessor; } void setAccessor(IdentifierInfo *II) { Accessor = II; } SourceLocation getAccessorLoc() const { return AccessorLoc; } void setAccessorLoc(SourceLocation L) { AccessorLoc = L; } /// getNumElements - Get the number of components being selected. unsigned getNumElements() const; /// containsDuplicateElements - Return true if any element access is /// repeated. bool containsDuplicateElements() const; /// getEncodedElementAccess - Encode the elements accessed into an llvm /// aggregate Constant of ConstantInt(s). void getEncodedElementAccess(SmallVectorImpl &Elts) const; SourceLocation getLocStart() const LLVM_READONLY { return getBase()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; } /// isArrow - Return true if the base expression is a pointer to vector, /// return false if the base expression is a vector. bool isArrow() const; static bool classof(const Stmt *T) { return T->getStmtClass() == ExtVectorElementExprClass; } // Iterators child_range children() { return child_range(&Base, &Base+1); } const_child_range children() const { return const_child_range(&Base, &Base + 1); } }; /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions. /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } class BlockExpr : public Expr { protected: BlockDecl *TheBlock; public: BlockExpr(BlockDecl *BD, QualType ty) : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary, ty->isDependentType(), ty->isDependentType(), ty->isInstantiationDependentType() || BD->isDependentContext(), false), TheBlock(BD) {} /// \brief Build an empty block expression. explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { } const BlockDecl *getBlockDecl() const { return TheBlock; } BlockDecl *getBlockDecl() { return TheBlock; } void setBlockDecl(BlockDecl *BD) { TheBlock = BD; } // Convenience functions for probing the underlying BlockDecl. SourceLocation getCaretLocation() const; const Stmt *getBody() const; Stmt *getBody(); SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); } /// getFunctionType - Return the underlying function type for this block. const FunctionProtoType *getFunctionType() const; static bool classof(const Stmt *T) { return T->getStmtClass() == BlockExprClass; } // Iterators child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } }; /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] /// This AST node provides support for reinterpreting a type to another /// type of the same size. class AsTypeExpr : public Expr { private: Stmt *SrcExpr; SourceLocation BuiltinLoc, RParenLoc; friend class ASTReader; friend class ASTStmtReader; explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {} public: AsTypeExpr(Expr* SrcExpr, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc) : Expr(AsTypeExprClass, DstType, VK, OK, DstType->isDependentType(), DstType->isDependentType() || SrcExpr->isValueDependent(), (DstType->isInstantiationDependentType() || SrcExpr->isInstantiationDependent()), (DstType->containsUnexpandedParameterPack() || SrcExpr->containsUnexpandedParameterPack())), SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {} /// getSrcExpr - Return the Expr to be converted. Expr *getSrcExpr() const { return cast(SrcExpr); } /// getBuiltinLoc - Return the location of the __builtin_astype token. SourceLocation getBuiltinLoc() const { return BuiltinLoc; } /// getRParenLoc - Return the location of final right parenthesis. SourceLocation getRParenLoc() const { return RParenLoc; } SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == AsTypeExprClass; } // Iterators child_range children() { return child_range(&SrcExpr, &SrcExpr+1); } const_child_range children() const { return const_child_range(&SrcExpr, &SrcExpr + 1); } }; /// PseudoObjectExpr - An expression which accesses a pseudo-object /// l-value. A pseudo-object is an abstract object, accesses to which /// are translated to calls. The pseudo-object expression has a /// syntactic form, which shows how the expression was actually /// written in the source code, and a semantic form, which is a series /// of expressions to be executed in order which detail how the /// operation is actually evaluated. Optionally, one of the semantic /// forms may also provide a result value for the expression. /// /// If any of the semantic-form expressions is an OpaqueValueExpr, /// that OVE is required to have a source expression, and it is bound /// to the result of that source expression. Such OVEs may appear /// only in subsequent semantic-form expressions and as /// sub-expressions of the syntactic form. /// /// PseudoObjectExpr should be used only when an operation can be /// usefully described in terms of fairly simple rewrite rules on /// objects and functions that are meant to be used by end-developers. /// For example, under the Itanium ABI, dynamic casts are implemented /// as a call to a runtime function called __dynamic_cast; using this /// class to describe that would be inappropriate because that call is /// not really part of the user-visible semantics, and instead the /// cast is properly reflected in the AST and IR-generation has been /// taught to generate the call as necessary. In contrast, an /// Objective-C property access is semantically defined to be /// equivalent to a particular message send, and this is very much /// part of the user model. The name of this class encourages this /// modelling design. class PseudoObjectExpr final : public Expr, private llvm::TrailingObjects { // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions. // Always at least two, because the first sub-expression is the // syntactic form. // PseudoObjectExprBits.ResultIndex - The index of the // sub-expression holding the result. 0 means the result is void, // which is unambiguous because it's the index of the syntactic // form. Note that this is therefore 1 higher than the value passed // in to Create, which is an index within the semantic forms. // Note also that ASTStmtWriter assumes this encoding. Expr **getSubExprsBuffer() { return getTrailingObjects(); } const Expr * const *getSubExprsBuffer() const { return getTrailingObjects(); } PseudoObjectExpr(QualType type, ExprValueKind VK, Expr *syntactic, ArrayRef semantic, unsigned resultIndex); PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs); unsigned getNumSubExprs() const { return PseudoObjectExprBits.NumSubExprs; } public: /// NoResult - A value for the result index indicating that there is /// no semantic result. enum : unsigned { NoResult = ~0U }; static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic, ArrayRef semantic, unsigned resultIndex); static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell, unsigned numSemanticExprs); /// Return the syntactic form of this expression, i.e. the /// expression it actually looks like. Likely to be expressed in /// terms of OpaqueValueExprs bound in the semantic form. Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; } const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; } /// Return the index of the result-bearing expression into the semantics /// expressions, or PseudoObjectExpr::NoResult if there is none. unsigned getResultExprIndex() const { if (PseudoObjectExprBits.ResultIndex == 0) return NoResult; return PseudoObjectExprBits.ResultIndex - 1; } /// Return the result-bearing expression, or null if there is none. Expr *getResultExpr() { if (PseudoObjectExprBits.ResultIndex == 0) return nullptr; return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex]; } const Expr *getResultExpr() const { return const_cast(this)->getResultExpr(); } unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; } typedef Expr * const *semantics_iterator; typedef const Expr * const *const_semantics_iterator; semantics_iterator semantics_begin() { return getSubExprsBuffer() + 1; } const_semantics_iterator semantics_begin() const { return getSubExprsBuffer() + 1; } semantics_iterator semantics_end() { return getSubExprsBuffer() + getNumSubExprs(); } const_semantics_iterator semantics_end() const { return getSubExprsBuffer() + getNumSubExprs(); } llvm::iterator_range semantics() { return llvm::make_range(semantics_begin(), semantics_end()); } llvm::iterator_range semantics() const { return llvm::make_range(semantics_begin(), semantics_end()); } Expr *getSemanticExpr(unsigned index) { assert(index + 1 < getNumSubExprs()); return getSubExprsBuffer()[index + 1]; } const Expr *getSemanticExpr(unsigned index) const { return const_cast(this)->getSemanticExpr(index); } SourceLocation getExprLoc() const LLVM_READONLY { return getSyntacticForm()->getExprLoc(); } SourceLocation getLocStart() const LLVM_READONLY { return getSyntacticForm()->getLocStart(); } SourceLocation getLocEnd() const LLVM_READONLY { return getSyntacticForm()->getLocEnd(); } child_range children() { const_child_range CCR = const_cast(this)->children(); return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end())); } const_child_range children() const { Stmt *const *cs = const_cast( reinterpret_cast(getSubExprsBuffer())); return const_child_range(cs, cs + getNumSubExprs()); } static bool classof(const Stmt *T) { return T->getStmtClass() == PseudoObjectExprClass; } friend TrailingObjects; friend class ASTStmtReader; }; /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the /// similarly-named C++11 instructions, and __c11 variants for . /// All of these instructions take one primary pointer and at least one memory /// order. class AtomicExpr : public Expr { public: enum AtomicOp { #define BUILTIN(ID, TYPE, ATTRS) #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID, #include "clang/Basic/Builtins.def" // Avoid trailing comma BI_First = 0 }; private: enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR }; Stmt* SubExprs[END_EXPR]; unsigned NumSubExprs; SourceLocation BuiltinLoc, RParenLoc; AtomicOp Op; friend class ASTStmtReader; public: AtomicExpr(SourceLocation BLoc, ArrayRef args, QualType t, AtomicOp op, SourceLocation RP); /// \brief Determine the number of arguments the specified atomic builtin /// should have. static unsigned getNumSubExprs(AtomicOp Op); /// \brief Build an empty AtomicExpr. explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { } Expr *getPtr() const { return cast(SubExprs[PTR]); } Expr *getOrder() const { return cast(SubExprs[ORDER]); } Expr *getVal1() const { if (Op == AO__c11_atomic_init) return cast(SubExprs[ORDER]); assert(NumSubExprs > VAL1); return cast(SubExprs[VAL1]); } Expr *getOrderFail() const { assert(NumSubExprs > ORDER_FAIL); return cast(SubExprs[ORDER_FAIL]); } Expr *getVal2() const { if (Op == AO__atomic_exchange) return cast(SubExprs[ORDER_FAIL]); assert(NumSubExprs > VAL2); return cast(SubExprs[VAL2]); } Expr *getWeak() const { assert(NumSubExprs > WEAK); return cast(SubExprs[WEAK]); } AtomicOp getOp() const { return Op; } unsigned getNumSubExprs() const { return NumSubExprs; } Expr **getSubExprs() { return reinterpret_cast(SubExprs); } const Expr * const *getSubExprs() const { return reinterpret_cast(SubExprs); } bool isVolatile() const { return getPtr()->getType()->getPointeeType().isVolatileQualified(); } bool isCmpXChg() const { return getOp() == AO__c11_atomic_compare_exchange_strong || getOp() == AO__c11_atomic_compare_exchange_weak || getOp() == AO__atomic_compare_exchange || getOp() == AO__atomic_compare_exchange_n; } SourceLocation getBuiltinLoc() const { return BuiltinLoc; } SourceLocation getRParenLoc() const { return RParenLoc; } SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; } SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; } static bool classof(const Stmt *T) { return T->getStmtClass() == AtomicExprClass; } // Iterators child_range children() { return child_range(SubExprs, SubExprs+NumSubExprs); } const_child_range children() const { return const_child_range(SubExprs, SubExprs + NumSubExprs); } }; /// TypoExpr - Internal placeholder for expressions where typo correction /// still needs to be performed and/or an error diagnostic emitted. class TypoExpr : public Expr { public: TypoExpr(QualType T) : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary, /*isTypeDependent*/ true, /*isValueDependent*/ true, /*isInstantiationDependent*/ true, /*containsUnexpandedParameterPack*/ false) { assert(T->isDependentType() && "TypoExpr given a non-dependent type"); } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); } SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); } static bool classof(const Stmt *T) { return T->getStmtClass() == TypoExprClass; } }; } // end namespace clang #endif // LLVM_CLANG_AST_EXPR_H Index: head/contrib/llvm/tools/clang/lib/AST/Expr.cpp =================================================================== --- head/contrib/llvm/tools/clang/lib/AST/Expr.cpp (revision 327929) +++ head/contrib/llvm/tools/clang/lib/AST/Expr.cpp (revision 327930) @@ -1,4010 +1,4021 @@ //===--- Expr.cpp - Expression AST Node Implementation --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expr class and subclasses. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/EvaluatedExprVisitor.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/Mangle.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Sema/SemaDiagnostic.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include #include using namespace clang; const Expr *Expr::getBestDynamicClassTypeExpr() const { const Expr *E = this; while (true) { E = E->ignoreParenBaseCasts(); // Follow the RHS of a comma operator. if (auto *BO = dyn_cast(E)) { if (BO->getOpcode() == BO_Comma) { E = BO->getRHS(); continue; } } // Step into initializer for materialized temporaries. if (auto *MTE = dyn_cast(E)) { E = MTE->GetTemporaryExpr(); continue; } break; } return E; } const CXXRecordDecl *Expr::getBestDynamicClassType() const { const Expr *E = getBestDynamicClassTypeExpr(); QualType DerivedType = E->getType(); if (const PointerType *PTy = DerivedType->getAs()) DerivedType = PTy->getPointeeType(); if (DerivedType->isDependentType()) return nullptr; const RecordType *Ty = DerivedType->castAs(); Decl *D = Ty->getDecl(); return cast(D); } const Expr *Expr::skipRValueSubobjectAdjustments( SmallVectorImpl &CommaLHSs, SmallVectorImpl &Adjustments) const { const Expr *E = this; while (true) { E = E->IgnoreParens(); if (const CastExpr *CE = dyn_cast(E)) { if ((CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_UncheckedDerivedToBase) && E->getType()->isRecordType()) { E = CE->getSubExpr(); CXXRecordDecl *Derived = cast(E->getType()->getAs()->getDecl()); Adjustments.push_back(SubobjectAdjustment(CE, Derived)); continue; } if (CE->getCastKind() == CK_NoOp) { E = CE->getSubExpr(); continue; } } else if (const MemberExpr *ME = dyn_cast(E)) { if (!ME->isArrow()) { assert(ME->getBase()->getType()->isRecordType()); if (FieldDecl *Field = dyn_cast(ME->getMemberDecl())) { if (!Field->isBitField() && !Field->getType()->isReferenceType()) { E = ME->getBase(); Adjustments.push_back(SubobjectAdjustment(Field)); continue; } } } } else if (const BinaryOperator *BO = dyn_cast(E)) { if (BO->isPtrMemOp()) { assert(BO->getRHS()->isRValue()); E = BO->getLHS(); const MemberPointerType *MPT = BO->getRHS()->getType()->getAs(); Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS())); continue; } else if (BO->getOpcode() == BO_Comma) { CommaLHSs.push_back(BO->getLHS()); E = BO->getRHS(); continue; } } // Nothing changed. break; } return E; } /// isKnownToHaveBooleanValue - Return true if this is an integer expression /// that is known to return 0 or 1. This happens for _Bool/bool expressions /// but also int expressions which are produced by things like comparisons in /// C. bool Expr::isKnownToHaveBooleanValue() const { const Expr *E = IgnoreParens(); // If this value has _Bool type, it is obvious 0/1. if (E->getType()->isBooleanType()) return true; // If this is a non-scalar-integer type, we don't care enough to try. if (!E->getType()->isIntegralOrEnumerationType()) return false; if (const UnaryOperator *UO = dyn_cast(E)) { switch (UO->getOpcode()) { case UO_Plus: return UO->getSubExpr()->isKnownToHaveBooleanValue(); case UO_LNot: return true; default: return false; } } // Only look through implicit casts. If the user writes // '(int) (a && b)' treat it as an arbitrary int. if (const ImplicitCastExpr *CE = dyn_cast(E)) return CE->getSubExpr()->isKnownToHaveBooleanValue(); if (const BinaryOperator *BO = dyn_cast(E)) { switch (BO->getOpcode()) { default: return false; case BO_LT: // Relational operators. case BO_GT: case BO_LE: case BO_GE: case BO_EQ: // Equality operators. case BO_NE: case BO_LAnd: // AND operator. case BO_LOr: // Logical OR operator. return true; case BO_And: // Bitwise AND operator. case BO_Xor: // Bitwise XOR operator. case BO_Or: // Bitwise OR operator. // Handle things like (x==2)|(y==12). return BO->getLHS()->isKnownToHaveBooleanValue() && BO->getRHS()->isKnownToHaveBooleanValue(); case BO_Comma: case BO_Assign: return BO->getRHS()->isKnownToHaveBooleanValue(); } } if (const ConditionalOperator *CO = dyn_cast(E)) return CO->getTrueExpr()->isKnownToHaveBooleanValue() && CO->getFalseExpr()->isKnownToHaveBooleanValue(); return false; } // Amusing macro metaprogramming hack: check whether a class provides // a more specific implementation of getExprLoc(). // // See also Stmt.cpp:{getLocStart(),getLocEnd()}. namespace { /// This implementation is used when a class provides a custom /// implementation of getExprLoc. template SourceLocation getExprLocImpl(const Expr *expr, SourceLocation (T::*v)() const) { return static_cast(expr)->getExprLoc(); } /// This implementation is used when a class doesn't provide /// a custom implementation of getExprLoc. Overload resolution /// should pick it over the implementation above because it's /// more specialized according to function template partial ordering. template SourceLocation getExprLocImpl(const Expr *expr, SourceLocation (Expr::*v)() const) { return static_cast(expr)->getLocStart(); } } SourceLocation Expr::getExprLoc() const { switch (getStmtClass()) { case Stmt::NoStmtClass: llvm_unreachable("statement without class"); #define ABSTRACT_STMT(type) #define STMT(type, base) \ case Stmt::type##Class: break; #define EXPR(type, base) \ case Stmt::type##Class: return getExprLocImpl(this, &type::getExprLoc); #include "clang/AST/StmtNodes.inc" } llvm_unreachable("unknown expression kind"); } //===----------------------------------------------------------------------===// // Primary Expressions. //===----------------------------------------------------------------------===// /// \brief Compute the type-, value-, and instantiation-dependence of a /// declaration reference /// based on the declaration being referenced. static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D, QualType T, bool &TypeDependent, bool &ValueDependent, bool &InstantiationDependent) { TypeDependent = false; ValueDependent = false; InstantiationDependent = false; // (TD) C++ [temp.dep.expr]p3: // An id-expression is type-dependent if it contains: // // and // // (VD) C++ [temp.dep.constexpr]p2: // An identifier is value-dependent if it is: // (TD) - an identifier that was declared with dependent type // (VD) - a name declared with a dependent type, if (T->isDependentType()) { TypeDependent = true; ValueDependent = true; InstantiationDependent = true; return; } else if (T->isInstantiationDependentType()) { InstantiationDependent = true; } // (TD) - a conversion-function-id that specifies a dependent type if (D->getDeclName().getNameKind() == DeclarationName::CXXConversionFunctionName) { QualType T = D->getDeclName().getCXXNameType(); if (T->isDependentType()) { TypeDependent = true; ValueDependent = true; InstantiationDependent = true; return; } if (T->isInstantiationDependentType()) InstantiationDependent = true; } // (VD) - the name of a non-type template parameter, if (isa(D)) { ValueDependent = true; InstantiationDependent = true; return; } // (VD) - a constant with integral or enumeration type and is // initialized with an expression that is value-dependent. // (VD) - a constant with literal type and is initialized with an // expression that is value-dependent [C++11]. // (VD) - FIXME: Missing from the standard: // - an entity with reference type and is initialized with an // expression that is value-dependent [C++11] if (VarDecl *Var = dyn_cast(D)) { if ((Ctx.getLangOpts().CPlusPlus11 ? Var->getType()->isLiteralType(Ctx) : Var->getType()->isIntegralOrEnumerationType()) && (Var->getType().isConstQualified() || Var->getType()->isReferenceType())) { if (const Expr *Init = Var->getAnyInitializer()) if (Init->isValueDependent()) { ValueDependent = true; InstantiationDependent = true; } } // (VD) - FIXME: Missing from the standard: // - a member function or a static data member of the current // instantiation if (Var->isStaticDataMember() && Var->getDeclContext()->isDependentContext()) { ValueDependent = true; InstantiationDependent = true; TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo(); if (TInfo->getType()->isIncompleteArrayType()) TypeDependent = true; } return; } // (VD) - FIXME: Missing from the standard: // - a member function or a static data member of the current // instantiation if (isa(D) && D->getDeclContext()->isDependentContext()) { ValueDependent = true; InstantiationDependent = true; } } void DeclRefExpr::computeDependence(const ASTContext &Ctx) { bool TypeDependent = false; bool ValueDependent = false; bool InstantiationDependent = false; computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent, ValueDependent, InstantiationDependent); ExprBits.TypeDependent |= TypeDependent; ExprBits.ValueDependent |= ValueDependent; ExprBits.InstantiationDependent |= InstantiationDependent; // Is the declaration a parameter pack? if (getDecl()->isParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; } DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK) : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false), D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) { DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0; if (QualifierLoc) { new (getTrailingObjects()) NestedNameSpecifierLoc(QualifierLoc); auto *NNS = QualifierLoc.getNestedNameSpecifier(); if (NNS->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (NNS->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; } DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0; if (FoundD) *getTrailingObjects() = FoundD; DeclRefExprBits.HasTemplateKWAndArgsInfo = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0; DeclRefExprBits.RefersToEnclosingVariableOrCapture = RefersToEnclosingVariableOrCapture; if (TemplateArgs) { bool Dependent = false; bool InstantiationDependent = false; bool ContainsUnexpandedParameterPack = false; getTrailingObjects()->initializeFrom( TemplateKWLoc, *TemplateArgs, getTrailingObjects(), Dependent, InstantiationDependent, ContainsUnexpandedParameterPack); assert(!Dependent && "built a DeclRefExpr with dependent template args"); ExprBits.InstantiationDependent |= InstantiationDependent; ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack; } else if (TemplateKWLoc.isValid()) { getTrailingObjects()->initializeFrom( TemplateKWLoc); } DeclRefExprBits.HadMultipleCandidates = 0; computeDependence(Ctx); } DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { return Create(Context, QualifierLoc, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture, DeclarationNameInfo(D->getDeclName(), NameLoc), T, VK, FoundD, TemplateArgs); } DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK, NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { // Filter out cases where the found Decl is the same as the value refenenced. if (D == FoundD) FoundD = nullptr; bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid(); std::size_t Size = totalSizeToAlloc( QualifierLoc ? 1 : 0, FoundD ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0, TemplateArgs ? TemplateArgs->size() : 0); void *Mem = Context.Allocate(Size, alignof(DeclRefExpr)); return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture, NameInfo, FoundD, TemplateArgs, T, VK); } DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) { assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo); std::size_t Size = totalSizeToAlloc( HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo, NumTemplateArgs); void *Mem = Context.Allocate(Size, alignof(DeclRefExpr)); return new (Mem) DeclRefExpr(EmptyShell()); } SourceLocation DeclRefExpr::getLocStart() const { if (hasQualifier()) return getQualifierLoc().getBeginLoc(); return getNameInfo().getLocStart(); } SourceLocation DeclRefExpr::getLocEnd() const { if (hasExplicitTemplateArgs()) return getRAngleLoc(); return getNameInfo().getLocEnd(); } PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT, StringLiteral *SL) : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary, FNTy->isDependentType(), FNTy->isDependentType(), FNTy->isInstantiationDependentType(), /*ContainsUnexpandedParameterPack=*/false), Loc(L), Type(IT), FnName(SL) {} StringLiteral *PredefinedExpr::getFunctionName() { return cast_or_null(FnName); } StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) { switch (IT) { case Func: return "__func__"; case Function: return "__FUNCTION__"; case FuncDName: return "__FUNCDNAME__"; case LFunction: return "L__FUNCTION__"; case PrettyFunction: return "__PRETTY_FUNCTION__"; case FuncSig: return "__FUNCSIG__"; case PrettyFunctionNoVirtual: break; } llvm_unreachable("Unknown ident type for PredefinedExpr"); } // FIXME: Maybe this should use DeclPrinter with a special "print predefined // expr" policy instead. std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) { ASTContext &Context = CurrentDecl->getASTContext(); if (IT == PredefinedExpr::FuncDName) { if (const NamedDecl *ND = dyn_cast(CurrentDecl)) { std::unique_ptr MC; MC.reset(Context.createMangleContext()); if (MC->shouldMangleDeclName(ND)) { SmallString<256> Buffer; llvm::raw_svector_ostream Out(Buffer); if (const CXXConstructorDecl *CD = dyn_cast(ND)) MC->mangleCXXCtor(CD, Ctor_Base, Out); else if (const CXXDestructorDecl *DD = dyn_cast(ND)) MC->mangleCXXDtor(DD, Dtor_Base, Out); else MC->mangleName(ND, Out); if (!Buffer.empty() && Buffer.front() == '\01') return Buffer.substr(1); return Buffer.str(); } else return ND->getIdentifier()->getName(); } return ""; } if (isa(CurrentDecl)) { // For blocks we only emit something if it is enclosed in a function // For top-level block we'd like to include the name of variable, but we // don't have it at this point. auto DC = CurrentDecl->getDeclContext(); if (DC->isFileContext()) return ""; SmallString<256> Buffer; llvm::raw_svector_ostream Out(Buffer); if (auto *DCBlock = dyn_cast(DC)) // For nested blocks, propagate up to the parent. Out << ComputeName(IT, DCBlock); else if (auto *DCDecl = dyn_cast(DC)) Out << ComputeName(IT, DCDecl) << "_block_invoke"; return Out.str(); } if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) { if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig) return FD->getNameAsString(); SmallString<256> Name; llvm::raw_svector_ostream Out(Name); if (const CXXMethodDecl *MD = dyn_cast(FD)) { if (MD->isVirtual() && IT != PrettyFunctionNoVirtual) Out << "virtual "; if (MD->isStatic()) Out << "static "; } PrintingPolicy Policy(Context.getLangOpts()); std::string Proto; llvm::raw_string_ostream POut(Proto); const FunctionDecl *Decl = FD; if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern()) Decl = Pattern; const FunctionType *AFT = Decl->getType()->getAs(); const FunctionProtoType *FT = nullptr; if (FD->hasWrittenPrototype()) FT = dyn_cast(AFT); if (IT == FuncSig) { switch (AFT->getCallConv()) { case CC_C: POut << "__cdecl "; break; case CC_X86StdCall: POut << "__stdcall "; break; case CC_X86FastCall: POut << "__fastcall "; break; case CC_X86ThisCall: POut << "__thiscall "; break; case CC_X86VectorCall: POut << "__vectorcall "; break; case CC_X86RegCall: POut << "__regcall "; break; // Only bother printing the conventions that MSVC knows about. default: break; } } FD->printQualifiedName(POut, Policy); POut << "("; if (FT) { for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) { if (i) POut << ", "; POut << Decl->getParamDecl(i)->getType().stream(Policy); } if (FT->isVariadic()) { if (FD->getNumParams()) POut << ", "; POut << "..."; } else if ((IT == FuncSig || !Context.getLangOpts().CPlusPlus) && !Decl->getNumParams()) { POut << "void"; } } POut << ")"; if (const CXXMethodDecl *MD = dyn_cast(FD)) { assert(FT && "We must have a written prototype in this case."); if (FT->isConst()) POut << " const"; if (FT->isVolatile()) POut << " volatile"; RefQualifierKind Ref = MD->getRefQualifier(); if (Ref == RQ_LValue) POut << " &"; else if (Ref == RQ_RValue) POut << " &&"; } typedef SmallVector SpecsTy; SpecsTy Specs; const DeclContext *Ctx = FD->getDeclContext(); while (Ctx && isa(Ctx)) { const ClassTemplateSpecializationDecl *Spec = dyn_cast(Ctx); if (Spec && !Spec->isExplicitSpecialization()) Specs.push_back(Spec); Ctx = Ctx->getParent(); } std::string TemplateParams; llvm::raw_string_ostream TOut(TemplateParams); for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend(); I != E; ++I) { const TemplateParameterList *Params = (*I)->getSpecializedTemplate()->getTemplateParameters(); const TemplateArgumentList &Args = (*I)->getTemplateArgs(); assert(Params->size() == Args.size()); for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) { StringRef Param = Params->getParam(i)->getName(); if (Param.empty()) continue; TOut << Param << " = "; Args.get(i).print(Policy, TOut); TOut << ", "; } } FunctionTemplateSpecializationInfo *FSI = FD->getTemplateSpecializationInfo(); if (FSI && !FSI->isExplicitSpecialization()) { const TemplateParameterList* Params = FSI->getTemplate()->getTemplateParameters(); const TemplateArgumentList* Args = FSI->TemplateArguments; assert(Params->size() == Args->size()); for (unsigned i = 0, e = Params->size(); i != e; ++i) { StringRef Param = Params->getParam(i)->getName(); if (Param.empty()) continue; TOut << Param << " = "; Args->get(i).print(Policy, TOut); TOut << ", "; } } TOut.flush(); if (!TemplateParams.empty()) { // remove the trailing comma and space TemplateParams.resize(TemplateParams.size() - 2); POut << " [" << TemplateParams << "]"; } POut.flush(); // Print "auto" for all deduced return types. This includes C++1y return // type deduction and lambdas. For trailing return types resolve the // decltype expression. Otherwise print the real type when this is // not a constructor or destructor. if (isa(FD) && cast(FD)->getParent()->isLambda()) Proto = "auto " + Proto; else if (FT && FT->getReturnType()->getAs()) FT->getReturnType() ->getAs() ->getUnderlyingType() .getAsStringInternal(Proto, Policy); else if (!isa(FD) && !isa(FD)) AFT->getReturnType().getAsStringInternal(Proto, Policy); Out << Proto; return Name.str().str(); } if (const CapturedDecl *CD = dyn_cast(CurrentDecl)) { for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent()) // Skip to its enclosing function or method, but not its enclosing // CapturedDecl. if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) { const Decl *D = Decl::castFromDeclContext(DC); return ComputeName(IT, D); } llvm_unreachable("CapturedDecl not inside a function or method"); } if (const ObjCMethodDecl *MD = dyn_cast(CurrentDecl)) { SmallString<256> Name; llvm::raw_svector_ostream Out(Name); Out << (MD->isInstanceMethod() ? '-' : '+'); Out << '['; // For incorrect code, there might not be an ObjCInterfaceDecl. Do // a null check to avoid a crash. if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) Out << *ID; if (const ObjCCategoryImplDecl *CID = dyn_cast(MD->getDeclContext())) Out << '(' << *CID << ')'; Out << ' '; MD->getSelector().print(Out); Out << ']'; return Name.str().str(); } if (isa(CurrentDecl) && IT == PrettyFunction) { // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string. return "top level"; } return ""; } void APNumericStorage::setIntValue(const ASTContext &C, const llvm::APInt &Val) { if (hasAllocation()) C.Deallocate(pVal); BitWidth = Val.getBitWidth(); unsigned NumWords = Val.getNumWords(); const uint64_t* Words = Val.getRawData(); if (NumWords > 1) { pVal = new (C) uint64_t[NumWords]; std::copy(Words, Words + NumWords, pVal); } else if (NumWords == 1) VAL = Words[0]; else VAL = 0; } IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l) : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false, false, false), Loc(l) { assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); assert(V.getBitWidth() == C.getIntWidth(type) && "Integer type is not the correct size for constant."); setValue(C, V); } IntegerLiteral * IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l) { return new (C) IntegerLiteral(C, V, type, l); } IntegerLiteral * IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) { return new (C) IntegerLiteral(Empty); } FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L) : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false, false, false), Loc(L) { setSemantics(V.getSemantics()); FloatingLiteralBits.IsExact = isexact; setValue(C, V); } FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty) : Expr(FloatingLiteralClass, Empty) { setRawSemantics(IEEEhalf); FloatingLiteralBits.IsExact = false; } FloatingLiteral * FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L) { return new (C) FloatingLiteral(C, V, isexact, Type, L); } FloatingLiteral * FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) { return new (C) FloatingLiteral(C, Empty); } const llvm::fltSemantics &FloatingLiteral::getSemantics() const { switch(FloatingLiteralBits.Semantics) { case IEEEhalf: return llvm::APFloat::IEEEhalf(); case IEEEsingle: return llvm::APFloat::IEEEsingle(); case IEEEdouble: return llvm::APFloat::IEEEdouble(); case x87DoubleExtended: return llvm::APFloat::x87DoubleExtended(); case IEEEquad: return llvm::APFloat::IEEEquad(); case PPCDoubleDouble: return llvm::APFloat::PPCDoubleDouble(); } llvm_unreachable("Unrecognised floating semantics"); } void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) { if (&Sem == &llvm::APFloat::IEEEhalf()) FloatingLiteralBits.Semantics = IEEEhalf; else if (&Sem == &llvm::APFloat::IEEEsingle()) FloatingLiteralBits.Semantics = IEEEsingle; else if (&Sem == &llvm::APFloat::IEEEdouble()) FloatingLiteralBits.Semantics = IEEEdouble; else if (&Sem == &llvm::APFloat::x87DoubleExtended()) FloatingLiteralBits.Semantics = x87DoubleExtended; else if (&Sem == &llvm::APFloat::IEEEquad()) FloatingLiteralBits.Semantics = IEEEquad; else if (&Sem == &llvm::APFloat::PPCDoubleDouble()) FloatingLiteralBits.Semantics = PPCDoubleDouble; else llvm_unreachable("Unknown floating semantics"); } /// getValueAsApproximateDouble - This returns the value as an inaccurate /// double. Note that this may cause loss of precision, but is useful for /// debugging dumps, etc. double FloatingLiteral::getValueAsApproximateDouble() const { llvm::APFloat V = getValue(); bool ignored; V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven, &ignored); return V.convertToDouble(); } int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) { int CharByteWidth = 0; switch(k) { case Ascii: case UTF8: CharByteWidth = target.getCharWidth(); break; case Wide: CharByteWidth = target.getWCharWidth(); break; case UTF16: CharByteWidth = target.getChar16Width(); break; case UTF32: CharByteWidth = target.getChar32Width(); break; } assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); CharByteWidth /= 8; assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4) && "character byte widths supported are 1, 2, and 4 only"); return CharByteWidth; } StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumStrs) { assert(C.getAsConstantArrayType(Ty) && "StringLiteral must be of constant array type!"); // Allocate enough space for the StringLiteral plus an array of locations for // any concatenated string tokens. void *Mem = C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1), alignof(StringLiteral)); StringLiteral *SL = new (Mem) StringLiteral(Ty); // OPTIMIZE: could allocate this appended to the StringLiteral. SL->setString(C,Str,Kind,Pascal); SL->TokLocs[0] = Loc[0]; SL->NumConcatenated = NumStrs; if (NumStrs != 1) memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1)); return SL; } StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C, unsigned NumStrs) { void *Mem = C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1), alignof(StringLiteral)); StringLiteral *SL = new (Mem) StringLiteral(QualType()); SL->CharByteWidth = 0; SL->Length = 0; SL->NumConcatenated = NumStrs; return SL; } void StringLiteral::outputString(raw_ostream &OS) const { switch (getKind()) { case Ascii: break; // no prefix. case Wide: OS << 'L'; break; case UTF8: OS << "u8"; break; case UTF16: OS << 'u'; break; case UTF32: OS << 'U'; break; } OS << '"'; static const char Hex[] = "0123456789ABCDEF"; unsigned LastSlashX = getLength(); for (unsigned I = 0, N = getLength(); I != N; ++I) { switch (uint32_t Char = getCodeUnit(I)) { default: // FIXME: Convert UTF-8 back to codepoints before rendering. // Convert UTF-16 surrogate pairs back to codepoints before rendering. // Leave invalid surrogates alone; we'll use \x for those. if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 && Char <= 0xdbff) { uint32_t Trail = getCodeUnit(I + 1); if (Trail >= 0xdc00 && Trail <= 0xdfff) { Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00); ++I; } } if (Char > 0xff) { // If this is a wide string, output characters over 0xff using \x // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a // codepoint: use \x escapes for invalid codepoints. if (getKind() == Wide || (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) { // FIXME: Is this the best way to print wchar_t? OS << "\\x"; int Shift = 28; while ((Char >> Shift) == 0) Shift -= 4; for (/**/; Shift >= 0; Shift -= 4) OS << Hex[(Char >> Shift) & 15]; LastSlashX = I; break; } if (Char > 0xffff) OS << "\\U00" << Hex[(Char >> 20) & 15] << Hex[(Char >> 16) & 15]; else OS << "\\u"; OS << Hex[(Char >> 12) & 15] << Hex[(Char >> 8) & 15] << Hex[(Char >> 4) & 15] << Hex[(Char >> 0) & 15]; break; } // If we used \x... for the previous character, and this character is a // hexadecimal digit, prevent it being slurped as part of the \x. if (LastSlashX + 1 == I) { switch (Char) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': OS << "\"\""; } } assert(Char <= 0xff && "Characters above 0xff should already have been handled."); if (isPrintable(Char)) OS << (char)Char; else // Output anything hard as an octal escape. OS << '\\' << (char)('0' + ((Char >> 6) & 7)) << (char)('0' + ((Char >> 3) & 7)) << (char)('0' + ((Char >> 0) & 7)); break; // Handle some common non-printable cases to make dumps prettier. case '\\': OS << "\\\\"; break; case '"': OS << "\\\""; break; case '\a': OS << "\\a"; break; case '\b': OS << "\\b"; break; case '\f': OS << "\\f"; break; case '\n': OS << "\\n"; break; case '\r': OS << "\\r"; break; case '\t': OS << "\\t"; break; case '\v': OS << "\\v"; break; } } OS << '"'; } void StringLiteral::setString(const ASTContext &C, StringRef Str, StringKind Kind, bool IsPascal) { //FIXME: we assume that the string data comes from a target that uses the same // code unit size and endianness for the type of string. this->Kind = Kind; this->IsPascal = IsPascal; CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind); assert((Str.size()%CharByteWidth == 0) && "size of data must be multiple of CharByteWidth"); Length = Str.size()/CharByteWidth; switch(CharByteWidth) { case 1: { char *AStrData = new (C) char[Length]; std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData)); StrData.asChar = AStrData; break; } case 2: { uint16_t *AStrData = new (C) uint16_t[Length]; std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData)); StrData.asUInt16 = AStrData; break; } case 4: { uint32_t *AStrData = new (C) uint32_t[Length]; std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData)); StrData.asUInt32 = AStrData; break; } default: llvm_unreachable("unsupported CharByteWidth"); } } /// getLocationOfByte - Return a source location that points to the specified /// byte of this string literal. /// /// Strings are amazingly complex. They can be formed from multiple tokens and /// can have escape sequences in them in addition to the usual trigraph and /// escaped newline business. This routine handles this complexity. /// /// The *StartToken sets the first token to be searched in this function and /// the *StartTokenByteOffset is the byte offset of the first token. Before /// returning, it updates the *StartToken to the TokNo of the token being found /// and sets *StartTokenByteOffset to the byte offset of the token in the /// string. /// Using these two parameters can reduce the time complexity from O(n^2) to /// O(n) if one wants to get the location of byte for all the tokens in a /// string. /// SourceLocation StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken, unsigned *StartTokenByteOffset) const { assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) && "Only narrow string literals are currently supported"); // Loop over all of the tokens in this string until we find the one that // contains the byte we're looking for. unsigned TokNo = 0; unsigned StringOffset = 0; if (StartToken) TokNo = *StartToken; if (StartTokenByteOffset) { StringOffset = *StartTokenByteOffset; ByteNo -= StringOffset; } while (1) { assert(TokNo < getNumConcatenated() && "Invalid byte number!"); SourceLocation StrTokLoc = getStrTokenLoc(TokNo); // Get the spelling of the string so that we can get the data that makes up // the string literal, not the identifier for the macro it is potentially // expanded through. SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc); // Re-lex the token to get its length and original spelling. std::pair LocInfo = SM.getDecomposedLoc(StrTokSpellingLoc); bool Invalid = false; StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) { if (StartTokenByteOffset != nullptr) *StartTokenByteOffset = StringOffset; if (StartToken != nullptr) *StartToken = TokNo; return StrTokSpellingLoc; } const char *StrData = Buffer.data()+LocInfo.second; // Create a lexer starting at the beginning of this token. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features, Buffer.begin(), StrData, Buffer.end()); Token TheTok; TheLexer.LexFromRawLexer(TheTok); // Use the StringLiteralParser to compute the length of the string in bytes. StringLiteralParser SLP(TheTok, SM, Features, Target); unsigned TokNumBytes = SLP.GetStringLength(); // If the byte is in this token, return the location of the byte. if (ByteNo < TokNumBytes || (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) { unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo); // Now that we know the offset of the token in the spelling, use the // preprocessor to get the offset in the original source. if (StartTokenByteOffset != nullptr) *StartTokenByteOffset = StringOffset; if (StartToken != nullptr) *StartToken = TokNo; return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features); } // Move to the next string token. StringOffset += TokNumBytes; ++TokNo; ByteNo -= TokNumBytes; } } /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "sizeof" or "[pre]++". StringRef UnaryOperator::getOpcodeStr(Opcode Op) { switch (Op) { #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling; #include "clang/AST/OperationKinds.def" } llvm_unreachable("Unknown unary operator"); } UnaryOperatorKind UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { switch (OO) { default: llvm_unreachable("No unary operator for overloaded function"); case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc; case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec; case OO_Amp: return UO_AddrOf; case OO_Star: return UO_Deref; case OO_Plus: return UO_Plus; case OO_Minus: return UO_Minus; case OO_Tilde: return UO_Not; case OO_Exclaim: return UO_LNot; case OO_Coawait: return UO_Coawait; } } OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { switch (Opc) { case UO_PostInc: case UO_PreInc: return OO_PlusPlus; case UO_PostDec: case UO_PreDec: return OO_MinusMinus; case UO_AddrOf: return OO_Amp; case UO_Deref: return OO_Star; case UO_Plus: return OO_Plus; case UO_Minus: return OO_Minus; case UO_Not: return OO_Tilde; case UO_LNot: return OO_Exclaim; case UO_Coawait: return OO_Coawait; default: return OO_None; } } //===----------------------------------------------------------------------===// // Postfix Operators. //===----------------------------------------------------------------------===// CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef preargs, ArrayRef args, QualType t, ExprValueKind VK, SourceLocation rparenloc) : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(), fn->isValueDependent(), fn->isInstantiationDependent(), fn->containsUnexpandedParameterPack()), NumArgs(args.size()) { unsigned NumPreArgs = preargs.size(); SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs]; SubExprs[FN] = fn; for (unsigned i = 0; i != NumPreArgs; ++i) { updateDependenciesFromArg(preargs[i]); SubExprs[i+PREARGS_START] = preargs[i]; } for (unsigned i = 0; i != args.size(); ++i) { updateDependenciesFromArg(args[i]); SubExprs[i+PREARGS_START+NumPreArgs] = args[i]; } CallExprBits.NumPreArgs = NumPreArgs; RParenLoc = rparenloc; } CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef args, QualType t, ExprValueKind VK, SourceLocation rparenloc) : CallExpr(C, SC, fn, ArrayRef(), args, t, VK, rparenloc) {} CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef args, QualType t, ExprValueKind VK, SourceLocation rparenloc) : CallExpr(C, CallExprClass, fn, ArrayRef(), args, t, VK, rparenloc) { } CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty) : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {} CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty) : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) { // FIXME: Why do we allocate this? SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs](); CallExprBits.NumPreArgs = NumPreArgs; } void CallExpr::updateDependenciesFromArg(Expr *Arg) { if (Arg->isTypeDependent()) ExprBits.TypeDependent = true; if (Arg->isValueDependent()) ExprBits.ValueDependent = true; if (Arg->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (Arg->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; } FunctionDecl *CallExpr::getDirectCallee() { return dyn_cast_or_null(getCalleeDecl()); } Decl *CallExpr::getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); } Decl *Expr::getReferencedDeclOfCallee() { Expr *CEE = IgnoreParenImpCasts(); while (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast(CEE)) { CEE = NTTP->getReplacement()->IgnoreParenCasts(); } // If we're calling a dereference, look at the pointer instead. if (BinaryOperator *BO = dyn_cast(CEE)) { if (BO->isPtrMemOp()) CEE = BO->getRHS()->IgnoreParenCasts(); } else if (UnaryOperator *UO = dyn_cast(CEE)) { if (UO->getOpcode() == UO_Deref) CEE = UO->getSubExpr()->IgnoreParenCasts(); } if (DeclRefExpr *DRE = dyn_cast(CEE)) return DRE->getDecl(); if (MemberExpr *ME = dyn_cast(CEE)) return ME->getMemberDecl(); return nullptr; } /// setNumArgs - This changes the number of arguments present in this call. /// Any orphaned expressions are deleted by this, and any new operands are set /// to null. void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) { // No change, just return. if (NumArgs == getNumArgs()) return; // If shrinking # arguments, just delete the extras and forgot them. if (NumArgs < getNumArgs()) { this->NumArgs = NumArgs; return; } // Otherwise, we are growing the # arguments. New an bigger argument array. unsigned NumPreArgs = getNumPreArgs(); Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs]; // Copy over args. for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i) NewSubExprs[i] = SubExprs[i]; // Null out new args. for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs; i != NumArgs+PREARGS_START+NumPreArgs; ++i) NewSubExprs[i] = nullptr; if (SubExprs) C.Deallocate(SubExprs); SubExprs = NewSubExprs; this->NumArgs = NumArgs; } /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If /// not, return 0. unsigned CallExpr::getBuiltinCallee() const { // All simple function calls (e.g. func()) are implicitly cast to pointer to // function. As a result, we try and obtain the DeclRefExpr from the // ImplicitCastExpr. const ImplicitCastExpr *ICE = dyn_cast(getCallee()); if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()). return 0; const DeclRefExpr *DRE = dyn_cast(ICE->getSubExpr()); if (!DRE) return 0; const FunctionDecl *FDecl = dyn_cast(DRE->getDecl()); if (!FDecl) return 0; if (!FDecl->getIdentifier()) return 0; return FDecl->getBuiltinID(); } bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const { if (unsigned BI = getBuiltinCallee()) return Ctx.BuiltinInfo.isUnevaluated(BI); return false; } QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const { const Expr *Callee = getCallee(); QualType CalleeType = Callee->getType(); if (const auto *FnTypePtr = CalleeType->getAs()) { CalleeType = FnTypePtr->getPointeeType(); } else if (const auto *BPT = CalleeType->getAs()) { CalleeType = BPT->getPointeeType(); } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) { if (isa(Callee->IgnoreParens())) return Ctx.VoidTy; // This should never be overloaded and so should never return null. CalleeType = Expr::findBoundMemberType(Callee); } const FunctionType *FnType = CalleeType->castAs(); return FnType->getReturnType(); } SourceLocation CallExpr::getLocStart() const { if (isa(this)) return cast(this)->getLocStart(); SourceLocation begin = getCallee()->getLocStart(); if (begin.isInvalid() && getNumArgs() > 0 && getArg(0)) begin = getArg(0)->getLocStart(); return begin; } SourceLocation CallExpr::getLocEnd() const { if (isa(this)) return cast(this)->getLocEnd(); SourceLocation end = getRParenLoc(); if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1)) end = getArg(getNumArgs() - 1)->getLocEnd(); return end; } OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef comps, ArrayRef exprs, SourceLocation RParenLoc) { void *Mem = C.Allocate( totalSizeToAlloc(comps.size(), exprs.size())); return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs, RParenLoc); } OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C, unsigned numComps, unsigned numExprs) { void *Mem = C.Allocate(totalSizeToAlloc(numComps, numExprs)); return new (Mem) OffsetOfExpr(numComps, numExprs); } OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef comps, ArrayRef exprs, SourceLocation RParenLoc) : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary, /*TypeDependent=*/false, /*ValueDependent=*/tsi->getType()->isDependentType(), tsi->getType()->isInstantiationDependentType(), tsi->getType()->containsUnexpandedParameterPack()), OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi), NumComps(comps.size()), NumExprs(exprs.size()) { for (unsigned i = 0; i != comps.size(); ++i) { setComponent(i, comps[i]); } for (unsigned i = 0; i != exprs.size(); ++i) { if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent()) ExprBits.ValueDependent = true; if (exprs[i]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; setIndexExpr(i, exprs[i]); } } IdentifierInfo *OffsetOfNode::getFieldName() const { assert(getKind() == Field || getKind() == Identifier); if (getKind() == Field) return getField()->getIdentifier(); return reinterpret_cast (Data & ~(uintptr_t)Mask); } UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr( UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType, SourceLocation op, SourceLocation rp) : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary, false, // Never type-dependent (C++ [temp.dep.expr]p3). // Value-dependent if the argument is type-dependent. E->isTypeDependent(), E->isInstantiationDependent(), E->containsUnexpandedParameterPack()), OpLoc(op), RParenLoc(rp) { UnaryExprOrTypeTraitExprBits.Kind = ExprKind; UnaryExprOrTypeTraitExprBits.IsType = false; Argument.Ex = E; // Check to see if we are in the situation where alignof(decl) should be // dependent because decl's alignment is dependent. if (ExprKind == UETT_AlignOf) { if (!isValueDependent() || !isInstantiationDependent()) { E = E->IgnoreParens(); const ValueDecl *D = nullptr; if (const auto *DRE = dyn_cast(E)) D = DRE->getDecl(); else if (const auto *ME = dyn_cast(E)) D = ME->getMemberDecl(); if (D) { for (const auto *I : D->specific_attrs()) { if (I->isAlignmentDependent()) { setValueDependent(true); setInstantiationDependent(true); break; } } } } } } MemberExpr *MemberExpr::Create( const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *memberdecl, DeclAccessPair founddecl, DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs, QualType ty, ExprValueKind vk, ExprObjectKind ok) { bool hasQualOrFound = (QualifierLoc || founddecl.getDecl() != memberdecl || founddecl.getAccess() != memberdecl->getAccess()); bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid(); std::size_t Size = totalSizeToAlloc(hasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0, targs ? targs->size() : 0); void *Mem = C.Allocate(Size, alignof(MemberExpr)); MemberExpr *E = new (Mem) MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok); if (hasQualOrFound) { // FIXME: Wrong. We should be looking at the member declaration we found. if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) { E->setValueDependent(true); E->setTypeDependent(true); E->setInstantiationDependent(true); } else if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) E->setInstantiationDependent(true); E->HasQualifierOrFoundDecl = true; MemberExprNameQualifier *NQ = E->getTrailingObjects(); NQ->QualifierLoc = QualifierLoc; NQ->FoundDecl = founddecl; } E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid()); if (targs) { bool Dependent = false; bool InstantiationDependent = false; bool ContainsUnexpandedParameterPack = false; E->getTrailingObjects()->initializeFrom( TemplateKWLoc, *targs, E->getTrailingObjects(), Dependent, InstantiationDependent, ContainsUnexpandedParameterPack); if (InstantiationDependent) E->setInstantiationDependent(true); } else if (TemplateKWLoc.isValid()) { E->getTrailingObjects()->initializeFrom( TemplateKWLoc); } return E; } SourceLocation MemberExpr::getLocStart() const { if (isImplicitAccess()) { if (hasQualifier()) return getQualifierLoc().getBeginLoc(); return MemberLoc; } // FIXME: We don't want this to happen. Rather, we should be able to // detect all kinds of implicit accesses more cleanly. SourceLocation BaseStartLoc = getBase()->getLocStart(); if (BaseStartLoc.isValid()) return BaseStartLoc; return MemberLoc; } SourceLocation MemberExpr::getLocEnd() const { SourceLocation EndLoc = getMemberNameInfo().getEndLoc(); if (hasExplicitTemplateArgs()) EndLoc = getRAngleLoc(); else if (EndLoc.isInvalid()) EndLoc = getBase()->getLocEnd(); return EndLoc; } bool CastExpr::CastConsistency() const { switch (getCastKind()) { case CK_DerivedToBase: case CK_UncheckedDerivedToBase: case CK_DerivedToBaseMemberPointer: case CK_BaseToDerived: case CK_BaseToDerivedMemberPointer: assert(!path_empty() && "Cast kind should have a base path!"); break; case CK_CPointerToObjCPointerCast: assert(getType()->isObjCObjectPointerType()); assert(getSubExpr()->getType()->isPointerType()); goto CheckNoBasePath; case CK_BlockPointerToObjCPointerCast: assert(getType()->isObjCObjectPointerType()); assert(getSubExpr()->getType()->isBlockPointerType()); goto CheckNoBasePath; case CK_ReinterpretMemberPointer: assert(getType()->isMemberPointerType()); assert(getSubExpr()->getType()->isMemberPointerType()); goto CheckNoBasePath; case CK_BitCast: // Arbitrary casts to C pointer types count as bitcasts. // Otherwise, we should only have block and ObjC pointer casts // here if they stay within the type kind. if (!getType()->isPointerType()) { assert(getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()); assert(getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()); } goto CheckNoBasePath; case CK_AnyPointerToBlockPointerCast: assert(getType()->isBlockPointerType()); assert(getSubExpr()->getType()->isAnyPointerType() && !getSubExpr()->getType()->isBlockPointerType()); goto CheckNoBasePath; case CK_CopyAndAutoreleaseBlockObject: assert(getType()->isBlockPointerType()); assert(getSubExpr()->getType()->isBlockPointerType()); goto CheckNoBasePath; case CK_FunctionToPointerDecay: assert(getType()->isPointerType()); assert(getSubExpr()->getType()->isFunctionType()); goto CheckNoBasePath; case CK_AddressSpaceConversion: assert(getType()->isPointerType() || getType()->isBlockPointerType()); assert(getSubExpr()->getType()->isPointerType() || getSubExpr()->getType()->isBlockPointerType()); assert(getType()->getPointeeType().getAddressSpace() != getSubExpr()->getType()->getPointeeType().getAddressSpace()); LLVM_FALLTHROUGH; // These should not have an inheritance path. case CK_Dynamic: case CK_ToUnion: case CK_ArrayToPointerDecay: case CK_NullToMemberPointer: case CK_NullToPointer: case CK_ConstructorConversion: case CK_IntegralToPointer: case CK_PointerToIntegral: case CK_ToVoid: case CK_VectorSplat: case CK_IntegralCast: case CK_BooleanToSignedIntegral: case CK_IntegralToFloating: case CK_FloatingToIntegral: case CK_FloatingCast: case CK_ObjCObjectLValueCast: case CK_FloatingRealToComplex: case CK_FloatingComplexToReal: case CK_FloatingComplexCast: case CK_FloatingComplexToIntegralComplex: case CK_IntegralRealToComplex: case CK_IntegralComplexToReal: case CK_IntegralComplexCast: case CK_IntegralComplexToFloatingComplex: case CK_ARCProduceObject: case CK_ARCConsumeObject: case CK_ARCReclaimReturnedObject: case CK_ARCExtendBlockObject: case CK_ZeroToOCLEvent: case CK_ZeroToOCLQueue: case CK_IntToOCLSampler: assert(!getType()->isBooleanType() && "unheralded conversion to bool"); goto CheckNoBasePath; case CK_Dependent: case CK_LValueToRValue: case CK_NoOp: case CK_AtomicToNonAtomic: case CK_NonAtomicToAtomic: case CK_PointerToBoolean: case CK_IntegralToBoolean: case CK_FloatingToBoolean: case CK_MemberPointerToBoolean: case CK_FloatingComplexToBoolean: case CK_IntegralComplexToBoolean: case CK_LValueBitCast: // -> bool& case CK_UserDefinedConversion: // operator bool() case CK_BuiltinFnToFnPtr: CheckNoBasePath: assert(path_empty() && "Cast kind should not have a base path!"); break; } return true; } const char *CastExpr::getCastKindName() const { switch (getCastKind()) { #define CAST_OPERATION(Name) case CK_##Name: return #Name; #include "clang/AST/OperationKinds.def" } llvm_unreachable("Unhandled cast kind!"); } namespace { Expr *skipImplicitTemporary(Expr *expr) { // Skip through reference binding to temporary. if (MaterializeTemporaryExpr *Materialize = dyn_cast(expr)) expr = Materialize->GetTemporaryExpr(); // Skip any temporary bindings; they're implicit. if (CXXBindTemporaryExpr *Binder = dyn_cast(expr)) expr = Binder->getSubExpr(); return expr; } } Expr *CastExpr::getSubExprAsWritten() { Expr *SubExpr = nullptr; CastExpr *E = this; do { SubExpr = skipImplicitTemporary(E->getSubExpr()); // Conversions by constructor and conversion functions have a // subexpression describing the call; strip it off. if (E->getCastKind() == CK_ConstructorConversion) SubExpr = skipImplicitTemporary(cast(SubExpr)->getArg(0)); else if (E->getCastKind() == CK_UserDefinedConversion) { assert((isa(SubExpr) || isa(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."); if (isa(SubExpr)) SubExpr = cast(SubExpr)->getImplicitObjectArgument(); } // If the subexpression we're left with is an implicit cast, look // through that, too. } while ((E = dyn_cast(SubExpr))); return SubExpr; } CXXBaseSpecifier **CastExpr::path_buffer() { switch (getStmtClass()) { #define ABSTRACT_STMT(x) #define CASTEXPR(Type, Base) \ case Stmt::Type##Class: \ return static_cast(this)->getTrailingObjects(); #define STMT(Type, Base) #include "clang/AST/StmtNodes.inc" default: llvm_unreachable("non-cast expressions not possible here"); } } ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind VK) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); ImplicitCastExpr *E = new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK); if (PathSize) std::uninitialized_copy_n(BasePath->data(), BasePath->size(), E->getTrailingObjects()); return E; } ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize); } CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); CStyleCastExpr *E = new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R); if (PathSize) std::uninitialized_copy_n(BasePath->data(), BasePath->size(), E->getTrailingObjects()); return E; } CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize); } /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it /// corresponds to, e.g. "<<=". StringRef BinaryOperator::getOpcodeStr(Opcode Op) { switch (Op) { #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling; #include "clang/AST/OperationKinds.def" } llvm_unreachable("Invalid OpCode!"); } BinaryOperatorKind BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { switch (OO) { default: llvm_unreachable("Not an overloadable binary operator"); case OO_Plus: return BO_Add; case OO_Minus: return BO_Sub; case OO_Star: return BO_Mul; case OO_Slash: return BO_Div; case OO_Percent: return BO_Rem; case OO_Caret: return BO_Xor; case OO_Amp: return BO_And; case OO_Pipe: return BO_Or; case OO_Equal: return BO_Assign; case OO_Less: return BO_LT; case OO_Greater: return BO_GT; case OO_PlusEqual: return BO_AddAssign; case OO_MinusEqual: return BO_SubAssign; case OO_StarEqual: return BO_MulAssign; case OO_SlashEqual: return BO_DivAssign; case OO_PercentEqual: return BO_RemAssign; case OO_CaretEqual: return BO_XorAssign; case OO_AmpEqual: return BO_AndAssign; case OO_PipeEqual: return BO_OrAssign; case OO_LessLess: return BO_Shl; case OO_GreaterGreater: return BO_Shr; case OO_LessLessEqual: return BO_ShlAssign; case OO_GreaterGreaterEqual: return BO_ShrAssign; case OO_EqualEqual: return BO_EQ; case OO_ExclaimEqual: return BO_NE; case OO_LessEqual: return BO_LE; case OO_GreaterEqual: return BO_GE; case OO_AmpAmp: return BO_LAnd; case OO_PipePipe: return BO_LOr; case OO_Comma: return BO_Comma; case OO_ArrowStar: return BO_PtrMemI; } } OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { static const OverloadedOperatorKind OverOps[] = { /* .* Cannot be overloaded */OO_None, OO_ArrowStar, OO_Star, OO_Slash, OO_Percent, OO_Plus, OO_Minus, OO_LessLess, OO_GreaterGreater, OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, OO_EqualEqual, OO_ExclaimEqual, OO_Amp, OO_Caret, OO_Pipe, OO_AmpAmp, OO_PipePipe, OO_Equal, OO_StarEqual, OO_SlashEqual, OO_PercentEqual, OO_PlusEqual, OO_MinusEqual, OO_LessLessEqual, OO_GreaterGreaterEqual, OO_AmpEqual, OO_CaretEqual, OO_PipeEqual, OO_Comma }; return OverOps[Opc]; } InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc, ArrayRef initExprs, SourceLocation rbraceloc) : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false, false, false), InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true) { sawArrayRangeDesignator(false); for (unsigned I = 0; I != initExprs.size(); ++I) { if (initExprs[I]->isTypeDependent()) ExprBits.TypeDependent = true; if (initExprs[I]->isValueDependent()) ExprBits.ValueDependent = true; if (initExprs[I]->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (initExprs[I]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; } InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end()); } void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) { if (NumInits > InitExprs.size()) InitExprs.reserve(C, NumInits); } void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) { InitExprs.resize(C, NumInits, nullptr); } Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) { if (Init >= InitExprs.size()) { InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr); setInit(Init, expr); return nullptr; } Expr *Result = cast_or_null(InitExprs[Init]); setInit(Init, expr); return Result; } void InitListExpr::setArrayFiller(Expr *filler) { assert(!hasArrayFiller() && "Filler already set!"); ArrayFillerOrUnionFieldInit = filler; // Fill out any "holes" in the array due to designated initializers. Expr **inits = getInits(); for (unsigned i = 0, e = getNumInits(); i != e; ++i) if (inits[i] == nullptr) inits[i] = filler; } bool InitListExpr::isStringLiteralInit() const { if (getNumInits() != 1) return false; const ArrayType *AT = getType()->getAsArrayTypeUnsafe(); if (!AT || !AT->getElementType()->isIntegerType()) return false; // It is possible for getInit() to return null. const Expr *Init = getInit(0); if (!Init) return false; Init = Init->IgnoreParens(); return isa(Init) || isa(Init); } bool InitListExpr::isTransparent() const { assert(isSemanticForm() && "syntactic form never semantically transparent"); // A glvalue InitListExpr is always just sugar. if (isGLValue()) { assert(getNumInits() == 1 && "multiple inits in glvalue init list"); return true; } // Otherwise, we're sugar if and only if we have exactly one initializer that // is of the same type. if (getNumInits() != 1 || !getInit(0)) return false; // Don't confuse aggregate initialization of a struct X { X &x; }; with a // transparent struct copy. if (!getInit(0)->isRValue() && getType()->isRecordType()) return false; return getType().getCanonicalType() == getInit(0)->getType().getCanonicalType(); } +bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const { + assert(isSyntacticForm() && "only test syntactic form as zero initializer"); + + if (LangOpts.CPlusPlus || getNumInits() != 1) { + return false; + } + + const IntegerLiteral *Lit = dyn_cast(getInit(0)); + return Lit && Lit->getValue() == 0; +} + SourceLocation InitListExpr::getLocStart() const { if (InitListExpr *SyntacticForm = getSyntacticForm()) return SyntacticForm->getLocStart(); SourceLocation Beg = LBraceLoc; if (Beg.isInvalid()) { // Find the first non-null initializer. for (InitExprsTy::const_iterator I = InitExprs.begin(), E = InitExprs.end(); I != E; ++I) { if (Stmt *S = *I) { Beg = S->getLocStart(); break; } } } return Beg; } SourceLocation InitListExpr::getLocEnd() const { if (InitListExpr *SyntacticForm = getSyntacticForm()) return SyntacticForm->getLocEnd(); SourceLocation End = RBraceLoc; if (End.isInvalid()) { // Find the first non-null initializer from the end. for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(), E = InitExprs.rend(); I != E; ++I) { if (Stmt *S = *I) { End = S->getLocEnd(); break; } } } return End; } /// getFunctionType - Return the underlying function type for this block. /// const FunctionProtoType *BlockExpr::getFunctionType() const { // The block pointer is never sugared, but the function type might be. return cast(getType()) ->getPointeeType()->castAs(); } SourceLocation BlockExpr::getCaretLocation() const { return TheBlock->getCaretLocation(); } const Stmt *BlockExpr::getBody() const { return TheBlock->getBody(); } Stmt *BlockExpr::getBody() { return TheBlock->getBody(); } //===----------------------------------------------------------------------===// // Generic Expression Routines //===----------------------------------------------------------------------===// /// isUnusedResultAWarning - Return true if this immediate expression should /// be warned about if the result is unused. If so, fill in Loc and Ranges /// with location to warn on and the source range[s] to report with the /// warning. bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const { // Don't warn if the expr is type dependent. The type could end up // instantiating to void. if (isTypeDependent()) return false; switch (getStmtClass()) { default: if (getType()->isVoidType()) return false; WarnE = this; Loc = getExprLoc(); R1 = getSourceRange(); return true; case ParenExprClass: return cast(this)->getSubExpr()-> isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case GenericSelectionExprClass: return cast(this)->getResultExpr()-> isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case ChooseExprClass: return cast(this)->getChosenSubExpr()-> isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case UnaryOperatorClass: { const UnaryOperator *UO = cast(this); switch (UO->getOpcode()) { case UO_Plus: case UO_Minus: case UO_AddrOf: case UO_Not: case UO_LNot: case UO_Deref: break; case UO_Coawait: // This is just the 'operator co_await' call inside the guts of a // dependent co_await call. case UO_PostInc: case UO_PostDec: case UO_PreInc: case UO_PreDec: // ++/-- return false; // Not a warning. case UO_Real: case UO_Imag: // accessing a piece of a volatile complex is a side-effect. if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) .isVolatileQualified()) return false; break; case UO_Extension: return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } WarnE = this; Loc = UO->getOperatorLoc(); R1 = UO->getSubExpr()->getSourceRange(); return true; } case BinaryOperatorClass: { const BinaryOperator *BO = cast(this); switch (BO->getOpcode()) { default: break; // Consider the RHS of comma for side effects. LHS was checked by // Sema::CheckCommaOperands. case BO_Comma: // ((foo = ), 0) is an idiom for hiding the result (and // lvalue-ness) of an assignment written in a macro. if (IntegerLiteral *IE = dyn_cast(BO->getRHS()->IgnoreParens())) if (IE->getValue() == 0) return false; return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); // Consider '||', '&&' to have side effects if the LHS or RHS does. case BO_LAnd: case BO_LOr: if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) || !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) return false; break; } if (BO->isAssignmentOp()) return false; WarnE = this; Loc = BO->getOperatorLoc(); R1 = BO->getLHS()->getSourceRange(); R2 = BO->getRHS()->getSourceRange(); return true; } case CompoundAssignOperatorClass: case VAArgExprClass: case AtomicExprClass: return false; case ConditionalOperatorClass: { // If only one of the LHS or RHS is a warning, the operator might // be being used for control flow. Only warn if both the LHS and // RHS are warnings. const ConditionalOperator *Exp = cast(this); if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) return false; if (!Exp->getLHS()) return true; return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } case MemberExprClass: WarnE = this; Loc = cast(this)->getMemberLoc(); R1 = SourceRange(Loc, Loc); R2 = cast(this)->getBase()->getSourceRange(); return true; case ArraySubscriptExprClass: WarnE = this; Loc = cast(this)->getRBracketLoc(); R1 = cast(this)->getLHS()->getSourceRange(); R2 = cast(this)->getRHS()->getSourceRange(); return true; case CXXOperatorCallExprClass: { // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator // overloads as there is no reasonable way to define these such that they // have non-trivial, desirable side-effects. See the -Wunused-comparison // warning: operators == and != are commonly typo'ed, and so warning on them // provides additional value as well. If this list is updated, // DiagnoseUnusedComparison should be as well. const CXXOperatorCallExpr *Op = cast(this); switch (Op->getOperator()) { default: break; case OO_EqualEqual: case OO_ExclaimEqual: case OO_Less: case OO_Greater: case OO_GreaterEqual: case OO_LessEqual: if (Op->getCallReturnType(Ctx)->isReferenceType() || Op->getCallReturnType(Ctx)->isVoidType()) break; WarnE = this; Loc = Op->getOperatorLoc(); R1 = Op->getSourceRange(); return true; } // Fallthrough for generic call handling. LLVM_FALLTHROUGH; } case CallExprClass: case CXXMemberCallExprClass: case UserDefinedLiteralClass: { // If this is a direct call, get the callee. const CallExpr *CE = cast(this); if (const Decl *FD = CE->getCalleeDecl()) { const FunctionDecl *Func = dyn_cast(FD); bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr() : FD->hasAttr(); // If the callee has attribute pure, const, or warn_unused_result, warn // about it. void foo() { strlen("bar"); } should warn. // // Note: If new cases are added here, DiagnoseUnusedExprResult should be // updated to match for QoI. if (HasWarnUnusedResultAttr || FD->hasAttr() || FD->hasAttr()) { WarnE = this; Loc = CE->getCallee()->getLocStart(); R1 = CE->getCallee()->getSourceRange(); if (unsigned NumArgs = CE->getNumArgs()) R2 = SourceRange(CE->getArg(0)->getLocStart(), CE->getArg(NumArgs-1)->getLocEnd()); return true; } } return false; } // If we don't know precisely what we're looking at, let's not warn. case UnresolvedLookupExprClass: case CXXUnresolvedConstructExprClass: return false; case CXXTemporaryObjectExprClass: case CXXConstructExprClass: { if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) { if (Type->hasAttr()) { WarnE = this; Loc = getLocStart(); R1 = getSourceRange(); return true; } } return false; } case ObjCMessageExprClass: { const ObjCMessageExpr *ME = cast(this); if (Ctx.getLangOpts().ObjCAutoRefCount && ME->isInstanceMessage() && !ME->getType()->isVoidType() && ME->getMethodFamily() == OMF_init) { WarnE = this; Loc = getExprLoc(); R1 = ME->getSourceRange(); return true; } if (const ObjCMethodDecl *MD = ME->getMethodDecl()) if (MD->hasAttr()) { WarnE = this; Loc = getExprLoc(); return true; } return false; } case ObjCPropertyRefExprClass: WarnE = this; Loc = getExprLoc(); R1 = getSourceRange(); return true; case PseudoObjectExprClass: { const PseudoObjectExpr *PO = cast(this); // Only complain about things that have the form of a getter. if (isa(PO->getSyntacticForm()) || isa(PO->getSyntacticForm())) return false; WarnE = this; Loc = getExprLoc(); R1 = getSourceRange(); return true; } case StmtExprClass: { // Statement exprs don't logically have side effects themselves, but are // sometimes used in macros in ways that give them a type that is unused. // For example ({ blah; foo(); }) will end up with a type if foo has a type. // however, if the result of the stmt expr is dead, we don't want to emit a // warning. const CompoundStmt *CS = cast(this)->getSubStmt(); if (!CS->body_empty()) { if (const Expr *E = dyn_cast(CS->body_back())) return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); if (const LabelStmt *Label = dyn_cast(CS->body_back())) if (const Expr *E = dyn_cast(Label->getSubStmt())) return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } if (getType()->isVoidType()) return false; WarnE = this; Loc = cast(this)->getLParenLoc(); R1 = getSourceRange(); return true; } case CXXFunctionalCastExprClass: case CStyleCastExprClass: { // Ignore an explicit cast to void unless the operand is a non-trivial // volatile lvalue. const CastExpr *CE = cast(this); if (CE->getCastKind() == CK_ToVoid) { if (CE->getSubExpr()->isGLValue() && CE->getSubExpr()->getType().isVolatileQualified()) { const DeclRefExpr *DRE = dyn_cast(CE->getSubExpr()->IgnoreParens()); if (!(DRE && isa(DRE->getDecl()) && cast(DRE->getDecl())->hasLocalStorage())) { return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } } return false; } // If this is a cast to a constructor conversion, check the operand. // Otherwise, the result of the cast is unused. if (CE->getCastKind() == CK_ConstructorConversion) return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); WarnE = this; if (const CXXFunctionalCastExpr *CXXCE = dyn_cast(this)) { Loc = CXXCE->getLocStart(); R1 = CXXCE->getSubExpr()->getSourceRange(); } else { const CStyleCastExpr *CStyleCE = cast(this); Loc = CStyleCE->getLParenLoc(); R1 = CStyleCE->getSubExpr()->getSourceRange(); } return true; } case ImplicitCastExprClass: { const CastExpr *ICE = cast(this); // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect. if (ICE->getCastKind() == CK_LValueToRValue && ICE->getSubExpr()->getType().isVolatileQualified()) return false; return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } case CXXDefaultArgExprClass: return (cast(this) ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); case CXXDefaultInitExprClass: return (cast(this) ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); case CXXNewExprClass: // FIXME: In theory, there might be new expressions that don't have side // effects (e.g. a placement new with an uninitialized POD). case CXXDeleteExprClass: return false; case MaterializeTemporaryExprClass: return cast(this)->GetTemporaryExpr() ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case CXXBindTemporaryExprClass: return cast(this)->getSubExpr() ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case ExprWithCleanupsClass: return cast(this)->getSubExpr() ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } } /// isOBJCGCCandidate - Check if an expression is objc gc'able. /// returns true, if it is; false otherwise. bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { const Expr *E = IgnoreParens(); switch (E->getStmtClass()) { default: return false; case ObjCIvarRefExprClass: return true; case Expr::UnaryOperatorClass: return cast(E)->getSubExpr()->isOBJCGCCandidate(Ctx); case ImplicitCastExprClass: return cast(E)->getSubExpr()->isOBJCGCCandidate(Ctx); case MaterializeTemporaryExprClass: return cast(E)->GetTemporaryExpr() ->isOBJCGCCandidate(Ctx); case CStyleCastExprClass: return cast(E)->getSubExpr()->isOBJCGCCandidate(Ctx); case DeclRefExprClass: { const Decl *D = cast(E)->getDecl(); if (const VarDecl *VD = dyn_cast(D)) { if (VD->hasGlobalStorage()) return true; QualType T = VD->getType(); // dereferencing to a pointer is always a gc'able candidate, // unless it is __weak. return T->isPointerType() && (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak); } return false; } case MemberExprClass: { const MemberExpr *M = cast(E); return M->getBase()->isOBJCGCCandidate(Ctx); } case ArraySubscriptExprClass: return cast(E)->getBase()->isOBJCGCCandidate(Ctx); } } bool Expr::isBoundMemberFunction(ASTContext &Ctx) const { if (isTypeDependent()) return false; return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; } QualType Expr::findBoundMemberType(const Expr *expr) { assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); // Bound member expressions are always one of these possibilities: // x->m x.m x->*y x.*y // (possibly parenthesized) expr = expr->IgnoreParens(); if (const MemberExpr *mem = dyn_cast(expr)) { assert(isa(mem->getMemberDecl())); return mem->getMemberDecl()->getType(); } if (const BinaryOperator *op = dyn_cast(expr)) { QualType type = op->getRHS()->getType()->castAs() ->getPointeeType(); assert(type->isFunctionType()); return type; } assert(isa(expr) || isa(expr)); return QualType(); } Expr* Expr::IgnoreParens() { Expr* E = this; while (true) { if (ParenExpr* P = dyn_cast(E)) { E = P->getSubExpr(); continue; } if (UnaryOperator* P = dyn_cast(E)) { if (P->getOpcode() == UO_Extension) { E = P->getSubExpr(); continue; } } if (GenericSelectionExpr* P = dyn_cast(E)) { if (!P->isResultDependent()) { E = P->getResultExpr(); continue; } } if (ChooseExpr* P = dyn_cast(E)) { if (!P->isConditionDependent()) { E = P->getChosenSubExpr(); continue; } } return E; } } /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr /// or CastExprs or ImplicitCastExprs, returning their operand. Expr *Expr::IgnoreParenCasts() { Expr *E = this; while (true) { E = E->IgnoreParens(); if (CastExpr *P = dyn_cast(E)) { E = P->getSubExpr(); continue; } if (MaterializeTemporaryExpr *Materialize = dyn_cast(E)) { E = Materialize->GetTemporaryExpr(); continue; } if (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast(E)) { E = NTTP->getReplacement(); continue; } return E; } } Expr *Expr::IgnoreCasts() { Expr *E = this; while (true) { if (CastExpr *P = dyn_cast(E)) { E = P->getSubExpr(); continue; } if (MaterializeTemporaryExpr *Materialize = dyn_cast(E)) { E = Materialize->GetTemporaryExpr(); continue; } if (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast(E)) { E = NTTP->getReplacement(); continue; } return E; } } /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue /// casts. This is intended purely as a temporary workaround for code /// that hasn't yet been rewritten to do the right thing about those /// casts, and may disappear along with the last internal use. Expr *Expr::IgnoreParenLValueCasts() { Expr *E = this; while (true) { E = E->IgnoreParens(); if (CastExpr *P = dyn_cast(E)) { if (P->getCastKind() == CK_LValueToRValue) { E = P->getSubExpr(); continue; } } else if (MaterializeTemporaryExpr *Materialize = dyn_cast(E)) { E = Materialize->GetTemporaryExpr(); continue; } else if (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast(E)) { E = NTTP->getReplacement(); continue; } break; } return E; } Expr *Expr::ignoreParenBaseCasts() { Expr *E = this; while (true) { E = E->IgnoreParens(); if (CastExpr *CE = dyn_cast(E)) { if (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_UncheckedDerivedToBase || CE->getCastKind() == CK_NoOp) { E = CE->getSubExpr(); continue; } } return E; } } Expr *Expr::IgnoreParenImpCasts() { Expr *E = this; while (true) { E = E->IgnoreParens(); if (ImplicitCastExpr *P = dyn_cast(E)) { E = P->getSubExpr(); continue; } if (MaterializeTemporaryExpr *Materialize = dyn_cast(E)) { E = Materialize->GetTemporaryExpr(); continue; } if (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast(E)) { E = NTTP->getReplacement(); continue; } return E; } } Expr *Expr::IgnoreConversionOperator() { if (CXXMemberCallExpr *MCE = dyn_cast(this)) { if (MCE->getMethodDecl() && isa(MCE->getMethodDecl())) return MCE->getImplicitObjectArgument(); } return this; } /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the /// value (including ptr->int casts of the same size). Strip off any /// ParenExpr or CastExprs, returning their operand. Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) { Expr *E = this; while (true) { E = E->IgnoreParens(); if (CastExpr *P = dyn_cast(E)) { // We ignore integer <-> casts that are of the same width, ptr<->ptr and // ptr<->int casts of the same width. We also ignore all identity casts. Expr *SE = P->getSubExpr(); if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) { E = SE; continue; } if ((E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) && (SE->getType()->isPointerType() || SE->getType()->isIntegralType(Ctx)) && Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) { E = SE; continue; } } if (SubstNonTypeTemplateParmExpr *NTTP = dyn_cast(E)) { E = NTTP->getReplacement(); continue; } return E; } } bool Expr::isDefaultArgument() const { const Expr *E = this; if (const MaterializeTemporaryExpr *M = dyn_cast(E)) E = M->GetTemporaryExpr(); while (const ImplicitCastExpr *ICE = dyn_cast(E)) E = ICE->getSubExprAsWritten(); return isa(E); } /// \brief Skip over any no-op casts and any temporary-binding /// expressions. static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { if (const MaterializeTemporaryExpr *M = dyn_cast(E)) E = M->GetTemporaryExpr(); while (const ImplicitCastExpr *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_NoOp) E = ICE->getSubExpr(); else break; } while (const CXXBindTemporaryExpr *BE = dyn_cast(E)) E = BE->getSubExpr(); while (const ImplicitCastExpr *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_NoOp) E = ICE->getSubExpr(); else break; } return E->IgnoreParens(); } /// isTemporaryObject - Determines if this expression produces a /// temporary of the given class type. bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy))) return false; const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this); // Temporaries are by definition pr-values of class type. if (!E->Classify(C).isPRValue()) { // In this context, property reference is a message call and is pr-value. if (!isa(E)) return false; } // Black-list a few cases which yield pr-values of class type that don't // refer to temporaries of that type: // - implicit derived-to-base conversions if (isa(E)) { switch (cast(E)->getCastKind()) { case CK_DerivedToBase: case CK_UncheckedDerivedToBase: return false; default: break; } } // - member expressions (all) if (isa(E)) return false; if (const BinaryOperator *BO = dyn_cast(E)) if (BO->isPtrMemOp()) return false; // - opaque values (all) if (isa(E)) return false; return true; } bool Expr::isImplicitCXXThis() const { const Expr *E = this; // Strip away parentheses and casts we don't care about. while (true) { if (const ParenExpr *Paren = dyn_cast(E)) { E = Paren->getSubExpr(); continue; } if (const ImplicitCastExpr *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_NoOp || ICE->getCastKind() == CK_LValueToRValue || ICE->getCastKind() == CK_DerivedToBase || ICE->getCastKind() == CK_UncheckedDerivedToBase) { E = ICE->getSubExpr(); continue; } } if (const UnaryOperator* UnOp = dyn_cast(E)) { if (UnOp->getOpcode() == UO_Extension) { E = UnOp->getSubExpr(); continue; } } if (const MaterializeTemporaryExpr *M = dyn_cast(E)) { E = M->GetTemporaryExpr(); continue; } break; } if (const CXXThisExpr *This = dyn_cast(E)) return This->isImplicit(); return false; } /// hasAnyTypeDependentArguments - Determines if any of the expressions /// in Exprs is type-dependent. bool Expr::hasAnyTypeDependentArguments(ArrayRef Exprs) { for (unsigned I = 0; I < Exprs.size(); ++I) if (Exprs[I]->isTypeDependent()) return true; return false; } bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef, const Expr **Culprit) const { // This function is attempting whether an expression is an initializer // which can be evaluated at compile-time. It very closely parallels // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it // will lead to unexpected results. Like ConstExprEmitter, it falls back // to isEvaluatable most of the time. // // If we ever capture reference-binding directly in the AST, we can // kill the second parameter. if (IsForRef) { EvalResult Result; if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects) return true; if (Culprit) *Culprit = this; return false; } switch (getStmtClass()) { default: break; case StringLiteralClass: case ObjCEncodeExprClass: return true; case CXXTemporaryObjectExprClass: case CXXConstructExprClass: { const CXXConstructExpr *CE = cast(this); if (CE->getConstructor()->isTrivial() && CE->getConstructor()->getParent()->hasTrivialDestructor()) { // Trivial default constructor if (!CE->getNumArgs()) return true; // Trivial copy constructor assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument"); return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit); } break; } case CompoundLiteralExprClass: { // This handles gcc's extension that allows global initializers like // "struct x {int x;} x = (struct x) {};". // FIXME: This accepts other cases it shouldn't! const Expr *Exp = cast(this)->getInitializer(); return Exp->isConstantInitializer(Ctx, false, Culprit); } case DesignatedInitUpdateExprClass: { const DesignatedInitUpdateExpr *DIUE = cast(this); return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) && DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit); } case InitListExprClass: { const InitListExpr *ILE = cast(this); if (ILE->getType()->isArrayType()) { unsigned numInits = ILE->getNumInits(); for (unsigned i = 0; i < numInits; i++) { if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit)) return false; } return true; } if (ILE->getType()->isRecordType()) { unsigned ElementNo = 0; RecordDecl *RD = ILE->getType()->getAs()->getDecl(); for (const auto *Field : RD->fields()) { // If this is a union, skip all the fields that aren't being initialized. if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field) continue; // Don't emit anonymous bitfields, they just affect layout. if (Field->isUnnamedBitfield()) continue; if (ElementNo < ILE->getNumInits()) { const Expr *Elt = ILE->getInit(ElementNo++); if (Field->isBitField()) { // Bitfields have to evaluate to an integer. llvm::APSInt ResultTmp; if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) { if (Culprit) *Culprit = Elt; return false; } } else { bool RefType = Field->getType()->isReferenceType(); if (!Elt->isConstantInitializer(Ctx, RefType, Culprit)) return false; } } } return true; } break; } case ImplicitValueInitExprClass: case NoInitExprClass: return true; case ParenExprClass: return cast(this)->getSubExpr() ->isConstantInitializer(Ctx, IsForRef, Culprit); case GenericSelectionExprClass: return cast(this)->getResultExpr() ->isConstantInitializer(Ctx, IsForRef, Culprit); case ChooseExprClass: if (cast(this)->isConditionDependent()) { if (Culprit) *Culprit = this; return false; } return cast(this)->getChosenSubExpr() ->isConstantInitializer(Ctx, IsForRef, Culprit); case UnaryOperatorClass: { const UnaryOperator* Exp = cast(this); if (Exp->getOpcode() == UO_Extension) return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit); break; } case CXXFunctionalCastExprClass: case CXXStaticCastExprClass: case ImplicitCastExprClass: case CStyleCastExprClass: case ObjCBridgedCastExprClass: case CXXDynamicCastExprClass: case CXXReinterpretCastExprClass: case CXXConstCastExprClass: { const CastExpr *CE = cast(this); // Handle misc casts we want to ignore. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue || CE->getCastKind() == CK_ToUnion || CE->getCastKind() == CK_ConstructorConversion || CE->getCastKind() == CK_NonAtomicToAtomic || CE->getCastKind() == CK_AtomicToNonAtomic || CE->getCastKind() == CK_IntToOCLSampler) return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit); break; } case MaterializeTemporaryExprClass: return cast(this)->GetTemporaryExpr() ->isConstantInitializer(Ctx, false, Culprit); case SubstNonTypeTemplateParmExprClass: return cast(this)->getReplacement() ->isConstantInitializer(Ctx, false, Culprit); case CXXDefaultArgExprClass: return cast(this)->getExpr() ->isConstantInitializer(Ctx, false, Culprit); case CXXDefaultInitExprClass: return cast(this)->getExpr() ->isConstantInitializer(Ctx, false, Culprit); } // Allow certain forms of UB in constant initializers: signed integer // overflow and floating-point division by zero. We'll give a warning on // these, but they're common enough that we have to accept them. if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior)) return true; if (Culprit) *Culprit = this; return false; } namespace { /// \brief Look for any side effects within a Stmt. class SideEffectFinder : public ConstEvaluatedExprVisitor { typedef ConstEvaluatedExprVisitor Inherited; const bool IncludePossibleEffects; bool HasSideEffects; public: explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible) : Inherited(Context), IncludePossibleEffects(IncludePossible), HasSideEffects(false) { } bool hasSideEffects() const { return HasSideEffects; } void VisitExpr(const Expr *E) { if (!HasSideEffects && E->HasSideEffects(Context, IncludePossibleEffects)) HasSideEffects = true; } }; } bool Expr::HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects) const { // In circumstances where we care about definite side effects instead of // potential side effects, we want to ignore expressions that are part of a // macro expansion as a potential side effect. if (!IncludePossibleEffects && getExprLoc().isMacroID()) return false; if (isInstantiationDependent()) return IncludePossibleEffects; switch (getStmtClass()) { case NoStmtClass: #define ABSTRACT_STMT(Type) #define STMT(Type, Base) case Type##Class: #define EXPR(Type, Base) #include "clang/AST/StmtNodes.inc" llvm_unreachable("unexpected Expr kind"); case DependentScopeDeclRefExprClass: case CXXUnresolvedConstructExprClass: case CXXDependentScopeMemberExprClass: case UnresolvedLookupExprClass: case UnresolvedMemberExprClass: case PackExpansionExprClass: case SubstNonTypeTemplateParmPackExprClass: case FunctionParmPackExprClass: case TypoExprClass: case CXXFoldExprClass: llvm_unreachable("shouldn't see dependent / unresolved nodes here"); case DeclRefExprClass: case ObjCIvarRefExprClass: case PredefinedExprClass: case IntegerLiteralClass: case FloatingLiteralClass: case ImaginaryLiteralClass: case StringLiteralClass: case CharacterLiteralClass: case OffsetOfExprClass: case ImplicitValueInitExprClass: case UnaryExprOrTypeTraitExprClass: case AddrLabelExprClass: case GNUNullExprClass: case ArrayInitIndexExprClass: case NoInitExprClass: case CXXBoolLiteralExprClass: case CXXNullPtrLiteralExprClass: case CXXThisExprClass: case CXXScalarValueInitExprClass: case TypeTraitExprClass: case ArrayTypeTraitExprClass: case ExpressionTraitExprClass: case CXXNoexceptExprClass: case SizeOfPackExprClass: case ObjCStringLiteralClass: case ObjCEncodeExprClass: case ObjCBoolLiteralExprClass: case ObjCAvailabilityCheckExprClass: case CXXUuidofExprClass: case OpaqueValueExprClass: // These never have a side-effect. return false; case CallExprClass: case CXXOperatorCallExprClass: case CXXMemberCallExprClass: case CUDAKernelCallExprClass: case UserDefinedLiteralClass: { // We don't know a call definitely has side effects, except for calls // to pure/const functions that definitely don't. // If the call itself is considered side-effect free, check the operands. const Decl *FD = cast(this)->getCalleeDecl(); bool IsPure = FD && (FD->hasAttr() || FD->hasAttr()); if (IsPure || !IncludePossibleEffects) break; return true; } case BlockExprClass: case CXXBindTemporaryExprClass: if (!IncludePossibleEffects) break; return true; case MSPropertyRefExprClass: case MSPropertySubscriptExprClass: case CompoundAssignOperatorClass: case VAArgExprClass: case AtomicExprClass: case CXXThrowExprClass: case CXXNewExprClass: case CXXDeleteExprClass: case CoawaitExprClass: case DependentCoawaitExprClass: case CoyieldExprClass: // These always have a side-effect. return true; case StmtExprClass: { // StmtExprs have a side-effect if any substatement does. SideEffectFinder Finder(Ctx, IncludePossibleEffects); Finder.Visit(cast(this)->getSubStmt()); return Finder.hasSideEffects(); } case ExprWithCleanupsClass: if (IncludePossibleEffects) if (cast(this)->cleanupsHaveSideEffects()) return true; break; case ParenExprClass: case ArraySubscriptExprClass: case OMPArraySectionExprClass: case MemberExprClass: case ConditionalOperatorClass: case BinaryConditionalOperatorClass: case CompoundLiteralExprClass: case ExtVectorElementExprClass: case DesignatedInitExprClass: case DesignatedInitUpdateExprClass: case ArrayInitLoopExprClass: case ParenListExprClass: case CXXPseudoDestructorExprClass: case CXXStdInitializerListExprClass: case SubstNonTypeTemplateParmExprClass: case MaterializeTemporaryExprClass: case ShuffleVectorExprClass: case ConvertVectorExprClass: case AsTypeExprClass: // These have a side-effect if any subexpression does. break; case UnaryOperatorClass: if (cast(this)->isIncrementDecrementOp()) return true; break; case BinaryOperatorClass: if (cast(this)->isAssignmentOp()) return true; break; case InitListExprClass: // FIXME: The children for an InitListExpr doesn't include the array filler. if (const Expr *E = cast(this)->getArrayFiller()) if (E->HasSideEffects(Ctx, IncludePossibleEffects)) return true; break; case GenericSelectionExprClass: return cast(this)->getResultExpr()-> HasSideEffects(Ctx, IncludePossibleEffects); case ChooseExprClass: return cast(this)->getChosenSubExpr()->HasSideEffects( Ctx, IncludePossibleEffects); case CXXDefaultArgExprClass: return cast(this)->getExpr()->HasSideEffects( Ctx, IncludePossibleEffects); case CXXDefaultInitExprClass: { const FieldDecl *FD = cast(this)->getField(); if (const Expr *E = FD->getInClassInitializer()) return E->HasSideEffects(Ctx, IncludePossibleEffects); // If we've not yet parsed the initializer, assume it has side-effects. return true; } case CXXDynamicCastExprClass: { // A dynamic_cast expression has side-effects if it can throw. const CXXDynamicCastExpr *DCE = cast(this); if (DCE->getTypeAsWritten()->isReferenceType() && DCE->getCastKind() == CK_Dynamic) return true; } // Fall through. case ImplicitCastExprClass: case CStyleCastExprClass: case CXXStaticCastExprClass: case CXXReinterpretCastExprClass: case CXXConstCastExprClass: case CXXFunctionalCastExprClass: { // While volatile reads are side-effecting in both C and C++, we treat them // as having possible (not definite) side-effects. This allows idiomatic // code to behave without warning, such as sizeof(*v) for a volatile- // qualified pointer. if (!IncludePossibleEffects) break; const CastExpr *CE = cast(this); if (CE->getCastKind() == CK_LValueToRValue && CE->getSubExpr()->getType().isVolatileQualified()) return true; break; } case CXXTypeidExprClass: // typeid might throw if its subexpression is potentially-evaluated, so has // side-effects in that case whether or not its subexpression does. return cast(this)->isPotentiallyEvaluated(); case CXXConstructExprClass: case CXXTemporaryObjectExprClass: { const CXXConstructExpr *CE = cast(this); if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects) return true; // A trivial constructor does not add any side-effects of its own. Just look // at its arguments. break; } case CXXInheritedCtorInitExprClass: { const auto *ICIE = cast(this); if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects) return true; break; } case LambdaExprClass: { const LambdaExpr *LE = cast(this); for (LambdaExpr::capture_iterator I = LE->capture_begin(), E = LE->capture_end(); I != E; ++I) if (I->getCaptureKind() == LCK_ByCopy) // FIXME: Only has a side-effect if the variable is volatile or if // the copy would invoke a non-trivial copy constructor. return true; return false; } case PseudoObjectExprClass: { // Only look for side-effects in the semantic form, and look past // OpaqueValueExpr bindings in that form. const PseudoObjectExpr *PO = cast(this); for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(), E = PO->semantics_end(); I != E; ++I) { const Expr *Subexpr = *I; if (const OpaqueValueExpr *OVE = dyn_cast(Subexpr)) Subexpr = OVE->getSourceExpr(); if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects)) return true; } return false; } case ObjCBoxedExprClass: case ObjCArrayLiteralClass: case ObjCDictionaryLiteralClass: case ObjCSelectorExprClass: case ObjCProtocolExprClass: case ObjCIsaExprClass: case ObjCIndirectCopyRestoreExprClass: case ObjCSubscriptRefExprClass: case ObjCBridgedCastExprClass: case ObjCMessageExprClass: case ObjCPropertyRefExprClass: // FIXME: Classify these cases better. if (IncludePossibleEffects) return true; break; } // Recurse to children. for (const Stmt *SubStmt : children()) if (SubStmt && cast(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects)) return true; return false; } namespace { /// \brief Look for a call to a non-trivial function within an expression. class NonTrivialCallFinder : public ConstEvaluatedExprVisitor { typedef ConstEvaluatedExprVisitor Inherited; bool NonTrivial; public: explicit NonTrivialCallFinder(const ASTContext &Context) : Inherited(Context), NonTrivial(false) { } bool hasNonTrivialCall() const { return NonTrivial; } void VisitCallExpr(const CallExpr *E) { if (const CXXMethodDecl *Method = dyn_cast_or_null(E->getCalleeDecl())) { if (Method->isTrivial()) { // Recurse to children of the call. Inherited::VisitStmt(E); return; } } NonTrivial = true; } void VisitCXXConstructExpr(const CXXConstructExpr *E) { if (E->getConstructor()->isTrivial()) { // Recurse to children of the call. Inherited::VisitStmt(E); return; } NonTrivial = true; } void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { if (E->getTemporary()->getDestructor()->isTrivial()) { Inherited::VisitStmt(E); return; } NonTrivial = true; } }; } bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const { NonTrivialCallFinder Finder(Ctx); Finder.Visit(this); return Finder.hasNonTrivialCall(); } /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null /// pointer constant or not, as well as the specific kind of constant detected. /// Null pointer constants can be integer constant expressions with the /// value zero, casts of zero to void*, nullptr (C++0X), or __null /// (a GNU extension). Expr::NullPointerConstantKind Expr::isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const { if (isValueDependent() && (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) { switch (NPC) { case NPC_NeverValueDependent: llvm_unreachable("Unexpected value dependent expression!"); case NPC_ValueDependentIsNull: if (isTypeDependent() || getType()->isIntegralType(Ctx)) return NPCK_ZeroExpression; else return NPCK_NotNull; case NPC_ValueDependentIsNotNull: return NPCK_NotNull; } } // Strip off a cast to void*, if it exists. Except in C++. if (const ExplicitCastExpr *CE = dyn_cast(this)) { if (!Ctx.getLangOpts().CPlusPlus) { // Check that it is a cast to void*. if (const PointerType *PT = CE->getType()->getAs()) { QualType Pointee = PT->getPointeeType(); Qualifiers Q = Pointee.getQualifiers(); // In OpenCL v2.0 generic address space acts as a placeholder // and should be ignored. bool IsASValid = true; if (Ctx.getLangOpts().OpenCLVersion >= 200) { if (Pointee.getAddressSpace() == LangAS::opencl_generic) Q.removeAddressSpace(); else IsASValid = false; } if (IsASValid && !Q.hasQualifiers() && Pointee->isVoidType() && // to void* CE->getSubExpr()->getType()->isIntegerType()) // from int. return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); } } } else if (const ImplicitCastExpr *ICE = dyn_cast(this)) { // Ignore the ImplicitCastExpr type entirely. return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); } else if (const ParenExpr *PE = dyn_cast(this)) { // Accept ((void*)0) as a null pointer constant, as many other // implementations do. return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); } else if (const GenericSelectionExpr *GE = dyn_cast(this)) { if (GE->isResultDependent()) return NPCK_NotNull; return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); } else if (const ChooseExpr *CE = dyn_cast(this)) { if (CE->isConditionDependent()) return NPCK_NotNull; return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC); } else if (const CXXDefaultArgExpr *DefaultArg = dyn_cast(this)) { // See through default argument expressions. return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); } else if (const CXXDefaultInitExpr *DefaultInit = dyn_cast(this)) { // See through default initializer expressions. return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC); } else if (isa(this)) { // The GNU __null extension is always a null pointer constant. return NPCK_GNUNull; } else if (const MaterializeTemporaryExpr *M = dyn_cast(this)) { return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC); } else if (const OpaqueValueExpr *OVE = dyn_cast(this)) { if (const Expr *Source = OVE->getSourceExpr()) return Source->isNullPointerConstant(Ctx, NPC); } // C++11 nullptr_t is always a null pointer constant. if (getType()->isNullPtrType()) return NPCK_CXX11_nullptr; if (const RecordType *UT = getType()->getAsUnionType()) if (!Ctx.getLangOpts().CPlusPlus11 && UT && UT->getDecl()->hasAttr()) if (const CompoundLiteralExpr *CLE = dyn_cast(this)){ const Expr *InitExpr = CLE->getInitializer(); if (const InitListExpr *ILE = dyn_cast(InitExpr)) return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); } // This expression must be an integer type. if (!getType()->isIntegerType() || (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType())) return NPCK_NotNull; if (Ctx.getLangOpts().CPlusPlus11) { // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with // value zero or a prvalue of type std::nullptr_t. // Microsoft mode permits C++98 rules reflecting MSVC behavior. const IntegerLiteral *Lit = dyn_cast(this); if (Lit && !Lit->getValue()) return NPCK_ZeroLiteral; else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx)) return NPCK_NotNull; } else { // If we have an integer constant expression, we need to *evaluate* it and // test for the value 0. if (!isIntegerConstantExpr(Ctx)) return NPCK_NotNull; } if (EvaluateKnownConstInt(Ctx) != 0) return NPCK_NotNull; if (isa(this)) return NPCK_ZeroLiteral; return NPCK_ZeroExpression; } /// \brief If this expression is an l-value for an Objective C /// property, find the underlying property reference expression. const ObjCPropertyRefExpr *Expr::getObjCProperty() const { const Expr *E = this; while (true) { assert((E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && "expression is not a property reference"); E = E->IgnoreParenCasts(); if (const BinaryOperator *BO = dyn_cast(E)) { if (BO->getOpcode() == BO_Comma) { E = BO->getRHS(); continue; } } break; } return cast(E); } bool Expr::isObjCSelfExpr() const { const Expr *E = IgnoreParenImpCasts(); const DeclRefExpr *DRE = dyn_cast(E); if (!DRE) return false; const ImplicitParamDecl *Param = dyn_cast(DRE->getDecl()); if (!Param) return false; const ObjCMethodDecl *M = dyn_cast(Param->getDeclContext()); if (!M) return false; return M->getSelfDecl() == Param; } FieldDecl *Expr::getSourceBitField() { Expr *E = this->IgnoreParens(); while (ImplicitCastExpr *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_LValueToRValue || (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp)) E = ICE->getSubExpr()->IgnoreParens(); else break; } if (MemberExpr *MemRef = dyn_cast(E)) if (FieldDecl *Field = dyn_cast(MemRef->getMemberDecl())) if (Field->isBitField()) return Field; if (ObjCIvarRefExpr *IvarRef = dyn_cast(E)) if (FieldDecl *Ivar = dyn_cast(IvarRef->getDecl())) if (Ivar->isBitField()) return Ivar; if (DeclRefExpr *DeclRef = dyn_cast(E)) { if (FieldDecl *Field = dyn_cast(DeclRef->getDecl())) if (Field->isBitField()) return Field; if (BindingDecl *BD = dyn_cast(DeclRef->getDecl())) if (Expr *E = BD->getBinding()) return E->getSourceBitField(); } if (BinaryOperator *BinOp = dyn_cast(E)) { if (BinOp->isAssignmentOp() && BinOp->getLHS()) return BinOp->getLHS()->getSourceBitField(); if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS()) return BinOp->getRHS()->getSourceBitField(); } if (UnaryOperator *UnOp = dyn_cast(E)) if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp()) return UnOp->getSubExpr()->getSourceBitField(); return nullptr; } bool Expr::refersToVectorElement() const { // FIXME: Why do we not just look at the ObjectKind here? const Expr *E = this->IgnoreParens(); while (const ImplicitCastExpr *ICE = dyn_cast(E)) { if (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp) E = ICE->getSubExpr()->IgnoreParens(); else break; } if (const ArraySubscriptExpr *ASE = dyn_cast(E)) return ASE->getBase()->getType()->isVectorType(); if (isa(E)) return true; if (auto *DRE = dyn_cast(E)) if (auto *BD = dyn_cast(DRE->getDecl())) if (auto *E = BD->getBinding()) return E->refersToVectorElement(); return false; } bool Expr::refersToGlobalRegisterVar() const { const Expr *E = this->IgnoreParenImpCasts(); if (const DeclRefExpr *DRE = dyn_cast(E)) if (const auto *VD = dyn_cast(DRE->getDecl())) if (VD->getStorageClass() == SC_Register && VD->hasAttr() && !VD->isLocalVarDecl()) return true; return false; } /// isArrow - Return true if the base expression is a pointer to vector, /// return false if the base expression is a vector. bool ExtVectorElementExpr::isArrow() const { return getBase()->getType()->isPointerType(); } unsigned ExtVectorElementExpr::getNumElements() const { if (const VectorType *VT = getType()->getAs()) return VT->getNumElements(); return 1; } /// containsDuplicateElements - Return true if any element access is repeated. bool ExtVectorElementExpr::containsDuplicateElements() const { // FIXME: Refactor this code to an accessor on the AST node which returns the // "type" of component access, and share with code below and in Sema. StringRef Comp = Accessor->getName(); // Halving swizzles do not contain duplicate elements. if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd") return false; // Advance past s-char prefix on hex swizzles. if (Comp[0] == 's' || Comp[0] == 'S') Comp = Comp.substr(1); for (unsigned i = 0, e = Comp.size(); i != e; ++i) if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos) return true; return false; } /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray. void ExtVectorElementExpr::getEncodedElementAccess( SmallVectorImpl &Elts) const { StringRef Comp = Accessor->getName(); bool isNumericAccessor = false; if (Comp[0] == 's' || Comp[0] == 'S') { Comp = Comp.substr(1); isNumericAccessor = true; } bool isHi = Comp == "hi"; bool isLo = Comp == "lo"; bool isEven = Comp == "even"; bool isOdd = Comp == "odd"; for (unsigned i = 0, e = getNumElements(); i != e; ++i) { uint64_t Index; if (isHi) Index = e + i; else if (isLo) Index = i; else if (isEven) Index = 2 * i; else if (isOdd) Index = 2 * i + 1; else Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor); Elts.push_back(Index); } } ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef args, QualType Type, SourceLocation BLoc, SourceLocation RP) : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary, Type->isDependentType(), Type->isDependentType(), Type->isInstantiationDependentType(), Type->containsUnexpandedParameterPack()), BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) { SubExprs = new (C) Stmt*[args.size()]; for (unsigned i = 0; i != args.size(); i++) { if (args[i]->isTypeDependent()) ExprBits.TypeDependent = true; if (args[i]->isValueDependent()) ExprBits.ValueDependent = true; if (args[i]->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (args[i]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; SubExprs[i] = args[i]; } } void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef Exprs) { if (SubExprs) C.Deallocate(SubExprs); this->NumExprs = Exprs.size(); SubExprs = new (C) Stmt*[NumExprs]; memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size()); } GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex) : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(), AssocExprs[ResultIndex]->getValueKind(), AssocExprs[ResultIndex]->getObjectKind(), AssocExprs[ResultIndex]->isTypeDependent(), AssocExprs[ResultIndex]->isValueDependent(), AssocExprs[ResultIndex]->isInstantiationDependent(), ContainsUnexpandedParameterPack), AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]), SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]), NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { SubExprs[CONTROLLING] = ControllingExpr; assert(AssocTypes.size() == AssocExprs.size()); std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes); std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR); } GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue, OK_Ordinary, /*isTypeDependent=*/true, /*isValueDependent=*/true, /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack), AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]), SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]), NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) { SubExprs[CONTROLLING] = ControllingExpr; assert(AssocTypes.size() == AssocExprs.size()); std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes); std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR); } //===----------------------------------------------------------------------===// // DesignatedInitExpr //===----------------------------------------------------------------------===// IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const { assert(Kind == FieldDesignator && "Only valid on a field designator"); if (Field.NameOrField & 0x01) return reinterpret_cast(Field.NameOrField&~0x01); else return getField()->getIdentifier(); } DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty, llvm::ArrayRef Designators, SourceLocation EqualOrColonLoc, bool GNUSyntax, ArrayRef IndexExprs, Expr *Init) : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(), Init->getObjectKind(), Init->isTypeDependent(), Init->isValueDependent(), Init->isInstantiationDependent(), Init->containsUnexpandedParameterPack()), EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax), NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) { this->Designators = new (C) Designator[NumDesignators]; // Record the initializer itself. child_iterator Child = child_begin(); *Child++ = Init; // Copy the designators and their subexpressions, computing // value-dependence along the way. unsigned IndexIdx = 0; for (unsigned I = 0; I != NumDesignators; ++I) { this->Designators[I] = Designators[I]; if (this->Designators[I].isArrayDesignator()) { // Compute type- and value-dependence. Expr *Index = IndexExprs[IndexIdx]; if (Index->isTypeDependent() || Index->isValueDependent()) ExprBits.TypeDependent = ExprBits.ValueDependent = true; if (Index->isInstantiationDependent()) ExprBits.InstantiationDependent = true; // Propagate unexpanded parameter packs. if (Index->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; // Copy the index expressions into permanent storage. *Child++ = IndexExprs[IndexIdx++]; } else if (this->Designators[I].isArrayRangeDesignator()) { // Compute type- and value-dependence. Expr *Start = IndexExprs[IndexIdx]; Expr *End = IndexExprs[IndexIdx + 1]; if (Start->isTypeDependent() || Start->isValueDependent() || End->isTypeDependent() || End->isValueDependent()) { ExprBits.TypeDependent = ExprBits.ValueDependent = true; ExprBits.InstantiationDependent = true; } else if (Start->isInstantiationDependent() || End->isInstantiationDependent()) { ExprBits.InstantiationDependent = true; } // Propagate unexpanded parameter packs. if (Start->containsUnexpandedParameterPack() || End->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; // Copy the start/end expressions into permanent storage. *Child++ = IndexExprs[IndexIdx++]; *Child++ = IndexExprs[IndexIdx++]; } } assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions"); } DesignatedInitExpr * DesignatedInitExpr::Create(const ASTContext &C, llvm::ArrayRef Designators, ArrayRef IndexExprs, SourceLocation ColonOrEqualLoc, bool UsesColonSyntax, Expr *Init) { void *Mem = C.Allocate(totalSizeToAlloc(IndexExprs.size() + 1), alignof(DesignatedInitExpr)); return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators, ColonOrEqualLoc, UsesColonSyntax, IndexExprs, Init); } DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C, unsigned NumIndexExprs) { void *Mem = C.Allocate(totalSizeToAlloc(NumIndexExprs + 1), alignof(DesignatedInitExpr)); return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); } void DesignatedInitExpr::setDesignators(const ASTContext &C, const Designator *Desigs, unsigned NumDesigs) { Designators = new (C) Designator[NumDesigs]; NumDesignators = NumDesigs; for (unsigned I = 0; I != NumDesigs; ++I) Designators[I] = Desigs[I]; } SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const { DesignatedInitExpr *DIE = const_cast(this); if (size() == 1) return DIE->getDesignator(0)->getSourceRange(); return SourceRange(DIE->getDesignator(0)->getLocStart(), DIE->getDesignator(size()-1)->getLocEnd()); } SourceLocation DesignatedInitExpr::getLocStart() const { SourceLocation StartLoc; auto *DIE = const_cast(this); Designator &First = *DIE->getDesignator(0); if (First.isFieldDesignator()) { if (GNUSyntax) StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc); else StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc); } else StartLoc = SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc); return StartLoc; } SourceLocation DesignatedInitExpr::getLocEnd() const { return getInit()->getLocEnd(); } Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const { assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); return getSubExpr(D.ArrayOrRange.Index + 1); } Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const { assert(D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"); return getSubExpr(D.ArrayOrRange.Index + 1); } Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const { assert(D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"); return getSubExpr(D.ArrayOrRange.Index + 2); } /// \brief Replaces the designator at index @p Idx with the series /// of designators in [First, Last). void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last) { unsigned NumNewDesignators = Last - First; if (NumNewDesignators == 0) { std::copy_backward(Designators + Idx + 1, Designators + NumDesignators, Designators + Idx); --NumNewDesignators; return; } else if (NumNewDesignators == 1) { Designators[Idx] = *First; return; } Designator *NewDesignators = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; std::copy(Designators, Designators + Idx, NewDesignators); std::copy(First, Last, NewDesignators + Idx); std::copy(Designators + Idx + 1, Designators + NumDesignators, NewDesignators + Idx + NumNewDesignators); Designators = NewDesignators; NumDesignators = NumDesignators - 1 + NumNewDesignators; } DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc) : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue, OK_Ordinary, false, false, false, false) { BaseAndUpdaterExprs[0] = baseExpr; InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc); ILE->setType(baseExpr->getType()); BaseAndUpdaterExprs[1] = ILE; } SourceLocation DesignatedInitUpdateExpr::getLocStart() const { return getBase()->getLocStart(); } SourceLocation DesignatedInitUpdateExpr::getLocEnd() const { return getBase()->getLocEnd(); } ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc, ArrayRef exprs, SourceLocation rparenloc) : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false, false, false), NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) { Exprs = new (C) Stmt*[exprs.size()]; for (unsigned i = 0; i != exprs.size(); ++i) { if (exprs[i]->isTypeDependent()) ExprBits.TypeDependent = true; if (exprs[i]->isValueDependent()) ExprBits.ValueDependent = true; if (exprs[i]->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (exprs[i]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; Exprs[i] = exprs[i]; } } const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { if (const ExprWithCleanups *ewc = dyn_cast(e)) e = ewc->getSubExpr(); if (const MaterializeTemporaryExpr *m = dyn_cast(e)) e = m->GetTemporaryExpr(); e = cast(e)->getArg(0); while (const ImplicitCastExpr *ice = dyn_cast(e)) e = ice->getSubExpr(); return cast(e); } PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context, EmptyShell sh, unsigned numSemanticExprs) { void *buffer = Context.Allocate(totalSizeToAlloc(1 + numSemanticExprs), alignof(PseudoObjectExpr)); return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); } PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) : Expr(PseudoObjectExprClass, shell) { PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; } PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax, ArrayRef semantics, unsigned resultIndex) { assert(syntax && "no syntactic expression!"); assert(semantics.size() && "no semantic expressions!"); QualType type; ExprValueKind VK; if (resultIndex == NoResult) { type = C.VoidTy; VK = VK_RValue; } else { assert(resultIndex < semantics.size()); type = semantics[resultIndex]->getType(); VK = semantics[resultIndex]->getValueKind(); assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary); } void *buffer = C.Allocate(totalSizeToAlloc(semantics.size() + 1), alignof(PseudoObjectExpr)); return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, resultIndex); } PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, Expr *syntax, ArrayRef semantics, unsigned resultIndex) : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary, /*filled in at end of ctor*/ false, false, false, false) { PseudoObjectExprBits.NumSubExprs = semantics.size() + 1; PseudoObjectExprBits.ResultIndex = resultIndex + 1; for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { Expr *E = (i == 0 ? syntax : semantics[i-1]); getSubExprsBuffer()[i] = E; if (E->isTypeDependent()) ExprBits.TypeDependent = true; if (E->isValueDependent()) ExprBits.ValueDependent = true; if (E->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (E->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; if (isa(E)) assert(cast(E)->getSourceExpr() != nullptr && "opaque-value semantic expressions for pseudo-object " "operations must have sources"); } } //===----------------------------------------------------------------------===// // Child Iterators for iterating over subexpressions/substatements //===----------------------------------------------------------------------===// // UnaryExprOrTypeTraitExpr Stmt::child_range UnaryExprOrTypeTraitExpr::children() { const_child_range CCR = const_cast(this)->children(); return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end())); } Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const { // If this is of a type and the type is a VLA type (and not a typedef), the // size expression of the VLA needs to be treated as an executable expression. // Why isn't this weirdness documented better in StmtIterator? if (isArgumentType()) { if (const VariableArrayType *T = dyn_cast(getArgumentType().getTypePtr())) return const_child_range(const_child_iterator(T), const_child_iterator()); return const_child_range(const_child_iterator(), const_child_iterator()); } return const_child_range(&Argument.Ex, &Argument.Ex + 1); } AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef args, QualType t, AtomicOp op, SourceLocation RP) : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary, false, false, false, false), NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) { assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions"); for (unsigned i = 0; i != args.size(); i++) { if (args[i]->isTypeDependent()) ExprBits.TypeDependent = true; if (args[i]->isValueDependent()) ExprBits.ValueDependent = true; if (args[i]->isInstantiationDependent()) ExprBits.InstantiationDependent = true; if (args[i]->containsUnexpandedParameterPack()) ExprBits.ContainsUnexpandedParameterPack = true; SubExprs[i] = args[i]; } } unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) { switch (Op) { case AO__c11_atomic_init: case AO__c11_atomic_load: case AO__atomic_load_n: return 2; case AO__c11_atomic_store: case AO__c11_atomic_exchange: case AO__atomic_load: case AO__atomic_store: case AO__atomic_store_n: case AO__atomic_exchange_n: case AO__c11_atomic_fetch_add: case AO__c11_atomic_fetch_sub: case AO__c11_atomic_fetch_and: case AO__c11_atomic_fetch_or: case AO__c11_atomic_fetch_xor: case AO__atomic_fetch_add: case AO__atomic_fetch_sub: case AO__atomic_fetch_and: case AO__atomic_fetch_or: case AO__atomic_fetch_xor: case AO__atomic_fetch_nand: case AO__atomic_add_fetch: case AO__atomic_sub_fetch: case AO__atomic_and_fetch: case AO__atomic_or_fetch: case AO__atomic_xor_fetch: case AO__atomic_nand_fetch: return 3; case AO__atomic_exchange: return 4; case AO__c11_atomic_compare_exchange_strong: case AO__c11_atomic_compare_exchange_weak: return 5; case AO__atomic_compare_exchange: case AO__atomic_compare_exchange_n: return 6; } llvm_unreachable("unknown atomic op"); } QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) { unsigned ArraySectionCount = 0; while (auto *OASE = dyn_cast(Base->IgnoreParens())) { Base = OASE->getBase(); ++ArraySectionCount; } while (auto *ASE = dyn_cast(Base->IgnoreParenImpCasts())) { Base = ASE->getBase(); ++ArraySectionCount; } Base = Base->IgnoreParenImpCasts(); auto OriginalTy = Base->getType(); if (auto *DRE = dyn_cast(Base)) if (auto *PVD = dyn_cast(DRE->getDecl())) OriginalTy = PVD->getOriginalType().getNonReferenceType(); for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) { if (OriginalTy->isAnyPointerType()) OriginalTy = OriginalTy->getPointeeType(); else { assert (OriginalTy->isArrayType()); OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType(); } } return OriginalTy; } Index: head/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp =================================================================== --- head/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp (revision 327929) +++ head/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp (revision 327930) @@ -1,8556 +1,8588 @@ //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for initializers. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/TargetInfo.h" #include "clang/Sema/Designator.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace clang; //===----------------------------------------------------------------------===// // Sema Initialization Checking //===----------------------------------------------------------------------===// /// \brief Check whether T is compatible with a wide character type (wchar_t, /// char16_t or char32_t). static bool IsWideCharCompatible(QualType T, ASTContext &Context) { if (Context.typesAreCompatible(Context.getWideCharType(), T)) return true; if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { return Context.typesAreCompatible(Context.Char16Ty, T) || Context.typesAreCompatible(Context.Char32Ty, T); } return false; } enum StringInitFailureKind { SIF_None, SIF_NarrowStringIntoWideChar, SIF_WideStringIntoChar, SIF_IncompatWideStringIntoWideChar, SIF_Other }; /// \brief Check whether the array of type AT can be initialized by the Init /// expression by means of string initialization. Returns SIF_None if so, /// otherwise returns a StringInitFailureKind that describes why the /// initialization would not work. static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, ASTContext &Context) { if (!isa(AT) && !isa(AT)) return SIF_Other; // See if this is a string literal or @encode. Init = Init->IgnoreParens(); // Handle @encode, which is a narrow string. if (isa(Init) && AT->getElementType()->isCharType()) return SIF_None; // Otherwise we can only handle string literals. StringLiteral *SL = dyn_cast(Init); if (!SL) return SIF_Other; const QualType ElemTy = Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); switch (SL->getKind()) { case StringLiteral::Ascii: case StringLiteral::UTF8: // char array can be initialized with a narrow string. // Only allow char x[] = "foo"; not char x[] = L"foo"; if (ElemTy->isCharType()) return SIF_None; if (IsWideCharCompatible(ElemTy, Context)) return SIF_NarrowStringIntoWideChar; return SIF_Other; // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: // "An array with element type compatible with a qualified or unqualified // version of wchar_t, char16_t, or char32_t may be initialized by a wide // string literal with the corresponding encoding prefix (L, u, or U, // respectively), optionally enclosed in braces. case StringLiteral::UTF16: if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) return SIF_None; if (ElemTy->isCharType()) return SIF_WideStringIntoChar; if (IsWideCharCompatible(ElemTy, Context)) return SIF_IncompatWideStringIntoWideChar; return SIF_Other; case StringLiteral::UTF32: if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) return SIF_None; if (ElemTy->isCharType()) return SIF_WideStringIntoChar; if (IsWideCharCompatible(ElemTy, Context)) return SIF_IncompatWideStringIntoWideChar; return SIF_Other; case StringLiteral::Wide: if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) return SIF_None; if (ElemTy->isCharType()) return SIF_WideStringIntoChar; if (IsWideCharCompatible(ElemTy, Context)) return SIF_IncompatWideStringIntoWideChar; return SIF_Other; } llvm_unreachable("missed a StringLiteral kind?"); } static StringInitFailureKind IsStringInit(Expr *init, QualType declType, ASTContext &Context) { const ArrayType *arrayType = Context.getAsArrayType(declType); if (!arrayType) return SIF_Other; return IsStringInit(init, arrayType, Context); } /// Update the type of a string literal, including any surrounding parentheses, /// to match the type of the object which it is initializing. static void updateStringLiteralType(Expr *E, QualType Ty) { while (true) { E->setType(Ty); if (isa(E) || isa(E)) break; else if (ParenExpr *PE = dyn_cast(E)) E = PE->getSubExpr(); else if (UnaryOperator *UO = dyn_cast(E)) E = UO->getSubExpr(); else if (GenericSelectionExpr *GSE = dyn_cast(E)) E = GSE->getResultExpr(); else llvm_unreachable("unexpected expr in string literal init"); } } static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S) { // Get the length of the string as parsed. auto *ConstantArrayTy = cast(Str->getType()->getAsArrayTypeUnsafe()); uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); if (const IncompleteArrayType *IAT = dyn_cast(AT)) { // C99 6.7.8p14. We have an array of character type with unknown size // being initialized to a string literal. llvm::APInt ConstVal(32, StrLength); // Return a new array type (C99 6.7.8p22). DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal, ArrayType::Normal, 0); updateStringLiteralType(Str, DeclT); return; } const ConstantArrayType *CAT = cast(AT); // We have an array of character type with known size. However, // the size may be smaller or larger than the string we are initializing. // FIXME: Avoid truncation for 64-bit length strings. if (S.getLangOpts().CPlusPlus) { if (StringLiteral *SL = dyn_cast(Str->IgnoreParens())) { // For Pascal strings it's OK to strip off the terminating null character, // so the example below is valid: // // unsigned char a[2] = "\pa"; if (SL->isPascal()) StrLength--; } // [dcl.init.string]p2 if (StrLength > CAT->getSize().getZExtValue()) S.Diag(Str->getLocStart(), diag::err_initializer_string_for_char_array_too_long) << Str->getSourceRange(); } else { // C99 6.7.8p14. if (StrLength-1 > CAT->getSize().getZExtValue()) S.Diag(Str->getLocStart(), diag::ext_initializer_string_for_char_array_too_long) << Str->getSourceRange(); } // Set the type to the actual size that we are initializing. If we have // something like: // char x[1] = "foo"; // then this will set the string literal's type to char[1]. updateStringLiteralType(Str, DeclT); } //===----------------------------------------------------------------------===// // Semantic checking for initializer lists. //===----------------------------------------------------------------------===// namespace { /// @brief Semantic checking for initializer lists. /// /// The InitListChecker class contains a set of routines that each /// handle the initialization of a certain kind of entity, e.g., /// arrays, vectors, struct/union types, scalars, etc. The /// InitListChecker itself performs a recursive walk of the subobject /// structure of the type to be initialized, while stepping through /// the initializer list one element at a time. The IList and Index /// parameters to each of the Check* routines contain the active /// (syntactic) initializer list and the index into that initializer /// list that represents the current initializer. Each routine is /// responsible for moving that Index forward as it consumes elements. /// /// Each Check* routine also has a StructuredList/StructuredIndex /// arguments, which contains the current "structured" (semantic) /// initializer list and the index into that initializer list where we /// are copying initializers as we map them over to the semantic /// list. Once we have completed our recursive walk of the subobject /// structure, we will have constructed a full semantic initializer /// list. /// /// C99 designators cause changes in the initializer list traversal, /// because they make the initialization "jump" into a specific /// subobject and then continue the initialization from that /// point. CheckDesignatedInitializer() recursively steps into the /// designated subobject and manages backing out the recursion to /// initialize the subobjects after the one designated. class InitListChecker { Sema &SemaRef; bool hadError; bool VerifyOnly; // no diagnostics, no structure building bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. llvm::DenseMap SyntacticToSemantic; InitListExpr *FullyStructuredList; void CheckImplicitInitList(const InitializedEntity &Entity, InitListExpr *ParentIList, QualType T, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckExplicitInitList(const InitializedEntity &Entity, InitListExpr *IList, QualType &T, InitListExpr *StructuredList, bool TopLevelObject = false); void CheckListElementTypes(const InitializedEntity &Entity, InitListExpr *IList, QualType &DeclType, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject = false); void CheckSubElementType(const InitializedEntity &Entity, InitListExpr *IList, QualType ElemType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckComplexType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckScalarType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckReferenceType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckVectorType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); void CheckStructUnionTypes(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject = false); void CheckArrayType(const InitializedEntity &Entity, InitListExpr *IList, QualType &DeclType, llvm::APSInt elementIndex, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex); bool CheckDesignatedInitializer(const InitializedEntity &Entity, InitListExpr *IList, DesignatedInitExpr *DIE, unsigned DesigIdx, QualType &CurrentObjectType, RecordDecl::field_iterator *NextField, llvm::APSInt *NextElementIndex, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool FinishSubobjectInit, bool TopLevelObject); InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, QualType CurrentObjectType, InitListExpr *StructuredList, unsigned StructuredIndex, SourceRange InitRange, bool IsFullyOverwritten = false); void UpdateStructuredListElement(InitListExpr *StructuredList, unsigned &StructuredIndex, Expr *expr); int numArrayElements(QualType DeclType); int numStructUnionElements(QualType DeclType); static ExprResult PerformEmptyInit(Sema &SemaRef, SourceLocation Loc, const InitializedEntity &Entity, bool VerifyOnly, bool TreatUnavailableAsInvalid); // Explanation on the "FillWithNoInit" mode: // // Assume we have the following definitions (Case#1): // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; // // l.lp.x[1][0..1] should not be filled with implicit initializers because the // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". // // But if we have (Case#2): // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; // // l.lp.x[1][0..1] are implicitly initialized and do not use values from the // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". // // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" // in the InitListExpr, the "holes" in Case#1 are filled not with empty // initializers but with special "NoInitExpr" place holders, which tells the // CodeGen not to generate any initializers for these parts. void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, const InitializedEntity &ParentEntity, InitListExpr *ILE, bool &RequiresSecondPass, bool FillWithNoInit); void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, const InitializedEntity &ParentEntity, InitListExpr *ILE, bool &RequiresSecondPass, bool FillWithNoInit = false); void FillInEmptyInitializations(const InitializedEntity &Entity, InitListExpr *ILE, bool &RequiresSecondPass, bool FillWithNoInit = false); bool CheckFlexibleArrayInit(const InitializedEntity &Entity, Expr *InitExpr, FieldDecl *Field, bool TopLevelObject); void CheckEmptyInitializable(const InitializedEntity &Entity, SourceLocation Loc); public: InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid); bool HadError() { return hadError; } // @brief Retrieves the fully-structured initializer list used for // semantic analysis and code generation. InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } }; } // end anonymous namespace ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef, SourceLocation Loc, const InitializedEntity &Entity, bool VerifyOnly, bool TreatUnavailableAsInvalid) { InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, true); MultiExprArg SubInit; Expr *InitExpr; InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); // C++ [dcl.init.aggr]p7: // If there are fewer initializer-clauses in the list than there are // members in the aggregate, then each member not explicitly initialized // ... bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); if (EmptyInitList) { // C++1y / DR1070: // shall be initialized [...] from an empty initializer list. // // We apply the resolution of this DR to C++11 but not C++98, since C++98 // does not have useful semantics for initialization from an init list. // We treat this as copy-initialization, because aggregate initialization // always performs copy-initialization on its elements. // // Only do this if we're initializing a class type, to avoid filling in // the initializer list where possible. InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) InitListExpr(SemaRef.Context, Loc, None, Loc); InitExpr->setType(SemaRef.Context.VoidTy); SubInit = InitExpr; Kind = InitializationKind::CreateCopy(Loc, Loc); } else { // C++03: // shall be value-initialized. } InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); // libstdc++4.6 marks the vector default constructor as explicit in // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. // stlport does so too. Look for std::__debug for libstdc++, and for // std:: for stlport. This is effectively a compiler-side implementation of // LWG2193. if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == InitializationSequence::FK_ExplicitConstructor) { OverloadCandidateSet::iterator Best; OverloadingResult O = InitSeq.getFailedCandidateSet() .BestViableFunction(SemaRef, Kind.getLocation(), Best); (void)O; assert(O == OR_Success && "Inconsistent overload resolution"); CXXConstructorDecl *CtorDecl = cast(Best->Function); CXXRecordDecl *R = CtorDecl->getParent(); if (CtorDecl->getMinRequiredArguments() == 0 && CtorDecl->isExplicit() && R->getDeclName() && SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { bool IsInStd = false; for (NamespaceDecl *ND = dyn_cast(R->getDeclContext()); ND && !IsInStd; ND = dyn_cast(ND->getParent())) { if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) IsInStd = true; } if (IsInStd && llvm::StringSwitch(R->getName()) .Cases("basic_string", "deque", "forward_list", true) .Cases("list", "map", "multimap", "multiset", true) .Cases("priority_queue", "queue", "set", "stack", true) .Cases("unordered_map", "unordered_set", "vector", true) .Default(false)) { InitSeq.InitializeFrom( SemaRef, Entity, InitializationKind::CreateValue(Loc, Loc, Loc, true), MultiExprArg(), /*TopLevelOfInitList=*/false, TreatUnavailableAsInvalid); // Emit a warning for this. System header warnings aren't shown // by default, but people working on system headers should see it. if (!VerifyOnly) { SemaRef.Diag(CtorDecl->getLocation(), diag::warn_invalid_initializer_from_system_header); if (Entity.getKind() == InitializedEntity::EK_Member) SemaRef.Diag(Entity.getDecl()->getLocation(), diag::note_used_in_initialization_here); else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) SemaRef.Diag(Loc, diag::note_used_in_initialization_here); } } } } if (!InitSeq) { if (!VerifyOnly) { InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); if (Entity.getKind() == InitializedEntity::EK_Member) SemaRef.Diag(Entity.getDecl()->getLocation(), diag::note_in_omitted_aggregate_initializer) << /*field*/1 << Entity.getDecl(); else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { bool IsTrailingArrayNewMember = Entity.getParent() && Entity.getParent()->isVariableLengthArrayNew(); SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) << (IsTrailingArrayNewMember ? 2 : /*array element*/0) << Entity.getElementIndex(); } } return ExprError(); } return VerifyOnly ? ExprResult(static_cast(nullptr)) : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); } void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, SourceLocation Loc) { assert(VerifyOnly && "CheckEmptyInitializable is only inteded for verification mode."); if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true, TreatUnavailableAsInvalid).isInvalid()) hadError = true; } void InitListChecker::FillInEmptyInitForBase( unsigned Init, const CXXBaseSpecifier &Base, const InitializedEntity &ParentEntity, InitListExpr *ILE, bool &RequiresSecondPass, bool FillWithNoInit) { assert(Init < ILE->getNumInits() && "should have been expanded"); InitializedEntity BaseEntity = InitializedEntity::InitializeBase( SemaRef.Context, &Base, false, &ParentEntity); if (!ILE->getInit(Init)) { ExprResult BaseInit = FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType()) : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity, /*VerifyOnly*/ false, TreatUnavailableAsInvalid); if (BaseInit.isInvalid()) { hadError = true; return; } ILE->setInit(Init, BaseInit.getAs()); } else if (InitListExpr *InnerILE = dyn_cast(ILE->getInit(Init))) { FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, FillWithNoInit); } else if (DesignatedInitUpdateExpr *InnerDIUE = dyn_cast(ILE->getInit(Init))) { FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), RequiresSecondPass, /*FillWithNoInit =*/true); } } void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, const InitializedEntity &ParentEntity, InitListExpr *ILE, bool &RequiresSecondPass, bool FillWithNoInit) { SourceLocation Loc = ILE->getLocEnd(); unsigned NumInits = ILE->getNumInits(); InitializedEntity MemberEntity = InitializedEntity::InitializeMember(Field, &ParentEntity); if (const RecordType *RType = ILE->getType()->getAs()) if (!RType->getDecl()->isUnion()) assert(Init < NumInits && "This ILE should have been expanded"); if (Init >= NumInits || !ILE->getInit(Init)) { if (FillWithNoInit) { Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); if (Init < NumInits) ILE->setInit(Init, Filler); else ILE->updateInit(SemaRef.Context, Init, Filler); return; } // C++1y [dcl.init.aggr]p7: // If there are fewer initializer-clauses in the list than there are // members in the aggregate, then each member not explicitly initialized // shall be initialized from its brace-or-equal-initializer [...] if (Field->hasInClassInitializer()) { ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); if (DIE.isInvalid()) { hadError = true; return; } if (Init < NumInits) ILE->setInit(Init, DIE.get()); else { ILE->updateInit(SemaRef.Context, Init, DIE.get()); RequiresSecondPass = true; } return; } if (Field->getType()->isReferenceType()) { // C++ [dcl.init.aggr]p9: // If an incomplete or empty initializer-list leaves a // member of reference type uninitialized, the program is // ill-formed. SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) << Field->getType() << ILE->getSyntacticForm()->getSourceRange(); SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member); hadError = true; return; } ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity, /*VerifyOnly*/false, TreatUnavailableAsInvalid); if (MemberInit.isInvalid()) { hadError = true; return; } if (hadError) { // Do nothing } else if (Init < NumInits) { ILE->setInit(Init, MemberInit.getAs()); } else if (!isa(MemberInit.get())) { // Empty initialization requires a constructor call, so // extend the initializer list to include the constructor // call and make a note that we'll need to take another pass // through the initializer list. ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs()); RequiresSecondPass = true; } } else if (InitListExpr *InnerILE = dyn_cast(ILE->getInit(Init))) FillInEmptyInitializations(MemberEntity, InnerILE, RequiresSecondPass, FillWithNoInit); else if (DesignatedInitUpdateExpr *InnerDIUE = dyn_cast(ILE->getInit(Init))) FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), RequiresSecondPass, /*FillWithNoInit =*/ true); } /// Recursively replaces NULL values within the given initializer list /// with expressions that perform value-initialization of the /// appropriate type. void InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, InitListExpr *ILE, bool &RequiresSecondPass, bool FillWithNoInit) { assert((ILE->getType() != SemaRef.Context.VoidTy) && "Should not have void type"); // A transparent ILE is not performing aggregate initialization and should // not be filled in. if (ILE->isTransparent()) return; if (const RecordType *RType = ILE->getType()->getAs()) { const RecordDecl *RDecl = RType->getDecl(); if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE, RequiresSecondPass, FillWithNoInit); else if (RDecl->isUnion() && isa(RDecl) && cast(RDecl)->hasInClassInitializer()) { for (auto *Field : RDecl->fields()) { if (Field->hasInClassInitializer()) { FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, FillWithNoInit); break; } } } else { // The fields beyond ILE->getNumInits() are default initialized, so in // order to leave them uninitialized, the ILE is expanded and the extra // fields are then filled with NoInitExpr. unsigned NumElems = numStructUnionElements(ILE->getType()); if (RDecl->hasFlexibleArrayMember()) ++NumElems; if (ILE->getNumInits() < NumElems) ILE->resizeInits(SemaRef.Context, NumElems); unsigned Init = 0; if (auto *CXXRD = dyn_cast(RDecl)) { for (auto &Base : CXXRD->bases()) { if (hadError) return; FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, FillWithNoInit); ++Init; } } for (auto *Field : RDecl->fields()) { if (Field->isUnnamedBitfield()) continue; if (hadError) return; FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, FillWithNoInit); if (hadError) return; ++Init; // Only look at the first initialization of a union. if (RDecl->isUnion()) break; } } return; } QualType ElementType; InitializedEntity ElementEntity = Entity; unsigned NumInits = ILE->getNumInits(); unsigned NumElements = NumInits; if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { ElementType = AType->getElementType(); if (const auto *CAType = dyn_cast(AType)) NumElements = CAType->getSize().getZExtValue(); // For an array new with an unknown bound, ask for one additional element // in order to populate the array filler. if (Entity.isVariableLengthArrayNew()) ++NumElements; ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); } else if (const VectorType *VType = ILE->getType()->getAs()) { ElementType = VType->getElementType(); NumElements = VType->getNumElements(); ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); } else ElementType = ILE->getType(); for (unsigned Init = 0; Init != NumElements; ++Init) { if (hadError) return; if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || ElementEntity.getKind() == InitializedEntity::EK_VectorElement) ElementEntity.setElementIndex(Init); Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) ILE->setInit(Init, ILE->getArrayFiller()); else if (!InitExpr && !ILE->hasArrayFiller()) { Expr *Filler = nullptr; if (FillWithNoInit) Filler = new (SemaRef.Context) NoInitExpr(ElementType); else { ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(), ElementEntity, /*VerifyOnly*/false, TreatUnavailableAsInvalid); if (ElementInit.isInvalid()) { hadError = true; return; } Filler = ElementInit.getAs(); } if (hadError) { // Do nothing } else if (Init < NumInits) { // For arrays, just set the expression used for value-initialization // of the "holes" in the array. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) ILE->setArrayFiller(Filler); else ILE->setInit(Init, Filler); } else { // For arrays, just set the expression used for value-initialization // of the rest of elements and exit. if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { ILE->setArrayFiller(Filler); return; } if (!isa(Filler) && !isa(Filler)) { // Empty initialization requires a constructor call, so // extend the initializer list to include the constructor // call and make a note that we'll need to take another pass // through the initializer list. ILE->updateInit(SemaRef.Context, Init, Filler); RequiresSecondPass = true; } } } else if (InitListExpr *InnerILE = dyn_cast_or_null(InitExpr)) FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, FillWithNoInit); else if (DesignatedInitUpdateExpr *InnerDIUE = dyn_cast_or_null(InitExpr)) FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), RequiresSecondPass, /*FillWithNoInit =*/ true); } } InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid) : SemaRef(S), VerifyOnly(VerifyOnly), TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) { // FIXME: Check that IL isn't already the semantic form of some other // InitListExpr. If it is, we'd create a broken AST. hadError = false; FullyStructuredList = getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange()); CheckExplicitInitList(Entity, IL, T, FullyStructuredList, /*TopLevelObject=*/true); if (!hadError && !VerifyOnly) { bool RequiresSecondPass = false; FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass); if (RequiresSecondPass && !hadError) FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass); } } int InitListChecker::numArrayElements(QualType DeclType) { // FIXME: use a proper constant int maxElements = 0x7FFFFFFF; if (const ConstantArrayType *CAT = SemaRef.Context.getAsConstantArrayType(DeclType)) { maxElements = static_cast(CAT->getSize().getZExtValue()); } return maxElements; } int InitListChecker::numStructUnionElements(QualType DeclType) { RecordDecl *structDecl = DeclType->getAs()->getDecl(); int InitializableMembers = 0; if (auto *CXXRD = dyn_cast(structDecl)) InitializableMembers += CXXRD->getNumBases(); for (const auto *Field : structDecl->fields()) if (!Field->isUnnamedBitfield()) ++InitializableMembers; if (structDecl->isUnion()) return std::min(InitializableMembers, 1); return InitializableMembers - structDecl->hasFlexibleArrayMember(); } +/// Determine whether Entity is an entity for which it is idiomatic to elide +/// the braces in aggregate initialization. +static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { + // Recursive initialization of the one and only field within an aggregate + // class is considered idiomatic. This case arises in particular for + // initialization of std::array, where the C++ standard suggests the idiom of + // + // std::array arr = {1, 2, 3}; + // + // (where std::array is an aggregate struct containing a single array field. + + // FIXME: Should aggregate initialization of a struct with a single + // base class and no members also suppress the warning? + if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent()) + return false; + + auto *ParentRD = + Entity.getParent()->getType()->castAs()->getDecl(); + if (CXXRecordDecl *CXXRD = dyn_cast(ParentRD)) + if (CXXRD->getNumBases()) + return false; + + auto FieldIt = ParentRD->field_begin(); + assert(FieldIt != ParentRD->field_end() && + "no fields but have initializer for member?"); + return ++FieldIt == ParentRD->field_end(); +} + /// Check whether the range of the initializer \p ParentIList from element /// \p Index onwards can be used to initialize an object of type \p T. Update /// \p Index to indicate how many elements of the list were consumed. /// /// This also fills in \p StructuredList, from element \p StructuredIndex /// onwards, with the fully-braced, desugared form of the initialization. void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, InitListExpr *ParentIList, QualType T, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { int maxElements = 0; if (T->isArrayType()) maxElements = numArrayElements(T); else if (T->isRecordType()) maxElements = numStructUnionElements(T); else if (T->isVectorType()) maxElements = T->getAs()->getNumElements(); else llvm_unreachable("CheckImplicitInitList(): Illegal type"); if (maxElements == 0) { if (!VerifyOnly) SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), diag::err_implicit_empty_initializer); ++Index; hadError = true; return; } // Build a structured initializer list corresponding to this subobject. InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, StructuredIndex, SourceRange(ParentIList->getInit(Index)->getLocStart(), ParentIList->getSourceRange().getEnd())); unsigned StructuredSubobjectInitIndex = 0; // Check the element types and build the structural subobject. unsigned StartIndex = Index; CheckListElementTypes(Entity, ParentIList, T, /*SubobjectIsDesignatorContext=*/false, Index, StructuredSubobjectInitList, StructuredSubobjectInitIndex); if (!VerifyOnly) { StructuredSubobjectInitList->setType(T); unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); // Update the structured sub-object initializer so that it's ending // range corresponds with the end of the last initializer it used. if (EndIndex < ParentIList->getNumInits() && ParentIList->getInit(EndIndex)) { SourceLocation EndLoc = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); StructuredSubobjectInitList->setRBraceLoc(EndLoc); } // Complain about missing braces. - if (T->isArrayType() || T->isRecordType()) { + if ((T->isArrayType() || T->isRecordType()) && + !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && + !isIdiomaticBraceElisionEntity(Entity)) { SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), diag::warn_missing_braces) << StructuredSubobjectInitList->getSourceRange() << FixItHint::CreateInsertion( StructuredSubobjectInitList->getLocStart(), "{") << FixItHint::CreateInsertion( SemaRef.getLocForEndOfToken( StructuredSubobjectInitList->getLocEnd()), "}"); } } } /// Warn that \p Entity was of scalar type and was initialized by a /// single-element braced initializer list. static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, SourceRange Braces) { // Don't warn during template instantiation. If the initialization was // non-dependent, we warned during the initial parse; otherwise, the // type might not be scalar in some uses of the template. if (S.inTemplateInstantiation()) return; unsigned DiagID = 0; switch (Entity.getKind()) { case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_ComplexElement: case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_Parameter: case InitializedEntity::EK_Parameter_CF_Audited: case InitializedEntity::EK_Result: // Extra braces here are suspicious. DiagID = diag::warn_braces_around_scalar_init; break; case InitializedEntity::EK_Member: // Warn on aggregate initialization but not on ctor init list or // default member initializer. if (Entity.getParent()) DiagID = diag::warn_braces_around_scalar_init; break; case InitializedEntity::EK_Variable: case InitializedEntity::EK_LambdaCapture: // No warning, might be direct-list-initialization. // FIXME: Should we warn for copy-list-initialization in these cases? break; case InitializedEntity::EK_New: case InitializedEntity::EK_Temporary: case InitializedEntity::EK_CompoundLiteralInit: // No warning, braces are part of the syntax of the underlying construct. break; case InitializedEntity::EK_RelatedResult: // No warning, we already warned when initializing the result. break; case InitializedEntity::EK_Exception: case InitializedEntity::EK_Base: case InitializedEntity::EK_Delegating: case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_Binding: llvm_unreachable("unexpected braced scalar init"); } if (DiagID) { S.Diag(Braces.getBegin(), DiagID) << Braces << FixItHint::CreateRemoval(Braces.getBegin()) << FixItHint::CreateRemoval(Braces.getEnd()); } } /// Check whether the initializer \p IList (that was written with explicit /// braces) can be used to initialize an object of type \p T. /// /// This also fills in \p StructuredList with the fully-braced, desugared /// form of the initialization. void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, InitListExpr *IList, QualType &T, InitListExpr *StructuredList, bool TopLevelObject) { if (!VerifyOnly) { SyntacticToSemantic[IList] = StructuredList; StructuredList->setSyntacticForm(IList); } unsigned Index = 0, StructuredIndex = 0; CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, Index, StructuredList, StructuredIndex, TopLevelObject); if (!VerifyOnly) { QualType ExprTy = T; if (!ExprTy->isArrayType()) ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); IList->setType(ExprTy); StructuredList->setType(ExprTy); } if (hadError) return; if (Index < IList->getNumInits()) { // We have leftover initializers if (VerifyOnly) { if (SemaRef.getLangOpts().CPlusPlus || (SemaRef.getLangOpts().OpenCL && IList->getType()->isVectorType())) { hadError = true; } return; } if (StructuredIndex == 1 && IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == SIF_None) { unsigned DK = diag::ext_excess_initializers_in_char_array_initializer; if (SemaRef.getLangOpts().CPlusPlus) { DK = diag::err_excess_initializers_in_char_array_initializer; hadError = true; } // Special-case SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) << IList->getInit(Index)->getSourceRange(); } else if (!T->isIncompleteType()) { // Don't complain for incomplete types, since we'll get an error // elsewhere QualType CurrentObjectType = StructuredList->getType(); int initKind = CurrentObjectType->isArrayType()? 0 : CurrentObjectType->isVectorType()? 1 : CurrentObjectType->isScalarType()? 2 : CurrentObjectType->isUnionType()? 3 : 4; unsigned DK = diag::ext_excess_initializers; if (SemaRef.getLangOpts().CPlusPlus) { DK = diag::err_excess_initializers; hadError = true; } if (SemaRef.getLangOpts().OpenCL && initKind == 1) { DK = diag::err_excess_initializers; hadError = true; } SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) << initKind << IList->getInit(Index)->getSourceRange(); } } if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 && !isa(IList->getInit(0))) warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); } void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, InitListExpr *IList, QualType &DeclType, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject) { if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { // Explicitly braced initializer for complex type can be real+imaginary // parts. CheckComplexType(Entity, IList, DeclType, Index, StructuredList, StructuredIndex); } else if (DeclType->isScalarType()) { CheckScalarType(Entity, IList, DeclType, Index, StructuredList, StructuredIndex); } else if (DeclType->isVectorType()) { CheckVectorType(Entity, IList, DeclType, Index, StructuredList, StructuredIndex); } else if (DeclType->isRecordType()) { assert(DeclType->isAggregateType() && "non-aggregate records should be handed in CheckSubElementType"); RecordDecl *RD = DeclType->getAs()->getDecl(); auto Bases = CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), CXXRecordDecl::base_class_iterator()); if (auto *CXXRD = dyn_cast(RD)) Bases = CXXRD->bases(); CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), SubobjectIsDesignatorContext, Index, StructuredList, StructuredIndex, TopLevelObject); } else if (DeclType->isArrayType()) { llvm::APSInt Zero( SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), false); CheckArrayType(Entity, IList, DeclType, Zero, SubobjectIsDesignatorContext, Index, StructuredList, StructuredIndex); } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { // This type is invalid, issue a diagnostic. ++Index; if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) << DeclType; hadError = true; } else if (DeclType->isReferenceType()) { CheckReferenceType(Entity, IList, DeclType, Index, StructuredList, StructuredIndex); } else if (DeclType->isObjCObjectType()) { if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class) << DeclType; hadError = true; } else { if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) << DeclType; hadError = true; } } void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, InitListExpr *IList, QualType ElemType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { Expr *expr = IList->getInit(Index); if (ElemType->isReferenceType()) return CheckReferenceType(Entity, IList, ElemType, Index, StructuredList, StructuredIndex); if (InitListExpr *SubInitList = dyn_cast(expr)) { if (SubInitList->getNumInits() == 1 && IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == SIF_None) { expr = SubInitList->getInit(0); } else if (!SemaRef.getLangOpts().CPlusPlus) { InitListExpr *InnerStructuredList = getStructuredSubobjectInit(IList, Index, ElemType, StructuredList, StructuredIndex, SubInitList->getSourceRange(), true); CheckExplicitInitList(Entity, SubInitList, ElemType, InnerStructuredList); if (!hadError && !VerifyOnly) { bool RequiresSecondPass = false; FillInEmptyInitializations(Entity, InnerStructuredList, RequiresSecondPass); if (RequiresSecondPass && !hadError) FillInEmptyInitializations(Entity, InnerStructuredList, RequiresSecondPass); } ++StructuredIndex; ++Index; return; } // C++ initialization is handled later. } else if (isa(expr)) { // This happens during template instantiation when we see an InitListExpr // that we've already checked once. assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && "found implicit initialization for the wrong type"); if (!VerifyOnly) UpdateStructuredListElement(StructuredList, StructuredIndex, expr); ++Index; return; } if (SemaRef.getLangOpts().CPlusPlus) { // C++ [dcl.init.aggr]p2: // Each member is copy-initialized from the corresponding // initializer-clause. // FIXME: Better EqualLoc? InitializationKind Kind = InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation()); InitializationSequence Seq(SemaRef, Entity, Kind, expr, /*TopLevelOfInitList*/ true); // C++14 [dcl.init.aggr]p13: // If the assignment-expression can initialize a member, the member is // initialized. Otherwise [...] brace elision is assumed // // Brace elision is never performed if the element is not an // assignment-expression. if (Seq || isa(expr)) { if (!VerifyOnly) { ExprResult Result = Seq.Perform(SemaRef, Entity, Kind, expr); if (Result.isInvalid()) hadError = true; UpdateStructuredListElement(StructuredList, StructuredIndex, Result.getAs()); } else if (!Seq) hadError = true; ++Index; return; } // Fall through for subaggregate initialization } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { // FIXME: Need to handle atomic aggregate types with implicit init lists. return CheckScalarType(Entity, IList, ElemType, Index, StructuredList, StructuredIndex); } else if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) { // arrayType can be incomplete if we're initializing a flexible // array member. There's nothing we can do with the completed // type here, though. if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { if (!VerifyOnly) { CheckStringInit(expr, ElemType, arrayType, SemaRef); UpdateStructuredListElement(StructuredList, StructuredIndex, expr); } ++Index; return; } // Fall through for subaggregate initialization. } else { assert((ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && "Unexpected type"); // C99 6.7.8p13: // // The initializer for a structure or union object that has // automatic storage duration shall be either an initializer // list as described below, or a single expression that has // compatible structure or union type. In the latter case, the // initial value of the object, including unnamed members, is // that of the expression. ExprResult ExprRes = expr; if (SemaRef.CheckSingleAssignmentConstraints( ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { if (ExprRes.isInvalid()) hadError = true; else { ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); if (ExprRes.isInvalid()) hadError = true; } UpdateStructuredListElement(StructuredList, StructuredIndex, ExprRes.getAs()); ++Index; return; } ExprRes.get(); // Fall through for subaggregate initialization } // C++ [dcl.init.aggr]p12: // // [...] Otherwise, if the member is itself a non-empty // subaggregate, brace elision is assumed and the initializer is // considered for the initialization of the first member of // the subaggregate. // OpenCL vector initializer is handled elsewhere. if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || ElemType->isAggregateType()) { CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, StructuredIndex); ++StructuredIndex; } else { if (!VerifyOnly) { // We cannot initialize this element, so let // PerformCopyInitialization produce the appropriate diagnostic. SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, /*TopLevelOfInitList=*/true); } hadError = true; ++Index; ++StructuredIndex; } } void InitListChecker::CheckComplexType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { assert(Index == 0 && "Index in explicit init list must be zero"); // As an extension, clang supports complex initializers, which initialize // a complex number component-wise. When an explicit initializer list for // a complex number contains two two initializers, this extension kicks in: // it exepcts the initializer list to contain two elements convertible to // the element type of the complex type. The first element initializes // the real part, and the second element intitializes the imaginary part. if (IList->getNumInits() != 2) return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, StructuredIndex); // This is an extension in C. (The builtin _Complex type does not exist // in the C++ standard.) if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init) << IList->getSourceRange(); // Initialize the complex number. QualType elementType = DeclType->getAs()->getElementType(); InitializedEntity ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); for (unsigned i = 0; i < 2; ++i) { ElementEntity.setElementIndex(Index); CheckSubElementType(ElementEntity, IList, elementType, Index, StructuredList, StructuredIndex); } } void InitListChecker::CheckScalarType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { if (Index >= IList->getNumInits()) { if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), SemaRef.getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_empty_scalar_initializer : diag::err_empty_scalar_initializer) << IList->getSourceRange(); hadError = !SemaRef.getLangOpts().CPlusPlus11; ++Index; ++StructuredIndex; return; } Expr *expr = IList->getInit(Index); if (InitListExpr *SubIList = dyn_cast(expr)) { // FIXME: This is invalid, and accepting it causes overload resolution // to pick the wrong overload in some corner cases. if (!VerifyOnly) SemaRef.Diag(SubIList->getLocStart(), diag::ext_many_braces_around_scalar_init) << SubIList->getSourceRange(); CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, StructuredIndex); return; } else if (isa(expr)) { if (!VerifyOnly) SemaRef.Diag(expr->getLocStart(), diag::err_designator_for_scalar_init) << DeclType << expr->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } if (VerifyOnly) { if (!SemaRef.CanPerformCopyInitialization(Entity,expr)) hadError = true; ++Index; return; } ExprResult Result = SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr, /*TopLevelOfInitList=*/true); Expr *ResultExpr = nullptr; if (Result.isInvalid()) hadError = true; // types weren't compatible. else { ResultExpr = Result.getAs(); if (ResultExpr != expr) { // The type was promoted, update initializer list. IList->setInit(Index, ResultExpr); } } if (hadError) ++StructuredIndex; else UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); ++Index; } void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { if (Index >= IList->getNumInits()) { // FIXME: It would be wonderful if we could point at the actual member. In // general, it would be useful to pass location information down the stack, // so that we know the location (or decl) of the "current object" being // initialized. if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::err_init_reference_member_uninitialized) << DeclType << IList->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } Expr *expr = IList->getInit(Index); if (isa(expr) && !SemaRef.getLangOpts().CPlusPlus11) { if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) << DeclType << IList->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } if (VerifyOnly) { if (!SemaRef.CanPerformCopyInitialization(Entity,expr)) hadError = true; ++Index; return; } ExprResult Result = SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr, /*TopLevelOfInitList=*/true); if (Result.isInvalid()) hadError = true; expr = Result.getAs(); IList->setInit(Index, expr); if (hadError) ++StructuredIndex; else UpdateStructuredListElement(StructuredList, StructuredIndex, expr); ++Index; } void InitListChecker::CheckVectorType(const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { const VectorType *VT = DeclType->getAs(); unsigned maxElements = VT->getNumElements(); unsigned numEltsInit = 0; QualType elementType = VT->getElementType(); if (Index >= IList->getNumInits()) { // Make sure the element type can be value-initialized. if (VerifyOnly) CheckEmptyInitializable( InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), IList->getLocEnd()); return; } if (!SemaRef.getLangOpts().OpenCL) { // If the initializing element is a vector, try to copy-initialize // instead of breaking it apart (which is doomed to failure anyway). Expr *Init = IList->getInit(Index); if (!isa(Init) && Init->getType()->isVectorType()) { if (VerifyOnly) { if (!SemaRef.CanPerformCopyInitialization(Entity, Init)) hadError = true; ++Index; return; } ExprResult Result = SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init, /*TopLevelOfInitList=*/true); Expr *ResultExpr = nullptr; if (Result.isInvalid()) hadError = true; // types weren't compatible. else { ResultExpr = Result.getAs(); if (ResultExpr != Init) { // The type was promoted, update initializer list. IList->setInit(Index, ResultExpr); } } if (hadError) ++StructuredIndex; else UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); ++Index; return; } InitializedEntity ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { // Don't attempt to go past the end of the init list if (Index >= IList->getNumInits()) { if (VerifyOnly) CheckEmptyInitializable(ElementEntity, IList->getLocEnd()); break; } ElementEntity.setElementIndex(Index); CheckSubElementType(ElementEntity, IList, elementType, Index, StructuredList, StructuredIndex); } if (VerifyOnly) return; bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); const VectorType *T = Entity.getType()->getAs(); if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || T->getVectorKind() == VectorType::NeonPolyVector)) { // The ability to use vector initializer lists is a GNU vector extension // and is unrelated to the NEON intrinsics in arm_neon.h. On little // endian machines it works fine, however on big endian machines it // exhibits surprising behaviour: // // uint32x2_t x = {42, 64}; // return vget_lane_u32(x, 0); // Will return 64. // // Because of this, explicitly call out that it is non-portable. // SemaRef.Diag(IList->getLocStart(), diag::warn_neon_vector_initializer_non_portable); const char *typeCode; unsigned typeSize = SemaRef.Context.getTypeSize(elementType); if (elementType->isFloatingType()) typeCode = "f"; else if (elementType->isSignedIntegerType()) typeCode = "s"; else if (elementType->isUnsignedIntegerType()) typeCode = "u"; else llvm_unreachable("Invalid element type!"); SemaRef.Diag(IList->getLocStart(), SemaRef.Context.getTypeSize(VT) > 64 ? diag::note_neon_vector_initializer_non_portable_q : diag::note_neon_vector_initializer_non_portable) << typeCode << typeSize; } return; } InitializedEntity ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); // OpenCL initializers allows vectors to be constructed from vectors. for (unsigned i = 0; i < maxElements; ++i) { // Don't attempt to go past the end of the init list if (Index >= IList->getNumInits()) break; ElementEntity.setElementIndex(Index); QualType IType = IList->getInit(Index)->getType(); if (!IType->isVectorType()) { CheckSubElementType(ElementEntity, IList, elementType, Index, StructuredList, StructuredIndex); ++numEltsInit; } else { QualType VecType; const VectorType *IVT = IType->getAs(); unsigned numIElts = IVT->getNumElements(); if (IType->isExtVectorType()) VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); else VecType = SemaRef.Context.getVectorType(elementType, numIElts, IVT->getVectorKind()); CheckSubElementType(ElementEntity, IList, VecType, Index, StructuredList, StructuredIndex); numEltsInit += numIElts; } } // OpenCL requires all elements to be initialized. if (numEltsInit != maxElements) { if (!VerifyOnly) SemaRef.Diag(IList->getLocStart(), diag::err_vector_incorrect_num_initializers) << (numEltsInit < maxElements) << maxElements << numEltsInit; hadError = true; } } void InitListChecker::CheckArrayType(const InitializedEntity &Entity, InitListExpr *IList, QualType &DeclType, llvm::APSInt elementIndex, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex) { const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); // Check for the special-case of initializing an array with a string. if (Index < IList->getNumInits()) { if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == SIF_None) { // We place the string literal directly into the resulting // initializer list. This is the only place where the structure // of the structured initializer list doesn't match exactly, // because doing so would involve allocating one character // constant for each string. if (!VerifyOnly) { CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); UpdateStructuredListElement(StructuredList, StructuredIndex, IList->getInit(Index)); StructuredList->resizeInits(SemaRef.Context, StructuredIndex); } ++Index; return; } } if (const VariableArrayType *VAT = dyn_cast(arrayType)) { // Check for VLAs; in standard C it would be possible to check this // earlier, but I don't know where clang accepts VLAs (gcc accepts // them in all sorts of strange places). if (!VerifyOnly) SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), diag::err_variable_object_no_init) << VAT->getSizeExpr()->getSourceRange(); hadError = true; ++Index; ++StructuredIndex; return; } // We might know the maximum number of elements in advance. llvm::APSInt maxElements(elementIndex.getBitWidth(), elementIndex.isUnsigned()); bool maxElementsKnown = false; if (const ConstantArrayType *CAT = dyn_cast(arrayType)) { maxElements = CAT->getSize(); elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); elementIndex.setIsUnsigned(maxElements.isUnsigned()); maxElementsKnown = true; } QualType elementType = arrayType->getElementType(); while (Index < IList->getNumInits()) { Expr *Init = IList->getInit(Index); if (DesignatedInitExpr *DIE = dyn_cast(Init)) { // If we're not the subobject that matches up with the '{' for // the designator, we shouldn't be handling the // designator. Return immediately. if (!SubobjectIsDesignatorContext) return; // Handle this designated initializer. elementIndex will be // updated to be the next array element we'll initialize. if (CheckDesignatedInitializer(Entity, IList, DIE, 0, DeclType, nullptr, &elementIndex, Index, StructuredList, StructuredIndex, true, false)) { hadError = true; continue; } if (elementIndex.getBitWidth() > maxElements.getBitWidth()) maxElements = maxElements.extend(elementIndex.getBitWidth()); else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) elementIndex = elementIndex.extend(maxElements.getBitWidth()); elementIndex.setIsUnsigned(maxElements.isUnsigned()); // If the array is of incomplete type, keep track of the number of // elements in the initializer. if (!maxElementsKnown && elementIndex > maxElements) maxElements = elementIndex; continue; } // If we know the maximum number of elements, and we've already // hit it, stop consuming elements in the initializer list. if (maxElementsKnown && elementIndex == maxElements) break; InitializedEntity ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, Entity); // Check this element. CheckSubElementType(ElementEntity, IList, elementType, Index, StructuredList, StructuredIndex); ++elementIndex; // If the array is of incomplete type, keep track of the number of // elements in the initializer. if (!maxElementsKnown && elementIndex > maxElements) maxElements = elementIndex; } if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { // If this is an incomplete array type, the actual type needs to // be calculated here. llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { // Sizing an array implicitly to zero is not allowed by ISO C, // but is supported by GNU. SemaRef.Diag(IList->getLocStart(), diag::ext_typecheck_zero_array_size); } DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, ArrayType::Normal, 0); } if (!hadError && VerifyOnly) { // If there are any members of the array that get value-initialized, check // that is possible. That happens if we know the bound and don't have // enough elements, or if we're performing an array new with an unknown // bound. // FIXME: This needs to detect holes left by designated initializers too. if ((maxElementsKnown && elementIndex < maxElements) || Entity.isVariableLengthArrayNew()) CheckEmptyInitializable(InitializedEntity::InitializeElement( SemaRef.Context, 0, Entity), IList->getLocEnd()); } } bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, Expr *InitExpr, FieldDecl *Field, bool TopLevelObject) { // Handle GNU flexible array initializers. unsigned FlexArrayDiag; if (isa(InitExpr) && cast(InitExpr)->getNumInits() == 0) { // Empty flexible array init always allowed as an extension FlexArrayDiag = diag::ext_flexible_array_init; } else if (SemaRef.getLangOpts().CPlusPlus) { // Disallow flexible array init in C++; it is not required for gcc // compatibility, and it needs work to IRGen correctly in general. FlexArrayDiag = diag::err_flexible_array_init; } else if (!TopLevelObject) { // Disallow flexible array init on non-top-level object FlexArrayDiag = diag::err_flexible_array_init; } else if (Entity.getKind() != InitializedEntity::EK_Variable) { // Disallow flexible array init on anything which is not a variable. FlexArrayDiag = diag::err_flexible_array_init; } else if (cast(Entity.getDecl())->hasLocalStorage()) { // Disallow flexible array init on local variables. FlexArrayDiag = diag::err_flexible_array_init; } else { // Allow other cases. FlexArrayDiag = diag::ext_flexible_array_init; } if (!VerifyOnly) { SemaRef.Diag(InitExpr->getLocStart(), FlexArrayDiag) << InitExpr->getLocStart(); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << Field; } return FlexArrayDiag != diag::ext_flexible_array_init; } void InitListChecker::CheckStructUnionTypes( const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, bool SubobjectIsDesignatorContext, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool TopLevelObject) { RecordDecl *structDecl = DeclType->getAs()->getDecl(); // If the record is invalid, some of it's members are invalid. To avoid // confusion, we forgo checking the intializer for the entire record. if (structDecl->isInvalidDecl()) { // Assume it was supposed to consume a single initializer. ++Index; hadError = true; return; } if (DeclType->isUnionType() && IList->getNumInits() == 0) { RecordDecl *RD = DeclType->getAs()->getDecl(); // If there's a default initializer, use it. if (isa(RD) && cast(RD)->hasInClassInitializer()) { if (VerifyOnly) return; for (RecordDecl::field_iterator FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) { if (Field->hasInClassInitializer()) { StructuredList->setInitializedFieldInUnion(*Field); // FIXME: Actually build a CXXDefaultInitExpr? return; } } } // Value-initialize the first member of the union that isn't an unnamed // bitfield. for (RecordDecl::field_iterator FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) { if (!Field->isUnnamedBitfield()) { if (VerifyOnly) CheckEmptyInitializable( InitializedEntity::InitializeMember(*Field, &Entity), IList->getLocEnd()); else StructuredList->setInitializedFieldInUnion(*Field); break; } } return; } bool InitializedSomething = false; // If we have any base classes, they are initialized prior to the fields. for (auto &Base : Bases) { Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd(); // Designated inits always initialize fields, so if we see one, all // remaining base classes have no explicit initializer. if (Init && isa(Init)) Init = nullptr; InitializedEntity BaseEntity = InitializedEntity::InitializeBase( SemaRef.Context, &Base, false, &Entity); if (Init) { CheckSubElementType(BaseEntity, IList, Base.getType(), Index, StructuredList, StructuredIndex); InitializedSomething = true; } else if (VerifyOnly) { CheckEmptyInitializable(BaseEntity, InitLoc); } } // If structDecl is a forward declaration, this loop won't do // anything except look at designated initializers; That's okay, // because an error should get printed out elsewhere. It might be // worthwhile to skip over the rest of the initializer, though. RecordDecl *RD = DeclType->getAs()->getDecl(); RecordDecl::field_iterator FieldEnd = RD->field_end(); - bool CheckForMissingFields = true; + bool CheckForMissingFields = + !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); + while (Index < IList->getNumInits()) { Expr *Init = IList->getInit(Index); if (DesignatedInitExpr *DIE = dyn_cast(Init)) { // If we're not the subobject that matches up with the '{' for // the designator, we shouldn't be handling the // designator. Return immediately. if (!SubobjectIsDesignatorContext) return; // Handle this designated initializer. Field will be updated to // the next field that we'll be initializing. if (CheckDesignatedInitializer(Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index, StructuredList, StructuredIndex, true, TopLevelObject)) hadError = true; InitializedSomething = true; // Disable check for missing fields when designators are used. // This matches gcc behaviour. CheckForMissingFields = false; continue; } if (Field == FieldEnd) { // We've run out of fields. We're done. break; } // We've already initialized a member of a union. We're done. if (InitializedSomething && DeclType->isUnionType()) break; // If we've hit the flexible array member at the end, we're done. if (Field->getType()->isIncompleteArrayType()) break; if (Field->isUnnamedBitfield()) { // Don't initialize unnamed bitfields, e.g. "int : 20;" ++Field; continue; } // Make sure we can use this declaration. bool InvalidUse; if (VerifyOnly) InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); else InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, IList->getInit(Index)->getLocStart()); if (InvalidUse) { ++Index; ++Field; hadError = true; continue; } InitializedEntity MemberEntity = InitializedEntity::InitializeMember(*Field, &Entity); CheckSubElementType(MemberEntity, IList, Field->getType(), Index, StructuredList, StructuredIndex); InitializedSomething = true; if (DeclType->isUnionType() && !VerifyOnly) { // Initialize the first field within the union. StructuredList->setInitializedFieldInUnion(*Field); } ++Field; } // Emit warnings for missing struct field initializers. if (!VerifyOnly && InitializedSomething && CheckForMissingFields && Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) { // It is possible we have one or more unnamed bitfields remaining. // Find first (if any) named field and emit warning. for (RecordDecl::field_iterator it = Field, end = RD->field_end(); it != end; ++it) { if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { SemaRef.Diag(IList->getSourceRange().getEnd(), diag::warn_missing_field_initializers) << *it; break; } } } // Check that any remaining fields can be value-initialized. if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() && !Field->getType()->isIncompleteArrayType()) { // FIXME: Should check for holes left by designated initializers too. for (; Field != FieldEnd && !hadError; ++Field) { if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) CheckEmptyInitializable( InitializedEntity::InitializeMember(*Field, &Entity), IList->getLocEnd()); } } if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || Index >= IList->getNumInits()) return; if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, TopLevelObject)) { hadError = true; ++Index; return; } InitializedEntity MemberEntity = InitializedEntity::InitializeMember(*Field, &Entity); if (isa(IList->getInit(Index))) CheckSubElementType(MemberEntity, IList, Field->getType(), Index, StructuredList, StructuredIndex); else CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, StructuredList, StructuredIndex); } /// \brief Expand a field designator that refers to a member of an /// anonymous struct or union into a series of field designators that /// refers to the field within the appropriate subobject. /// static void ExpandAnonymousFieldDesignator(Sema &SemaRef, DesignatedInitExpr *DIE, unsigned DesigIdx, IndirectFieldDecl *IndirectField) { typedef DesignatedInitExpr::Designator Designator; // Build the replacement designators. SmallVector Replacements; for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), PE = IndirectField->chain_end(); PI != PE; ++PI) { if (PI + 1 == PE) Replacements.push_back(Designator((IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(), DIE->getDesignator(DesigIdx)->getFieldLoc())); else Replacements.push_back(Designator((IdentifierInfo *)nullptr, SourceLocation(), SourceLocation())); assert(isa(*PI)); Replacements.back().setField(cast(*PI)); } // Expand the current designator into the set of replacement // designators, so we have a full subobject path down to where the // member of the anonymous struct/union is actually stored. DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], &Replacements[0] + Replacements.size()); } static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE) { unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; SmallVector IndexExprs(NumIndexExprs); for (unsigned I = 0; I < NumIndexExprs; ++I) IndexExprs[I] = DIE->getSubExpr(I + 1); return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), IndexExprs, DIE->getEqualOrColonLoc(), DIE->usesGNUSyntax(), DIE->getInit()); } namespace { // Callback to only accept typo corrections that are for field members of // the given struct or union. class FieldInitializerValidatorCCC : public CorrectionCandidateCallback { public: explicit FieldInitializerValidatorCCC(RecordDecl *RD) : Record(RD) {} bool ValidateCandidate(const TypoCorrection &candidate) override { FieldDecl *FD = candidate.getCorrectionDeclAs(); return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); } private: RecordDecl *Record; }; } // end anonymous namespace /// @brief Check the well-formedness of a C99 designated initializer. /// /// Determines whether the designated initializer @p DIE, which /// resides at the given @p Index within the initializer list @p /// IList, is well-formed for a current object of type @p DeclType /// (C99 6.7.8). The actual subobject that this designator refers to /// within the current subobject is returned in either /// @p NextField or @p NextElementIndex (whichever is appropriate). /// /// @param IList The initializer list in which this designated /// initializer occurs. /// /// @param DIE The designated initializer expression. /// /// @param DesigIdx The index of the current designator. /// /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), /// into which the designation in @p DIE should refer. /// /// @param NextField If non-NULL and the first designator in @p DIE is /// a field, this will be set to the field declaration corresponding /// to the field named by the designator. /// /// @param NextElementIndex If non-NULL and the first designator in @p /// DIE is an array designator or GNU array-range designator, this /// will be set to the last index initialized by this designator. /// /// @param Index Index into @p IList where the designated initializer /// @p DIE occurs. /// /// @param StructuredList The initializer list expression that /// describes all of the subobject initializers in the order they'll /// actually be initialized. /// /// @returns true if there was an error, false otherwise. bool InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, InitListExpr *IList, DesignatedInitExpr *DIE, unsigned DesigIdx, QualType &CurrentObjectType, RecordDecl::field_iterator *NextField, llvm::APSInt *NextElementIndex, unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex, bool FinishSubobjectInit, bool TopLevelObject) { if (DesigIdx == DIE->size()) { // Check the actual initialization for the designated object type. bool prevHadError = hadError; // Temporarily remove the designator expression from the // initializer list that the child calls see, so that we don't try // to re-process the designator. unsigned OldIndex = Index; IList->setInit(OldIndex, DIE->getInit()); CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList, StructuredIndex); // Restore the designated initializer expression in the syntactic // form of the initializer list. if (IList->getInit(OldIndex) != DIE->getInit()) DIE->setInit(IList->getInit(OldIndex)); IList->setInit(OldIndex, DIE); return hadError && !prevHadError; } DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); bool IsFirstDesignator = (DesigIdx == 0); if (!VerifyOnly) { assert((IsFirstDesignator || StructuredList) && "Need a non-designated initializer list to start from"); // Determine the structural initializer list that corresponds to the // current subobject. if (IsFirstDesignator) StructuredList = SyntacticToSemantic.lookup(IList); else { Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? StructuredList->getInit(StructuredIndex) : nullptr; if (!ExistingInit && StructuredList->hasArrayFiller()) ExistingInit = StructuredList->getArrayFiller(); if (!ExistingInit) StructuredList = getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList, StructuredIndex, SourceRange(D->getLocStart(), DIE->getLocEnd())); else if (InitListExpr *Result = dyn_cast(ExistingInit)) StructuredList = Result; else { if (DesignatedInitUpdateExpr *E = dyn_cast(ExistingInit)) StructuredList = E->getUpdater(); else { DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context, D->getLocStart(), ExistingInit, DIE->getLocEnd()); StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); StructuredList = DIUE->getUpdater(); } // We need to check on source range validity because the previous // initializer does not have to be an explicit initializer. e.g., // // struct P { int a, b; }; // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; // // There is an overwrite taking place because the first braced initializer // list "{ .a = 2 }" already provides value for .p.b (which is zero). if (ExistingInit->getSourceRange().isValid()) { // We are creating an initializer list that initializes the // subobjects of the current object, but there was already an // initialization that completely initialized the current // subobject, e.g., by a compound literal: // // struct X { int a, b; }; // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; // // Here, xs[0].a == 0 and xs[0].b == 3, since the second, // designated initializer re-initializes the whole // subobject [0], overwriting previous initializers. SemaRef.Diag(D->getLocStart(), diag::warn_subobject_initializer_overrides) << SourceRange(D->getLocStart(), DIE->getLocEnd()); SemaRef.Diag(ExistingInit->getLocStart(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange(); } } } assert(StructuredList && "Expected a structured initializer list"); } if (D->isFieldDesignator()) { // C99 6.7.8p7: // // If a designator has the form // // . identifier // // then the current object (defined below) shall have // structure or union type and the identifier shall be the // name of a member of that type. const RecordType *RT = CurrentObjectType->getAs(); if (!RT) { SourceLocation Loc = D->getDotLoc(); if (Loc.isInvalid()) Loc = D->getFieldLoc(); if (!VerifyOnly) SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; ++Index; return true; } FieldDecl *KnownField = D->getField(); if (!KnownField) { IdentifierInfo *FieldName = D->getFieldName(); DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); for (NamedDecl *ND : Lookup) { if (auto *FD = dyn_cast(ND)) { KnownField = FD; break; } if (auto *IFD = dyn_cast(ND)) { // In verify mode, don't modify the original. if (VerifyOnly) DIE = CloneDesignatedInitExpr(SemaRef, DIE); ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); D = DIE->getDesignator(DesigIdx); KnownField = cast(*IFD->chain_begin()); break; } } if (!KnownField) { if (VerifyOnly) { ++Index; return true; // No typo correction when just trying this out. } // Name lookup found something, but it wasn't a field. if (!Lookup.empty()) { SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) << FieldName; SemaRef.Diag(Lookup.front()->getLocation(), diag::note_field_designator_found); ++Index; return true; } // Name lookup didn't find anything. // Determine whether this was a typo for another field name. if (TypoCorrection Corrected = SemaRef.CorrectTypo( DeclarationNameInfo(FieldName, D->getFieldLoc()), Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, llvm::make_unique(RT->getDecl()), Sema::CTK_ErrorRecovery, RT->getDecl())) { SemaRef.diagnoseTypo( Corrected, SemaRef.PDiag(diag::err_field_designator_unknown_suggest) << FieldName << CurrentObjectType); KnownField = Corrected.getCorrectionDeclAs(); hadError = true; } else { // Typo correction didn't find anything. SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) << FieldName << CurrentObjectType; ++Index; return true; } } } unsigned FieldIndex = 0; if (auto *CXXRD = dyn_cast(RT->getDecl())) FieldIndex = CXXRD->getNumBases(); for (auto *FI : RT->getDecl()->fields()) { if (FI->isUnnamedBitfield()) continue; if (declaresSameEntity(KnownField, FI)) { KnownField = FI; break; } ++FieldIndex; } RecordDecl::field_iterator Field = RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); // All of the fields of a union are located at the same place in // the initializer list. if (RT->getDecl()->isUnion()) { FieldIndex = 0; if (!VerifyOnly) { FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { assert(StructuredList->getNumInits() == 1 && "A union should never have more than one initializer!"); Expr *ExistingInit = StructuredList->getInit(0); if (ExistingInit) { // We're about to throw away an initializer, emit warning. SemaRef.Diag(D->getFieldLoc(), diag::warn_initializer_overrides) << D->getSourceRange(); SemaRef.Diag(ExistingInit->getLocStart(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange(); } // remove existing initializer StructuredList->resizeInits(SemaRef.Context, 0); StructuredList->setInitializedFieldInUnion(nullptr); } StructuredList->setInitializedFieldInUnion(*Field); } } // Make sure we can use this declaration. bool InvalidUse; if (VerifyOnly) InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); else InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); if (InvalidUse) { ++Index; return true; } if (!VerifyOnly) { // Update the designator with the field declaration. D->setField(*Field); // Make sure that our non-designated initializer list has space // for a subobject corresponding to this field. if (FieldIndex >= StructuredList->getNumInits()) StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); } // This designator names a flexible array member. if (Field->getType()->isIncompleteArrayType()) { bool Invalid = false; if ((DesigIdx + 1) != DIE->size()) { // We can't designate an object within the flexible array // member (because GCC doesn't allow it). if (!VerifyOnly) { DesignatedInitExpr::Designator *NextD = DIE->getDesignator(DesigIdx + 1); SemaRef.Diag(NextD->getLocStart(), diag::err_designator_into_flexible_array_member) << SourceRange(NextD->getLocStart(), DIE->getLocEnd()); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; } Invalid = true; } if (!hadError && !isa(DIE->getInit()) && !isa(DIE->getInit())) { // The initializer is not an initializer list. if (!VerifyOnly) { SemaRef.Diag(DIE->getInit()->getLocStart(), diag::err_flexible_array_init_needs_braces) << DIE->getInit()->getSourceRange(); SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) << *Field; } Invalid = true; } // Check GNU flexible array initializer. if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, TopLevelObject)) Invalid = true; if (Invalid) { ++Index; return true; } // Initialize the array. bool prevHadError = hadError; unsigned newStructuredIndex = FieldIndex; unsigned OldIndex = Index; IList->setInit(Index, DIE->getInit()); InitializedEntity MemberEntity = InitializedEntity::InitializeMember(*Field, &Entity); CheckSubElementType(MemberEntity, IList, Field->getType(), Index, StructuredList, newStructuredIndex); IList->setInit(OldIndex, DIE); if (hadError && !prevHadError) { ++Field; ++FieldIndex; if (NextField) *NextField = Field; StructuredIndex = FieldIndex; return true; } } else { // Recurse to check later designated subobjects. QualType FieldType = Field->getType(); unsigned newStructuredIndex = FieldIndex; InitializedEntity MemberEntity = InitializedEntity::InitializeMember(*Field, &Entity); if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, FieldType, nullptr, nullptr, Index, StructuredList, newStructuredIndex, FinishSubobjectInit, false)) return true; } // Find the position of the next field to be initialized in this // subobject. ++Field; ++FieldIndex; // If this the first designator, our caller will continue checking // the rest of this struct/class/union subobject. if (IsFirstDesignator) { if (NextField) *NextField = Field; StructuredIndex = FieldIndex; return false; } if (!FinishSubobjectInit) return false; // We've already initialized something in the union; we're done. if (RT->getDecl()->isUnion()) return hadError; // Check the remaining fields within this class/struct/union subobject. bool prevHadError = hadError; auto NoBases = CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), CXXRecordDecl::base_class_iterator()); CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, false, Index, StructuredList, FieldIndex); return hadError && !prevHadError; } // C99 6.7.8p6: // // If a designator has the form // // [ constant-expression ] // // then the current object (defined below) shall have array // type and the expression shall be an integer constant // expression. If the array is of unknown size, any // nonnegative value is valid. // // Additionally, cope with the GNU extension that permits // designators of the form // // [ constant-expression ... constant-expression ] const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); if (!AT) { if (!VerifyOnly) SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) << CurrentObjectType; ++Index; return true; } Expr *IndexExpr = nullptr; llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; if (D->isArrayDesignator()) { IndexExpr = DIE->getArrayIndex(*D); DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); DesignatedEndIndex = DesignatedStartIndex; } else { assert(D->isArrayRangeDesignator() && "Need array-range designator"); DesignatedStartIndex = DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); DesignatedEndIndex = DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); IndexExpr = DIE->getArrayRangeEnd(*D); // Codegen can't handle evaluating array range designators that have side // effects, because we replicate the AST value for each initialized element. // As such, set the sawArrayRangeDesignator() bit if we initialize multiple // elements with something that has a side effect, so codegen can emit an // "error unsupported" error instead of miscompiling the app. if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) FullyStructuredList->sawArrayRangeDesignator(); } if (isa(AT)) { llvm::APSInt MaxElements(cast(AT)->getSize(), false); DesignatedStartIndex = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); DesignatedEndIndex = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); if (DesignatedEndIndex >= MaxElements) { if (!VerifyOnly) SemaRef.Diag(IndexExpr->getLocStart(), diag::err_array_designator_too_large) << DesignatedEndIndex.toString(10) << MaxElements.toString(10) << IndexExpr->getSourceRange(); ++Index; return true; } } else { unsigned DesignatedIndexBitWidth = ConstantArrayType::getMaxSizeBits(SemaRef.Context); DesignatedStartIndex = DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); DesignatedEndIndex = DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); DesignatedStartIndex.setIsUnsigned(true); DesignatedEndIndex.setIsUnsigned(true); } if (!VerifyOnly && StructuredList->isStringLiteralInit()) { // We're modifying a string literal init; we have to decompose the string // so we can modify the individual characters. ASTContext &Context = SemaRef.Context; Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); // Compute the character type QualType CharTy = AT->getElementType(); // Compute the type of the integer literals. QualType PromotedCharTy = CharTy; if (CharTy->isPromotableIntegerType()) PromotedCharTy = Context.getPromotedIntegerType(CharTy); unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); if (StringLiteral *SL = dyn_cast(SubExpr)) { // Get the length of the string. uint64_t StrLen = SL->getLength(); if (cast(AT)->getSize().ult(StrLen)) StrLen = cast(AT)->getSize().getZExtValue(); StructuredList->resizeInits(Context, StrLen); // Build a literal for each character in the string, and put them into // the init list. for (unsigned i = 0, e = StrLen; i != e; ++i) { llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); Expr *Init = new (Context) IntegerLiteral( Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); if (CharTy != PromotedCharTy) Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, nullptr, VK_RValue); StructuredList->updateInit(Context, i, Init); } } else { ObjCEncodeExpr *E = cast(SubExpr); std::string Str; Context.getObjCEncodingForType(E->getEncodedType(), Str); // Get the length of the string. uint64_t StrLen = Str.size(); if (cast(AT)->getSize().ult(StrLen)) StrLen = cast(AT)->getSize().getZExtValue(); StructuredList->resizeInits(Context, StrLen); // Build a literal for each character in the string, and put them into // the init list. for (unsigned i = 0, e = StrLen; i != e; ++i) { llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); Expr *Init = new (Context) IntegerLiteral( Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); if (CharTy != PromotedCharTy) Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, nullptr, VK_RValue); StructuredList->updateInit(Context, i, Init); } } } // Make sure that our non-designated initializer list has space // for a subobject corresponding to this array element. if (!VerifyOnly && DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) StructuredList->resizeInits(SemaRef.Context, DesignatedEndIndex.getZExtValue() + 1); // Repeatedly perform subobject initializations in the range // [DesignatedStartIndex, DesignatedEndIndex]. // Move to the next designator unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); unsigned OldIndex = Index; InitializedEntity ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); while (DesignatedStartIndex <= DesignatedEndIndex) { // Recurse to check later designated subobjects. QualType ElementType = AT->getElementType(); Index = OldIndex; ElementEntity.setElementIndex(ElementIndex); if (CheckDesignatedInitializer( ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, nullptr, Index, StructuredList, ElementIndex, FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), false)) return true; // Move to the next index in the array that we'll be initializing. ++DesignatedStartIndex; ElementIndex = DesignatedStartIndex.getZExtValue(); } // If this the first designator, our caller will continue checking // the rest of this array subobject. if (IsFirstDesignator) { if (NextElementIndex) *NextElementIndex = DesignatedStartIndex; StructuredIndex = ElementIndex; return false; } if (!FinishSubobjectInit) return false; // Check the remaining elements within this array subobject. bool prevHadError = hadError; CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, /*SubobjectIsDesignatorContext=*/false, Index, StructuredList, ElementIndex); return hadError && !prevHadError; } // Get the structured initializer list for a subobject of type // @p CurrentObjectType. InitListExpr * InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, QualType CurrentObjectType, InitListExpr *StructuredList, unsigned StructuredIndex, SourceRange InitRange, bool IsFullyOverwritten) { if (VerifyOnly) return nullptr; // No structured list in verification-only mode. Expr *ExistingInit = nullptr; if (!StructuredList) ExistingInit = SyntacticToSemantic.lookup(IList); else if (StructuredIndex < StructuredList->getNumInits()) ExistingInit = StructuredList->getInit(StructuredIndex); if (InitListExpr *Result = dyn_cast_or_null(ExistingInit)) // There might have already been initializers for subobjects of the current // object, but a subsequent initializer list will overwrite the entirety // of the current object. (See DR 253 and C99 6.7.8p21). e.g., // // struct P { char x[6]; }; // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; // // The first designated initializer is ignored, and l.x is just "f". if (!IsFullyOverwritten) return Result; if (ExistingInit) { // We are creating an initializer list that initializes the // subobjects of the current object, but there was already an // initialization that completely initialized the current // subobject, e.g., by a compound literal: // // struct X { int a, b; }; // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; // // Here, xs[0].a == 0 and xs[0].b == 3, since the second, // designated initializer re-initializes the whole // subobject [0], overwriting previous initializers. SemaRef.Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides) << InitRange; SemaRef.Diag(ExistingInit->getLocStart(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange(); } InitListExpr *Result = new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(), None, InitRange.getEnd()); QualType ResultType = CurrentObjectType; if (!ResultType->isArrayType()) ResultType = ResultType.getNonLValueExprType(SemaRef.Context); Result->setType(ResultType); // Pre-allocate storage for the structured initializer list. unsigned NumElements = 0; unsigned NumInits = 0; bool GotNumInits = false; if (!StructuredList) { NumInits = IList->getNumInits(); GotNumInits = true; } else if (Index < IList->getNumInits()) { if (InitListExpr *SubList = dyn_cast(IList->getInit(Index))) { NumInits = SubList->getNumInits(); GotNumInits = true; } } if (const ArrayType *AType = SemaRef.Context.getAsArrayType(CurrentObjectType)) { if (const ConstantArrayType *CAType = dyn_cast(AType)) { NumElements = CAType->getSize().getZExtValue(); // Simple heuristic so that we don't allocate a very large // initializer with many empty entries at the end. if (GotNumInits && NumElements > NumInits) NumElements = 0; } } else if (const VectorType *VType = CurrentObjectType->getAs()) NumElements = VType->getNumElements(); else if (const RecordType *RType = CurrentObjectType->getAs()) { RecordDecl *RDecl = RType->getDecl(); if (RDecl->isUnion()) NumElements = 1; else NumElements = std::distance(RDecl->field_begin(), RDecl->field_end()); } Result->reserveInits(SemaRef.Context, NumElements); // Link this new initializer list into the structured initializer // lists. if (StructuredList) StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); else { Result->setSyntacticForm(IList); SyntacticToSemantic[IList] = Result; } return Result; } /// Update the initializer at index @p StructuredIndex within the /// structured initializer list to the value @p expr. void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, unsigned &StructuredIndex, Expr *expr) { // No structured initializer list to update if (!StructuredList) return; if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, StructuredIndex, expr)) { // This initializer overwrites a previous initializer. Warn. // We need to check on source range validity because the previous // initializer does not have to be an explicit initializer. // struct P { int a, b; }; // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; // There is an overwrite taking place because the first braced initializer // list "{ .a = 2 }' already provides value for .p.b (which is zero). if (PrevInit->getSourceRange().isValid()) { SemaRef.Diag(expr->getLocStart(), diag::warn_initializer_overrides) << expr->getSourceRange(); SemaRef.Diag(PrevInit->getLocStart(), diag::note_previous_initializer) << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange(); } } ++StructuredIndex; } /// Check that the given Index expression is a valid array designator /// value. This is essentially just a wrapper around /// VerifyIntegerConstantExpression that also checks for negative values /// and produces a reasonable diagnostic if there is a /// failure. Returns the index expression, possibly with an implicit cast /// added, on success. If everything went okay, Value will receive the /// value of the constant expression. static ExprResult CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { SourceLocation Loc = Index->getLocStart(); // Make sure this is an integer constant expression. ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value); if (Result.isInvalid()) return Result; if (Value.isSigned() && Value.isNegative()) return S.Diag(Loc, diag::err_array_designator_negative) << Value.toString(10) << Index->getSourceRange(); Value.setIsUnsigned(true); return Result; } ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, SourceLocation Loc, bool GNUSyntax, ExprResult Init) { typedef DesignatedInitExpr::Designator ASTDesignator; bool Invalid = false; SmallVector Designators; SmallVector InitExpressions; // Build designators and check array designator expressions. for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { const Designator &D = Desig.getDesignator(Idx); switch (D.getKind()) { case Designator::FieldDesignator: Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), D.getFieldLoc())); break; case Designator::ArrayDesignator: { Expr *Index = static_cast(D.getArrayIndex()); llvm::APSInt IndexValue; if (!Index->isTypeDependent() && !Index->isValueDependent()) Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); if (!Index) Invalid = true; else { Designators.push_back(ASTDesignator(InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc())); InitExpressions.push_back(Index); } break; } case Designator::ArrayRangeDesignator: { Expr *StartIndex = static_cast(D.getArrayRangeStart()); Expr *EndIndex = static_cast(D.getArrayRangeEnd()); llvm::APSInt StartValue; llvm::APSInt EndValue; bool StartDependent = StartIndex->isTypeDependent() || StartIndex->isValueDependent(); bool EndDependent = EndIndex->isTypeDependent() || EndIndex->isValueDependent(); if (!StartDependent) StartIndex = CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); if (!EndDependent) EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); if (!StartIndex || !EndIndex) Invalid = true; else { // Make sure we're comparing values with the same bit width. if (StartDependent || EndDependent) { // Nothing to compute. } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) EndValue = EndValue.extend(StartValue.getBitWidth()); else if (StartValue.getBitWidth() < EndValue.getBitWidth()) StartValue = StartValue.extend(EndValue.getBitWidth()); if (!StartDependent && !EndDependent && EndValue < StartValue) { Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) << StartValue.toString(10) << EndValue.toString(10) << StartIndex->getSourceRange() << EndIndex->getSourceRange(); Invalid = true; } else { Designators.push_back(ASTDesignator(InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(), D.getRBracketLoc())); InitExpressions.push_back(StartIndex); InitExpressions.push_back(EndIndex); } } break; } } } if (Invalid || Init.isInvalid()) return ExprError(); // Clear out the expressions within the designation. Desig.ClearExprs(*this); DesignatedInitExpr *DIE = DesignatedInitExpr::Create(Context, Designators, InitExpressions, Loc, GNUSyntax, Init.getAs()); if (!getLangOpts().C99) Diag(DIE->getLocStart(), diag::ext_designated_init) << DIE->getSourceRange(); return DIE; } //===----------------------------------------------------------------------===// // Initialization entity //===----------------------------------------------------------------------===// InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, const InitializedEntity &Parent) : Parent(&Parent), Index(Index) { if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { Kind = EK_ArrayElement; Type = AT->getElementType(); } else if (const VectorType *VT = Parent.getType()->getAs()) { Kind = EK_VectorElement; Type = VT->getElementType(); } else { const ComplexType *CT = Parent.getType()->getAs(); assert(CT && "Unexpected type"); Kind = EK_ComplexElement; Type = CT->getElementType(); } } InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent) { InitializedEntity Result; Result.Kind = EK_Base; Result.Parent = Parent; Result.Base = reinterpret_cast(Base); if (IsInheritedVirtualBase) Result.Base |= 0x01; Result.Type = Base->getType(); return Result; } DeclarationName InitializedEntity::getName() const { switch (getKind()) { case EK_Parameter: case EK_Parameter_CF_Audited: { ParmVarDecl *D = reinterpret_cast(Parameter & ~0x1); return (D ? D->getDeclName() : DeclarationName()); } case EK_Variable: case EK_Member: case EK_Binding: return Variable.VariableOrMember->getDeclName(); case EK_LambdaCapture: return DeclarationName(Capture.VarID); case EK_Result: case EK_Exception: case EK_New: case EK_Temporary: case EK_Base: case EK_Delegating: case EK_ArrayElement: case EK_VectorElement: case EK_ComplexElement: case EK_BlockElement: case EK_LambdaToBlockConversionBlockElement: case EK_CompoundLiteralInit: case EK_RelatedResult: return DeclarationName(); } llvm_unreachable("Invalid EntityKind!"); } ValueDecl *InitializedEntity::getDecl() const { switch (getKind()) { case EK_Variable: case EK_Member: case EK_Binding: return Variable.VariableOrMember; case EK_Parameter: case EK_Parameter_CF_Audited: return reinterpret_cast(Parameter & ~0x1); case EK_Result: case EK_Exception: case EK_New: case EK_Temporary: case EK_Base: case EK_Delegating: case EK_ArrayElement: case EK_VectorElement: case EK_ComplexElement: case EK_BlockElement: case EK_LambdaToBlockConversionBlockElement: case EK_LambdaCapture: case EK_CompoundLiteralInit: case EK_RelatedResult: return nullptr; } llvm_unreachable("Invalid EntityKind!"); } bool InitializedEntity::allowsNRVO() const { switch (getKind()) { case EK_Result: case EK_Exception: return LocAndNRVO.NRVO; case EK_Variable: case EK_Parameter: case EK_Parameter_CF_Audited: case EK_Member: case EK_Binding: case EK_New: case EK_Temporary: case EK_CompoundLiteralInit: case EK_Base: case EK_Delegating: case EK_ArrayElement: case EK_VectorElement: case EK_ComplexElement: case EK_BlockElement: case EK_LambdaToBlockConversionBlockElement: case EK_LambdaCapture: case EK_RelatedResult: break; } return false; } unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { assert(getParent() != this); unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; for (unsigned I = 0; I != Depth; ++I) OS << "`-"; switch (getKind()) { case EK_Variable: OS << "Variable"; break; case EK_Parameter: OS << "Parameter"; break; case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; break; case EK_Result: OS << "Result"; break; case EK_Exception: OS << "Exception"; break; case EK_Member: OS << "Member"; break; case EK_Binding: OS << "Binding"; break; case EK_New: OS << "New"; break; case EK_Temporary: OS << "Temporary"; break; case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; case EK_RelatedResult: OS << "RelatedResult"; break; case EK_Base: OS << "Base"; break; case EK_Delegating: OS << "Delegating"; break; case EK_ArrayElement: OS << "ArrayElement " << Index; break; case EK_VectorElement: OS << "VectorElement " << Index; break; case EK_ComplexElement: OS << "ComplexElement " << Index; break; case EK_BlockElement: OS << "Block"; break; case EK_LambdaToBlockConversionBlockElement: OS << "Block (lambda)"; break; case EK_LambdaCapture: OS << "LambdaCapture "; OS << DeclarationName(Capture.VarID); break; } if (auto *D = getDecl()) { OS << " "; D->printQualifiedName(OS); } OS << " '" << getType().getAsString() << "'\n"; return Depth + 1; } LLVM_DUMP_METHOD void InitializedEntity::dump() const { dumpImpl(llvm::errs()); } //===----------------------------------------------------------------------===// // Initialization sequence //===----------------------------------------------------------------------===// void InitializationSequence::Step::Destroy() { switch (Kind) { case SK_ResolveAddressOfOverloadedFunction: case SK_CastDerivedToBaseRValue: case SK_CastDerivedToBaseXValue: case SK_CastDerivedToBaseLValue: case SK_BindReference: case SK_BindReferenceToTemporary: case SK_FinalCopy: case SK_ExtraneousCopyToTemporary: case SK_UserConversion: case SK_QualificationConversionRValue: case SK_QualificationConversionXValue: case SK_QualificationConversionLValue: case SK_AtomicConversion: case SK_LValueToRValue: case SK_ListInitialization: case SK_UnwrapInitList: case SK_RewrapInitList: case SK_ConstructorInitialization: case SK_ConstructorInitializationFromList: case SK_ZeroInitialization: case SK_CAssignment: case SK_StringInit: case SK_ObjCObjectConversion: case SK_ArrayLoopIndex: case SK_ArrayLoopInit: case SK_ArrayInit: case SK_GNUArrayInit: case SK_ParenthesizedArrayInit: case SK_PassByIndirectCopyRestore: case SK_PassByIndirectRestore: case SK_ProduceObjCObject: case SK_StdInitializerList: case SK_StdInitializerListConstructorCall: case SK_OCLSamplerInit: case SK_OCLZeroEvent: case SK_OCLZeroQueue: break; case SK_ConversionSequence: case SK_ConversionSequenceNoNarrowing: delete ICS; } } bool InitializationSequence::isDirectReferenceBinding() const { // There can be some lvalue adjustments after the SK_BindReference step. for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { if (I->Kind == SK_BindReference) return true; if (I->Kind == SK_BindReferenceToTemporary) return false; } return false; } bool InitializationSequence::isAmbiguous() const { if (!Failed()) return false; switch (getFailureKind()) { case FK_TooManyInitsForReference: case FK_ParenthesizedListInitForReference: case FK_ArrayNeedsInitList: case FK_ArrayNeedsInitListOrStringLiteral: case FK_ArrayNeedsInitListOrWideStringLiteral: case FK_NarrowStringIntoWideCharArray: case FK_WideStringIntoCharArray: case FK_IncompatWideStringIntoWideChar: case FK_AddressOfOverloadFailed: // FIXME: Could do better case FK_NonConstLValueReferenceBindingToTemporary: case FK_NonConstLValueReferenceBindingToBitfield: case FK_NonConstLValueReferenceBindingToVectorElement: case FK_NonConstLValueReferenceBindingToUnrelated: case FK_RValueReferenceBindingToLValue: case FK_ReferenceInitDropsQualifiers: case FK_ReferenceInitFailed: case FK_ConversionFailed: case FK_ConversionFromPropertyFailed: case FK_TooManyInitsForScalar: case FK_ParenthesizedListInitForScalar: case FK_ReferenceBindingToInitList: case FK_InitListBadDestinationType: case FK_DefaultInitOfConst: case FK_Incomplete: case FK_ArrayTypeMismatch: case FK_NonConstantArrayInit: case FK_ListInitializationFailed: case FK_VariableLengthArrayHasInitializer: case FK_PlaceholderType: case FK_ExplicitConstructor: case FK_AddressOfUnaddressableFunction: return false; case FK_ReferenceInitOverloadFailed: case FK_UserConversionOverloadFailed: case FK_ConstructorOverloadFailed: case FK_ListConstructorOverloadFailed: return FailedOverloadResult == OR_Ambiguous; } llvm_unreachable("Invalid EntityKind!"); } bool InitializationSequence::isConstructorInitialization() const { return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; } void InitializationSequence ::AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates) { Step S; S.Kind = SK_ResolveAddressOfOverloadedFunction; S.Type = Function->getType(); S.Function.HadMultipleCandidates = HadMultipleCandidates; S.Function.Function = Function; S.Function.FoundDecl = Found; Steps.push_back(S); } void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind VK) { Step S; switch (VK) { case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; } S.Type = BaseType; Steps.push_back(S); } void InitializationSequence::AddReferenceBindingStep(QualType T, bool BindingTemporary) { Step S; S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddFinalCopy(QualType T) { Step S; S.Kind = SK_FinalCopy; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { Step S; S.Kind = SK_ExtraneousCopyToTemporary; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, DeclAccessPair FoundDecl, QualType T, bool HadMultipleCandidates) { Step S; S.Kind = SK_UserConversion; S.Type = T; S.Function.HadMultipleCandidates = HadMultipleCandidates; S.Function.Function = Function; S.Function.FoundDecl = FoundDecl; Steps.push_back(S); } void InitializationSequence::AddQualificationConversionStep(QualType Ty, ExprValueKind VK) { Step S; S.Kind = SK_QualificationConversionRValue; // work around a gcc warning switch (VK) { case VK_RValue: S.Kind = SK_QualificationConversionRValue; break; case VK_XValue: S.Kind = SK_QualificationConversionXValue; break; case VK_LValue: S.Kind = SK_QualificationConversionLValue; break; } S.Type = Ty; Steps.push_back(S); } void InitializationSequence::AddAtomicConversionStep(QualType Ty) { Step S; S.Kind = SK_AtomicConversion; S.Type = Ty; Steps.push_back(S); } void InitializationSequence::AddLValueToRValueStep(QualType Ty) { assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers"); Step S; S.Kind = SK_LValueToRValue; S.Type = Ty; Steps.push_back(S); } void InitializationSequence::AddConversionSequenceStep( const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList) { Step S; S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing : SK_ConversionSequence; S.Type = T; S.ICS = new ImplicitConversionSequence(ICS); Steps.push_back(S); } void InitializationSequence::AddListInitializationStep(QualType T) { Step S; S.Kind = SK_ListInitialization; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddConstructorInitializationStep( DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { Step S; S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall : SK_ConstructorInitializationFromList : SK_ConstructorInitialization; S.Type = T; S.Function.HadMultipleCandidates = HadMultipleCandidates; S.Function.Function = Constructor; S.Function.FoundDecl = FoundDecl; Steps.push_back(S); } void InitializationSequence::AddZeroInitializationStep(QualType T) { Step S; S.Kind = SK_ZeroInitialization; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddCAssignmentStep(QualType T) { Step S; S.Kind = SK_CAssignment; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddStringInitStep(QualType T) { Step S; S.Kind = SK_StringInit; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddObjCObjectConversionStep(QualType T) { Step S; S.Kind = SK_ObjCObjectConversion; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { Step S; S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { Step S; S.Kind = SK_ArrayLoopIndex; S.Type = EltT; Steps.insert(Steps.begin(), S); S.Kind = SK_ArrayLoopInit; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { Step S; S.Kind = SK_ParenthesizedArrayInit; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, bool shouldCopy) { Step s; s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore : SK_PassByIndirectRestore); s.Type = type; Steps.push_back(s); } void InitializationSequence::AddProduceObjCObjectStep(QualType T) { Step S; S.Kind = SK_ProduceObjCObject; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { Step S; S.Kind = SK_StdInitializerList; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddOCLSamplerInitStep(QualType T) { Step S; S.Kind = SK_OCLSamplerInit; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddOCLZeroEventStep(QualType T) { Step S; S.Kind = SK_OCLZeroEvent; S.Type = T; Steps.push_back(S); } void InitializationSequence::AddOCLZeroQueueStep(QualType T) { Step S; S.Kind = SK_OCLZeroQueue; S.Type = T; Steps.push_back(S); } void InitializationSequence::RewrapReferenceInitList(QualType T, InitListExpr *Syntactic) { assert(Syntactic->getNumInits() == 1 && "Can only rewrap trivial init lists."); Step S; S.Kind = SK_UnwrapInitList; S.Type = Syntactic->getInit(0)->getType(); Steps.insert(Steps.begin(), S); S.Kind = SK_RewrapInitList; S.Type = T; S.WrappingSyntacticList = Syntactic; Steps.push_back(S); } void InitializationSequence::SetOverloadFailure(FailureKind Failure, OverloadingResult Result) { setSequenceKind(FailedSequence); this->Failure = Failure; this->FailedOverloadResult = Result; } //===----------------------------------------------------------------------===// // Attempt initialization //===----------------------------------------------------------------------===// /// Tries to add a zero initializer. Returns true if that worked. static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity) { if (Entity.getKind() != InitializedEntity::EK_Variable) return false; VarDecl *VD = cast(Entity.getDecl()); if (VD->getInit() || VD->getLocEnd().isMacroID()) return false; QualType VariableTy = VD->getType().getCanonicalType(); SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd()); std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); if (!Init.empty()) { Sequence.AddZeroInitializationStep(Entity.getType()); Sequence.SetZeroInitializationFixit(Init, Loc); return true; } return false; } static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity) { if (!S.getLangOpts().ObjCAutoRefCount) return; /// When initializing a parameter, produce the value if it's marked /// __attribute__((ns_consumed)). if (Entity.isParameterKind()) { if (!Entity.isParameterConsumed()) return; assert(Entity.getType()->isObjCRetainableType() && "consuming an object of unretainable type?"); Sequence.AddProduceObjCObjectStep(Entity.getType()); /// When initializing a return value, if the return type is a /// retainable type, then returns need to immediately retain the /// object. If an autorelease is required, it will be done at the /// last instant. } else if (Entity.getKind() == InitializedEntity::EK_Result) { if (!Entity.getType()->isObjCRetainableType()) return; Sequence.AddProduceObjCObjectStep(Entity.getType()); } } static void TryListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid); /// \brief When initializing from init list via constructor, handle /// initialization of an object of type std::initializer_list. /// /// \return true if we have handled initialization of an object of type /// std::initializer_list, false otherwise. static bool TryInitializerListConstruction(Sema &S, InitListExpr *List, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid) { QualType E; if (!S.isStdInitializerList(DestType, &E)) return false; if (!S.isCompleteType(List->getExprLoc(), E)) { Sequence.setIncompleteTypeFailure(E); return true; } // Try initializing a temporary array from the init list. QualType ArrayType = S.Context.getConstantArrayType( E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), List->getNumInits()), clang::ArrayType::Normal, 0); InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(ArrayType); InitializationKind Kind = InitializationKind::CreateDirectList(List->getExprLoc()); TryListInitialization(S, HiddenArray, Kind, List, Sequence, TreatUnavailableAsInvalid); if (Sequence) Sequence.AddStdInitializerListConstructionStep(DestType); return true; } /// Determine if the constructor has the signature of a copy or move /// constructor for the type T of the class in which it was found. That is, /// determine if its first parameter is of type T or reference to (possibly /// cv-qualified) T. static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, const ConstructorInfo &Info) { if (Info.Constructor->getNumParams() == 0) return false; QualType ParmT = Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); QualType ClassT = Ctx.getRecordType(cast(Info.FoundDecl->getDeclContext())); return Ctx.hasSameUnqualifiedType(ParmT, ClassT); } static OverloadingResult ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, MultiExprArg Args, OverloadCandidateSet &CandidateSet, DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, bool IsListInit, bool SecondStepOfCopyInit = false) { CandidateSet.clear(); for (NamedDecl *D : Ctors) { auto Info = getConstructorInfo(D); if (!Info.Constructor || Info.Constructor->isInvalidDecl()) continue; if (!AllowExplicit && Info.Constructor->isExplicit()) continue; if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) continue; // C++11 [over.best.ics]p4: // ... and the constructor or user-defined conversion function is a // candidate by // - 13.3.1.3, when the argument is the temporary in the second step // of a class copy-initialization, or // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] // - the second phase of 13.3.1.7 when the initializer list has exactly // one element that is itself an initializer list, and the target is // the first parameter of a constructor of class X, and the conversion // is to X or reference to (possibly cv-qualified X), // user-defined conversion sequences are not considered. bool SuppressUserConversions = SecondStepOfCopyInit || (IsListInit && Args.size() == 1 && isa(Args[0]) && hasCopyOrMoveCtorParam(S.Context, Info)); if (Info.ConstructorTmpl) S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions); else { // C++ [over.match.copy]p1: // - When initializing a temporary to be bound to the first parameter // of a constructor [for type T] that takes a reference to possibly // cv-qualified T as its first argument, called with a single // argument in the context of direct-initialization, explicit // conversion functions are also considered. // FIXME: What if a constructor template instantiates to such a signature? bool AllowExplicitConv = AllowExplicit && !CopyInitializing && Args.size() == 1 && hasCopyOrMoveCtorParam(S.Context, Info); S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, CandidateSet, SuppressUserConversions, /*PartialOverloading=*/false, /*AllowExplicit=*/AllowExplicitConv); } } // Perform overload resolution and return the result. return CandidateSet.BestViableFunction(S, DeclLoc, Best); } /// \brief Attempt initialization by constructor (C++ [dcl.init]), which /// enumerates the constructors of the initialized entity and performs overload /// resolution to select the best. /// \param DestType The destination class type. /// \param DestArrayType The destination type, which is either DestType or /// a (possibly multidimensional) array of DestType. /// \param IsListInit Is this list-initialization? /// \param IsInitListCopy Is this non-list-initialization resulting from a /// list-initialization from {x} where x is the same /// type as the entity? static void TryConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, QualType DestArrayType, InitializationSequence &Sequence, bool IsListInit = false, bool IsInitListCopy = false) { assert(((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa(Args[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument."); InitListExpr *ILE = (IsListInit || IsInitListCopy) ? cast(Args[0]) : nullptr; MultiExprArg UnwrappedArgs = ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; // The type we're constructing needs to be complete. if (!S.isCompleteType(Kind.getLocation(), DestType)) { Sequence.setIncompleteTypeFailure(DestType); return; } // C++1z [dcl.init]p17: // - If the initializer expression is a prvalue and the cv-unqualified // version of the source type is the same class as the class of the // destination, the initializer expression is used to initialize the // destination object. // Per DR (no number yet), this does not apply when initializing a base // class or delegating to another constructor from a mem-initializer. // ObjC++: Lambda captured by the block in the lambda to block conversion // should avoid copy elision. if (S.getLangOpts().CPlusPlus1z && Entity.getKind() != InitializedEntity::EK_Base && Entity.getKind() != InitializedEntity::EK_Delegating && Entity.getKind() != InitializedEntity::EK_LambdaToBlockConversionBlockElement && UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { // Convert qualifications if necessary. Sequence.AddQualificationConversionStep(DestType, VK_RValue); if (ILE) Sequence.RewrapReferenceInitList(DestType, ILE); return; } const RecordType *DestRecordType = DestType->getAs(); assert(DestRecordType && "Constructor initialization requires record type"); CXXRecordDecl *DestRecordDecl = cast(DestRecordType->getDecl()); // Build the candidate set directly in the initialization sequence // structure, so that it will persist if we fail. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); // Determine whether we are allowed to call explicit constructors or // explicit conversion operators. bool AllowExplicit = Kind.AllowExplicit() || IsListInit; bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; // - Otherwise, if T is a class type, constructors are considered. The // applicable constructors are enumerated, and the best one is chosen // through overload resolution. DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); OverloadingResult Result = OR_No_Viable_Function; OverloadCandidateSet::iterator Best; bool AsInitializerList = false; // C++11 [over.match.list]p1, per DR1467: // When objects of non-aggregate type T are list-initialized, such that // 8.5.4 [dcl.init.list] specifies that overload resolution is performed // according to the rules in this section, overload resolution selects // the constructor in two phases: // // - Initially, the candidate functions are the initializer-list // constructors of the class T and the argument list consists of the // initializer list as a single argument. if (IsListInit) { AsInitializerList = true; // If the initializer list has no elements and T has a default constructor, // the first phase is omitted. if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor())) Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, CandidateSet, Ctors, Best, CopyInitialization, AllowExplicit, /*OnlyListConstructor=*/true, IsListInit); } // C++11 [over.match.list]p1: // - If no viable initializer-list constructor is found, overload resolution // is performed again, where the candidate functions are all the // constructors of the class T and the argument list consists of the // elements of the initializer list. if (Result == OR_No_Viable_Function) { AsInitializerList = false; Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, CandidateSet, Ctors, Best, CopyInitialization, AllowExplicit, /*OnlyListConstructors=*/false, IsListInit); } if (Result) { Sequence.SetOverloadFailure(IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed : InitializationSequence::FK_ConstructorOverloadFailed, Result); return; } // C++11 [dcl.init]p6: // If a program calls for the default initialization of an object // of a const-qualified type T, T shall be a class type with a // user-provided default constructor. // C++ core issue 253 proposal: // If the implicit default constructor initializes all subobjects, no // initializer should be required. // The 253 proposal is for example needed to process libstdc++ headers in 5.x. CXXConstructorDecl *CtorDecl = cast(Best->Function); if (Kind.getKind() == InitializationKind::IK_Default && Entity.getType().isConstQualified()) { if (!CtorDecl->getParent()->allowConstDefaultInit()) { if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); return; } } // C++11 [over.match.list]p1: // In copy-list-initialization, if an explicit constructor is chosen, the // initializer is ill-formed. if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); return; } // Add the constructor initialization step. Any cv-qualification conversion is // subsumed by the initialization. bool HadMultipleCandidates = (CandidateSet.size() > 1); Sequence.AddConstructorInitializationStep( Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, IsListInit | IsInitListCopy, AsInitializerList); } static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence) { if (S.Context.getCanonicalType(UnqualifiedSourceType) == S.Context.OverloadTy) { DeclAccessPair Found; bool HadMultipleCandidates = false; if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, UnqualifiedTargetType, false, Found, &HadMultipleCandidates)) { Sequence.AddAddressOverloadResolutionStep(Fn, Found, HadMultipleCandidates); SourceType = Fn->getType(); UnqualifiedSourceType = SourceType.getUnqualifiedType(); } else if (!UnqualifiedTargetType->isRecordType()) { Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); return true; } } return false; } static void TryReferenceInitializationCore(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, QualType cv1T1, QualType T1, Qualifiers T1Quals, QualType cv2T2, QualType T2, Qualifiers T2Quals, InitializationSequence &Sequence); static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList = nullptr); /// \brief Attempt list initialization of a reference. static void TryReferenceListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid) { // First, catch C++03 where this isn't possible. if (!S.getLangOpts().CPlusPlus11) { Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); return; } // Can't reference initialize a compound literal. if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); return; } QualType DestType = Entity.getType(); QualType cv1T1 = DestType->getAs()->getPointeeType(); Qualifiers T1Quals; QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); // Reference initialization via an initializer list works thus: // If the initializer list consists of a single element that is // reference-related to the referenced type, bind directly to that element // (possibly creating temporaries). // Otherwise, initialize a temporary with the initializer list and // bind to that. if (InitList->getNumInits() == 1) { Expr *Initializer = InitList->getInit(0); QualType cv2T2 = Initializer->getType(); Qualifiers T2Quals; QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); // If this fails, creating a temporary wouldn't work either. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, T1, Sequence)) return; SourceLocation DeclLoc = Initializer->getLocStart(); bool dummy1, dummy2, dummy3; Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1, dummy2, dummy3); if (RefRelationship >= Sema::Ref_Related) { // Try to bind the reference here. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, T1Quals, cv2T2, T2, T2Quals, Sequence); if (Sequence) Sequence.RewrapReferenceInitList(cv1T1, InitList); return; } // Update the initializer if we've resolved an overloaded function. if (Sequence.step_begin() != Sequence.step_end()) Sequence.RewrapReferenceInitList(cv1T1, InitList); } // Not reference-related. Create a temporary and bind to that. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); TryListInitialization(S, TempEntity, Kind, InitList, Sequence, TreatUnavailableAsInvalid); if (Sequence) { if (DestType->isRValueReferenceType() || (T1Quals.hasConst() && !T1Quals.hasVolatile())) Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); else Sequence.SetFailed( InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); } } /// \brief Attempt list initialization (C++0x [dcl.init.list]) static void TryListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid) { QualType DestType = Entity.getType(); // C++ doesn't allow scalar initialization with more than one argument. // But C99 complex numbers are scalars and it makes sense there. if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); return; } if (DestType->isReferenceType()) { TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, TreatUnavailableAsInvalid); return; } if (DestType->isRecordType() && !S.isCompleteType(InitList->getLocStart(), DestType)) { Sequence.setIncompleteTypeFailure(DestType); return; } // C++11 [dcl.init.list]p3, per DR1467: // - If T is a class type and the initializer list has a single element of // type cv U, where U is T or a class derived from T, the object is // initialized from that element (by copy-initialization for // copy-list-initialization, or by direct-initialization for // direct-list-initialization). // - Otherwise, if T is a character array and the initializer list has a // single element that is an appropriately-typed string literal // (8.5.2 [dcl.init.string]), initialization is performed as described // in that section. // - Otherwise, if T is an aggregate, [...] (continue below). if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { if (DestType->isRecordType()) { QualType InitType = InitList->getInit(0)->getType(); if (S.Context.hasSameUnqualifiedType(InitType, DestType) || S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) { Expr *InitListAsExpr = InitList; TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, DestType, Sequence, /*InitListSyntax*/false, /*IsInitListCopy*/true); return; } } if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { Expr *SubInit[1] = {InitList->getInit(0)}; if (!isa(DestAT) && IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { InitializationKind SubKind = Kind.getKind() == InitializationKind::IK_DirectList ? InitializationKind::CreateDirect(Kind.getLocation(), InitList->getLBraceLoc(), InitList->getRBraceLoc()) : Kind; Sequence.InitializeFrom(S, Entity, SubKind, SubInit, /*TopLevelOfInitList*/ true, TreatUnavailableAsInvalid); // TryStringLiteralInitialization() (in InitializeFrom()) will fail if // the element is not an appropriately-typed string literal, in which // case we should proceed as in C++11 (below). if (Sequence) { Sequence.RewrapReferenceInitList(Entity.getType(), InitList); return; } } } } // C++11 [dcl.init.list]p3: // - If T is an aggregate, aggregate initialization is performed. if ((DestType->isRecordType() && !DestType->isAggregateType()) || (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, nullptr))) { if (S.getLangOpts().CPlusPlus11) { // - Otherwise, if the initializer list has no elements and T is a // class type with a default constructor, the object is // value-initialized. if (InitList->getNumInits() == 0) { CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); if (RD->hasDefaultConstructor()) { TryValueInitialization(S, Entity, Kind, Sequence, InitList); return; } } // - Otherwise, if T is a specialization of std::initializer_list, // an initializer_list object constructed [...] if (TryInitializerListConstruction(S, InitList, DestType, Sequence, TreatUnavailableAsInvalid)) return; // - Otherwise, if T is a class type, constructors are considered. Expr *InitListAsExpr = InitList; TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, DestType, Sequence, /*InitListSyntax*/true); } else Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); return; } if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && InitList->getNumInits() == 1) { Expr *E = InitList->getInit(0); // - Otherwise, if T is an enumeration with a fixed underlying type, // the initializer-list has a single element v, and the initialization // is direct-list-initialization, the object is initialized with the // value T(v); if a narrowing conversion is required to convert v to // the underlying type of T, the program is ill-formed. auto *ET = DestType->getAs(); if (S.getLangOpts().CPlusPlus1z && Kind.getKind() == InitializationKind::IK_DirectList && ET && ET->getDecl()->isFixed() && !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && (E->getType()->isIntegralOrEnumerationType() || E->getType()->isFloatingType())) { // There are two ways that T(v) can work when T is an enumeration type. // If there is either an implicit conversion sequence from v to T or // a conversion function that can convert from v to T, then we use that. // Otherwise, if v is of integral, enumeration, or floating-point type, // it is converted to the enumeration type via its underlying type. // There is no overlap possible between these two cases (except when the // source value is already of the destination type), and the first // case is handled by the general case for single-element lists below. ImplicitConversionSequence ICS; ICS.setStandard(); ICS.Standard.setAsIdentityConversion(); if (!E->isRValue()) ICS.Standard.First = ICK_Lvalue_To_Rvalue; // If E is of a floating-point type, then the conversion is ill-formed // due to narrowing, but go through the motions in order to produce the // right diagnostic. ICS.Standard.Second = E->getType()->isFloatingType() ? ICK_Floating_Integral : ICK_Integral_Conversion; ICS.Standard.setFromType(E->getType()); ICS.Standard.setToType(0, E->getType()); ICS.Standard.setToType(1, DestType); ICS.Standard.setToType(2, DestType); Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), /*TopLevelOfInitList*/true); Sequence.RewrapReferenceInitList(Entity.getType(), InitList); return; } // - Otherwise, if the initializer list has a single element of type E // [...references are handled above...], the object or reference is // initialized from that element (by copy-initialization for // copy-list-initialization, or by direct-initialization for // direct-list-initialization); if a narrowing conversion is required // to convert the element to T, the program is ill-formed. // // Per core-24034, this is direct-initialization if we were performing // direct-list-initialization and copy-initialization otherwise. // We can't use InitListChecker for this, because it always performs // copy-initialization. This only matters if we might use an 'explicit' // conversion operator, so we only need to handle the cases where the source // is of record type. if (InitList->getInit(0)->getType()->isRecordType()) { InitializationKind SubKind = Kind.getKind() == InitializationKind::IK_DirectList ? InitializationKind::CreateDirect(Kind.getLocation(), InitList->getLBraceLoc(), InitList->getRBraceLoc()) : Kind; Expr *SubInit[1] = { InitList->getInit(0) }; Sequence.InitializeFrom(S, Entity, SubKind, SubInit, /*TopLevelOfInitList*/true, TreatUnavailableAsInvalid); if (Sequence) Sequence.RewrapReferenceInitList(Entity.getType(), InitList); return; } } InitListChecker CheckInitList(S, Entity, InitList, DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); if (CheckInitList.HadError()) { Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); return; } // Add the list initialization step with the built init list. Sequence.AddListInitializationStep(DestType); } /// \brief Try a reference initialization that involves calling a conversion /// function. static OverloadingResult TryRefInitWithConversionFunction( Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, bool AllowRValues, bool IsLValueRef, InitializationSequence &Sequence) { QualType DestType = Entity.getType(); QualType cv1T1 = DestType->getAs()->getPointeeType(); QualType T1 = cv1T1.getUnqualifiedType(); QualType cv2T2 = Initializer->getType(); QualType T2 = cv2T2.getUnqualifiedType(); bool DerivedToBase; bool ObjCConversion; bool ObjCLifetimeConversion; assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion) && "Must have incompatible references when binding via conversion"); (void)DerivedToBase; (void)ObjCConversion; (void)ObjCLifetimeConversion; // Build the candidate set directly in the initialization sequence // structure, so that it will persist if we fail. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); CandidateSet.clear(); // Determine whether we are allowed to call explicit constructors or // explicit conversion operators. bool AllowExplicit = Kind.AllowExplicit(); bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); const RecordType *T1RecordType = nullptr; if (AllowRValues && (T1RecordType = T1->getAs()) && S.isCompleteType(Kind.getLocation(), T1)) { // The type we're converting to is a class type. Enumerate its constructors // to see if there is a suitable conversion. CXXRecordDecl *T1RecordDecl = cast(T1RecordType->getDecl()); for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { auto Info = getConstructorInfo(D); if (!Info.Constructor) continue; if (!Info.Constructor->isInvalidDecl() && Info.Constructor->isConvertingConstructor(AllowExplicit)) { if (Info.ConstructorTmpl) S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, /*SuppressUserConversions=*/true); else S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, /*SuppressUserConversions=*/true); } } } if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) return OR_No_Viable_Function; const RecordType *T2RecordType = nullptr; if ((T2RecordType = T2->getAs()) && S.isCompleteType(Kind.getLocation(), T2)) { // The type we're converting from is a class type, enumerate its conversion // functions. CXXRecordDecl *T2RecordDecl = cast(T2RecordType->getDecl()); const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { NamedDecl *D = *I; CXXRecordDecl *ActingDC = cast(D->getDeclContext()); if (isa(D)) D = cast(D)->getTargetDecl(); FunctionTemplateDecl *ConvTemplate = dyn_cast(D); CXXConversionDecl *Conv; if (ConvTemplate) Conv = cast(ConvTemplate->getTemplatedDecl()); else Conv = cast(D); // If the conversion function doesn't return a reference type, // it can't be considered for this conversion unless we're allowed to // consider rvalues. // FIXME: Do we need to make sure that we only consider conversion // candidates with reference-compatible results? That might be needed to // break recursion. if ((AllowExplicitConvs || !Conv->isExplicit()) && (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ if (ConvTemplate) S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, /*AllowObjCConversionOnExplicit=*/ false); else S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, /*AllowObjCConversionOnExplicit=*/false); } } } if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) return OR_No_Viable_Function; SourceLocation DeclLoc = Initializer->getLocStart(); // Perform overload resolution. If it fails, return the failed result. OverloadCandidateSet::iterator Best; if (OverloadingResult Result = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) return Result; FunctionDecl *Function = Best->Function; // This is the overload that will be used for this initialization step if we // use this initialization. Mark it as referenced. Function->setReferenced(); // Compute the returned type and value kind of the conversion. QualType cv3T3; if (isa(Function)) cv3T3 = Function->getReturnType(); else cv3T3 = T1; ExprValueKind VK = VK_RValue; if (cv3T3->isLValueReferenceType()) VK = VK_LValue; else if (const auto *RRef = cv3T3->getAs()) VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; cv3T3 = cv3T3.getNonLValueExprType(S.Context); // Add the user-defined conversion step. bool HadMultipleCandidates = (CandidateSet.size() > 1); Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, HadMultipleCandidates); // Determine whether we'll need to perform derived-to-base adjustments or // other conversions. bool NewDerivedToBase = false; bool NewObjCConversion = false; bool NewObjCLifetimeConversion = false; Sema::ReferenceCompareResult NewRefRelationship = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, NewDerivedToBase, NewObjCConversion, NewObjCLifetimeConversion); // Add the final conversion sequence, if necessary. if (NewRefRelationship == Sema::Ref_Incompatible) { assert(!isa(Function) && "should not have conversion after constructor"); ImplicitConversionSequence ICS; ICS.setStandard(); ICS.Standard = Best->FinalConversion; Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); // Every implicit conversion results in a prvalue, except for a glvalue // derived-to-base conversion, which we handle below. cv3T3 = ICS.Standard.getToType(2); VK = VK_RValue; } // If the converted initializer is a prvalue, its type T4 is adjusted to // type "cv1 T4" and the temporary materialization conversion is applied. // // We adjust the cv-qualifications to match the reference regardless of // whether we have a prvalue so that the AST records the change. In this // case, T4 is "cv3 T3". QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) Sequence.AddQualificationConversionStep(cv1T4, VK); Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); VK = IsLValueRef ? VK_LValue : VK_XValue; if (NewDerivedToBase) Sequence.AddDerivedToBaseCastStep(cv1T1, VK); else if (NewObjCConversion) Sequence.AddObjCObjectConversionStep(cv1T1); return OR_Success; } static void CheckCXX98CompatAccessibleCopy(Sema &S, const InitializedEntity &Entity, Expr *CurInitExpr); /// \brief Attempt reference initialization (C++0x [dcl.init.ref]) static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence) { QualType DestType = Entity.getType(); QualType cv1T1 = DestType->getAs()->getPointeeType(); Qualifiers T1Quals; QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); QualType cv2T2 = Initializer->getType(); Qualifiers T2Quals; QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); // If the initializer is the address of an overloaded function, try // to resolve the overloaded function. If all goes well, T2 is the // type of the resulting function. if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, T1, Sequence)) return; // Delegate everything else to a subfunction. TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, T1Quals, cv2T2, T2, T2Quals, Sequence); } /// Determine whether an expression is a non-referenceable glvalue (one to /// which a reference can never bind). Attemting to bind a reference to /// such a glvalue will always create a temporary. static bool isNonReferenceableGLValue(Expr *E) { return E->refersToBitField() || E->refersToVectorElement(); } /// \brief Reference initialization without resolving overloaded functions. static void TryReferenceInitializationCore(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, QualType cv1T1, QualType T1, Qualifiers T1Quals, QualType cv2T2, QualType T2, Qualifiers T2Quals, InitializationSequence &Sequence) { QualType DestType = Entity.getType(); SourceLocation DeclLoc = Initializer->getLocStart(); // Compute some basic properties of the types and the initializer. bool isLValueRef = DestType->isLValueReferenceType(); bool isRValueRef = !isLValueRef; bool DerivedToBase = false; bool ObjCConversion = false; bool ObjCLifetimeConversion = false; Expr::Classification InitCategory = Initializer->Classify(S.Context); Sema::ReferenceCompareResult RefRelationship = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion); // C++0x [dcl.init.ref]p5: // A reference to type "cv1 T1" is initialized by an expression of type // "cv2 T2" as follows: // // - If the reference is an lvalue reference and the initializer // expression // Note the analogous bullet points for rvalue refs to functions. Because // there are no function rvalues in C++, rvalue refs to functions are treated // like lvalue refs. OverloadingResult ConvOvlResult = OR_Success; bool T1Function = T1->isFunctionType(); if (isLValueRef || T1Function) { if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && (RefRelationship == Sema::Ref_Compatible || (Kind.isCStyleOrFunctionalCast() && RefRelationship == Sema::Ref_Related))) { // - is an lvalue (but is not a bit-field), and "cv1 T1" is // reference-compatible with "cv2 T2," or if (T1Quals != T2Quals) // Convert to cv1 T2. This should only add qualifiers unless this is a // c-style cast. The removal of qualifiers in that case notionally // happens after the reference binding, but that doesn't matter. Sequence.AddQualificationConversionStep( S.Context.getQualifiedType(T2, T1Quals), Initializer->getValueKind()); if (DerivedToBase) Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); else if (ObjCConversion) Sequence.AddObjCObjectConversionStep(cv1T1); // We only create a temporary here when binding a reference to a // bit-field or vector element. Those cases are't supposed to be // handled by this bullet, but the outcome is the same either way. Sequence.AddReferenceBindingStep(cv1T1, false); return; } // - has a class type (i.e., T2 is a class type), where T1 is not // reference-related to T2, and can be implicitly converted to an // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible // with "cv3 T3" (this conversion is selected by enumerating the // applicable conversion functions (13.3.1.6) and choosing the best // one through overload resolution (13.3)), // If we have an rvalue ref to function type here, the rhs must be // an rvalue. DR1287 removed the "implicitly" here. if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && (isLValueRef || InitCategory.isRValue())) { ConvOvlResult = TryRefInitWithConversionFunction( S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, /*IsLValueRef*/ isLValueRef, Sequence); if (ConvOvlResult == OR_Success) return; if (ConvOvlResult != OR_No_Viable_Function) Sequence.SetOverloadFailure( InitializationSequence::FK_ReferenceInitOverloadFailed, ConvOvlResult); } } // - Otherwise, the reference shall be an lvalue reference to a // non-volatile const type (i.e., cv1 shall be const), or the reference // shall be an rvalue reference. if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) { if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) Sequence.SetOverloadFailure( InitializationSequence::FK_ReferenceInitOverloadFailed, ConvOvlResult); else if (!InitCategory.isLValue()) Sequence.SetFailed( InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); else { InitializationSequence::FailureKind FK; switch (RefRelationship) { case Sema::Ref_Compatible: if (Initializer->refersToBitField()) FK = InitializationSequence:: FK_NonConstLValueReferenceBindingToBitfield; else if (Initializer->refersToVectorElement()) FK = InitializationSequence:: FK_NonConstLValueReferenceBindingToVectorElement; else llvm_unreachable("unexpected kind of compatible initializer"); break; case Sema::Ref_Related: FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; break; case Sema::Ref_Incompatible: FK = InitializationSequence:: FK_NonConstLValueReferenceBindingToUnrelated; break; } Sequence.SetFailed(FK); } return; } // - If the initializer expression // - is an // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or // [1z] rvalue (but not a bit-field) or // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" // // Note: functions are handled above and below rather than here... if (!T1Function && (RefRelationship == Sema::Ref_Compatible || (Kind.isCStyleOrFunctionalCast() && RefRelationship == Sema::Ref_Related)) && ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || (InitCategory.isPRValue() && (S.getLangOpts().CPlusPlus1z || T2->isRecordType() || T2->isArrayType())))) { ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; if (InitCategory.isPRValue() && T2->isRecordType()) { // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the // compiler the freedom to perform a copy here or bind to the // object, while C++0x requires that we bind directly to the // object. Hence, we always bind to the object without making an // extra copy. However, in C++03 requires that we check for the // presence of a suitable copy constructor: // // The constructor that would be used to make the copy shall // be callable whether or not the copy is actually done. if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) Sequence.AddExtraneousCopyToTemporary(cv2T2); else if (S.getLangOpts().CPlusPlus11) CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); } // C++1z [dcl.init.ref]/5.2.1.2: // If the converted initializer is a prvalue, its type T4 is adjusted // to type "cv1 T4" and the temporary materialization conversion is // applied. QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals); if (T1Quals != T2Quals) Sequence.AddQualificationConversionStep(cv1T4, ValueKind); Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); ValueKind = isLValueRef ? VK_LValue : VK_XValue; // In any case, the reference is bound to the resulting glvalue (or to // an appropriate base class subobject). if (DerivedToBase) Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); else if (ObjCConversion) Sequence.AddObjCObjectConversionStep(cv1T1); return; } // - has a class type (i.e., T2 is a class type), where T1 is not // reference-related to T2, and can be implicitly converted to an // xvalue, class prvalue, or function lvalue of type "cv3 T3", // where "cv1 T1" is reference-compatible with "cv3 T3", // // DR1287 removes the "implicitly" here. if (T2->isRecordType()) { if (RefRelationship == Sema::Ref_Incompatible) { ConvOvlResult = TryRefInitWithConversionFunction( S, Entity, Kind, Initializer, /*AllowRValues*/ true, /*IsLValueRef*/ isLValueRef, Sequence); if (ConvOvlResult) Sequence.SetOverloadFailure( InitializationSequence::FK_ReferenceInitOverloadFailed, ConvOvlResult); return; } if (RefRelationship == Sema::Ref_Compatible && isRValueRef && InitCategory.isLValue()) { Sequence.SetFailed( InitializationSequence::FK_RValueReferenceBindingToLValue); return; } Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); return; } // - Otherwise, a temporary of type "cv1 T1" is created and initialized // from the initializer expression using the rules for a non-reference // copy-initialization (8.5). The reference is then bound to the // temporary. [...] InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); // FIXME: Why do we use an implicit conversion here rather than trying // copy-initialization? ImplicitConversionSequence ICS = S.TryImplicitConversion(Initializer, TempEntity.getType(), /*SuppressUserConversions=*/false, /*AllowExplicit=*/false, /*FIXME:InOverloadResolution=*/false, /*CStyle=*/Kind.isCStyleOrFunctionalCast(), /*AllowObjCWritebackConversion=*/false); if (ICS.isBad()) { // FIXME: Use the conversion function set stored in ICS to turn // this into an overloading ambiguity diagnostic. However, we need // to keep that set as an OverloadCandidateSet rather than as some // other kind of set. if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) Sequence.SetOverloadFailure( InitializationSequence::FK_ReferenceInitOverloadFailed, ConvOvlResult); else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); else Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); return; } else { Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); } // [...] If T1 is reference-related to T2, cv1 must be the // same cv-qualification as, or greater cv-qualification // than, cv2; otherwise, the program is ill-formed. unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); if (RefRelationship == Sema::Ref_Related && (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); return; } // [...] If T1 is reference-related to T2 and the reference is an rvalue // reference, the initializer expression shall not be an lvalue. if (RefRelationship >= Sema::Ref_Related && !isLValueRef && InitCategory.isLValue()) { Sequence.SetFailed( InitializationSequence::FK_RValueReferenceBindingToLValue); return; } Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); } /// \brief Attempt character array initialization from a string literal /// (C++ [dcl.init.string], C99 6.7.8). static void TryStringLiteralInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence) { Sequence.AddStringInitStep(Entity.getType()); } /// \brief Attempt value initialization (C++ [dcl.init]p7). static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList) { assert((!InitList || InitList->getNumInits() == 0) && "Shouldn't use value-init for non-empty init lists"); // C++98 [dcl.init]p5, C++11 [dcl.init]p7: // // To value-initialize an object of type T means: QualType T = Entity.getType(); // -- if T is an array type, then each element is value-initialized; T = S.Context.getBaseElementType(T); if (const RecordType *RT = T->getAs()) { if (CXXRecordDecl *ClassDecl = dyn_cast(RT->getDecl())) { bool NeedZeroInitialization = true; // C++98: // -- if T is a class type (clause 9) with a user-declared constructor // (12.1), then the default constructor for T is called (and the // initialization is ill-formed if T has no accessible default // constructor); // C++11: // -- if T is a class type (clause 9) with either no default constructor // (12.1 [class.ctor]) or a default constructor that is user-provided // or deleted, then the object is default-initialized; // // Note that the C++11 rule is the same as the C++98 rule if there are no // defaulted or deleted constructors, so we just use it unconditionally. CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) NeedZeroInitialization = false; // -- if T is a (possibly cv-qualified) non-union class type without a // user-provided or deleted default constructor, then the object is // zero-initialized and, if T has a non-trivial default constructor, // default-initialized; // The 'non-union' here was removed by DR1502. The 'non-trivial default // constructor' part was removed by DR1507. if (NeedZeroInitialization) Sequence.AddZeroInitializationStep(Entity.getType()); // C++03: // -- if T is a non-union class type without a user-declared constructor, // then every non-static data member and base class component of T is // value-initialized; // [...] A program that calls for [...] value-initialization of an // entity of reference type is ill-formed. // // C++11 doesn't need this handling, because value-initialization does not // occur recursively there, and the implicit default constructor is // defined as deleted in the problematic cases. if (!S.getLangOpts().CPlusPlus11 && ClassDecl->hasUninitializedReferenceMember()) { Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); return; } // If this is list-value-initialization, pass the empty init list on when // building the constructor call. This affects the semantics of a few // things (such as whether an explicit default constructor can be called). Expr *InitListAsExpr = InitList; MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); bool InitListSyntax = InitList; // FIXME: Instead of creating a CXXConstructExpr of array type here, // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. return TryConstructorInitialization( S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); } } Sequence.AddZeroInitializationStep(Entity.getType()); } /// \brief Attempt default initialization (C++ [dcl.init]p6). static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence) { assert(Kind.getKind() == InitializationKind::IK_Default); // C++ [dcl.init]p6: // To default-initialize an object of type T means: // - if T is an array type, each element is default-initialized; QualType DestType = S.Context.getBaseElementType(Entity.getType()); // - if T is a (possibly cv-qualified) class type (Clause 9), the default // constructor for T is called (and the initialization is ill-formed if // T has no accessible default constructor); if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { TryConstructorInitialization(S, Entity, Kind, None, DestType, Entity.getType(), Sequence); return; } // - otherwise, no initialization is performed. // If a program calls for the default initialization of an object of // a const-qualified type T, T shall be a class type with a user-provided // default constructor. if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); return; } // If the destination type has a lifetime property, zero-initialize it. if (DestType.getQualifiers().hasObjCLifetime()) { Sequence.AddZeroInitializationStep(Entity.getType()); return; } } /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), /// which enumerates all conversion functions and performs overload resolution /// to select the best. static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList) { assert(!DestType->isReferenceType() && "References are handled elsewhere"); QualType SourceType = Initializer->getType(); assert((DestType->isRecordType() || SourceType->isRecordType()) && "Must have a class type to perform a user-defined conversion"); // Build the candidate set directly in the initialization sequence // structure, so that it will persist if we fail. OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); CandidateSet.clear(); // Determine whether we are allowed to call explicit constructors or // explicit conversion operators. bool AllowExplicit = Kind.AllowExplicit(); if (const RecordType *DestRecordType = DestType->getAs()) { // The type we're converting to is a class type. Enumerate its constructors // to see if there is a suitable conversion. CXXRecordDecl *DestRecordDecl = cast(DestRecordType->getDecl()); // Try to complete the type we're converting to. if (S.isCompleteType(Kind.getLocation(), DestType)) { for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { auto Info = getConstructorInfo(D); if (!Info.Constructor) continue; if (!Info.Constructor->isInvalidDecl() && Info.Constructor->isConvertingConstructor(AllowExplicit)) { if (Info.ConstructorTmpl) S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, /*SuppressUserConversions=*/true); else S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, /*SuppressUserConversions=*/true); } } } } SourceLocation DeclLoc = Initializer->getLocStart(); if (const RecordType *SourceRecordType = SourceType->getAs()) { // The type we're converting from is a class type, enumerate its conversion // functions. // We can only enumerate the conversion functions for a complete type; if // the type isn't complete, simply skip this step. if (S.isCompleteType(DeclLoc, SourceType)) { CXXRecordDecl *SourceRecordDecl = cast(SourceRecordType->getDecl()); const auto &Conversions = SourceRecordDecl->getVisibleConversionFunctions(); for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { NamedDecl *D = *I; CXXRecordDecl *ActingDC = cast(D->getDeclContext()); if (isa(D)) D = cast(D)->getTargetDecl(); FunctionTemplateDecl *ConvTemplate = dyn_cast(D); CXXConversionDecl *Conv; if (ConvTemplate) Conv = cast(ConvTemplate->getTemplatedDecl()); else Conv = cast(D); if (AllowExplicit || !Conv->isExplicit()) { if (ConvTemplate) S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, AllowExplicit); else S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, AllowExplicit); } } } } // Perform overload resolution. If it fails, return the failed result. OverloadCandidateSet::iterator Best; if (OverloadingResult Result = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { Sequence.SetOverloadFailure( InitializationSequence::FK_UserConversionOverloadFailed, Result); return; } FunctionDecl *Function = Best->Function; Function->setReferenced(); bool HadMultipleCandidates = (CandidateSet.size() > 1); if (isa(Function)) { // Add the user-defined conversion step. Any cv-qualification conversion is // subsumed by the initialization. Per DR5, the created temporary is of the // cv-unqualified type of the destination. Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType.getUnqualifiedType(), HadMultipleCandidates); // C++14 and before: // - if the function is a constructor, the call initializes a temporary // of the cv-unqualified version of the destination type. The [...] // temporary [...] is then used to direct-initialize, according to the // rules above, the object that is the destination of the // copy-initialization. // Note that this just performs a simple object copy from the temporary. // // C++1z: // - if the function is a constructor, the call is a prvalue of the // cv-unqualified version of the destination type whose return object // is initialized by the constructor. The call is used to // direct-initialize, according to the rules above, the object that // is the destination of the copy-initialization. // Therefore we need to do nothing further. // // FIXME: Mark this copy as extraneous. if (!S.getLangOpts().CPlusPlus1z) Sequence.AddFinalCopy(DestType); else if (DestType.hasQualifiers()) Sequence.AddQualificationConversionStep(DestType, VK_RValue); return; } // Add the user-defined conversion step that calls the conversion function. QualType ConvType = Function->getCallResultType(); Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, HadMultipleCandidates); if (ConvType->getAs()) { // The call is used to direct-initialize [...] the object that is the // destination of the copy-initialization. // // In C++1z, this does not call a constructor if we enter /17.6.1: // - If the initializer expression is a prvalue and the cv-unqualified // version of the source type is the same as the class of the // destination [... do not make an extra copy] // // FIXME: Mark this copy as extraneous. if (!S.getLangOpts().CPlusPlus1z || Function->getReturnType()->isReferenceType() || !S.Context.hasSameUnqualifiedType(ConvType, DestType)) Sequence.AddFinalCopy(DestType); else if (!S.Context.hasSameType(ConvType, DestType)) Sequence.AddQualificationConversionStep(DestType, VK_RValue); return; } // If the conversion following the call to the conversion function // is interesting, add it as a separate step. if (Best->FinalConversion.First || Best->FinalConversion.Second || Best->FinalConversion.Third) { ImplicitConversionSequence ICS; ICS.setStandard(); ICS.Standard = Best->FinalConversion; Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); } } /// An egregious hack for compatibility with libstdc++-4.2: in , /// a function with a pointer return type contains a 'return false;' statement. /// In C++11, 'false' is not a null pointer, so this breaks the build of any /// code using that header. /// /// Work around this by treating 'return false;' as zero-initializing the result /// if it's used in a pointer-returning function in a system header. static bool isLibstdcxxPointerReturnFalseHack(Sema &S, const InitializedEntity &Entity, const Expr *Init) { return S.getLangOpts().CPlusPlus11 && Entity.getKind() == InitializedEntity::EK_Result && Entity.getType()->isPointerType() && isa(Init) && !cast(Init)->getValue() && S.getSourceManager().isInSystemHeader(Init->getExprLoc()); } /// The non-zero enum values here are indexes into diagnostic alternatives. enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; /// Determines whether this expression is an acceptable ICR source. static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess) { // Skip parens. e = e->IgnoreParens(); // Skip address-of nodes. if (UnaryOperator *op = dyn_cast(e)) { if (op->getOpcode() == UO_AddrOf) return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, isWeakAccess); // Skip certain casts. } else if (CastExpr *ce = dyn_cast(e)) { switch (ce->getCastKind()) { case CK_Dependent: case CK_BitCast: case CK_LValueBitCast: case CK_NoOp: return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); case CK_ArrayToPointerDecay: return IIK_nonscalar; case CK_NullToPointer: return IIK_okay; default: break; } // If we have a declaration reference, it had better be a local variable. } else if (isa(e)) { // set isWeakAccess to true, to mean that there will be an implicit // load which requires a cleanup. if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) isWeakAccess = true; if (!isAddressOf) return IIK_nonlocal; VarDecl *var = dyn_cast(cast(e)->getDecl()); if (!var) return IIK_nonlocal; return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); // If we have a conditional operator, check both sides. } else if (ConditionalOperator *cond = dyn_cast(e)) { if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, isWeakAccess)) return iik; return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); // These are never scalar. } else if (isa(e)) { return IIK_nonscalar; // Otherwise, it needs to be a null pointer constant. } else { return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) ? IIK_okay : IIK_nonlocal); } return IIK_nonlocal; } /// Check whether the given expression is a valid operand for an /// indirect copy/restore. static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { assert(src->isRValue()); bool isWeakAccess = false; InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); // If isWeakAccess to true, there will be an implicit // load which requires a cleanup. if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) S.Cleanup.setExprNeedsCleanups(true); if (iik == IIK_okay) return; S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) << ((unsigned) iik - 1) // shift index into diagnostic explanations << src->getSourceRange(); } /// \brief Determine whether we have compatible array types for the /// purposes of GNU by-copy array initialization. static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, const ArrayType *Source) { // If the source and destination array types are equivalent, we're // done. if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) return true; // Make sure that the element types are the same. if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) return false; // The only mismatch we allow is when the destination is an // incomplete array type and the source is a constant array type. return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); } static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer) { bool ArrayDecay = false; QualType ArgType = Initializer->getType(); QualType ArgPointee; if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { ArrayDecay = true; ArgPointee = ArgArrayType->getElementType(); ArgType = S.Context.getPointerType(ArgPointee); } // Handle write-back conversion. QualType ConvertedArgType; if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), ConvertedArgType)) return false; // We should copy unless we're passing to an argument explicitly // marked 'out'. bool ShouldCopy = true; if (ParmVarDecl *param = cast_or_null(Entity.getDecl())) ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); // Do we need an lvalue conversion? if (ArrayDecay || Initializer->isGLValue()) { ImplicitConversionSequence ICS; ICS.setStandard(); ICS.Standard.setAsIdentityConversion(); QualType ResultType; if (ArrayDecay) { ICS.Standard.First = ICK_Array_To_Pointer; ResultType = S.Context.getPointerType(ArgPointee); } else { ICS.Standard.First = ICK_Lvalue_To_Rvalue; ResultType = Initializer->getType().getNonLValueExprType(S.Context); } Sequence.AddConversionSequenceStep(ICS, ResultType); } Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); return true; } static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer) { if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || (!Initializer->isIntegerConstantExpr(S.Context) && !Initializer->getType()->isSamplerT())) return false; Sequence.AddOCLSamplerInitStep(DestType); return true; } // // OpenCL 1.2 spec, s6.12.10 // // The event argument can also be used to associate the // async_work_group_copy with a previous async copy allowing // an event to be shared by multiple async copies; otherwise // event should be zero. // static bool TryOCLZeroEventInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer) { if (!S.getLangOpts().OpenCL || !DestType->isEventT() || !Initializer->isIntegerConstantExpr(S.getASTContext()) || (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0)) return false; Sequence.AddOCLZeroEventStep(DestType); return true; } static bool TryOCLZeroQueueInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer) { if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 || !DestType->isQueueT() || !Initializer->isIntegerConstantExpr(S.getASTContext()) || (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0)) return false; Sequence.AddOCLZeroQueueStep(DestType); return true; } InitializationSequence::InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, TreatUnavailableAsInvalid); } /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the /// address of that function, this returns true. Otherwise, it returns false. static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { auto *DRE = dyn_cast(E); if (!DRE || !isa(DRE->getDecl())) return false; return !S.checkAddressOfFunctionIsAvailable( cast(DRE->getDecl())); } /// Determine whether we can perform an elementwise array copy for this kind /// of entity. static bool canPerformArrayCopy(const InitializedEntity &Entity) { switch (Entity.getKind()) { case InitializedEntity::EK_LambdaCapture: // C++ [expr.prim.lambda]p24: // For array members, the array elements are direct-initialized in // increasing subscript order. return true; case InitializedEntity::EK_Variable: // C++ [dcl.decomp]p1: // [...] each element is copy-initialized or direct-initialized from the // corresponding element of the assignment-expression [...] return isa(Entity.getDecl()); case InitializedEntity::EK_Member: // C++ [class.copy.ctor]p14: // - if the member is an array, each element is direct-initialized with // the corresponding subobject of x return Entity.isImplicitMemberInitializer(); case InitializedEntity::EK_ArrayElement: // All the above cases are intended to apply recursively, even though none // of them actually say that. if (auto *E = Entity.getParent()) return canPerformArrayCopy(*E); break; default: break; } return false; } void InitializationSequence::InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) { ASTContext &Context = S.Context; // Eliminate non-overload placeholder types in the arguments. We // need to do this before checking whether types are dependent // because lowering a pseudo-object expression might well give us // something of dependent type. for (unsigned I = 0, E = Args.size(); I != E; ++I) if (Args[I]->getType()->isNonOverloadPlaceholderType()) { // FIXME: should we be doing this here? ExprResult result = S.CheckPlaceholderExpr(Args[I]); if (result.isInvalid()) { SetFailed(FK_PlaceholderType); return; } Args[I] = result.get(); } // C++0x [dcl.init]p16: // The semantics of initializers are as follows. The destination type is // the type of the object or reference being initialized and the source // type is the type of the initializer expression. The source type is not // defined when the initializer is a braced-init-list or when it is a // parenthesized list of expressions. QualType DestType = Entity.getType(); if (DestType->isDependentType() || Expr::hasAnyTypeDependentArguments(Args)) { SequenceKind = DependentSequence; return; } // Almost everything is a normal sequence. setSequenceKind(NormalSequence); QualType SourceType; Expr *Initializer = nullptr; if (Args.size() == 1) { Initializer = Args[0]; if (S.getLangOpts().ObjC1) { if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(), DestType, Initializer->getType(), Initializer) || S.ConversionToObjCStringLiteralCheck(DestType, Initializer)) Args[0] = Initializer; } if (!isa(Initializer)) SourceType = Initializer->getType(); } // - If the initializer is a (non-parenthesized) braced-init-list, the // object is list-initialized (8.5.4). if (Kind.getKind() != InitializationKind::IK_Direct) { if (InitListExpr *InitList = dyn_cast_or_null(Initializer)) { TryListInitialization(S, Entity, Kind, InitList, *this, TreatUnavailableAsInvalid); return; } } // - If the destination type is a reference type, see 8.5.3. if (DestType->isReferenceType()) { // C++0x [dcl.init.ref]p1: // A variable declared to be a T& or T&&, that is, "reference to type T" // (8.3.2), shall be initialized by an object, or function, of type T or // by an object that can be converted into a T. // (Therefore, multiple arguments are not permitted.) if (Args.size() != 1) SetFailed(FK_TooManyInitsForReference); // C++17 [dcl.init.ref]p5: // A reference [...] is initialized by an expression [...] as follows: // If the initializer is not an expression, presumably we should reject, // but the standard fails to actually say so. else if (isa(Args[0])) SetFailed(FK_ParenthesizedListInitForReference); else TryReferenceInitialization(S, Entity, Kind, Args[0], *this); return; } // - If the initializer is (), the object is value-initialized. if (Kind.getKind() == InitializationKind::IK_Value || (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { TryValueInitialization(S, Entity, Kind, *this); return; } // Handle default initialization. if (Kind.getKind() == InitializationKind::IK_Default) { TryDefaultInitialization(S, Entity, Kind, *this); return; } // - If the destination type is an array of characters, an array of // char16_t, an array of char32_t, or an array of wchar_t, and the // initializer is a string literal, see 8.5.2. // - Otherwise, if the destination type is an array, the program is // ill-formed. if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { if (Initializer && isa(DestAT)) { SetFailed(FK_VariableLengthArrayHasInitializer); return; } if (Initializer) { switch (IsStringInit(Initializer, DestAT, Context)) { case SIF_None: TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); return; case SIF_NarrowStringIntoWideChar: SetFailed(FK_NarrowStringIntoWideCharArray); return; case SIF_WideStringIntoChar: SetFailed(FK_WideStringIntoCharArray); return; case SIF_IncompatWideStringIntoWideChar: SetFailed(FK_IncompatWideStringIntoWideChar); return; case SIF_Other: break; } } // Some kinds of initialization permit an array to be initialized from // another array of the same type, and perform elementwise initialization. if (Initializer && isa(DestAT) && S.Context.hasSameUnqualifiedType(Initializer->getType(), Entity.getType()) && canPerformArrayCopy(Entity)) { // If source is a prvalue, use it directly. if (Initializer->getValueKind() == VK_RValue) { AddArrayInitStep(DestType, /*IsGNUExtension*/false); return; } // Emit element-at-a-time copy loop. InitializedEntity Element = InitializedEntity::InitializeElement(S.Context, 0, Entity); QualType InitEltT = Context.getAsArrayType(Initializer->getType())->getElementType(); OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(), Initializer->getObjectKind()); Expr *OVEAsExpr = &OVE; InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, TreatUnavailableAsInvalid); if (!Failed()) AddArrayInitLoopStep(Entity.getType(), InitEltT); return; } // Note: as an GNU C extension, we allow initialization of an // array from a compound literal that creates an array of the same // type, so long as the initializer has no side effects. if (!S.getLangOpts().CPlusPlus && Initializer && isa(Initializer->IgnoreParens()) && Initializer->getType()->isArrayType()) { const ArrayType *SourceAT = Context.getAsArrayType(Initializer->getType()); if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) SetFailed(FK_ArrayTypeMismatch); else if (Initializer->HasSideEffects(S.Context)) SetFailed(FK_NonConstantArrayInit); else { AddArrayInitStep(DestType, /*IsGNUExtension*/true); } } // Note: as a GNU C++ extension, we allow list-initialization of a // class member of array type from a parenthesized initializer list. else if (S.getLangOpts().CPlusPlus && Entity.getKind() == InitializedEntity::EK_Member && Initializer && isa(Initializer)) { TryListInitialization(S, Entity, Kind, cast(Initializer), *this, TreatUnavailableAsInvalid); AddParenthesizedArrayInitStep(DestType); } else if (DestAT->getElementType()->isCharType()) SetFailed(FK_ArrayNeedsInitListOrStringLiteral); else if (IsWideCharCompatible(DestAT->getElementType(), Context)) SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); else SetFailed(FK_ArrayNeedsInitList); return; } // Determine whether we should consider writeback conversions for // Objective-C ARC. bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && Entity.isParameterKind(); // We're at the end of the line for C: it's either a write-back conversion // or it's a C assignment. There's no need to check anything else. if (!S.getLangOpts().CPlusPlus) { // If allowed, check whether this is an Objective-C writeback conversion. if (allowObjCWritebackConversion && tryObjCWritebackConversion(S, *this, Entity, Initializer)) { return; } if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) return; if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer)) return; if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer)) return; // Handle initialization in C AddCAssignmentStep(DestType); MaybeProduceObjCObject(S, *this, Entity); return; } assert(S.getLangOpts().CPlusPlus); // - If the destination type is a (possibly cv-qualified) class type: if (DestType->isRecordType()) { // - If the initialization is direct-initialization, or if it is // copy-initialization where the cv-unqualified version of the // source type is the same class as, or a derived class of, the // class of the destination, constructors are considered. [...] if (Kind.getKind() == InitializationKind::IK_Direct || (Kind.getKind() == InitializationKind::IK_Copy && (Context.hasSameUnqualifiedType(SourceType, DestType) || S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType)))) TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType, *this); // - Otherwise (i.e., for the remaining copy-initialization cases), // user-defined conversion sequences that can convert from the source // type to the destination type or (when a conversion function is // used) to a derived class thereof are enumerated as described in // 13.3.1.4, and the best one is chosen through overload resolution // (13.3). else TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, TopLevelOfInitList); return; } assert(Args.size() >= 1 && "Zero-argument case handled above"); // The remaining cases all need a source type. if (Args.size() > 1) { SetFailed(FK_TooManyInitsForScalar); return; } else if (isa(Args[0])) { SetFailed(FK_ParenthesizedListInitForScalar); return; } // - Otherwise, if the source type is a (possibly cv-qualified) class // type, conversion functions are considered. if (!SourceType.isNull() && SourceType->isRecordType()) { // For a conversion to _Atomic(T) from either T or a class type derived // from T, initialize the T object then convert to _Atomic type. bool NeedAtomicConversion = false; if (const AtomicType *Atomic = DestType->getAs()) { if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || S.IsDerivedFrom(Initializer->getLocStart(), SourceType, Atomic->getValueType())) { DestType = Atomic->getValueType(); NeedAtomicConversion = true; } } TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, TopLevelOfInitList); MaybeProduceObjCObject(S, *this, Entity); if (!Failed() && NeedAtomicConversion) AddAtomicConversionStep(Entity.getType()); return; } // - Otherwise, the initial value of the object being initialized is the // (possibly converted) value of the initializer expression. Standard // conversions (Clause 4) will be used, if necessary, to convert the // initializer expression to the cv-unqualified version of the // destination type; no user-defined conversions are considered. ImplicitConversionSequence ICS = S.TryImplicitConversion(Initializer, DestType, /*SuppressUserConversions*/true, /*AllowExplicitConversions*/ false, /*InOverloadResolution*/ false, /*CStyle=*/Kind.isCStyleOrFunctionalCast(), allowObjCWritebackConversion); if (ICS.isStandard() && ICS.Standard.Second == ICK_Writeback_Conversion) { // Objective-C ARC writeback conversion. // We should copy unless we're passing to an argument explicitly // marked 'out'. bool ShouldCopy = true; if (ParmVarDecl *Param = cast_or_null(Entity.getDecl())) ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); // If there was an lvalue adjustment, add it as a separate conversion. if (ICS.Standard.First == ICK_Array_To_Pointer || ICS.Standard.First == ICK_Lvalue_To_Rvalue) { ImplicitConversionSequence LvalueICS; LvalueICS.setStandard(); LvalueICS.Standard.setAsIdentityConversion(); LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); LvalueICS.Standard.First = ICS.Standard.First; AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); } AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); } else if (ICS.isBad()) { DeclAccessPair dap; if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { AddZeroInitializationStep(Entity.getType()); } else if (Initializer->getType() == Context.OverloadTy && !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, false, dap)) SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); else if (Initializer->getType()->isFunctionType() && isExprAnUnaddressableFunction(S, Initializer)) SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); else SetFailed(InitializationSequence::FK_ConversionFailed); } else { AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); MaybeProduceObjCObject(S, *this, Entity); } } InitializationSequence::~InitializationSequence() { for (auto &S : Steps) S.Destroy(); } //===----------------------------------------------------------------------===// // Perform initialization //===----------------------------------------------------------------------===// static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { switch(Entity.getKind()) { case InitializedEntity::EK_Variable: case InitializedEntity::EK_New: case InitializedEntity::EK_Exception: case InitializedEntity::EK_Base: case InitializedEntity::EK_Delegating: return Sema::AA_Initializing; case InitializedEntity::EK_Parameter: if (Entity.getDecl() && isa(Entity.getDecl()->getDeclContext())) return Sema::AA_Sending; return Sema::AA_Passing; case InitializedEntity::EK_Parameter_CF_Audited: if (Entity.getDecl() && isa(Entity.getDecl()->getDeclContext())) return Sema::AA_Sending; return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; case InitializedEntity::EK_Result: return Sema::AA_Returning; case InitializedEntity::EK_Temporary: case InitializedEntity::EK_RelatedResult: // FIXME: Can we tell apart casting vs. converting? return Sema::AA_Casting; case InitializedEntity::EK_Member: case InitializedEntity::EK_Binding: case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_ComplexElement: case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_LambdaCapture: case InitializedEntity::EK_CompoundLiteralInit: return Sema::AA_Initializing; } llvm_unreachable("Invalid EntityKind!"); } /// \brief Whether we should bind a created object as a temporary when /// initializing the given entity. static bool shouldBindAsTemporary(const InitializedEntity &Entity) { switch (Entity.getKind()) { case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_Member: case InitializedEntity::EK_Result: case InitializedEntity::EK_New: case InitializedEntity::EK_Variable: case InitializedEntity::EK_Base: case InitializedEntity::EK_Delegating: case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_ComplexElement: case InitializedEntity::EK_Exception: case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_LambdaCapture: case InitializedEntity::EK_CompoundLiteralInit: return false; case InitializedEntity::EK_Parameter: case InitializedEntity::EK_Parameter_CF_Audited: case InitializedEntity::EK_Temporary: case InitializedEntity::EK_RelatedResult: case InitializedEntity::EK_Binding: return true; } llvm_unreachable("missed an InitializedEntity kind?"); } /// \brief Whether the given entity, when initialized with an object /// created for that initialization, requires destruction. static bool shouldDestroyEntity(const InitializedEntity &Entity) { switch (Entity.getKind()) { case InitializedEntity::EK_Result: case InitializedEntity::EK_New: case InitializedEntity::EK_Base: case InitializedEntity::EK_Delegating: case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_ComplexElement: case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_LambdaCapture: return false; case InitializedEntity::EK_Member: case InitializedEntity::EK_Binding: case InitializedEntity::EK_Variable: case InitializedEntity::EK_Parameter: case InitializedEntity::EK_Parameter_CF_Audited: case InitializedEntity::EK_Temporary: case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_Exception: case InitializedEntity::EK_CompoundLiteralInit: case InitializedEntity::EK_RelatedResult: return true; } llvm_unreachable("missed an InitializedEntity kind?"); } /// \brief Get the location at which initialization diagnostics should appear. static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer) { switch (Entity.getKind()) { case InitializedEntity::EK_Result: return Entity.getReturnLoc(); case InitializedEntity::EK_Exception: return Entity.getThrowLoc(); case InitializedEntity::EK_Variable: case InitializedEntity::EK_Binding: return Entity.getDecl()->getLocation(); case InitializedEntity::EK_LambdaCapture: return Entity.getCaptureLoc(); case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_Member: case InitializedEntity::EK_Parameter: case InitializedEntity::EK_Parameter_CF_Audited: case InitializedEntity::EK_Temporary: case InitializedEntity::EK_New: case InitializedEntity::EK_Base: case InitializedEntity::EK_Delegating: case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_ComplexElement: case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_CompoundLiteralInit: case InitializedEntity::EK_RelatedResult: return Initializer->getLocStart(); } llvm_unreachable("missed an InitializedEntity kind?"); } /// \brief Make a (potentially elidable) temporary copy of the object /// provided by the given initializer by calling the appropriate copy /// constructor. /// /// \param S The Sema object used for type-checking. /// /// \param T The type of the temporary object, which must either be /// the type of the initializer expression or a superclass thereof. /// /// \param Entity The entity being initialized. /// /// \param CurInit The initializer expression. /// /// \param IsExtraneousCopy Whether this is an "extraneous" copy that /// is permitted in C++03 (but not C++0x) when binding a reference to /// an rvalue. /// /// \returns An expression that copies the initializer expression into /// a temporary object, or an error expression if a copy could not be /// created. static ExprResult CopyObject(Sema &S, QualType T, const InitializedEntity &Entity, ExprResult CurInit, bool IsExtraneousCopy) { if (CurInit.isInvalid()) return CurInit; // Determine which class type we're copying to. Expr *CurInitExpr = (Expr *)CurInit.get(); CXXRecordDecl *Class = nullptr; if (const RecordType *Record = T->getAs()) Class = cast(Record->getDecl()); if (!Class) return CurInit; SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); // Make sure that the type we are copying is complete. if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) return CurInit; // Perform overload resolution using the class's constructors. Per // C++11 [dcl.init]p16, second bullet for class types, this initialization // is direct-initialization. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); DeclContext::lookup_result Ctors = S.LookupConstructors(Class); OverloadCandidateSet::iterator Best; switch (ResolveConstructorOverload( S, Loc, CurInitExpr, CandidateSet, Ctors, Best, /*CopyInitializing=*/false, /*AllowExplicit=*/true, /*OnlyListConstructors=*/false, /*IsListInit=*/false, /*SecondStepOfCopyInit=*/true)) { case OR_Success: break; case OR_No_Viable_Function: S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() ? diag::ext_rvalue_to_reference_temp_copy_no_viable : diag::err_temp_copy_no_viable) << (int)Entity.getKind() << CurInitExpr->getType() << CurInitExpr->getSourceRange(); CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); if (!IsExtraneousCopy || S.isSFINAEContext()) return ExprError(); return CurInit; case OR_Ambiguous: S.Diag(Loc, diag::err_temp_copy_ambiguous) << (int)Entity.getKind() << CurInitExpr->getType() << CurInitExpr->getSourceRange(); CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); return ExprError(); case OR_Deleted: S.Diag(Loc, diag::err_temp_copy_deleted) << (int)Entity.getKind() << CurInitExpr->getType() << CurInitExpr->getSourceRange(); S.NoteDeletedFunction(Best->Function); return ExprError(); } bool HadMultipleCandidates = CandidateSet.size() > 1; CXXConstructorDecl *Constructor = cast(Best->Function); SmallVector ConstructorArgs; CurInit.get(); // Ownership transferred into MultiExprArg, below. S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, IsExtraneousCopy); if (IsExtraneousCopy) { // If this is a totally extraneous copy for C++03 reference // binding purposes, just return the original initialization // expression. We don't generate an (elided) copy operation here // because doing so would require us to pass down a flag to avoid // infinite recursion, where each step adds another extraneous, // elidable copy. // Instantiate the default arguments of any extra parameters in // the selected copy constructor, as if we were going to create a // proper call to the copy constructor. for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { ParmVarDecl *Parm = Constructor->getParamDecl(I); if (S.RequireCompleteType(Loc, Parm->getType(), diag::err_call_incomplete_argument)) break; // Build the default argument expression; we don't actually care // if this succeeds or not, because this routine will complain // if there was a problem. S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); } return CurInitExpr; } // Determine the arguments required to actually perform the // constructor call (we might have derived-to-base conversions, or // the copy constructor may have default arguments). if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) return ExprError(); // C++0x [class.copy]p32: // When certain criteria are met, an implementation is allowed to // omit the copy/move construction of a class object, even if the // copy/move constructor and/or destructor for the object have // side effects. [...] // - when a temporary class object that has not been bound to a // reference (12.2) would be copied/moved to a class object // with the same cv-unqualified type, the copy/move operation // can be omitted by constructing the temporary object // directly into the target of the omitted copy/move // // Note that the other three bullets are handled elsewhere. Copy // elision for return statements and throw expressions are handled as part // of constructor initialization, while copy elision for exception handlers // is handled by the run-time. // // FIXME: If the function parameter is not the same type as the temporary, we // should still be able to elide the copy, but we don't have a way to // represent in the AST how much should be elided in this case. bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class) && S.Context.hasSameUnqualifiedType( Best->Function->getParamDecl(0)->getType().getNonReferenceType(), CurInitExpr->getType()); // Actually perform the constructor call. CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs, HadMultipleCandidates, /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, CXXConstructExpr::CK_Complete, SourceRange()); // If we're supposed to bind temporaries, do so. if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) CurInit = S.MaybeBindToTemporary(CurInit.getAs()); return CurInit; } /// \brief Check whether elidable copy construction for binding a reference to /// a temporary would have succeeded if we were building in C++98 mode, for /// -Wc++98-compat. static void CheckCXX98CompatAccessibleCopy(Sema &S, const InitializedEntity &Entity, Expr *CurInitExpr) { assert(S.getLangOpts().CPlusPlus11); const RecordType *Record = CurInitExpr->getType()->getAs(); if (!Record) return; SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) return; // Find constructors which would have been considered. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); DeclContext::lookup_result Ctors = S.LookupConstructors(cast(Record->getDecl())); // Perform overload resolution. OverloadCandidateSet::iterator Best; OverloadingResult OR = ResolveConstructorOverload( S, Loc, CurInitExpr, CandidateSet, Ctors, Best, /*CopyInitializing=*/false, /*AllowExplicit=*/true, /*OnlyListConstructors=*/false, /*IsListInit=*/false, /*SecondStepOfCopyInit=*/true); PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) << OR << (int)Entity.getKind() << CurInitExpr->getType() << CurInitExpr->getSourceRange(); switch (OR) { case OR_Success: S.CheckConstructorAccess(Loc, cast(Best->Function), Best->FoundDecl, Entity, Diag); // FIXME: Check default arguments as far as that's possible. break; case OR_No_Viable_Function: S.Diag(Loc, Diag); CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr); break; case OR_Ambiguous: S.Diag(Loc, Diag); CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr); break; case OR_Deleted: S.Diag(Loc, Diag); S.NoteDeletedFunction(Best->Function); break; } } void InitializationSequence::PrintInitLocationNote(Sema &S, const InitializedEntity &Entity) { if (Entity.isParameterKind() && Entity.getDecl()) { if (Entity.getDecl()->getLocation().isInvalid()) return; if (Entity.getDecl()->getDeclName()) S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) << Entity.getDecl()->getDeclName(); else S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); } else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && Entity.getMethodDecl()) S.Diag(Entity.getMethodDecl()->getLocation(), diag::note_method_return_type_change) << Entity.getMethodDecl()->getDeclName(); } /// Returns true if the parameters describe a constructor initialization of /// an explicit temporary object, e.g. "Point(x, y)". static bool isExplicitTemporary(const InitializedEntity &Entity, const InitializationKind &Kind, unsigned NumArgs) { switch (Entity.getKind()) { case InitializedEntity::EK_Temporary: case InitializedEntity::EK_CompoundLiteralInit: case InitializedEntity::EK_RelatedResult: break; default: return false; } switch (Kind.getKind()) { case InitializationKind::IK_DirectList: return true; // FIXME: Hack to work around cast weirdness. case InitializationKind::IK_Direct: case InitializationKind::IK_Value: return NumArgs != 1; default: return false; } } static ExprResult PerformConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, const InitializationSequence::Step& Step, bool &ConstructorInitRequiresZeroInit, bool IsListInitialization, bool IsStdInitListInitialization, SourceLocation LBraceLoc, SourceLocation RBraceLoc) { unsigned NumArgs = Args.size(); CXXConstructorDecl *Constructor = cast(Step.Function.Function); bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; // Build a call to the selected constructor. SmallVector ConstructorArgs; SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) ? Kind.getEqualLoc() : Kind.getLocation(); if (Kind.getKind() == InitializationKind::IK_Default) { // Force even a trivial, implicit default constructor to be // semantically checked. We do this explicitly because we don't build // the definition for completely trivial constructors. assert(Constructor->getParent() && "No parent class for constructor."); if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && Constructor->isTrivial() && !Constructor->isUsed(false)) S.DefineImplicitDefaultConstructor(Loc, Constructor); } ExprResult CurInit((Expr *)nullptr); // C++ [over.match.copy]p1: // - When initializing a temporary to be bound to the first parameter // of a constructor that takes a reference to possibly cv-qualified // T as its first argument, called with a single argument in the // context of direct-initialization, explicit conversion functions // are also considered. bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && hasCopyOrMoveCtorParam(S.Context, getConstructorInfo(Step.Function.FoundDecl)); // Determine the arguments required to actually perform the constructor // call. if (S.CompleteConstructorCall(Constructor, Args, Loc, ConstructorArgs, AllowExplicitConv, IsListInitialization)) return ExprError(); if (isExplicitTemporary(Entity, Kind, NumArgs)) { // An explicitly-constructed temporary, e.g., X(1, 2). if (S.DiagnoseUseOfDecl(Constructor, Loc)) return ExprError(); TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); if (!TSInfo) TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); SourceRange ParenOrBraceRange = (Kind.getKind() == InitializationKind::IK_DirectList) ? SourceRange(LBraceLoc, RBraceLoc) : Kind.getParenRange(); if (auto *Shadow = dyn_cast( Step.Function.FoundDecl.getDecl())) { Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow); if (S.DiagnoseUseOfDecl(Constructor, Loc)) return ExprError(); } S.MarkFunctionReferenced(Loc, Constructor); CurInit = new (S.Context) CXXTemporaryObjectExpr( S.Context, Constructor, Entity.getType().getNonLValueExprType(S.Context), TSInfo, ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, ConstructorInitRequiresZeroInit); } else { CXXConstructExpr::ConstructionKind ConstructKind = CXXConstructExpr::CK_Complete; if (Entity.getKind() == InitializedEntity::EK_Base) { ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? CXXConstructExpr::CK_VirtualBase : CXXConstructExpr::CK_NonVirtualBase; } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { ConstructKind = CXXConstructExpr::CK_Delegating; } // Only get the parenthesis or brace range if it is a list initialization or // direct construction. SourceRange ParenOrBraceRange; if (IsListInitialization) ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); else if (Kind.getKind() == InitializationKind::IK_Direct) ParenOrBraceRange = Kind.getParenRange(); // If the entity allows NRVO, mark the construction as elidable // unconditionally. if (Entity.allowsNRVO()) CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, Step.Function.FoundDecl, Constructor, /*Elidable=*/true, ConstructorArgs, HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, ConstructorInitRequiresZeroInit, ConstructKind, ParenOrBraceRange); else CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, Step.Function.FoundDecl, Constructor, ConstructorArgs, HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, ConstructorInitRequiresZeroInit, ConstructKind, ParenOrBraceRange); } if (CurInit.isInvalid()) return ExprError(); // Only check access if all of that succeeded. S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) return ExprError(); if (shouldBindAsTemporary(Entity)) CurInit = S.MaybeBindToTemporary(CurInit.get()); return CurInit; } /// Determine whether the specified InitializedEntity definitely has a lifetime /// longer than the current full-expression. Conservatively returns false if /// it's unclear. static bool InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) { const InitializedEntity *Top = &Entity; while (Top->getParent()) Top = Top->getParent(); switch (Top->getKind()) { case InitializedEntity::EK_Variable: case InitializedEntity::EK_Result: case InitializedEntity::EK_Exception: case InitializedEntity::EK_Member: case InitializedEntity::EK_Binding: case InitializedEntity::EK_New: case InitializedEntity::EK_Base: case InitializedEntity::EK_Delegating: return true; case InitializedEntity::EK_ArrayElement: case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_ComplexElement: // Could not determine what the full initialization is. Assume it might not // outlive the full-expression. return false; case InitializedEntity::EK_Parameter: case InitializedEntity::EK_Parameter_CF_Audited: case InitializedEntity::EK_Temporary: case InitializedEntity::EK_LambdaCapture: case InitializedEntity::EK_CompoundLiteralInit: case InitializedEntity::EK_RelatedResult: // The entity being initialized might not outlive the full-expression. return false; } llvm_unreachable("unknown entity kind"); } /// Determine the declaration which an initialized entity ultimately refers to, /// for the purpose of lifetime-extending a temporary bound to a reference in /// the initialization of \p Entity. static const InitializedEntity *getEntityForTemporaryLifetimeExtension( const InitializedEntity *Entity, const InitializedEntity *FallbackDecl = nullptr) { // C++11 [class.temporary]p5: switch (Entity->getKind()) { case InitializedEntity::EK_Variable: // The temporary [...] persists for the lifetime of the reference return Entity; case InitializedEntity::EK_Member: // For subobjects, we look at the complete object. if (Entity->getParent()) return getEntityForTemporaryLifetimeExtension(Entity->getParent(), Entity); // except: // -- A temporary bound to a reference member in a constructor's // ctor-initializer persists until the constructor exits. return Entity; case InitializedEntity::EK_Binding: // Per [dcl.decomp]p3, the binding is treated as a variable of reference // type. return Entity; case InitializedEntity::EK_Parameter: case InitializedEntity::EK_Parameter_CF_Audited: // -- A temporary bound to a reference parameter in a function call // persists until the completion of the full-expression containing // the call. case InitializedEntity::EK_Result: // -- The lifetime of a temporary bound to the returned value in a // function return statement is not extended; the temporary is // destroyed at the end of the full-expression in the return statement. case InitializedEntity::EK_New: // -- A temporary bound to a reference in a new-initializer persists // until the completion of the full-expression containing the // new-initializer. return nullptr; case InitializedEntity::EK_Temporary: case InitializedEntity::EK_CompoundLiteralInit: case InitializedEntity::EK_RelatedResult: // We don't yet know the storage duration of the surrounding temporary. // Assume it's got full-expression duration for now, it will patch up our // storage duration if that's not correct. return nullptr; case InitializedEntity::EK_ArrayElement: // For subobjects, we look at the complete object. return getEntityForTemporaryLifetimeExtension(Entity->getParent(), FallbackDecl); case InitializedEntity::EK_Base: // For subobjects, we look at the complete object. if (Entity->getParent()) return getEntityForTemporaryLifetimeExtension(Entity->getParent(), Entity); // Fall through. case InitializedEntity::EK_Delegating: // We can reach this case for aggregate initialization in a constructor: // struct A { int &&r; }; // struct B : A { B() : A{0} {} }; // In this case, use the innermost field decl as the context. return FallbackDecl; case InitializedEntity::EK_BlockElement: case InitializedEntity::EK_LambdaToBlockConversionBlockElement: case InitializedEntity::EK_LambdaCapture: case InitializedEntity::EK_Exception: case InitializedEntity::EK_VectorElement: case InitializedEntity::EK_ComplexElement: return nullptr; } llvm_unreachable("unknown entity kind"); } static void performLifetimeExtension(Expr *Init, const InitializedEntity *ExtendingEntity); /// Update a glvalue expression that is used as the initializer of a reference /// to note that its lifetime is extended. /// \return \c true if any temporary had its lifetime extended. static bool performReferenceExtension(Expr *Init, const InitializedEntity *ExtendingEntity) { // Walk past any constructs which we can lifetime-extend across. Expr *Old; do { Old = Init; if (InitListExpr *ILE = dyn_cast(Init)) { if (ILE->getNumInits() == 1 && ILE->isGLValue()) { // This is just redundant braces around an initializer. Step over it. Init = ILE->getInit(0); } } // Step over any subobject adjustments; we may have a materialized // temporary inside them. Init = const_cast(Init->skipRValueSubobjectAdjustments()); // Per current approach for DR1376, look through casts to reference type // when performing lifetime extension. if (CastExpr *CE = dyn_cast(Init)) if (CE->getSubExpr()->isGLValue()) Init = CE->getSubExpr(); // Per the current approach for DR1299, look through array element access // when performing lifetime extension. if (auto *ASE = dyn_cast(Init)) Init = ASE->getBase(); } while (Init != Old); if (MaterializeTemporaryExpr *ME = dyn_cast(Init)) { // Update the storage duration of the materialized temporary. // FIXME: Rebuild the expression instead of mutating it. ME->setExtendingDecl(ExtendingEntity->getDecl(), ExtendingEntity->allocateManglingNumber()); performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity); return true; } return false; } /// Update a prvalue expression that is going to be materialized as a /// lifetime-extended temporary. static void performLifetimeExtension(Expr *Init, const InitializedEntity *ExtendingEntity) { // Dig out the expression which constructs the extended temporary. Init = const_cast(Init->skipRValueSubobjectAdjustments()); if (CXXBindTemporaryExpr *BTE = dyn_cast(Init)) Init = BTE->getSubExpr(); if (CXXStdInitializerListExpr *ILE = dyn_cast(Init)) { performReferenceExtension(ILE->getSubExpr(), ExtendingEntity); return; } if (InitListExpr *ILE = dyn_cast(Init)) { if (ILE->getType()->isArrayType()) { for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) performLifetimeExtension(ILE->getInit(I), ExtendingEntity); return; } if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { assert(RD->isAggregate() && "aggregate init on non-aggregate"); // If we lifetime-extend a braced initializer which is initializing an // aggregate, and that aggregate contains reference members which are // bound to temporaries, those temporaries are also lifetime-extended. if (RD->isUnion() && ILE->getInitializedFieldInUnion() && ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) performReferenceExtension(ILE->getInit(0), ExtendingEntity); else { unsigned Index = 0; for (const auto *I : RD->fields()) { if (Index >= ILE->getNumInits()) break; if (I->isUnnamedBitfield()) continue; Expr *SubInit = ILE->getInit(Index); if (I->getType()->isReferenceType()) performReferenceExtension(SubInit, ExtendingEntity); else if (isa(SubInit) || isa(SubInit)) // This may be either aggregate-initialization of a member or // initialization of a std::initializer_list object. Either way, // we should recursively lifetime-extend that initializer. performLifetimeExtension(SubInit, ExtendingEntity); ++Index; } } } } } static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity, const Expr *Init, bool IsInitializerList, const ValueDecl *ExtendingDecl) { // Warn if a field lifetime-extends a temporary. if (isa(ExtendingDecl)) { if (IsInitializerList) { S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list) << /*at end of constructor*/true; return; } bool IsSubobjectMember = false; for (const InitializedEntity *Ent = Entity.getParent(); Ent; Ent = Ent->getParent()) { if (Ent->getKind() != InitializedEntity::EK_Base) { IsSubobjectMember = true; break; } } S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) << ExtendingDecl << Init->getSourceRange() << IsSubobjectMember << IsInitializerList; if (IsSubobjectMember) S.Diag(ExtendingDecl->getLocation(), diag::note_ref_subobject_of_member_declared_here); else S.Diag(ExtendingDecl->getLocation(), diag::note_ref_or_ptr_member_declared_here) << /*is pointer*/false; } } static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit); /// Provide warnings when std::move is used on construction. static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt) { if (!InitExpr) return; if (S.inTemplateInstantiation()) return; QualType DestType = InitExpr->getType(); if (!DestType->isRecordType()) return; unsigned DiagID = 0; if (IsReturnStmt) { const CXXConstructExpr *CCE = dyn_cast(InitExpr->IgnoreParens()); if (!CCE || CCE->getNumArgs() != 1) return; if (!CCE->getConstructor()->isCopyOrMoveConstructor()) return; InitExpr = CCE->getArg(0)->IgnoreImpCasts(); } // Find the std::move call and get the argument. const CallExpr *CE = dyn_cast(InitExpr->IgnoreParens()); if (!CE || CE->getNumArgs() != 1) return; const FunctionDecl *MoveFunction = CE->getDirectCallee(); if (!MoveFunction || !MoveFunction->isInStdNamespace() || !MoveFunction->getIdentifier() || !MoveFunction->getIdentifier()->isStr("move")) return; const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); if (IsReturnStmt) { const DeclRefExpr *DRE = dyn_cast(Arg->IgnoreParenImpCasts()); if (!DRE || DRE->refersToEnclosingVariableOrCapture()) return; const VarDecl *VD = dyn_cast(DRE->getDecl()); if (!VD || !VD->hasLocalStorage()) return; QualType SourceType = VD->getType(); if (!SourceType->isRecordType()) return; if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { return; } // If we're returning a function parameter, copy elision // is not possible. if (isa(VD)) DiagID = diag::warn_redundant_move_on_return; else DiagID = diag::warn_pessimizing_move_on_return; } else { DiagID = diag::warn_pessimizing_move_on_initialization; const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) return; } S.Diag(CE->getLocStart(), DiagID); // Get all the locations for a fix-it. Don't emit the fix-it if any location // is within a macro. SourceLocation CallBegin = CE->getCallee()->getLocStart(); if (CallBegin.isMacroID()) return; SourceLocation RParen = CE->getRParenLoc(); if (RParen.isMacroID()) return; SourceLocation LParen; SourceLocation ArgLoc = Arg->getLocStart(); // Special testing for the argument location. Since the fix-it needs the // location right before the argument, the argument location can be in a // macro only if it is at the beginning of the macro. while (ArgLoc.isMacroID() && S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first; } if (LParen.isMacroID()) return; LParen = ArgLoc.getLocWithOffset(-1); S.Diag(CE->getLocStart(), diag::note_remove_move) << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); } static void CheckForNullPointerDereference(Sema &S, const Expr *E) { // Check to see if we are dereferencing a null pointer. If so, this is // undefined behavior, so warn about it. This only handles the pattern // "*null", which is a very syntactic check. if (const UnaryOperator *UO = dyn_cast(E->IgnoreParenCasts())) if (UO->getOpcode() == UO_Deref && UO->getSubExpr()->IgnoreParenCasts()-> isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, S.PDiag(diag::warn_binding_null_to_reference) << UO->getSubExpr()->getSourceRange()); } } MaterializeTemporaryExpr * Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference) { auto MTE = new (Context) MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); // Order an ExprWithCleanups for lifetime marks. // // TODO: It'll be good to have a single place to check the access of the // destructor and generate ExprWithCleanups for various uses. Currently these // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, // but there may be a chance to merge them. Cleanup.setExprNeedsCleanups(false); return MTE; } ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { // In C++98, we don't want to implicitly create an xvalue. // FIXME: This means that AST consumers need to deal with "prvalues" that // denote materialized temporaries. Maybe we should add another ValueKind // for "xvalue pretending to be a prvalue" for C++98 support. if (!E->isRValue() || !getLangOpts().CPlusPlus11) return E; // C++1z [conv.rval]/1: T shall be a complete type. // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? // If so, we should check for a non-abstract class type here too. QualType T = E->getType(); if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) return ExprError(); return CreateMaterializeTemporaryExpr(E->getType(), E, false); } ExprResult InitializationSequence::Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType) { if (Failed()) { Diagnose(S, Entity, Kind, Args); return ExprError(); } if (!ZeroInitializationFixit.empty()) { unsigned DiagID = diag::err_default_init_const; if (Decl *D = Entity.getDecl()) if (S.getLangOpts().MSVCCompat && D->hasAttr()) DiagID = diag::ext_default_init_const; // The initialization would have succeeded with this fixit. Since the fixit // is on the error, we need to build a valid AST in this case, so this isn't // handled in the Failed() branch above. QualType DestType = Entity.getType(); S.Diag(Kind.getLocation(), DiagID) << DestType << (bool)DestType->getAs() << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, ZeroInitializationFixit); } if (getKind() == DependentSequence) { // If the declaration is a non-dependent, incomplete array type // that has an initializer, then its type will be completed once // the initializer is instantiated. if (ResultType && !Entity.getType()->isDependentType() && Args.size() == 1) { QualType DeclType = Entity.getType(); if (const IncompleteArrayType *ArrayT = S.Context.getAsIncompleteArrayType(DeclType)) { // FIXME: We don't currently have the ability to accurately // compute the length of an initializer list without // performing full type-checking of the initializer list // (since we have to determine where braces are implicitly // introduced and such). So, we fall back to making the array // type a dependently-sized array type with no specified // bound. if (isa((Expr *)Args[0])) { SourceRange Brackets; // Scavange the location of the brackets from the entity, if we can. if (auto *DD = dyn_cast_or_null(Entity.getDecl())) { if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { TypeLoc TL = TInfo->getTypeLoc(); if (IncompleteArrayTypeLoc ArrayLoc = TL.getAs()) Brackets = ArrayLoc.getBracketsRange(); } } *ResultType = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), /*NumElts=*/nullptr, ArrayT->getSizeModifier(), ArrayT->getIndexTypeCVRQualifiers(), Brackets); } } } if (Kind.getKind() == InitializationKind::IK_Direct && !Kind.isExplicitCast()) { // Rebuild the ParenListExpr. SourceRange ParenRange = Kind.getParenRange(); return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), Args); } assert(Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList); return ExprResult(Args[0]); } // No steps means no initialization. if (Steps.empty()) return ExprResult((Expr *)nullptr); if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && Args.size() == 1 && isa(Args[0]) && !Entity.isParameterKind()) { // Produce a C++98 compatibility warning if we are initializing a reference // from an initializer list. For parameters, we produce a better warning // elsewhere. Expr *Init = Args[0]; S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init) << Init->getSourceRange(); } // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope QualType ETy = Entity.getType(); Qualifiers TyQualifiers = ETy.getQualifiers(); bool HasGlobalAS = TyQualifiers.hasAddressSpace() && TyQualifiers.getAddressSpace() == LangAS::opencl_global; if (S.getLangOpts().OpenCLVersion >= 200 && ETy->isAtomicType() && !HasGlobalAS && Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 << SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd()); return ExprError(); } // Diagnose cases where we initialize a pointer to an array temporary, and the // pointer obviously outlives the temporary. if (Args.size() == 1 && Args[0]->getType()->isArrayType() && Entity.getType()->isPointerType() && InitializedEntityOutlivesFullExpression(Entity)) { const Expr *Init = Args[0]->skipRValueSubobjectAdjustments(); if (auto *MTE = dyn_cast(Init)) Init = MTE->GetTemporaryExpr(); Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context); if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary) S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay) << Init->getSourceRange(); } QualType DestType = Entity.getType().getNonReferenceType(); // FIXME: Ugly hack around the fact that Entity.getType() is not // the same as Entity.getDecl()->getType() in cases involving type merging, // and we want latter when it makes sense. if (ResultType) *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : Entity.getType(); ExprResult CurInit((Expr *)nullptr); SmallVector ArrayLoopCommonExprs; // For initialization steps that start with a single initializer, // grab the only argument out the Args and place it into the "current" // initializer. switch (Steps.front().Kind) { case SK_ResolveAddressOfOverloadedFunction: case SK_CastDerivedToBaseRValue: case SK_CastDerivedToBaseXValue: case SK_CastDerivedToBaseLValue: case SK_BindReference: case SK_BindReferenceToTemporary: case SK_FinalCopy: case SK_ExtraneousCopyToTemporary: case SK_UserConversion: case SK_QualificationConversionLValue: case SK_QualificationConversionXValue: case SK_QualificationConversionRValue: case SK_AtomicConversion: case SK_LValueToRValue: case SK_ConversionSequence: case SK_ConversionSequenceNoNarrowing: case SK_ListInitialization: case SK_UnwrapInitList: case SK_RewrapInitList: case SK_CAssignment: case SK_StringInit: case SK_ObjCObjectConversion: case SK_ArrayLoopIndex: case SK_ArrayLoopInit: case SK_ArrayInit: case SK_GNUArrayInit: case SK_ParenthesizedArrayInit: case SK_PassByIndirectCopyRestore: case SK_PassByIndirectRestore: case SK_ProduceObjCObject: case SK_StdInitializerList: case SK_OCLSamplerInit: case SK_OCLZeroEvent: case SK_OCLZeroQueue: { assert(Args.size() == 1); CurInit = Args[0]; if (!CurInit.get()) return ExprError(); break; } case SK_ConstructorInitialization: case SK_ConstructorInitializationFromList: case SK_StdInitializerListConstructorCall: case SK_ZeroInitialization: break; } // Promote from an unevaluated context to an unevaluated list context in // C++11 list-initialization; we need to instantiate entities usable in // constant expressions here in order to perform narrowing checks =( EnterExpressionEvaluationContext Evaluated( S, EnterExpressionEvaluationContext::InitList, CurInit.get() && isa(CurInit.get())); // C++ [class.abstract]p2: // no objects of an abstract class can be created except as subobjects // of a class derived from it auto checkAbstractType = [&](QualType T) -> bool { if (Entity.getKind() == InitializedEntity::EK_Base || Entity.getKind() == InitializedEntity::EK_Delegating) return false; return S.RequireNonAbstractType(Kind.getLocation(), T, diag::err_allocation_of_abstract_type); }; // Walk through the computed steps for the initialization sequence, // performing the specified conversions along the way. bool ConstructorInitRequiresZeroInit = false; for (step_iterator Step = step_begin(), StepEnd = step_end(); Step != StepEnd; ++Step) { if (CurInit.isInvalid()) return ExprError(); QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); switch (Step->Kind) { case SK_ResolveAddressOfOverloadedFunction: // Overload resolution determined which function invoke; update the // initializer to reflect that choice. S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) return ExprError(); CurInit = S.FixOverloadedFunctionReference(CurInit, Step->Function.FoundDecl, Step->Function.Function); break; case SK_CastDerivedToBaseRValue: case SK_CastDerivedToBaseXValue: case SK_CastDerivedToBaseLValue: { // We have a derived-to-base cast that produces either an rvalue or an // lvalue. Perform that cast. CXXCastPath BasePath; // Casts to inaccessible base classes are allowed with C-style casts. bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, CurInit.get()->getLocStart(), CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) return ExprError(); ExprValueKind VK = Step->Kind == SK_CastDerivedToBaseLValue ? VK_LValue : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue : VK_RValue); CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase, CurInit.get(), &BasePath, VK); break; } case SK_BindReference: // Reference binding does not have any corresponding ASTs. // Check exception specifications if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) return ExprError(); // We don't check for e.g. function pointers here, since address // availability checks should only occur when the function first decays // into a pointer or reference. if (CurInit.get()->getType()->isFunctionProtoType()) { if (auto *DRE = dyn_cast(CurInit.get()->IgnoreParens())) { if (auto *FD = dyn_cast(DRE->getDecl())) { if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, DRE->getLocStart())) return ExprError(); } } } // Even though we didn't materialize a temporary, the binding may still // extend the lifetime of a temporary. This happens if we bind a reference // to the result of a cast to reference type. if (const InitializedEntity *ExtendingEntity = getEntityForTemporaryLifetimeExtension(&Entity)) if (performReferenceExtension(CurInit.get(), ExtendingEntity)) warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false, ExtendingEntity->getDecl()); CheckForNullPointerDereference(S, CurInit.get()); break; case SK_BindReferenceToTemporary: { // Make sure the "temporary" is actually an rvalue. assert(CurInit.get()->isRValue() && "not a temporary"); // Check exception specifications if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) return ExprError(); // Materialize the temporary into memory. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType()); // Maybe lifetime-extend the temporary's subobjects to match the // entity's lifetime. if (const InitializedEntity *ExtendingEntity = getEntityForTemporaryLifetimeExtension(&Entity)) if (performReferenceExtension(MTE, ExtendingEntity)) warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false, ExtendingEntity->getDecl()); // If we're extending this temporary to automatic storage duration -- we // need to register its cleanup during the full-expression's cleanups. if (MTE->getStorageDuration() == SD_Automatic && MTE->getType().isDestructedType()) S.Cleanup.setExprNeedsCleanups(true); CurInit = MTE; break; } case SK_FinalCopy: if (checkAbstractType(Step->Type)) return ExprError(); // If the overall initialization is initializing a temporary, we already // bound our argument if it was necessary to do so. If not (if we're // ultimately initializing a non-temporary), our argument needs to be // bound since it's initializing a function parameter. // FIXME: This is a mess. Rationalize temporary destruction. if (!shouldBindAsTemporary(Entity)) CurInit = S.MaybeBindToTemporary(CurInit.get()); CurInit = CopyObject(S, Step->Type, Entity, CurInit, /*IsExtraneousCopy=*/false); break; case SK_ExtraneousCopyToTemporary: CurInit = CopyObject(S, Step->Type, Entity, CurInit, /*IsExtraneousCopy=*/true); break; case SK_UserConversion: { // We have a user-defined conversion that invokes either a constructor // or a conversion function. CastKind CastKind; FunctionDecl *Fn = Step->Function.Function; DeclAccessPair FoundFn = Step->Function.FoundDecl; bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; bool CreatedObject = false; if (CXXConstructorDecl *Constructor = dyn_cast(Fn)) { // Build a call to the selected constructor. SmallVector ConstructorArgs; SourceLocation Loc = CurInit.get()->getLocStart(); // Determine the arguments required to actually perform the constructor // call. Expr *Arg = CurInit.get(); if (S.CompleteConstructorCall(Constructor, MultiExprArg(&Arg, 1), Loc, ConstructorArgs)) return ExprError(); // Build an expression that constructs a temporary. CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, FoundFn, Constructor, ConstructorArgs, HadMultipleCandidates, /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, CXXConstructExpr::CK_Complete, SourceRange()); if (CurInit.isInvalid()) return ExprError(); S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, Entity); if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) return ExprError(); CastKind = CK_ConstructorConversion; CreatedObject = true; } else { // Build a call to the conversion function. CXXConversionDecl *Conversion = cast(Fn); S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, FoundFn); if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) return ExprError(); // FIXME: Should we move this initialization into a separate // derived-to-base conversion? I believe the answer is "no", because // we don't want to turn off access control here for c-style casts. CurInit = S.PerformObjectArgumentInitialization(CurInit.get(), /*Qualifier=*/nullptr, FoundFn, Conversion); if (CurInit.isInvalid()) return ExprError(); // Build the actual call to the conversion function. CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, HadMultipleCandidates); if (CurInit.isInvalid()) return ExprError(); CastKind = CK_UserDefinedConversion; CreatedObject = Conversion->getReturnType()->isRecordType(); } if (CreatedObject && checkAbstractType(CurInit.get()->getType())) return ExprError(); CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr, CurInit.get()->getValueKind()); if (shouldBindAsTemporary(Entity)) // The overall entity is temporary, so this expression should be // destroyed at the end of its full-expression. CurInit = S.MaybeBindToTemporary(CurInit.getAs()); else if (CreatedObject && shouldDestroyEntity(Entity)) { // The object outlasts the full-expression, but we need to prepare for // a destructor being run on it. // FIXME: It makes no sense to do this here. This should happen // regardless of how we initialized the entity. QualType T = CurInit.get()->getType(); if (const RecordType *Record = T->getAs()) { CXXDestructorDecl *Destructor = S.LookupDestructor(cast(Record->getDecl())); S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, S.PDiag(diag::err_access_dtor_temp) << T); S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor); if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart())) return ExprError(); } } break; } case SK_QualificationConversionLValue: case SK_QualificationConversionXValue: case SK_QualificationConversionRValue: { // Perform a qualification conversion; these can never go wrong. ExprValueKind VK = Step->Kind == SK_QualificationConversionLValue ? VK_LValue : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue : VK_RValue); CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK); break; } case SK_AtomicConversion: { assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic"); CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NonAtomicToAtomic, VK_RValue); break; } case SK_LValueToRValue: { assert(CurInit.get()->isGLValue() && "cannot load from a prvalue"); CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, CK_LValueToRValue, CurInit.get(), /*BasePath=*/nullptr, VK_RValue); break; } case SK_ConversionSequence: case SK_ConversionSequenceNoNarrowing: { Sema::CheckedConversionKind CCK = Kind.isCStyleCast()? Sema::CCK_CStyleCast : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast : Kind.isExplicitCast()? Sema::CCK_OtherCast : Sema::CCK_ImplicitConversion; ExprResult CurInitExprRes = S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK); if (CurInitExprRes.isInvalid()) return ExprError(); S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); CurInit = CurInitExprRes; if (Step->Kind == SK_ConversionSequenceNoNarrowing && S.getLangOpts().CPlusPlus) DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), CurInit.get()); break; } case SK_ListInitialization: { if (checkAbstractType(Step->Type)) return ExprError(); InitListExpr *InitList = cast(CurInit.get()); // If we're not initializing the top-level entity, we need to create an // InitializeTemporary entity for our target type. QualType Ty = Step->Type; bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; InitListChecker PerformInitList(S, InitEntity, InitList, Ty, /*VerifyOnly=*/false, /*TreatUnavailableAsInvalid=*/false); if (PerformInitList.HadError()) return ExprError(); // Hack: We must update *ResultType if available in order to set the // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. // Worst case: 'const int (&arref)[] = {1, 2, 3};'. if (ResultType && ResultType->getNonReferenceType()->isIncompleteArrayType()) { if ((*ResultType)->isRValueReferenceType()) Ty = S.Context.getRValueReferenceType(Ty); else if ((*ResultType)->isLValueReferenceType()) Ty = S.Context.getLValueReferenceType(Ty, (*ResultType)->getAs()->isSpelledAsLValue()); *ResultType = Ty; } InitListExpr *StructuredInitList = PerformInitList.getFullyStructuredList(); CurInit.get(); CurInit = shouldBindAsTemporary(InitEntity) ? S.MaybeBindToTemporary(StructuredInitList) : StructuredInitList; break; } case SK_ConstructorInitializationFromList: { if (checkAbstractType(Step->Type)) return ExprError(); // When an initializer list is passed for a parameter of type "reference // to object", we don't get an EK_Temporary entity, but instead an // EK_Parameter entity with reference type. // FIXME: This is a hack. What we really should do is create a user // conversion step for this case, but this makes it considerably more // complicated. For now, this will do. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( Entity.getType().getNonReferenceType()); bool UseTemporary = Entity.getType()->isReferenceType(); assert(Args.size() == 1 && "expected a single argument for list init"); InitListExpr *InitList = cast(Args[0]); S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) << InitList->getSourceRange(); MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : Entity, Kind, Arg, *Step, ConstructorInitRequiresZeroInit, /*IsListInitialization*/true, /*IsStdInitListInit*/false, InitList->getLBraceLoc(), InitList->getRBraceLoc()); break; } case SK_UnwrapInitList: CurInit = cast(CurInit.get())->getInit(0); break; case SK_RewrapInitList: { Expr *E = CurInit.get(); InitListExpr *Syntactic = Step->WrappingSyntacticList; InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); ILE->setSyntacticForm(Syntactic); ILE->setType(E->getType()); ILE->setValueKind(E->getValueKind()); CurInit = ILE; break; } case SK_ConstructorInitialization: case SK_StdInitializerListConstructorCall: { if (checkAbstractType(Step->Type)) return ExprError(); // When an initializer list is passed for a parameter of type "reference // to object", we don't get an EK_Temporary entity, but instead an // EK_Parameter entity with reference type. // FIXME: This is a hack. What we really should do is create a user // conversion step for this case, but this makes it considerably more // complicated. For now, this will do. InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( Entity.getType().getNonReferenceType()); bool UseTemporary = Entity.getType()->isReferenceType(); bool IsStdInitListInit = Step->Kind == SK_StdInitializerListConstructorCall; Expr *Source = CurInit.get(); CurInit = PerformConstructorInitialization( S, UseTemporary ? TempEntity : Entity, Kind, Source ? MultiExprArg(Source) : Args, *Step, ConstructorInitRequiresZeroInit, /*IsListInitialization*/ IsStdInitListInit, /*IsStdInitListInitialization*/ IsStdInitListInit, /*LBraceLoc*/ SourceLocation(), /*RBraceLoc*/ SourceLocation()); break; } case SK_ZeroInitialization: { step_iterator NextStep = Step; ++NextStep; if (NextStep != StepEnd && (NextStep->Kind == SK_ConstructorInitialization || NextStep->Kind == SK_ConstructorInitializationFromList)) { // The need for zero-initialization is recorded directly into // the call to the object's constructor within the next step. ConstructorInitRequiresZeroInit = true; } else if (Kind.getKind() == InitializationKind::IK_Value && S.getLangOpts().CPlusPlus && !Kind.isImplicitValueInit()) { TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); if (!TSInfo) TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, Kind.getRange().getBegin()); CurInit = new (S.Context) CXXScalarValueInitExpr( Entity.getType().getNonLValueExprType(S.Context), TSInfo, Kind.getRange().getEnd()); } else { CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); } break; } case SK_CAssignment: { QualType SourceType = CurInit.get()->getType(); // Save off the initial CurInit in case we need to emit a diagnostic ExprResult InitialCurInit = CurInit; ExprResult Result = CurInit; Sema::AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints(Step->Type, Result, true, Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); if (Result.isInvalid()) return ExprError(); CurInit = Result; // If this is a call, allow conversion to a transparent union. ExprResult CurInitExprRes = CurInit; if (ConvTy != Sema::Compatible && Entity.isParameterKind() && S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) == Sema::Compatible) ConvTy = Sema::Compatible; if (CurInitExprRes.isInvalid()) return ExprError(); CurInit = CurInitExprRes; bool Complained; if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), Step->Type, SourceType, InitialCurInit.get(), getAssignmentAction(Entity, true), &Complained)) { PrintInitLocationNote(S, Entity); return ExprError(); } else if (Complained) PrintInitLocationNote(S, Entity); break; } case SK_StringInit: { QualType Ty = Step->Type; CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, S.Context.getAsArrayType(Ty), S); break; } case SK_ObjCObjectConversion: CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_ObjCObjectLValueCast, CurInit.get()->getValueKind()); break; case SK_ArrayLoopIndex: { Expr *Cur = CurInit.get(); Expr *BaseExpr = new (S.Context) OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), Cur->getValueKind(), Cur->getObjectKind(), Cur); Expr *IndexExpr = new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); CurInit = S.CreateBuiltinArraySubscriptExpr( BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); ArrayLoopCommonExprs.push_back(BaseExpr); break; } case SK_ArrayLoopInit: { assert(!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit"); Expr *Common = ArrayLoopCommonExprs.pop_back_val(); CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, CurInit.get()); break; } case SK_GNUArrayInit: // Okay: we checked everything before creating this step. Note that // this is a GNU extension. S.Diag(Kind.getLocation(), diag::ext_array_init_copy) << Step->Type << CurInit.get()->getType() << CurInit.get()->getSourceRange(); LLVM_FALLTHROUGH; case SK_ArrayInit: // If the destination type is an incomplete array type, update the // type accordingly. if (ResultType) { if (const IncompleteArrayType *IncompleteDest = S.Context.getAsIncompleteArrayType(Step->Type)) { if (const ConstantArrayType *ConstantSource = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { *ResultType = S.Context.getConstantArrayType( IncompleteDest->getElementType(), ConstantSource->getSize(), ArrayType::Normal, 0); } } } break; case SK_ParenthesizedArrayInit: // Okay: we checked everything before creating this step. Note that // this is a GNU extension. S.Diag(Kind.getLocation(), diag::ext_array_init_parens) << CurInit.get()->getSourceRange(); break; case SK_PassByIndirectCopyRestore: case SK_PassByIndirectRestore: checkIndirectCopyRestoreSource(S, CurInit.get()); CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( CurInit.get(), Step->Type, Step->Kind == SK_PassByIndirectCopyRestore); break; case SK_ProduceObjCObject: CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr, VK_RValue); break; case SK_StdInitializerList: { S.Diag(CurInit.get()->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init) << CurInit.get()->getSourceRange(); // Materialize the temporary into memory. MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( CurInit.get()->getType(), CurInit.get(), /*BoundToLvalueReference=*/false); // Maybe lifetime-extend the array temporary's subobjects to match the // entity's lifetime. if (const InitializedEntity *ExtendingEntity = getEntityForTemporaryLifetimeExtension(&Entity)) if (performReferenceExtension(MTE, ExtendingEntity)) warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/true, ExtendingEntity->getDecl()); // Wrap it in a construction of a std::initializer_list. CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); // Bind the result, in case the library has given initializer_list a // non-trivial destructor. if (shouldBindAsTemporary(Entity)) CurInit = S.MaybeBindToTemporary(CurInit.get()); break; } case SK_OCLSamplerInit: { // Sampler initialzation have 5 cases: // 1. function argument passing // 1a. argument is a file-scope variable // 1b. argument is a function-scope variable // 1c. argument is one of caller function's parameters // 2. variable initialization // 2a. initializing a file-scope variable // 2b. initializing a function-scope variable // // For file-scope variables, since they cannot be initialized by function // call of __translate_sampler_initializer in LLVM IR, their references // need to be replaced by a cast from their literal initializers to // sampler type. Since sampler variables can only be used in function // calls as arguments, we only need to replace them when handling the // argument passing. assert(Step->Type->isSamplerT() && "Sampler initialization on non-sampler type."); Expr *Init = CurInit.get(); QualType SourceType = Init->getType(); // Case 1 if (Entity.isParameterKind()) { if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) << SourceType; break; } else if (const DeclRefExpr *DRE = dyn_cast(Init)) { auto Var = cast(DRE->getDecl()); // Case 1b and 1c // No cast from integer to sampler is needed. if (!Var->hasGlobalStorage()) { CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, CK_LValueToRValue, Init, /*BasePath=*/nullptr, VK_RValue); break; } // Case 1a // For function call with a file-scope sampler variable as argument, // get the integer literal. // Do not diagnose if the file-scope variable does not have initializer // since this has already been diagnosed when parsing the variable // declaration. if (!Var->getInit() || !isa(Var->getInit())) break; Init = cast(const_cast( Var->getInit()))->getSubExpr(); SourceType = Init->getType(); } } else { // Case 2 // Check initializer is 32 bit integer constant. // If the initializer is taken from global variable, do not diagnose since // this has already been done when parsing the variable declaration. if (!Init->isConstantInitializer(S.Context, false)) break; if (!SourceType->isIntegerType() || 32 != S.Context.getIntWidth(SourceType)) { S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) << SourceType; break; } llvm::APSInt Result; Init->EvaluateAsInt(Result, S.Context); const uint64_t SamplerValue = Result.getLimitedValue(); // 32-bit value of sampler's initializer is interpreted as // bit-field with the following structure: // |unspecified|Filter|Addressing Mode| Normalized Coords| // |31 6|5 4|3 1| 0| // This structure corresponds to enum values of sampler properties // defined in SPIR spec v1.2 and also opencl-c.h unsigned AddressingMode = (0x0E & SamplerValue) >> 1; unsigned FilterMode = (0x30 & SamplerValue) >> 4; if (FilterMode != 1 && FilterMode != 2) S.Diag(Kind.getLocation(), diag::warn_sampler_initializer_invalid_bits) << "Filter Mode"; if (AddressingMode > 4) S.Diag(Kind.getLocation(), diag::warn_sampler_initializer_invalid_bits) << "Addressing Mode"; } // Cases 1a, 2a and 2b // Insert cast from integer to sampler. CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, CK_IntToOCLSampler); break; } case SK_OCLZeroEvent: { assert(Step->Type->isEventT() && "Event initialization on non-event type."); CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_ZeroToOCLEvent, CurInit.get()->getValueKind()); break; } case SK_OCLZeroQueue: { assert(Step->Type->isQueueT() && "Event initialization on non queue type."); CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_ZeroToOCLQueue, CurInit.get()->getValueKind()); break; } } } // Diagnose non-fatal problems with the completed initialization. if (Entity.getKind() == InitializedEntity::EK_Member && cast(Entity.getDecl())->isBitField()) S.CheckBitFieldInitialization(Kind.getLocation(), cast(Entity.getDecl()), CurInit.get()); // Check for std::move on construction. if (const Expr *E = CurInit.get()) { CheckMoveOnConstruction(S, E, Entity.getKind() == InitializedEntity::EK_Result); } return CurInit; } /// Somewhere within T there is an uninitialized reference subobject. /// Dig it out and diagnose it. static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T) { if (T->isReferenceType()) { S.Diag(Loc, diag::err_reference_without_init) << T.getNonReferenceType(); return true; } CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); if (!RD || !RD->hasUninitializedReferenceMember()) return false; for (const auto *FI : RD->fields()) { if (FI->isUnnamedBitfield()) continue; if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { S.Diag(Loc, diag::note_value_initialization_here) << RD; return true; } } for (const auto &BI : RD->bases()) { if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) { S.Diag(Loc, diag::note_value_initialization_here) << RD; return true; } } return false; } //===----------------------------------------------------------------------===// // Diagnose initialization failures //===----------------------------------------------------------------------===// /// Emit notes associated with an initialization that failed due to a /// "simple" conversion failure. static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, Expr *op) { QualType destType = entity.getType(); if (destType.getNonReferenceType()->isObjCObjectPointerType() && op->getType()->isObjCObjectPointerType()) { // Emit a possible note about the conversion failing because the // operand is a message send with a related result type. S.EmitRelatedResultTypeNote(op); // Emit a possible note about a return failing because we're // expecting a related result type. if (entity.getKind() == InitializedEntity::EK_Result) S.EmitRelatedResultTypeNoteForReturn(destType); } } static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList) { QualType DestType = Entity.getType(); QualType E; if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { QualType ArrayType = S.Context.getConstantArrayType( E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), InitList->getNumInits()), clang::ArrayType::Normal, 0); InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(ArrayType); return diagnoseListInit(S, HiddenArray, InitList); } if (DestType->isReferenceType()) { // A list-initialization failure for a reference means that we tried to // create a temporary of the inner type (per [dcl.init.list]p3.6) and the // inner initialization failed. QualType T = DestType->getAs()->getPointeeType(); diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); SourceLocation Loc = InitList->getLocStart(); if (auto *D = Entity.getDecl()) Loc = D->getLocation(); S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; return; } InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, /*VerifyOnly=*/false, /*TreatUnavailableAsInvalid=*/false); assert(DiagnoseInitList.HadError() && "Inconsistent init list check result."); } bool InitializationSequence::Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef Args) { if (!Failed()) return false; QualType DestType = Entity.getType(); switch (Failure) { case FK_TooManyInitsForReference: // FIXME: Customize for the initialized entity? if (Args.empty()) { // Dig out the reference subobject which is uninitialized and diagnose it. // If this is value-initialization, this could be nested some way within // the target type. assert(Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()); bool Diagnosed = DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); assert(Diagnosed && "couldn't find uninitialized reference to diagnose"); (void)Diagnosed; } else // FIXME: diagnostic below could be better! S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd()); break; case FK_ParenthesizedListInitForReference: S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) << 1 << Entity.getType() << Args[0]->getSourceRange(); break; case FK_ArrayNeedsInitList: S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; break; case FK_ArrayNeedsInitListOrStringLiteral: S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; break; case FK_ArrayNeedsInitListOrWideStringLiteral: S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; break; case FK_NarrowStringIntoWideCharArray: S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); break; case FK_WideStringIntoCharArray: S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); break; case FK_IncompatWideStringIntoWideChar: S.Diag(Kind.getLocation(), diag::err_array_init_incompat_wide_string_into_wchar); break; case FK_ArrayTypeMismatch: case FK_NonConstantArrayInit: S.Diag(Kind.getLocation(), (Failure == FK_ArrayTypeMismatch ? diag::err_array_init_different_type : diag::err_array_init_non_constant_array)) << DestType.getNonReferenceType() << Args[0]->getType() << Args[0]->getSourceRange(); break; case FK_VariableLengthArrayHasInitializer: S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) << Args[0]->getSourceRange(); break; case FK_AddressOfOverloadFailed: { DeclAccessPair Found; S.ResolveAddressOfOverloadedFunction(Args[0], DestType.getNonReferenceType(), true, Found); break; } case FK_AddressOfUnaddressableFunction: { auto *FD = cast(cast(Args[0])->getDecl()); S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, Args[0]->getLocStart()); break; } case FK_ReferenceInitOverloadFailed: case FK_UserConversionOverloadFailed: switch (FailedOverloadResult) { case OR_Ambiguous: if (Failure == FK_UserConversionOverloadFailed) S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) << Args[0]->getType() << DestType << Args[0]->getSourceRange(); else S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) << DestType << Args[0]->getType() << Args[0]->getSourceRange(); FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); break; case OR_No_Viable_Function: if (!S.RequireCompleteType(Kind.getLocation(), DestType.getNonReferenceType(), diag::err_typecheck_nonviable_condition_incomplete, Args[0]->getType(), Args[0]->getSourceRange())) S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) << (Entity.getKind() == InitializedEntity::EK_Result) << Args[0]->getType() << Args[0]->getSourceRange() << DestType.getNonReferenceType(); FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); break; case OR_Deleted: { S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) << Args[0]->getType() << DestType.getNonReferenceType() << Args[0]->getSourceRange(); OverloadCandidateSet::iterator Best; OverloadingResult Ovl = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, true); if (Ovl == OR_Deleted) { S.NoteDeletedFunction(Best->Function); } else { llvm_unreachable("Inconsistent overload resolution?"); } break; } case OR_Success: llvm_unreachable("Conversion did not fail!"); } break; case FK_NonConstLValueReferenceBindingToTemporary: if (isa(Args[0])) { S.Diag(Kind.getLocation(), diag::err_lvalue_reference_bind_to_initlist) << DestType.getNonReferenceType().isVolatileQualified() << DestType.getNonReferenceType() << Args[0]->getSourceRange(); break; } // Intentional fallthrough case FK_NonConstLValueReferenceBindingToUnrelated: S.Diag(Kind.getLocation(), Failure == FK_NonConstLValueReferenceBindingToTemporary ? diag::err_lvalue_reference_bind_to_temporary : diag::err_lvalue_reference_bind_to_unrelated) << DestType.getNonReferenceType().isVolatileQualified() << DestType.getNonReferenceType() << Args[0]->getType() << Args[0]->getSourceRange(); break; case FK_NonConstLValueReferenceBindingToBitfield: { // We don't necessarily have an unambiguous source bit-field. FieldDecl *BitField = Args[0]->getSourceBitField(); S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) << DestType.isVolatileQualified() << (BitField ? BitField->getDeclName() : DeclarationName()) << (BitField != nullptr) << Args[0]->getSourceRange(); if (BitField) S.Diag(BitField->getLocation(), diag::note_bitfield_decl); break; } case FK_NonConstLValueReferenceBindingToVectorElement: S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) << DestType.isVolatileQualified() << Args[0]->getSourceRange(); break; case FK_RValueReferenceBindingToLValue: S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) << DestType.getNonReferenceType() << Args[0]->getType() << Args[0]->getSourceRange(); break; case FK_ReferenceInitDropsQualifiers: { QualType SourceType = Args[0]->getType(); QualType NonRefType = DestType.getNonReferenceType(); Qualifiers DroppedQualifiers = SourceType.getQualifiers() - NonRefType.getQualifiers(); S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) << SourceType << NonRefType << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); break; } case FK_ReferenceInitFailed: S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) << DestType.getNonReferenceType() << Args[0]->isLValue() << Args[0]->getType() << Args[0]->getSourceRange(); emitBadConversionNotes(S, Entity, Args[0]); break; case FK_ConversionFailed: { QualType FromType = Args[0]->getType(); PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) << (int)Entity.getKind() << DestType << Args[0]->isLValue() << FromType << Args[0]->getSourceRange(); S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); S.Diag(Kind.getLocation(), PDiag); emitBadConversionNotes(S, Entity, Args[0]); break; } case FK_ConversionFromPropertyFailed: // No-op. This error has already been reported. break; case FK_TooManyInitsForScalar: { SourceRange R; auto *InitList = dyn_cast(Args[0]); if (InitList && InitList->getNumInits() >= 1) { R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd()); } else { assert(Args.size() > 1 && "Expected multiple initializers!"); R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd()); } R.setBegin(S.getLocForEndOfToken(R.getBegin())); if (Kind.isCStyleOrFunctionalCast()) S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) << R; else S.Diag(Kind.getLocation(), diag::err_excess_initializers) << /*scalar=*/2 << R; break; } case FK_ParenthesizedListInitForScalar: S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) << 0 << Entity.getType() << Args[0]->getSourceRange(); break; case FK_ReferenceBindingToInitList: S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) << DestType.getNonReferenceType() << Args[0]->getSourceRange(); break; case FK_InitListBadDestinationType: S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); break; case FK_ListConstructorOverloadFailed: case FK_ConstructorOverloadFailed: { SourceRange ArgsRange; if (Args.size()) ArgsRange = SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd()); if (Failure == FK_ListConstructorOverloadFailed) { assert(Args.size() == 1 && "List construction from other than 1 argument."); InitListExpr *InitList = cast(Args[0]); Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); } // FIXME: Using "DestType" for the entity we're printing is probably // bad. switch (FailedOverloadResult) { case OR_Ambiguous: S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) << DestType << ArgsRange; FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args); break; case OR_No_Viable_Function: if (Kind.getKind() == InitializationKind::IK_Default && (Entity.getKind() == InitializedEntity::EK_Base || Entity.getKind() == InitializedEntity::EK_Member) && isa(S.CurContext)) { // This is implicit default initialization of a member or // base within a constructor. If no viable function was // found, notify the user that they need to explicitly // initialize this base/member. CXXConstructorDecl *Constructor = cast(S.CurContext); const CXXRecordDecl *InheritedFrom = nullptr; if (auto Inherited = Constructor->getInheritedConstructor()) InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); if (Entity.getKind() == InitializedEntity::EK_Base) { S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) << S.Context.getTypeDeclType(Constructor->getParent()) << /*base=*/0 << Entity.getType() << InheritedFrom; RecordDecl *BaseDecl = Entity.getBaseSpecifier()->getType()->getAs() ->getDecl(); S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) << S.Context.getTagDeclType(BaseDecl); } else { S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) << S.Context.getTypeDeclType(Constructor->getParent()) << /*member=*/1 << Entity.getName() << InheritedFrom; S.Diag(Entity.getDecl()->getLocation(), diag::note_member_declared_at); if (const RecordType *Record = Entity.getType()->getAs()) S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl) << S.Context.getTagDeclType(Record->getDecl()); } break; } S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) << DestType << ArgsRange; FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args); break; case OR_Deleted: { OverloadCandidateSet::iterator Best; OverloadingResult Ovl = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); if (Ovl != OR_Deleted) { S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) << true << DestType << ArgsRange; llvm_unreachable("Inconsistent overload resolution?"); break; } // If this is a defaulted or implicitly-declared function, then // it was implicitly deleted. Make it clear that the deletion was // implicit. if (S.isImplicitlyDeleted(Best->Function)) S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) << S.getSpecialMember(cast(Best->Function)) << DestType << ArgsRange; else S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) << true << DestType << ArgsRange; S.NoteDeletedFunction(Best->Function); break; } case OR_Success: llvm_unreachable("Conversion did not fail!"); } } break; case FK_DefaultInitOfConst: if (Entity.getKind() == InitializedEntity::EK_Member && isa(S.CurContext)) { // This is implicit default-initialization of a const member in // a constructor. Complain that it needs to be explicitly // initialized. CXXConstructorDecl *Constructor = cast(S.CurContext); S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) << (Constructor->getInheritedConstructor() ? 2 : Constructor->isImplicit() ? 1 : 0) << S.Context.getTypeDeclType(Constructor->getParent()) << /*const=*/1 << Entity.getName(); S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) << Entity.getName(); } else { S.Diag(Kind.getLocation(), diag::err_default_init_const) << DestType << (bool)DestType->getAs(); } break; case FK_Incomplete: S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, diag::err_init_incomplete_type); break; case FK_ListInitializationFailed: { // Run the init list checker again to emit diagnostics. InitListExpr *InitList = cast(Args[0]); diagnoseListInit(S, Entity, InitList); break; } case FK_PlaceholderType: { // FIXME: Already diagnosed! break; } case FK_ExplicitConstructor: { S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) << Args[0]->getSourceRange(); OverloadCandidateSet::iterator Best; OverloadingResult Ovl = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); (void)Ovl; assert(Ovl == OR_Success && "Inconsistent overload resolution"); CXXConstructorDecl *CtorDecl = cast(Best->Function); S.Diag(CtorDecl->getLocation(), diag::note_explicit_ctor_deduction_guide_here) << false; break; } } PrintInitLocationNote(S, Entity); return true; } void InitializationSequence::dump(raw_ostream &OS) const { switch (SequenceKind) { case FailedSequence: { OS << "Failed sequence: "; switch (Failure) { case FK_TooManyInitsForReference: OS << "too many initializers for reference"; break; case FK_ParenthesizedListInitForReference: OS << "parenthesized list init for reference"; break; case FK_ArrayNeedsInitList: OS << "array requires initializer list"; break; case FK_AddressOfUnaddressableFunction: OS << "address of unaddressable function was taken"; break; case FK_ArrayNeedsInitListOrStringLiteral: OS << "array requires initializer list or string literal"; break; case FK_ArrayNeedsInitListOrWideStringLiteral: OS << "array requires initializer list or wide string literal"; break; case FK_NarrowStringIntoWideCharArray: OS << "narrow string into wide char array"; break; case FK_WideStringIntoCharArray: OS << "wide string into char array"; break; case FK_IncompatWideStringIntoWideChar: OS << "incompatible wide string into wide char array"; break; case FK_ArrayTypeMismatch: OS << "array type mismatch"; break; case FK_NonConstantArrayInit: OS << "non-constant array initializer"; break; case FK_AddressOfOverloadFailed: OS << "address of overloaded function failed"; break; case FK_ReferenceInitOverloadFailed: OS << "overload resolution for reference initialization failed"; break; case FK_NonConstLValueReferenceBindingToTemporary: OS << "non-const lvalue reference bound to temporary"; break; case FK_NonConstLValueReferenceBindingToBitfield: OS << "non-const lvalue reference bound to bit-field"; break; case FK_NonConstLValueReferenceBindingToVectorElement: OS << "non-const lvalue reference bound to vector element"; break; case FK_NonConstLValueReferenceBindingToUnrelated: OS << "non-const lvalue reference bound to unrelated type"; break; case FK_RValueReferenceBindingToLValue: OS << "rvalue reference bound to an lvalue"; break; case FK_ReferenceInitDropsQualifiers: OS << "reference initialization drops qualifiers"; break; case FK_ReferenceInitFailed: OS << "reference initialization failed"; break; case FK_ConversionFailed: OS << "conversion failed"; break; case FK_ConversionFromPropertyFailed: OS << "conversion from property failed"; break; case FK_TooManyInitsForScalar: OS << "too many initializers for scalar"; break; case FK_ParenthesizedListInitForScalar: OS << "parenthesized list init for reference"; break; case FK_ReferenceBindingToInitList: OS << "referencing binding to initializer list"; break; case FK_InitListBadDestinationType: OS << "initializer list for non-aggregate, non-scalar type"; break; case FK_UserConversionOverloadFailed: OS << "overloading failed for user-defined conversion"; break; case FK_ConstructorOverloadFailed: OS << "constructor overloading failed"; break; case FK_DefaultInitOfConst: OS << "default initialization of a const variable"; break; case FK_Incomplete: OS << "initialization of incomplete type"; break; case FK_ListInitializationFailed: OS << "list initialization checker failure"; break; case FK_VariableLengthArrayHasInitializer: OS << "variable length array has an initializer"; break; case FK_PlaceholderType: OS << "initializer expression isn't contextually valid"; break; case FK_ListConstructorOverloadFailed: OS << "list constructor overloading failed"; break; case FK_ExplicitConstructor: OS << "list copy initialization chose explicit constructor"; break; } OS << '\n'; return; } case DependentSequence: OS << "Dependent sequence\n"; return; case NormalSequence: OS << "Normal sequence: "; break; } for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { if (S != step_begin()) { OS << " -> "; } switch (S->Kind) { case SK_ResolveAddressOfOverloadedFunction: OS << "resolve address of overloaded function"; break; case SK_CastDerivedToBaseRValue: OS << "derived-to-base (rvalue)"; break; case SK_CastDerivedToBaseXValue: OS << "derived-to-base (xvalue)"; break; case SK_CastDerivedToBaseLValue: OS << "derived-to-base (lvalue)"; break; case SK_BindReference: OS << "bind reference to lvalue"; break; case SK_BindReferenceToTemporary: OS << "bind reference to a temporary"; break; case SK_FinalCopy: OS << "final copy in class direct-initialization"; break; case SK_ExtraneousCopyToTemporary: OS << "extraneous C++03 copy to temporary"; break; case SK_UserConversion: OS << "user-defined conversion via " << *S->Function.Function; break; case SK_QualificationConversionRValue: OS << "qualification conversion (rvalue)"; break; case SK_QualificationConversionXValue: OS << "qualification conversion (xvalue)"; break; case SK_QualificationConversionLValue: OS << "qualification conversion (lvalue)"; break; case SK_AtomicConversion: OS << "non-atomic-to-atomic conversion"; break; case SK_LValueToRValue: OS << "load (lvalue to rvalue)"; break; case SK_ConversionSequence: OS << "implicit conversion sequence ("; S->ICS->dump(); // FIXME: use OS OS << ")"; break; case SK_ConversionSequenceNoNarrowing: OS << "implicit conversion sequence with narrowing prohibited ("; S->ICS->dump(); // FIXME: use OS OS << ")"; break; case SK_ListInitialization: OS << "list aggregate initialization"; break; case SK_UnwrapInitList: OS << "unwrap reference initializer list"; break; case SK_RewrapInitList: OS << "rewrap reference initializer list"; break; case SK_ConstructorInitialization: OS << "constructor initialization"; break; case SK_ConstructorInitializationFromList: OS << "list initialization via constructor"; break; case SK_ZeroInitialization: OS << "zero initialization"; break; case SK_CAssignment: OS << "C assignment"; break; case SK_StringInit: OS << "string initialization"; break; case SK_ObjCObjectConversion: OS << "Objective-C object conversion"; break; case SK_ArrayLoopIndex: OS << "indexing for array initialization loop"; break; case SK_ArrayLoopInit: OS << "array initialization loop"; break; case SK_ArrayInit: OS << "array initialization"; break; case SK_GNUArrayInit: OS << "array initialization (GNU extension)"; break; case SK_ParenthesizedArrayInit: OS << "parenthesized array initialization"; break; case SK_PassByIndirectCopyRestore: OS << "pass by indirect copy and restore"; break; case SK_PassByIndirectRestore: OS << "pass by indirect restore"; break; case SK_ProduceObjCObject: OS << "Objective-C object retension"; break; case SK_StdInitializerList: OS << "std::initializer_list from initializer list"; break; case SK_StdInitializerListConstructorCall: OS << "list initialization from std::initializer_list"; break; case SK_OCLSamplerInit: OS << "OpenCL sampler_t from integer constant"; break; case SK_OCLZeroEvent: OS << "OpenCL event_t from zero"; break; case SK_OCLZeroQueue: OS << "OpenCL queue_t from zero"; break; } OS << " [" << S->Type.getAsString() << ']'; } OS << '\n'; } void InitializationSequence::dump() const { dump(llvm::errs()); } static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit) { const StandardConversionSequence *SCS = nullptr; switch (ICS.getKind()) { case ImplicitConversionSequence::StandardConversion: SCS = &ICS.Standard; break; case ImplicitConversionSequence::UserDefinedConversion: SCS = &ICS.UserDefined.After; break; case ImplicitConversionSequence::AmbiguousConversion: case ImplicitConversionSequence::EllipsisConversion: case ImplicitConversionSequence::BadConversion: return; } // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. APValue ConstantValue; QualType ConstantType; switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, ConstantType)) { case NK_Not_Narrowing: case NK_Dependent_Narrowing: // No narrowing occurred. return; case NK_Type_Narrowing: // This was a floating-to-integer conversion, which is always considered a // narrowing conversion even if the value is a constant and can be // represented exactly as an integer. S.Diag(PostInit->getLocStart(), (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) ? diag::warn_init_list_type_narrowing : diag::ext_init_list_type_narrowing) << PostInit->getSourceRange() << PreNarrowingType.getLocalUnqualifiedType() << EntityType.getLocalUnqualifiedType(); break; case NK_Constant_Narrowing: // A constant value was narrowed. S.Diag(PostInit->getLocStart(), (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) ? diag::warn_init_list_constant_narrowing : diag::ext_init_list_constant_narrowing) << PostInit->getSourceRange() << ConstantValue.getAsString(S.getASTContext(), ConstantType) << EntityType.getLocalUnqualifiedType(); break; case NK_Variable_Narrowing: // A variable's value may have been narrowed. S.Diag(PostInit->getLocStart(), (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11) ? diag::warn_init_list_variable_narrowing : diag::ext_init_list_variable_narrowing) << PostInit->getSourceRange() << PreNarrowingType.getLocalUnqualifiedType() << EntityType.getLocalUnqualifiedType(); break; } SmallString<128> StaticCast; llvm::raw_svector_ostream OS(StaticCast); OS << "static_cast<"; if (const TypedefType *TT = EntityType->getAs()) { // It's important to use the typedef's name if there is one so that the // fixit doesn't break code using types like int64_t. // // FIXME: This will break if the typedef requires qualification. But // getQualifiedNameAsString() includes non-machine-parsable components. OS << *TT->getDecl(); } else if (const BuiltinType *BT = EntityType->getAs()) OS << BT->getName(S.getLangOpts()); else { // Oops, we didn't find the actual type of the variable. Don't emit a fixit // with a broken cast. return; } OS << ">("; S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence) << PostInit->getSourceRange() << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str()) << FixItHint::CreateInsertion( S.getLocForEndOfToken(PostInit->getLocEnd()), ")"); } //===----------------------------------------------------------------------===// // Initialization helper functions //===----------------------------------------------------------------------===// bool Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init) { if (Init.isInvalid()) return false; Expr *InitE = Init.get(); assert(InitE && "No initialization expression"); InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation()); InitializationSequence Seq(*this, Entity, Kind, InitE); return !Seq.Failed(); } ExprResult Sema::PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList, bool AllowExplicit) { if (Init.isInvalid()) return ExprError(); Expr *InitE = Init.get(); assert(InitE && "No initialization expression?"); if (EqualLoc.isInvalid()) EqualLoc = InitE->getLocStart(); InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), EqualLoc, AllowExplicit); InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); // Prevent infinite recursion when performing parameter copy-initialization. const bool ShouldTrackCopy = Entity.isParameterKind() && Seq.isConstructorInitialization(); if (ShouldTrackCopy) { if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != CurrentParameterCopyTypes.end()) { Seq.SetOverloadFailure( InitializationSequence::FK_ConstructorOverloadFailed, OR_No_Viable_Function); // Try to give a meaningful diagnostic note for the problematic // constructor. const auto LastStep = Seq.step_end() - 1; assert(LastStep->Kind == InitializationSequence::SK_ConstructorInitialization); const FunctionDecl *Function = LastStep->Function.Function; auto Candidate = llvm::find_if(Seq.getFailedCandidateSet(), [Function](const OverloadCandidate &Candidate) -> bool { return Candidate.Viable && Candidate.Function == Function && Candidate.Conversions.size() > 0; }); if (Candidate != Seq.getFailedCandidateSet().end() && Function->getNumParams() > 0) { Candidate->Viable = false; Candidate->FailureKind = ovl_fail_bad_conversion; Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, InitE, Function->getParamDecl(0)->getType()); } } CurrentParameterCopyTypes.push_back(Entity.getType()); } ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); if (ShouldTrackCopy) CurrentParameterCopyTypes.pop_back(); return Result; } QualType Sema::DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TSInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Inits) { auto *DeducedTST = dyn_cast( TSInfo->getType()->getContainedDeducedType()); assert(DeducedTST && "not a deduced template specialization type"); // We can only perform deduction for class templates. auto TemplateName = DeducedTST->getTemplateName(); auto *Template = dyn_cast_or_null(TemplateName.getAsTemplateDecl()); if (!Template) { Diag(Kind.getLocation(), diag::err_deduced_non_class_template_specialization_type) << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; if (auto *TD = TemplateName.getAsTemplateDecl()) Diag(TD->getLocation(), diag::note_template_decl_here); return QualType(); } // Can't deduce from dependent arguments. if (Expr::hasAnyTypeDependentArguments(Inits)) return Context.DependentTy; // FIXME: Perform "exact type" matching first, per CWG discussion? // Or implement this via an implied 'T(T) -> T' deduction guide? // FIXME: Do we need/want a std::initializer_list special case? // Look up deduction guides, including those synthesized from constructors. // // C++1z [over.match.class.deduct]p1: // A set of functions and function templates is formed comprising: // - For each constructor of the class template designated by the // template-name, a function template [...] // - For each deduction-guide, a function or function template [...] DeclarationNameInfo NameInfo( Context.DeclarationNames.getCXXDeductionGuideName(Template), TSInfo->getTypeLoc().getEndLoc()); LookupResult Guides(*this, NameInfo, LookupOrdinaryName); LookupQualifiedName(Guides, Template->getDeclContext()); // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't // clear on this, but they're not found by name so access does not apply. Guides.suppressDiagnostics(); // Figure out if this is list-initialization. InitListExpr *ListInit = (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) ? dyn_cast(Inits[0]) : nullptr; // C++1z [over.match.class.deduct]p1: // Initialization and overload resolution are performed as described in // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] // (as appropriate for the type of initialization performed) for an object // of a hypothetical class type, where the selected functions and function // templates are considered to be the constructors of that class type // // Since we know we're initializing a class type of a type unrelated to that // of the initializer, this reduces to something fairly reasonable. OverloadCandidateSet Candidates(Kind.getLocation(), OverloadCandidateSet::CSK_Normal); OverloadCandidateSet::iterator Best; auto tryToResolveOverload = [&](bool OnlyListConstructors) -> OverloadingResult { Candidates.clear(); for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { NamedDecl *D = (*I)->getUnderlyingDecl(); if (D->isInvalidDecl()) continue; auto *TD = dyn_cast(D); auto *GD = dyn_cast_or_null( TD ? TD->getTemplatedDecl() : dyn_cast(D)); if (!GD) continue; // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) // For copy-initialization, the candidate functions are all the // converting constructors (12.3.1) of that class. // C++ [over.match.copy]p1: (non-list copy-initialization from class) // The converting constructors of T are candidate functions. if (Kind.isCopyInit() && !ListInit) { // Only consider converting constructors. if (GD->isExplicit()) continue; // When looking for a converting constructor, deduction guides that // could never be called with one argument are not interesting to // check or note. if (GD->getMinRequiredArguments() > 1 || (GD->getNumParams() == 0 && !GD->isVariadic())) continue; } // C++ [over.match.list]p1.1: (first phase list initialization) // Initially, the candidate functions are the initializer-list // constructors of the class T if (OnlyListConstructors && !isInitListConstructor(GD)) continue; // C++ [over.match.list]p1.2: (second phase list initialization) // the candidate functions are all the constructors of the class T // C++ [over.match.ctor]p1: (all other cases) // the candidate functions are all the constructors of the class of // the object being initialized // C++ [over.best.ics]p4: // When [...] the constructor [...] is a candidate by // - [over.match.copy] (in all cases) // FIXME: The "second phase of [over.match.list] case can also // theoretically happen here, but it's not clear whether we can // ever have a parameter of the right type. bool SuppressUserConversions = Kind.isCopyInit(); if (TD) AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, Inits, Candidates, SuppressUserConversions); else AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, SuppressUserConversions); } return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); }; OverloadingResult Result = OR_No_Viable_Function; // C++11 [over.match.list]p1, per DR1467: for list-initialization, first // try initializer-list constructors. if (ListInit) { bool TryListConstructors = true; // Try list constructors unless the list is empty and the class has one or // more default constructors, in which case those constructors win. if (!ListInit->getNumInits()) { for (NamedDecl *D : Guides) { auto *FD = dyn_cast(D->getUnderlyingDecl()); if (FD && FD->getMinRequiredArguments() == 0) { TryListConstructors = false; break; } } } if (TryListConstructors) Result = tryToResolveOverload(/*OnlyListConstructor*/true); // Then unwrap the initializer list and try again considering all // constructors. Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); } // If list-initialization fails, or if we're doing any other kind of // initialization, we (eventually) consider constructors. if (Result == OR_No_Viable_Function) Result = tryToResolveOverload(/*OnlyListConstructor*/false); switch (Result) { case OR_Ambiguous: Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous) << TemplateName; // FIXME: For list-initialization candidates, it'd usually be better to // list why they were not viable when given the initializer list itself as // an argument. Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits); return QualType(); case OR_No_Viable_Function: { CXXRecordDecl *Primary = cast(Template)->getTemplatedDecl(); bool Complete = isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); Diag(Kind.getLocation(), Complete ? diag::err_deduced_class_template_ctor_no_viable : diag::err_deduced_class_template_incomplete) << TemplateName << !Guides.empty(); Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits); return QualType(); } case OR_Deleted: { Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) << TemplateName; NoteDeletedFunction(Best->Function); return QualType(); } case OR_Success: // C++ [over.match.list]p1: // In copy-list-initialization, if an explicit constructor is chosen, the // initialization is ill-formed. if (Kind.isCopyInit() && ListInit && cast(Best->Function)->isExplicit()) { bool IsDeductionGuide = !Best->Function->isImplicit(); Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) << TemplateName << IsDeductionGuide; Diag(Best->Function->getLocation(), diag::note_explicit_ctor_deduction_guide_here) << IsDeductionGuide; return QualType(); } // Make sure we didn't select an unusable deduction guide, and mark it // as referenced. DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); MarkFunctionReferenced(Kind.getLocation(), Best->Function); break; } // C++ [dcl.type.class.deduct]p1: // The placeholder is replaced by the return type of the function selected // by overload resolution for class template deduction. return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); }