clang API Documentation

Initialization.h
Go to the documentation of this file.
00001 //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file provides supporting data types for initialization of objects.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
00014 #define LLVM_CLANG_SEMA_INITIALIZATION_H
00015 
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/Type.h"
00019 #include "clang/AST/UnresolvedSet.h"
00020 #include "clang/Basic/SourceLocation.h"
00021 #include "clang/Sema/Overload.h"
00022 #include "clang/Sema/Ownership.h"
00023 #include "llvm/ADT/PointerIntPair.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include <cassert>
00026 
00027 namespace clang {
00028   
00029 class CXXBaseSpecifier;
00030 class DeclaratorDecl;
00031 class DeclaratorInfo;
00032 class FieldDecl;
00033 class FunctionDecl;
00034 class ParmVarDecl;
00035 class Sema;
00036 class TypeLoc;
00037 class VarDecl;
00038 class ObjCMethodDecl;
00039   
00040 /// \brief Describes an entity that is being initialized.
00041 class InitializedEntity {
00042 public:
00043   /// \brief Specifies the kind of entity being initialized.
00044   enum EntityKind {
00045     /// \brief The entity being initialized is a variable.
00046     EK_Variable,
00047     /// \brief The entity being initialized is a function parameter.
00048     EK_Parameter,
00049     /// \brief The entity being initialized is the result of a function call.
00050     EK_Result,
00051     /// \brief The entity being initialized is an exception object that
00052     /// is being thrown.
00053     EK_Exception,
00054     /// \brief The entity being initialized is a non-static data member 
00055     /// subobject.
00056     EK_Member,
00057     /// \brief The entity being initialized is an element of an array.
00058     EK_ArrayElement,
00059     /// \brief The entity being initialized is an object (or array of
00060     /// objects) allocated via new.
00061     EK_New,
00062     /// \brief The entity being initialized is a temporary object.
00063     EK_Temporary,
00064     /// \brief The entity being initialized is a base member subobject.
00065     EK_Base,
00066     /// \brief The initialization is being done by a delegating constructor.
00067     EK_Delegating,
00068     /// \brief The entity being initialized is an element of a vector.
00069     /// or vector.
00070     EK_VectorElement,
00071     /// \brief The entity being initialized is a field of block descriptor for
00072     /// the copied-in c++ object.
00073     EK_BlockElement,
00074     /// \brief The entity being initialized is the real or imaginary part of a
00075     /// complex number.
00076     EK_ComplexElement,
00077     /// \brief The entity being initialized is the field that captures a 
00078     /// variable in a lambda.
00079     EK_LambdaCapture,
00080     /// \brief The entity being initialized is the initializer for a compound
00081     /// literal.
00082     EK_CompoundLiteralInit,
00083     /// \brief The entity being implicitly initialized back to the formal
00084     /// result type.
00085     EK_RelatedResult,
00086     /// \brief The entity being initialized is a function parameter; function
00087     /// is member of group of audited CF APIs.
00088     EK_Parameter_CF_Audited
00089 
00090     // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
00091     // enum as an index for its first %select.  When modifying this list,
00092     // that diagnostic text needs to be updated as well.
00093   };
00094   
00095 private:
00096   /// \brief The kind of entity being initialized.
00097   EntityKind Kind;
00098 
00099   /// \brief If non-NULL, the parent entity in which this
00100   /// initialization occurs.
00101   const InitializedEntity *Parent;
00102 
00103   /// \brief The type of the object or reference being initialized.
00104   QualType Type;
00105 
00106   /// \brief The mangling number for the next reference temporary to be created.
00107   mutable unsigned ManglingNumber;
00108 
00109   struct LN {
00110     /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
00111     /// location of the 'return', 'throw', or 'new' keyword,
00112     /// respectively. When Kind == EK_Temporary, the location where
00113     /// the temporary is being created.
00114     unsigned Location;
00115 
00116     /// \brief Whether the entity being initialized may end up using the
00117     /// named return value optimization (NRVO).
00118     bool NRVO;
00119   };
00120 
00121   struct C {
00122     /// \brief The name of the variable being captured by an EK_LambdaCapture.
00123     IdentifierInfo *VarID;
00124 
00125     /// \brief The source location at which the capture occurs.
00126     unsigned Location;
00127   };
00128 
00129   union {
00130     /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
00131     /// FieldDecl, respectively.
00132     DeclaratorDecl *VariableOrMember;
00133     
00134     /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where
00135     /// result type was implicitly changed to accommodate ARC semantics.
00136     ObjCMethodDecl *MethodDecl;
00137 
00138     /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
00139     /// low bit indicating whether the parameter is "consumed".
00140     uintptr_t Parameter;
00141     
00142     /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
00143     /// source information for the temporary.
00144     TypeSourceInfo *TypeInfo;
00145 
00146     struct LN LocAndNRVO;
00147     
00148     /// \brief When Kind == EK_Base, the base specifier that provides the 
00149     /// base class. The lower bit specifies whether the base is an inherited
00150     /// virtual base.
00151     uintptr_t Base;
00152 
00153     /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
00154     /// EK_ComplexElement, the index of the array or vector element being
00155     /// initialized. 
00156     unsigned Index;
00157 
00158     struct C Capture;
00159   };
00160 
00161   InitializedEntity() : ManglingNumber(0) {}
00162 
00163   /// \brief Create the initialization entity for a variable.
00164   InitializedEntity(VarDecl *Var)
00165     : Kind(EK_Variable), Parent(nullptr), Type(Var->getType()),
00166       ManglingNumber(0), VariableOrMember(Var) { }
00167   
00168   /// \brief Create the initialization entity for the result of a
00169   /// function, throwing an object, performing an explicit cast, or
00170   /// initializing a parameter for which there is no declaration.
00171   InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
00172                     bool NRVO = false)
00173     : Kind(Kind), Parent(nullptr), Type(Type), ManglingNumber(0)
00174   {
00175     LocAndNRVO.Location = Loc.getRawEncoding();
00176     LocAndNRVO.NRVO = NRVO;
00177   }
00178   
00179   /// \brief Create the initialization entity for a member subobject.
00180   InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent) 
00181     : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
00182       ManglingNumber(0), VariableOrMember(Member) { }
00183   
00184   /// \brief Create the initialization entity for an array element.
00185   InitializedEntity(ASTContext &Context, unsigned Index, 
00186                     const InitializedEntity &Parent);
00187 
00188   /// \brief Create the initialization entity for a lambda capture.
00189   InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
00190     : Kind(EK_LambdaCapture), Parent(nullptr), Type(FieldType),
00191       ManglingNumber(0)
00192   {
00193     Capture.VarID = VarID;
00194     Capture.Location = Loc.getRawEncoding();
00195   }
00196   
00197 public:
00198   /// \brief Create the initialization entity for a variable.
00199   static InitializedEntity InitializeVariable(VarDecl *Var) {
00200     return InitializedEntity(Var);
00201   }
00202 
00203   /// \brief Create the initialization entity for a parameter.
00204   static InitializedEntity InitializeParameter(ASTContext &Context,
00205                                                ParmVarDecl *Parm) {
00206     return InitializeParameter(Context, Parm, Parm->getType());
00207   }
00208 
00209   /// \brief Create the initialization entity for a parameter, but use
00210   /// another type.
00211   static InitializedEntity InitializeParameter(ASTContext &Context,
00212                                                ParmVarDecl *Parm,
00213                                                QualType Type) {
00214     bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
00215                      Parm->hasAttr<NSConsumedAttr>());
00216 
00217     InitializedEntity Entity;
00218     Entity.Kind = EK_Parameter;
00219     Entity.Type =
00220       Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
00221     Entity.Parent = nullptr;
00222     Entity.Parameter
00223       = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
00224     return Entity;
00225   }
00226 
00227   /// \brief Create the initialization entity for a parameter that is
00228   /// only known by its type.
00229   static InitializedEntity InitializeParameter(ASTContext &Context,
00230                                                QualType Type,
00231                                                bool Consumed) {
00232     InitializedEntity Entity;
00233     Entity.Kind = EK_Parameter;
00234     Entity.Type = Context.getVariableArrayDecayedType(Type);
00235     Entity.Parent = nullptr;
00236     Entity.Parameter = (Consumed);
00237     return Entity;
00238   }
00239 
00240   /// \brief Create the initialization entity for the result of a function.
00241   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
00242                                             QualType Type, bool NRVO) {
00243     return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
00244   }
00245 
00246   static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
00247                                            QualType Type, bool NRVO) {
00248     return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
00249   }
00250   
00251   /// \brief Create the initialization entity for an exception object.
00252   static InitializedEntity InitializeException(SourceLocation ThrowLoc,
00253                                                QualType Type, bool NRVO) {
00254     return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
00255   }
00256 
00257   /// \brief Create the initialization entity for an object allocated via new.
00258   static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
00259     return InitializedEntity(EK_New, NewLoc, Type);
00260   }
00261   
00262   /// \brief Create the initialization entity for a temporary.
00263   static InitializedEntity InitializeTemporary(QualType Type) {
00264     InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
00265     Result.TypeInfo = nullptr;
00266     return Result;
00267   }
00268 
00269   /// \brief Create the initialization entity for a temporary.
00270   static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
00271     InitializedEntity Result(EK_Temporary, SourceLocation(), 
00272                              TypeInfo->getType());
00273     Result.TypeInfo = TypeInfo;
00274     return Result;
00275   }
00276   
00277   /// \brief Create the initialization entity for a related result.
00278   static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
00279                                                    QualType Type) {
00280     InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
00281     Result.MethodDecl = MD;
00282     return Result;
00283   }
00284 
00285 
00286   /// \brief Create the initialization entity for a base class subobject.
00287   static InitializedEntity InitializeBase(ASTContext &Context,
00288                                           const CXXBaseSpecifier *Base,
00289                                           bool IsInheritedVirtualBase);
00290 
00291   /// \brief Create the initialization entity for a delegated constructor.
00292   static InitializedEntity InitializeDelegation(QualType Type) {
00293     return InitializedEntity(EK_Delegating, SourceLocation(), Type);
00294   }
00295   
00296   /// \brief Create the initialization entity for a member subobject.
00297   static InitializedEntity
00298   InitializeMember(FieldDecl *Member,
00299                    const InitializedEntity *Parent = nullptr) {
00300     return InitializedEntity(Member, Parent);
00301   }
00302   
00303   /// \brief Create the initialization entity for a member subobject.
00304   static InitializedEntity
00305   InitializeMember(IndirectFieldDecl *Member,
00306                    const InitializedEntity *Parent = nullptr) {
00307     return InitializedEntity(Member->getAnonField(), Parent);
00308   }
00309 
00310   /// \brief Create the initialization entity for an array element.
00311   static InitializedEntity InitializeElement(ASTContext &Context, 
00312                                              unsigned Index, 
00313                                              const InitializedEntity &Parent) {
00314     return InitializedEntity(Context, Index, Parent);
00315   }
00316 
00317   /// \brief Create the initialization entity for a lambda capture.
00318   static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
00319                                                    QualType FieldType,
00320                                                    SourceLocation Loc) {
00321     return InitializedEntity(VarID, FieldType, Loc);
00322   }
00323 
00324   /// \brief Create the entity for a compound literal initializer.
00325   static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
00326     InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
00327                              TSI->getType());
00328     Result.TypeInfo = TSI;
00329     return Result;
00330   }
00331 
00332 
00333   /// \brief Determine the kind of initialization.
00334   EntityKind getKind() const { return Kind; }
00335   
00336   /// \brief Retrieve the parent of the entity being initialized, when
00337   /// the initialization itself is occurring within the context of a
00338   /// larger initialization.
00339   const InitializedEntity *getParent() const { return Parent; }
00340 
00341   /// \brief Retrieve type being initialized.
00342   QualType getType() const { return Type; }
00343   
00344   /// \brief Retrieve complete type-source information for the object being 
00345   /// constructed, if known.
00346   TypeSourceInfo *getTypeSourceInfo() const {
00347     if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
00348       return TypeInfo;
00349     
00350     return nullptr;
00351   }
00352   
00353   /// \brief Retrieve the name of the entity being initialized.
00354   DeclarationName getName() const;
00355 
00356   /// \brief Retrieve the variable, parameter, or field being
00357   /// initialized.
00358   DeclaratorDecl *getDecl() const;
00359   
00360   /// \brief Retrieve the ObjectiveC method being initialized.
00361   ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
00362 
00363   /// \brief Determine whether this initialization allows the named return 
00364   /// value optimization, which also applies to thrown objects.
00365   bool allowsNRVO() const;
00366 
00367   bool isParameterKind() const {
00368     return (getKind() == EK_Parameter  ||
00369             getKind() == EK_Parameter_CF_Audited);
00370   }
00371   /// \brief Determine whether this initialization consumes the
00372   /// parameter.
00373   bool isParameterConsumed() const {
00374     assert(isParameterKind() && "Not a parameter");
00375     return (Parameter & 1);
00376   }
00377                                   
00378   /// \brief Retrieve the base specifier.
00379   const CXXBaseSpecifier *getBaseSpecifier() const {
00380     assert(getKind() == EK_Base && "Not a base specifier");
00381     return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
00382   }
00383 
00384   /// \brief Return whether the base is an inherited virtual base.
00385   bool isInheritedVirtualBase() const {
00386     assert(getKind() == EK_Base && "Not a base specifier");
00387     return Base & 0x1;
00388   }
00389 
00390   /// \brief Determine the location of the 'return' keyword when initializing
00391   /// the result of a function call.
00392   SourceLocation getReturnLoc() const {
00393     assert(getKind() == EK_Result && "No 'return' location!");
00394     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
00395   }
00396 
00397   /// \brief Determine the location of the 'throw' keyword when initializing
00398   /// an exception object.
00399   SourceLocation getThrowLoc() const {
00400     assert(getKind() == EK_Exception && "No 'throw' location!");
00401     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
00402   }
00403 
00404   /// \brief If this is an array, vector, or complex number element, get the
00405   /// element's index.
00406   unsigned getElementIndex() const {
00407     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
00408            getKind() == EK_ComplexElement);
00409     return Index;
00410   }
00411   /// \brief If this is already the initializer for an array or vector
00412   /// element, sets the element index.
00413   void setElementIndex(unsigned Index) {
00414     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
00415            getKind() == EK_ComplexElement);
00416     this->Index = Index;
00417   }
00418   /// \brief For a lambda capture, return the capture's name.
00419   StringRef getCapturedVarName() const {
00420     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
00421     return Capture.VarID->getName();
00422   }
00423   /// \brief Determine the location of the capture when initializing
00424   /// field from a captured variable in a lambda.
00425   SourceLocation getCaptureLoc() const {
00426     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
00427     return SourceLocation::getFromRawEncoding(Capture.Location);
00428   }
00429   
00430   void setParameterCFAudited() {
00431     Kind = EK_Parameter_CF_Audited;
00432   }
00433 
00434   unsigned allocateManglingNumber() const { return ++ManglingNumber; }
00435 
00436   /// Dump a representation of the initialized entity to standard error,
00437   /// for debugging purposes.
00438   void dump() const;
00439 
00440 private:
00441   unsigned dumpImpl(raw_ostream &OS) const;
00442 };
00443   
00444 /// \brief Describes the kind of initialization being performed, along with 
00445 /// location information for tokens related to the initialization (equal sign,
00446 /// parentheses).
00447 class InitializationKind {
00448 public:
00449   /// \brief The kind of initialization being performed.
00450   enum InitKind {
00451     IK_Direct,       ///< Direct initialization
00452     IK_DirectList,   ///< Direct list-initialization
00453     IK_Copy,         ///< Copy initialization
00454     IK_Default,      ///< Default initialization
00455     IK_Value         ///< Value initialization
00456   };
00457   
00458 private:
00459   /// \brief The context of the initialization.
00460   enum InitContext {
00461     IC_Normal,         ///< Normal context
00462     IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion funcs
00463     IC_Implicit,       ///< Implicit context (value initialization)
00464     IC_StaticCast,     ///< Static cast context
00465     IC_CStyleCast,     ///< C-style cast context
00466     IC_FunctionalCast  ///< Functional cast context
00467   };
00468   
00469   /// \brief The kind of initialization being performed.
00470   InitKind Kind : 8;
00471 
00472   /// \brief The context of the initialization.
00473   InitContext Context : 8;
00474   
00475   /// \brief The source locations involved in the initialization.
00476   SourceLocation Locations[3];
00477   
00478   InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, 
00479                      SourceLocation Loc2, SourceLocation Loc3)
00480     : Kind(Kind), Context(Context)
00481   {
00482     Locations[0] = Loc1;
00483     Locations[1] = Loc2;
00484     Locations[2] = Loc3;
00485   }
00486   
00487 public:
00488   /// \brief Create a direct initialization.
00489   static InitializationKind CreateDirect(SourceLocation InitLoc,
00490                                          SourceLocation LParenLoc,
00491                                          SourceLocation RParenLoc) {
00492     return InitializationKind(IK_Direct, IC_Normal,
00493                               InitLoc, LParenLoc, RParenLoc);
00494   }
00495 
00496   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
00497     return InitializationKind(IK_DirectList, IC_Normal,
00498                               InitLoc, InitLoc, InitLoc);
00499   }
00500 
00501   /// \brief Create a direct initialization due to a cast that isn't a C-style 
00502   /// or functional cast.
00503   static InitializationKind CreateCast(SourceRange TypeRange) {
00504     return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
00505                               TypeRange.getBegin(), TypeRange.getEnd());
00506   }
00507   
00508   /// \brief Create a direct initialization for a C-style cast.
00509   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
00510                                              SourceRange TypeRange,
00511                                              bool InitList) {
00512     // C++ cast syntax doesn't permit init lists, but C compound literals are
00513     // exactly that.
00514     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
00515                               IC_CStyleCast, StartLoc, TypeRange.getBegin(),
00516                               TypeRange.getEnd());
00517   }
00518 
00519   /// \brief Create a direct initialization for a functional cast.
00520   static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
00521                                                  bool InitList) {
00522     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
00523                               IC_FunctionalCast, TypeRange.getBegin(),
00524                               TypeRange.getBegin(), TypeRange.getEnd());
00525   }
00526 
00527   /// \brief Create a copy initialization.
00528   static InitializationKind CreateCopy(SourceLocation InitLoc,
00529                                        SourceLocation EqualLoc,
00530                                        bool AllowExplicitConvs = false) {
00531     return InitializationKind(IK_Copy, 
00532                               AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
00533                               InitLoc, EqualLoc, EqualLoc);
00534   }
00535   
00536   /// \brief Create a default initialization.
00537   static InitializationKind CreateDefault(SourceLocation InitLoc) {
00538     return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
00539   }
00540   
00541   /// \brief Create a value initialization.
00542   static InitializationKind CreateValue(SourceLocation InitLoc,
00543                                         SourceLocation LParenLoc,
00544                                         SourceLocation RParenLoc,
00545                                         bool isImplicit = false) {
00546     return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
00547                               InitLoc, LParenLoc, RParenLoc);
00548   }
00549   
00550   /// \brief Determine the initialization kind.
00551   InitKind getKind() const {
00552     return Kind;
00553   }
00554   
00555   /// \brief Determine whether this initialization is an explicit cast.
00556   bool isExplicitCast() const {
00557     return Context >= IC_StaticCast;
00558   }
00559   
00560   /// \brief Determine whether this initialization is a C-style cast.
00561   bool isCStyleOrFunctionalCast() const { 
00562     return Context >= IC_CStyleCast; 
00563   }
00564 
00565   /// \brief Determine whether this is a C-style cast.
00566   bool isCStyleCast() const {
00567     return Context == IC_CStyleCast;
00568   }
00569 
00570   /// \brief Determine whether this is a functional-style cast.
00571   bool isFunctionalCast() const {
00572     return Context == IC_FunctionalCast;
00573   }
00574 
00575   /// \brief Determine whether this initialization is an implicit
00576   /// value-initialization, e.g., as occurs during aggregate
00577   /// initialization.
00578   bool isImplicitValueInit() const { return Context == IC_Implicit; }
00579 
00580   /// \brief Retrieve the location at which initialization is occurring.
00581   SourceLocation getLocation() const { return Locations[0]; }
00582   
00583   /// \brief Retrieve the source range that covers the initialization.
00584   SourceRange getRange() const { 
00585     return SourceRange(Locations[0], Locations[2]);
00586   }
00587   
00588   /// \brief Retrieve the location of the equal sign for copy initialization
00589   /// (if present).
00590   SourceLocation getEqualLoc() const {
00591     assert(Kind == IK_Copy && "Only copy initialization has an '='");
00592     return Locations[1];
00593   }
00594 
00595   bool isCopyInit() const { return Kind == IK_Copy; }
00596 
00597   /// \brief Retrieve whether this initialization allows the use of explicit
00598   ///        constructors.
00599   bool AllowExplicit() const { return !isCopyInit(); }
00600 
00601   /// \brief Retrieve whether this initialization allows the use of explicit
00602   /// conversion functions when binding a reference. If the reference is the
00603   /// first parameter in a copy or move constructor, such conversions are
00604   /// permitted even though we are performing copy-initialization.
00605   bool allowExplicitConversionFunctionsInRefBinding() const {
00606     return !isCopyInit() || Context == IC_ExplicitConvs;
00607   }
00608   
00609   /// \brief Retrieve the source range containing the locations of the open
00610   /// and closing parentheses for value and direct initializations.
00611   SourceRange getParenRange() const {
00612     assert((Kind == IK_Direct || Kind == IK_Value) &&
00613            "Only direct- and value-initialization have parentheses");
00614     return SourceRange(Locations[1], Locations[2]);
00615   }
00616 };
00617 
00618 /// \brief Describes the sequence of initializations required to initialize
00619 /// a given object or reference with a set of arguments.
00620 class InitializationSequence {
00621 public:
00622   /// \brief Describes the kind of initialization sequence computed.
00623   enum SequenceKind {
00624     /// \brief A failed initialization sequence. The failure kind tells what
00625     /// happened.
00626     FailedSequence = 0,
00627 
00628     /// \brief A dependent initialization, which could not be
00629     /// type-checked due to the presence of dependent types or
00630     /// dependently-typed expressions.
00631     DependentSequence,
00632 
00633     /// \brief A normal sequence.
00634     NormalSequence
00635   };
00636   
00637   /// \brief Describes the kind of a particular step in an initialization
00638   /// sequence.
00639   enum StepKind {
00640     /// \brief Resolve the address of an overloaded function to a specific
00641     /// function declaration.
00642     SK_ResolveAddressOfOverloadedFunction,
00643     /// \brief Perform a derived-to-base cast, producing an rvalue.
00644     SK_CastDerivedToBaseRValue,
00645     /// \brief Perform a derived-to-base cast, producing an xvalue.
00646     SK_CastDerivedToBaseXValue,
00647     /// \brief Perform a derived-to-base cast, producing an lvalue.
00648     SK_CastDerivedToBaseLValue,
00649     /// \brief Reference binding to an lvalue.
00650     SK_BindReference,
00651     /// \brief Reference binding to a temporary.
00652     SK_BindReferenceToTemporary,
00653     /// \brief An optional copy of a temporary object to another
00654     /// temporary object, which is permitted (but not required) by
00655     /// C++98/03 but not C++0x.
00656     SK_ExtraneousCopyToTemporary,
00657     /// \brief Perform a user-defined conversion, either via a conversion
00658     /// function or via a constructor.
00659     SK_UserConversion,
00660     /// \brief Perform a qualification conversion, producing an rvalue.
00661     SK_QualificationConversionRValue,
00662     /// \brief Perform a qualification conversion, producing an xvalue.
00663     SK_QualificationConversionXValue,
00664     /// \brief Perform a qualification conversion, producing an lvalue.
00665     SK_QualificationConversionLValue,
00666     /// \brief Perform a conversion adding _Atomic to a type.
00667     SK_AtomicConversion,
00668     /// \brief Perform a load from a glvalue, producing an rvalue.
00669     SK_LValueToRValue,
00670     /// \brief Perform an implicit conversion sequence.
00671     SK_ConversionSequence,
00672     /// \brief Perform an implicit conversion sequence without narrowing.
00673     SK_ConversionSequenceNoNarrowing,
00674     /// \brief Perform list-initialization without a constructor.
00675     SK_ListInitialization,
00676     /// \brief Unwrap the single-element initializer list for a reference.
00677     SK_UnwrapInitList,
00678     /// \brief Rewrap the single-element initializer list for a reference.
00679     SK_RewrapInitList,
00680     /// \brief Perform initialization via a constructor.
00681     SK_ConstructorInitialization,
00682     /// \brief Perform initialization via a constructor, taking arguments from
00683     /// a single InitListExpr.
00684     SK_ConstructorInitializationFromList,
00685     /// \brief Zero-initialize the object
00686     SK_ZeroInitialization,
00687     /// \brief C assignment
00688     SK_CAssignment,
00689     /// \brief Initialization by string
00690     SK_StringInit,
00691     /// \brief An initialization that "converts" an Objective-C object
00692     /// (not a point to an object) to another Objective-C object type.
00693     SK_ObjCObjectConversion,
00694     /// \brief Array initialization (from an array rvalue).
00695     /// This is a GNU C extension.
00696     SK_ArrayInit,
00697     /// \brief Array initialization from a parenthesized initializer list.
00698     /// This is a GNU C++ extension.
00699     SK_ParenthesizedArrayInit,
00700     /// \brief Pass an object by indirect copy-and-restore.
00701     SK_PassByIndirectCopyRestore,
00702     /// \brief Pass an object by indirect restore.
00703     SK_PassByIndirectRestore,
00704     /// \brief Produce an Objective-C object pointer.
00705     SK_ProduceObjCObject,
00706     /// \brief Construct a std::initializer_list from an initializer list.
00707     SK_StdInitializerList,
00708     /// \brief Perform initialization via a constructor taking a single
00709     /// std::initializer_list argument.
00710     SK_StdInitializerListConstructorCall,
00711     /// \brief Initialize an OpenCL sampler from an integer.
00712     SK_OCLSamplerInit,
00713     /// \brief Passing zero to a function where OpenCL event_t is expected.
00714     SK_OCLZeroEvent
00715   };
00716   
00717   /// \brief A single step in the initialization sequence.
00718   class Step {
00719   public:
00720     /// \brief The kind of conversion or initialization step we are taking.
00721     StepKind Kind;
00722     
00723     // \brief The type that results from this initialization.
00724     QualType Type;
00725 
00726     struct F {
00727       bool HadMultipleCandidates;
00728       FunctionDecl *Function;
00729       DeclAccessPair FoundDecl;
00730     };
00731 
00732     union {
00733       /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
00734       /// SK_UserConversion, the function that the expression should be 
00735       /// resolved to or the conversion function to call, respectively.
00736       /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
00737       /// the constructor to be called.
00738       ///
00739       /// Always a FunctionDecl, plus a Boolean flag telling if it was
00740       /// selected from an overloaded set having size greater than 1.
00741       /// For conversion decls, the naming class is the source type.
00742       /// For construct decls, the naming class is the target type.
00743       struct F Function;
00744 
00745       /// \brief When Kind = SK_ConversionSequence, the implicit conversion
00746       /// sequence.
00747       ImplicitConversionSequence *ICS;
00748 
00749       /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
00750       /// wrapping list.
00751       InitListExpr *WrappingSyntacticList;
00752     };
00753 
00754     void Destroy();
00755   };
00756   
00757 private:
00758   /// \brief The kind of initialization sequence computed.
00759   enum SequenceKind SequenceKind;
00760   
00761   /// \brief Steps taken by this initialization.
00762   SmallVector<Step, 4> Steps;
00763   
00764 public:
00765   /// \brief Describes why initialization failed.
00766   enum FailureKind {
00767     /// \brief Too many initializers provided for a reference.
00768     FK_TooManyInitsForReference,
00769     /// \brief Array must be initialized with an initializer list.
00770     FK_ArrayNeedsInitList,
00771     /// \brief Array must be initialized with an initializer list or a 
00772     /// string literal.
00773     FK_ArrayNeedsInitListOrStringLiteral,
00774     /// \brief Array must be initialized with an initializer list or a
00775     /// wide string literal.
00776     FK_ArrayNeedsInitListOrWideStringLiteral,
00777     /// \brief Initializing a wide char array with narrow string literal.
00778     FK_NarrowStringIntoWideCharArray,
00779     /// \brief Initializing char array with wide string literal.
00780     FK_WideStringIntoCharArray,
00781     /// \brief Initializing wide char array with incompatible wide string
00782     /// literal.
00783     FK_IncompatWideStringIntoWideChar,
00784     /// \brief Array type mismatch.
00785     FK_ArrayTypeMismatch,
00786     /// \brief Non-constant array initializer
00787     FK_NonConstantArrayInit,
00788     /// \brief Cannot resolve the address of an overloaded function.
00789     FK_AddressOfOverloadFailed,
00790     /// \brief Overloading due to reference initialization failed.
00791     FK_ReferenceInitOverloadFailed,
00792     /// \brief Non-const lvalue reference binding to a temporary.
00793     FK_NonConstLValueReferenceBindingToTemporary,
00794     /// \brief Non-const lvalue reference binding to an lvalue of unrelated
00795     /// type.
00796     FK_NonConstLValueReferenceBindingToUnrelated,
00797     /// \brief Rvalue reference binding to an lvalue.
00798     FK_RValueReferenceBindingToLValue,
00799     /// \brief Reference binding drops qualifiers.
00800     FK_ReferenceInitDropsQualifiers,
00801     /// \brief Reference binding failed.
00802     FK_ReferenceInitFailed,
00803     /// \brief Implicit conversion failed.
00804     FK_ConversionFailed,
00805     /// \brief Implicit conversion failed.
00806     FK_ConversionFromPropertyFailed,
00807     /// \brief Too many initializers for scalar
00808     FK_TooManyInitsForScalar,
00809     /// \brief Reference initialization from an initializer list
00810     FK_ReferenceBindingToInitList,
00811     /// \brief Initialization of some unused destination type with an
00812     /// initializer list.
00813     FK_InitListBadDestinationType,
00814     /// \brief Overloading for a user-defined conversion failed.
00815     FK_UserConversionOverloadFailed,
00816     /// \brief Overloading for initialization by constructor failed.
00817     FK_ConstructorOverloadFailed,
00818     /// \brief Overloading for list-initialization by constructor failed.
00819     FK_ListConstructorOverloadFailed,
00820     /// \brief Default-initialization of a 'const' object.
00821     FK_DefaultInitOfConst,
00822     /// \brief Initialization of an incomplete type.
00823     FK_Incomplete,
00824     /// \brief Variable-length array must not have an initializer.
00825     FK_VariableLengthArrayHasInitializer,
00826     /// \brief List initialization failed at some point.
00827     FK_ListInitializationFailed,
00828     /// \brief Initializer has a placeholder type which cannot be
00829     /// resolved by initialization.
00830     FK_PlaceholderType,
00831     /// \brief List-copy-initialization chose an explicit constructor.
00832     FK_ExplicitConstructor
00833   };
00834   
00835 private:
00836   /// \brief The reason why initialization failed.
00837   FailureKind Failure;
00838 
00839   /// \brief The failed result of overload resolution.
00840   OverloadingResult FailedOverloadResult;
00841   
00842   /// \brief The candidate set created when initialization failed.
00843   OverloadCandidateSet FailedCandidateSet;
00844 
00845   /// \brief The incomplete type that caused a failure.
00846   QualType FailedIncompleteType;
00847   
00848   /// \brief Prints a follow-up note that highlights the location of
00849   /// the initialized entity, if it's remote.
00850   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
00851 
00852 public:
00853   /// \brief Try to perform initialization of the given entity, creating a 
00854   /// record of the steps required to perform the initialization.
00855   ///
00856   /// The generated initialization sequence will either contain enough
00857   /// information to diagnose 
00858   ///
00859   /// \param S the semantic analysis object.
00860   ///
00861   /// \param Entity the entity being initialized.
00862   ///
00863   /// \param Kind the kind of initialization being performed.
00864   ///
00865   /// \param Args the argument(s) provided for initialization.
00866   ///
00867   /// \param TopLevelOfInitList true if we are initializing from an expression
00868   ///        at the top level inside an initializer list. This disallows
00869   ///        narrowing conversions in C++11 onwards.
00870   InitializationSequence(Sema &S, 
00871                          const InitializedEntity &Entity,
00872                          const InitializationKind &Kind,
00873                          MultiExprArg Args,
00874                          bool TopLevelOfInitList = false);
00875   void InitializeFrom(Sema &S, const InitializedEntity &Entity,
00876                       const InitializationKind &Kind, MultiExprArg Args,
00877                       bool TopLevelOfInitList);
00878 
00879   ~InitializationSequence();
00880   
00881   /// \brief Perform the actual initialization of the given entity based on
00882   /// the computed initialization sequence.
00883   ///
00884   /// \param S the semantic analysis object.
00885   ///
00886   /// \param Entity the entity being initialized.
00887   ///
00888   /// \param Kind the kind of initialization being performed.
00889   ///
00890   /// \param Args the argument(s) provided for initialization, ownership of
00891   /// which is transferred into the routine.
00892   ///
00893   /// \param ResultType if non-NULL, will be set to the type of the
00894   /// initialized object, which is the type of the declaration in most
00895   /// cases. However, when the initialized object is a variable of
00896   /// incomplete array type and the initializer is an initializer
00897   /// list, this type will be set to the completed array type.
00898   ///
00899   /// \returns an expression that performs the actual object initialization, if
00900   /// the initialization is well-formed. Otherwise, emits diagnostics
00901   /// and returns an invalid expression.
00902   ExprResult Perform(Sema &S,
00903                      const InitializedEntity &Entity,
00904                      const InitializationKind &Kind,
00905                      MultiExprArg Args,
00906                      QualType *ResultType = nullptr);
00907   
00908   /// \brief Diagnose an potentially-invalid initialization sequence.
00909   ///
00910   /// \returns true if the initialization sequence was ill-formed, 
00911   /// false otherwise.
00912   bool Diagnose(Sema &S, 
00913                 const InitializedEntity &Entity,
00914                 const InitializationKind &Kind,
00915                 ArrayRef<Expr *> Args);
00916   
00917   /// \brief Determine the kind of initialization sequence computed.
00918   enum SequenceKind getKind() const { return SequenceKind; }
00919   
00920   /// \brief Set the kind of sequence computed.
00921   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
00922   
00923   /// \brief Determine whether the initialization sequence is valid.
00924   LLVM_EXPLICIT operator bool() const { return !Failed(); }
00925 
00926   /// \brief Determine whether the initialization sequence is invalid.
00927   bool Failed() const { return SequenceKind == FailedSequence; }
00928 
00929   typedef SmallVectorImpl<Step>::const_iterator step_iterator;
00930   step_iterator step_begin() const { return Steps.begin(); }
00931   step_iterator step_end()   const { return Steps.end(); }
00932 
00933   /// \brief Determine whether this initialization is a direct reference 
00934   /// binding (C++ [dcl.init.ref]).
00935   bool isDirectReferenceBinding() const;
00936   
00937   /// \brief Determine whether this initialization failed due to an ambiguity.
00938   bool isAmbiguous() const;
00939   
00940   /// \brief Determine whether this initialization is direct call to a 
00941   /// constructor.
00942   bool isConstructorInitialization() const;
00943 
00944   /// \brief Returns whether the last step in this initialization sequence is a
00945   /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
00946   ///
00947   /// If this function returns true, *isInitializerConstant will be set to
00948   /// describe whether *Initializer was a constant expression.  If
00949   /// *isInitializerConstant is set to true, *ConstantValue will be set to the
00950   /// evaluated value of *Initializer.
00951   bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
00952                          bool *isInitializerConstant,
00953                          APValue *ConstantValue) const;
00954 
00955   /// \brief Add a new step in the initialization that resolves the address
00956   /// of an overloaded function to a specific function declaration.
00957   ///
00958   /// \param Function the function to which the overloaded function reference
00959   /// resolves.
00960   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
00961                                         DeclAccessPair Found,
00962                                         bool HadMultipleCandidates);
00963 
00964   /// \brief Add a new step in the initialization that performs a derived-to-
00965   /// base cast.
00966   ///
00967   /// \param BaseType the base type to which we will be casting.
00968   ///
00969   /// \param Category Indicates whether the result will be treated as an
00970   /// rvalue, an xvalue, or an lvalue.
00971   void AddDerivedToBaseCastStep(QualType BaseType,
00972                                 ExprValueKind Category);
00973      
00974   /// \brief Add a new step binding a reference to an object.
00975   ///
00976   /// \param BindingTemporary True if we are binding a reference to a temporary
00977   /// object (thereby extending its lifetime); false if we are binding to an
00978   /// lvalue or an lvalue treated as an rvalue.
00979   void AddReferenceBindingStep(QualType T, bool BindingTemporary);
00980 
00981   /// \brief Add a new step that makes an extraneous copy of the input
00982   /// to a temporary of the same class type.
00983   ///
00984   /// This extraneous copy only occurs during reference binding in
00985   /// C++98/03, where we are permitted (but not required) to introduce
00986   /// an extra copy. At a bare minimum, we must check that we could
00987   /// call the copy constructor, and produce a diagnostic if the copy
00988   /// constructor is inaccessible or no copy constructor matches.
00989   //
00990   /// \param T The type of the temporary being created.
00991   void AddExtraneousCopyToTemporary(QualType T);
00992 
00993   /// \brief Add a new step invoking a conversion function, which is either
00994   /// a constructor or a conversion function.
00995   void AddUserConversionStep(FunctionDecl *Function,
00996                              DeclAccessPair FoundDecl,
00997                              QualType T,
00998                              bool HadMultipleCandidates);
00999 
01000   /// \brief Add a new step that performs a qualification conversion to the
01001   /// given type.
01002   void AddQualificationConversionStep(QualType Ty,
01003                                      ExprValueKind Category);
01004 
01005   /// \brief Add a new step that performs conversion from non-atomic to atomic
01006   /// type.
01007   void AddAtomicConversionStep(QualType Ty);
01008 
01009   /// \brief Add a new step that performs a load of the given type.
01010   ///
01011   /// Although the term "LValueToRValue" is conventional, this applies to both
01012   /// lvalues and xvalues.
01013   void AddLValueToRValueStep(QualType Ty);
01014 
01015   /// \brief Add a new step that applies an implicit conversion sequence.
01016   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
01017                                  QualType T, bool TopLevelOfInitList = false);
01018 
01019   /// \brief Add a list-initialization step.
01020   void AddListInitializationStep(QualType T);
01021 
01022   /// \brief Add a constructor-initialization step.
01023   ///
01024   /// \param FromInitList The constructor call is syntactically an initializer
01025   /// list.
01026   /// \param AsInitList The constructor is called as an init list constructor.
01027   void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
01028                                         AccessSpecifier Access,
01029                                         QualType T,
01030                                         bool HadMultipleCandidates,
01031                                         bool FromInitList, bool AsInitList);
01032 
01033   /// \brief Add a zero-initialization step.
01034   void AddZeroInitializationStep(QualType T);
01035 
01036   /// \brief Add a C assignment step.
01037   //
01038   // FIXME: It isn't clear whether this should ever be needed;
01039   // ideally, we would handle everything needed in C in the common
01040   // path. However, that isn't the case yet.
01041   void AddCAssignmentStep(QualType T);
01042 
01043   /// \brief Add a string init step.
01044   void AddStringInitStep(QualType T);
01045 
01046   /// \brief Add an Objective-C object conversion step, which is
01047   /// always a no-op.
01048   void AddObjCObjectConversionStep(QualType T);
01049 
01050   /// \brief Add an array initialization step.
01051   void AddArrayInitStep(QualType T);
01052 
01053   /// \brief Add a parenthesized array initialization step.
01054   void AddParenthesizedArrayInitStep(QualType T);
01055 
01056   /// \brief Add a step to pass an object by indirect copy-restore.
01057   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
01058 
01059   /// \brief Add a step to "produce" an Objective-C object (by
01060   /// retaining it).
01061   void AddProduceObjCObjectStep(QualType T);
01062 
01063   /// \brief Add a step to construct a std::initializer_list object from an
01064   /// initializer list.
01065   void AddStdInitializerListConstructionStep(QualType T);
01066 
01067   /// \brief Add a step to initialize an OpenCL sampler from an integer
01068   /// constant.
01069   void AddOCLSamplerInitStep(QualType T);
01070 
01071   /// \brief Add a step to initialize an OpenCL event_t from a NULL
01072   /// constant.
01073   void AddOCLZeroEventStep(QualType T);
01074 
01075   /// \brief Add steps to unwrap a initializer list for a reference around a
01076   /// single element and rewrap it at the end.
01077   void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
01078 
01079   /// \brief Note that this initialization sequence failed.
01080   void SetFailed(FailureKind Failure) {
01081     SequenceKind = FailedSequence;
01082     this->Failure = Failure;
01083     assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
01084            "Incomplete type failure requires a type!");
01085   }
01086   
01087   /// \brief Note that this initialization sequence failed due to failed
01088   /// overload resolution.
01089   void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
01090   
01091   /// \brief Retrieve a reference to the candidate set when overload
01092   /// resolution fails.
01093   OverloadCandidateSet &getFailedCandidateSet() {
01094     return FailedCandidateSet;
01095   }
01096 
01097   /// \brief Get the overloading result, for when the initialization
01098   /// sequence failed due to a bad overload.
01099   OverloadingResult getFailedOverloadResult() const {
01100     return FailedOverloadResult;
01101   }
01102 
01103   /// \brief Note that this initialization sequence failed due to an
01104   /// incomplete type.
01105   void setIncompleteTypeFailure(QualType IncompleteType) {
01106     FailedIncompleteType = IncompleteType;
01107     SetFailed(FK_Incomplete);
01108   }
01109 
01110   /// \brief Determine why initialization failed.
01111   FailureKind getFailureKind() const {
01112     assert(Failed() && "Not an initialization failure!");
01113     return Failure;
01114   }
01115 
01116   /// \brief Dump a representation of this initialization sequence to 
01117   /// the given stream, for debugging purposes.
01118   void dump(raw_ostream &OS) const;
01119   
01120   /// \brief Dump a representation of this initialization sequence to 
01121   /// standard error, for debugging purposes.
01122   void dump() const;
01123 };
01124   
01125 } // end namespace clang
01126 
01127 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H