1 //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides supporting data types for initialization of objects. 11 // 12 //===----------------------------------------------------------------------===// 13 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H 14 #define LLVM_CLANG_SEMA_INITIALIZATION_H 15 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/Type.h" 19 #include "clang/AST/UnresolvedSet.h" 20 #include "clang/Basic/SourceLocation.h" 21 #include "clang/Sema/Overload.h" 22 #include "clang/Sema/Ownership.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include <cassert> 26 27 namespace clang { 28 29 class CXXBaseSpecifier; 30 class DeclaratorDecl; 31 class DeclaratorInfo; 32 class FieldDecl; 33 class FunctionDecl; 34 class ParmVarDecl; 35 class Sema; 36 class TypeLoc; 37 class VarDecl; 38 class ObjCMethodDecl; 39 40 /// \brief Describes an entity that is being initialized. 41 class InitializedEntity { 42 public: 43 /// \brief Specifies the kind of entity being initialized. 44 enum EntityKind { 45 /// \brief The entity being initialized is a variable. 46 EK_Variable, 47 /// \brief The entity being initialized is a function parameter. 48 EK_Parameter, 49 /// \brief The entity being initialized is the result of a function call. 50 EK_Result, 51 /// \brief The entity being initialized is an exception object that 52 /// is being thrown. 53 EK_Exception, 54 /// \brief The entity being initialized is a non-static data member 55 /// subobject. 56 EK_Member, 57 /// \brief The entity being initialized is an element of an array. 58 EK_ArrayElement, 59 /// \brief The entity being initialized is an object (or array of 60 /// objects) allocated via new. 61 EK_New, 62 /// \brief The entity being initialized is a temporary object. 63 EK_Temporary, 64 /// \brief The entity being initialized is a base member subobject. 65 EK_Base, 66 /// \brief The initialization is being done by a delegating constructor. 67 EK_Delegating, 68 /// \brief The entity being initialized is an element of a vector. 69 /// or vector. 70 EK_VectorElement, 71 /// \brief The entity being initialized is a field of block descriptor for 72 /// the copied-in c++ object. 73 EK_BlockElement, 74 /// \brief The entity being initialized is the real or imaginary part of a 75 /// complex number. 76 EK_ComplexElement, 77 /// \brief The entity being initialized is the field that captures a 78 /// variable in a lambda. 79 EK_LambdaCapture, 80 /// \brief The entity being initialized is the initializer for a compound 81 /// literal. 82 EK_CompoundLiteralInit, 83 /// \brief The entity being implicitly initialized back to the formal 84 /// result type. 85 EK_RelatedResult, 86 /// \brief The entity being initialized is a function parameter; function 87 /// is member of group of audited CF APIs. 88 EK_Parameter_CF_Audited 89 90 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this 91 // enum as an index for its first %select. When modifying this list, 92 // that diagnostic text needs to be updated as well. 93 }; 94 95 private: 96 /// \brief The kind of entity being initialized. 97 EntityKind Kind; 98 99 /// \brief If non-NULL, the parent entity in which this 100 /// initialization occurs. 101 const InitializedEntity *Parent; 102 103 /// \brief The type of the object or reference being initialized. 104 QualType Type; 105 106 /// \brief The mangling number for the next reference temporary to be created. 107 mutable unsigned ManglingNumber; 108 109 struct LN { 110 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the 111 /// location of the 'return', 'throw', or 'new' keyword, 112 /// respectively. When Kind == EK_Temporary, the location where 113 /// the temporary is being created. 114 unsigned Location; 115 116 /// \brief Whether the entity being initialized may end up using the 117 /// named return value optimization (NRVO). 118 bool NRVO; 119 }; 120 121 struct C { 122 /// \brief The name of the variable being captured by an EK_LambdaCapture. 123 IdentifierInfo *VarID; 124 125 /// \brief The source location at which the capture occurs. 126 unsigned Location; 127 }; 128 129 union { 130 /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or 131 /// FieldDecl, respectively. 132 DeclaratorDecl *VariableOrMember; 133 134 /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where 135 /// result type was implicitly changed to accommodate ARC semantics. 136 ObjCMethodDecl *MethodDecl; 137 138 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the 139 /// low bit indicating whether the parameter is "consumed". 140 uintptr_t Parameter; 141 142 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type 143 /// source information for the temporary. 144 TypeSourceInfo *TypeInfo; 145 146 struct LN LocAndNRVO; 147 148 /// \brief When Kind == EK_Base, the base specifier that provides the 149 /// base class. The lower bit specifies whether the base is an inherited 150 /// virtual base. 151 uintptr_t Base; 152 153 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or 154 /// EK_ComplexElement, the index of the array or vector element being 155 /// initialized. 156 unsigned Index; 157 158 struct C Capture; 159 }; 160 InitializedEntity()161 InitializedEntity() : ManglingNumber(0) {} 162 163 /// \brief Create the initialization entity for a variable. InitializedEntity(VarDecl * Var)164 InitializedEntity(VarDecl *Var) 165 : Kind(EK_Variable), Parent(nullptr), Type(Var->getType()), 166 ManglingNumber(0), VariableOrMember(Var) { } 167 168 /// \brief Create the initialization entity for the result of a 169 /// function, throwing an object, performing an explicit cast, or 170 /// initializing a parameter for which there is no declaration. 171 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type, 172 bool NRVO = false) Kind(Kind)173 : Kind(Kind), Parent(nullptr), Type(Type), ManglingNumber(0) 174 { 175 LocAndNRVO.Location = Loc.getRawEncoding(); 176 LocAndNRVO.NRVO = NRVO; 177 } 178 179 /// \brief Create the initialization entity for a member subobject. InitializedEntity(FieldDecl * Member,const InitializedEntity * Parent)180 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent) 181 : Kind(EK_Member), Parent(Parent), Type(Member->getType()), 182 ManglingNumber(0), VariableOrMember(Member) { } 183 184 /// \brief Create the initialization entity for an array element. 185 InitializedEntity(ASTContext &Context, unsigned Index, 186 const InitializedEntity &Parent); 187 188 /// \brief Create the initialization entity for a lambda capture. InitializedEntity(IdentifierInfo * VarID,QualType FieldType,SourceLocation Loc)189 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc) 190 : Kind(EK_LambdaCapture), Parent(nullptr), Type(FieldType), 191 ManglingNumber(0) 192 { 193 Capture.VarID = VarID; 194 Capture.Location = Loc.getRawEncoding(); 195 } 196 197 public: 198 /// \brief Create the initialization entity for a variable. InitializeVariable(VarDecl * Var)199 static InitializedEntity InitializeVariable(VarDecl *Var) { 200 return InitializedEntity(Var); 201 } 202 203 /// \brief Create the initialization entity for a parameter. InitializeParameter(ASTContext & Context,ParmVarDecl * Parm)204 static InitializedEntity InitializeParameter(ASTContext &Context, 205 ParmVarDecl *Parm) { 206 return InitializeParameter(Context, Parm, Parm->getType()); 207 } 208 209 /// \brief Create the initialization entity for a parameter, but use 210 /// another type. InitializeParameter(ASTContext & Context,ParmVarDecl * Parm,QualType Type)211 static InitializedEntity InitializeParameter(ASTContext &Context, 212 ParmVarDecl *Parm, 213 QualType Type) { 214 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount && 215 Parm->hasAttr<NSConsumedAttr>()); 216 217 InitializedEntity Entity; 218 Entity.Kind = EK_Parameter; 219 Entity.Type = 220 Context.getVariableArrayDecayedType(Type.getUnqualifiedType()); 221 Entity.Parent = nullptr; 222 Entity.Parameter 223 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm)); 224 return Entity; 225 } 226 227 /// \brief Create the initialization entity for a parameter that is 228 /// only known by its type. InitializeParameter(ASTContext & Context,QualType Type,bool Consumed)229 static InitializedEntity InitializeParameter(ASTContext &Context, 230 QualType Type, 231 bool Consumed) { 232 InitializedEntity Entity; 233 Entity.Kind = EK_Parameter; 234 Entity.Type = Context.getVariableArrayDecayedType(Type); 235 Entity.Parent = nullptr; 236 Entity.Parameter = (Consumed); 237 return Entity; 238 } 239 240 /// \brief Create the initialization entity for the result of a function. InitializeResult(SourceLocation ReturnLoc,QualType Type,bool NRVO)241 static InitializedEntity InitializeResult(SourceLocation ReturnLoc, 242 QualType Type, bool NRVO) { 243 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO); 244 } 245 InitializeBlock(SourceLocation BlockVarLoc,QualType Type,bool NRVO)246 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, 247 QualType Type, bool NRVO) { 248 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO); 249 } 250 251 /// \brief Create the initialization entity for an exception object. InitializeException(SourceLocation ThrowLoc,QualType Type,bool NRVO)252 static InitializedEntity InitializeException(SourceLocation ThrowLoc, 253 QualType Type, bool NRVO) { 254 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO); 255 } 256 257 /// \brief Create the initialization entity for an object allocated via new. InitializeNew(SourceLocation NewLoc,QualType Type)258 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) { 259 return InitializedEntity(EK_New, NewLoc, Type); 260 } 261 262 /// \brief Create the initialization entity for a temporary. InitializeTemporary(QualType Type)263 static InitializedEntity InitializeTemporary(QualType Type) { 264 InitializedEntity Result(EK_Temporary, SourceLocation(), Type); 265 Result.TypeInfo = nullptr; 266 return Result; 267 } 268 269 /// \brief Create the initialization entity for a temporary. InitializeTemporary(TypeSourceInfo * TypeInfo)270 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) { 271 InitializedEntity Result(EK_Temporary, SourceLocation(), 272 TypeInfo->getType()); 273 Result.TypeInfo = TypeInfo; 274 return Result; 275 } 276 277 /// \brief Create the initialization entity for a related result. InitializeRelatedResult(ObjCMethodDecl * MD,QualType Type)278 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, 279 QualType Type) { 280 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type); 281 Result.MethodDecl = MD; 282 return Result; 283 } 284 285 286 /// \brief Create the initialization entity for a base class subobject. 287 static InitializedEntity 288 InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, 289 bool IsInheritedVirtualBase, 290 const InitializedEntity *Parent = nullptr); 291 292 /// \brief Create the initialization entity for a delegated constructor. InitializeDelegation(QualType Type)293 static InitializedEntity InitializeDelegation(QualType Type) { 294 return InitializedEntity(EK_Delegating, SourceLocation(), Type); 295 } 296 297 /// \brief Create the initialization entity for a member subobject. 298 static InitializedEntity 299 InitializeMember(FieldDecl *Member, 300 const InitializedEntity *Parent = nullptr) { 301 return InitializedEntity(Member, Parent); 302 } 303 304 /// \brief Create the initialization entity for a member subobject. 305 static InitializedEntity 306 InitializeMember(IndirectFieldDecl *Member, 307 const InitializedEntity *Parent = nullptr) { 308 return InitializedEntity(Member->getAnonField(), Parent); 309 } 310 311 /// \brief Create the initialization entity for an array element. InitializeElement(ASTContext & Context,unsigned Index,const InitializedEntity & Parent)312 static InitializedEntity InitializeElement(ASTContext &Context, 313 unsigned Index, 314 const InitializedEntity &Parent) { 315 return InitializedEntity(Context, Index, Parent); 316 } 317 318 /// \brief Create the initialization entity for a lambda capture. InitializeLambdaCapture(IdentifierInfo * VarID,QualType FieldType,SourceLocation Loc)319 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, 320 QualType FieldType, 321 SourceLocation Loc) { 322 return InitializedEntity(VarID, FieldType, Loc); 323 } 324 325 /// \brief Create the entity for a compound literal initializer. InitializeCompoundLiteralInit(TypeSourceInfo * TSI)326 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) { 327 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(), 328 TSI->getType()); 329 Result.TypeInfo = TSI; 330 return Result; 331 } 332 333 334 /// \brief Determine the kind of initialization. getKind()335 EntityKind getKind() const { return Kind; } 336 337 /// \brief Retrieve the parent of the entity being initialized, when 338 /// the initialization itself is occurring within the context of a 339 /// larger initialization. getParent()340 const InitializedEntity *getParent() const { return Parent; } 341 342 /// \brief Retrieve type being initialized. getType()343 QualType getType() const { return Type; } 344 345 /// \brief Retrieve complete type-source information for the object being 346 /// constructed, if known. getTypeSourceInfo()347 TypeSourceInfo *getTypeSourceInfo() const { 348 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit) 349 return TypeInfo; 350 351 return nullptr; 352 } 353 354 /// \brief Retrieve the name of the entity being initialized. 355 DeclarationName getName() const; 356 357 /// \brief Retrieve the variable, parameter, or field being 358 /// initialized. 359 DeclaratorDecl *getDecl() const; 360 361 /// \brief Retrieve the ObjectiveC method being initialized. getMethodDecl()362 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; } 363 364 /// \brief Determine whether this initialization allows the named return 365 /// value optimization, which also applies to thrown objects. 366 bool allowsNRVO() const; 367 isParameterKind()368 bool isParameterKind() const { 369 return (getKind() == EK_Parameter || 370 getKind() == EK_Parameter_CF_Audited); 371 } 372 /// \brief Determine whether this initialization consumes the 373 /// parameter. isParameterConsumed()374 bool isParameterConsumed() const { 375 assert(isParameterKind() && "Not a parameter"); 376 return (Parameter & 1); 377 } 378 379 /// \brief Retrieve the base specifier. getBaseSpecifier()380 const CXXBaseSpecifier *getBaseSpecifier() const { 381 assert(getKind() == EK_Base && "Not a base specifier"); 382 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1); 383 } 384 385 /// \brief Return whether the base is an inherited virtual base. isInheritedVirtualBase()386 bool isInheritedVirtualBase() const { 387 assert(getKind() == EK_Base && "Not a base specifier"); 388 return Base & 0x1; 389 } 390 391 /// \brief Determine the location of the 'return' keyword when initializing 392 /// the result of a function call. getReturnLoc()393 SourceLocation getReturnLoc() const { 394 assert(getKind() == EK_Result && "No 'return' location!"); 395 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location); 396 } 397 398 /// \brief Determine the location of the 'throw' keyword when initializing 399 /// an exception object. getThrowLoc()400 SourceLocation getThrowLoc() const { 401 assert(getKind() == EK_Exception && "No 'throw' location!"); 402 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location); 403 } 404 405 /// \brief If this is an array, vector, or complex number element, get the 406 /// element's index. getElementIndex()407 unsigned getElementIndex() const { 408 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement || 409 getKind() == EK_ComplexElement); 410 return Index; 411 } 412 /// \brief If this is already the initializer for an array or vector 413 /// element, sets the element index. setElementIndex(unsigned Index)414 void setElementIndex(unsigned Index) { 415 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement || 416 getKind() == EK_ComplexElement); 417 this->Index = Index; 418 } 419 /// \brief For a lambda capture, return the capture's name. getCapturedVarName()420 StringRef getCapturedVarName() const { 421 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!"); 422 return Capture.VarID->getName(); 423 } 424 /// \brief Determine the location of the capture when initializing 425 /// field from a captured variable in a lambda. getCaptureLoc()426 SourceLocation getCaptureLoc() const { 427 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!"); 428 return SourceLocation::getFromRawEncoding(Capture.Location); 429 } 430 setParameterCFAudited()431 void setParameterCFAudited() { 432 Kind = EK_Parameter_CF_Audited; 433 } 434 allocateManglingNumber()435 unsigned allocateManglingNumber() const { return ++ManglingNumber; } 436 437 /// Dump a representation of the initialized entity to standard error, 438 /// for debugging purposes. 439 void dump() const; 440 441 private: 442 unsigned dumpImpl(raw_ostream &OS) const; 443 }; 444 445 /// \brief Describes the kind of initialization being performed, along with 446 /// location information for tokens related to the initialization (equal sign, 447 /// parentheses). 448 class InitializationKind { 449 public: 450 /// \brief The kind of initialization being performed. 451 enum InitKind { 452 IK_Direct, ///< Direct initialization 453 IK_DirectList, ///< Direct list-initialization 454 IK_Copy, ///< Copy initialization 455 IK_Default, ///< Default initialization 456 IK_Value ///< Value initialization 457 }; 458 459 private: 460 /// \brief The context of the initialization. 461 enum InitContext { 462 IC_Normal, ///< Normal context 463 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs 464 IC_Implicit, ///< Implicit context (value initialization) 465 IC_StaticCast, ///< Static cast context 466 IC_CStyleCast, ///< C-style cast context 467 IC_FunctionalCast ///< Functional cast context 468 }; 469 470 /// \brief The kind of initialization being performed. 471 InitKind Kind : 8; 472 473 /// \brief The context of the initialization. 474 InitContext Context : 8; 475 476 /// \brief The source locations involved in the initialization. 477 SourceLocation Locations[3]; 478 InitializationKind(InitKind Kind,InitContext Context,SourceLocation Loc1,SourceLocation Loc2,SourceLocation Loc3)479 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, 480 SourceLocation Loc2, SourceLocation Loc3) 481 : Kind(Kind), Context(Context) 482 { 483 Locations[0] = Loc1; 484 Locations[1] = Loc2; 485 Locations[2] = Loc3; 486 } 487 488 public: 489 /// \brief Create a direct initialization. CreateDirect(SourceLocation InitLoc,SourceLocation LParenLoc,SourceLocation RParenLoc)490 static InitializationKind CreateDirect(SourceLocation InitLoc, 491 SourceLocation LParenLoc, 492 SourceLocation RParenLoc) { 493 return InitializationKind(IK_Direct, IC_Normal, 494 InitLoc, LParenLoc, RParenLoc); 495 } 496 CreateDirectList(SourceLocation InitLoc)497 static InitializationKind CreateDirectList(SourceLocation InitLoc) { 498 return InitializationKind(IK_DirectList, IC_Normal, 499 InitLoc, InitLoc, InitLoc); 500 } 501 502 /// \brief Create a direct initialization due to a cast that isn't a C-style 503 /// or functional cast. CreateCast(SourceRange TypeRange)504 static InitializationKind CreateCast(SourceRange TypeRange) { 505 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(), 506 TypeRange.getBegin(), TypeRange.getEnd()); 507 } 508 509 /// \brief Create a direct initialization for a C-style cast. CreateCStyleCast(SourceLocation StartLoc,SourceRange TypeRange,bool InitList)510 static InitializationKind CreateCStyleCast(SourceLocation StartLoc, 511 SourceRange TypeRange, 512 bool InitList) { 513 // C++ cast syntax doesn't permit init lists, but C compound literals are 514 // exactly that. 515 return InitializationKind(InitList ? IK_DirectList : IK_Direct, 516 IC_CStyleCast, StartLoc, TypeRange.getBegin(), 517 TypeRange.getEnd()); 518 } 519 520 /// \brief Create a direct initialization for a functional cast. CreateFunctionalCast(SourceRange TypeRange,bool InitList)521 static InitializationKind CreateFunctionalCast(SourceRange TypeRange, 522 bool InitList) { 523 return InitializationKind(InitList ? IK_DirectList : IK_Direct, 524 IC_FunctionalCast, TypeRange.getBegin(), 525 TypeRange.getBegin(), TypeRange.getEnd()); 526 } 527 528 /// \brief Create a copy initialization. 529 static InitializationKind CreateCopy(SourceLocation InitLoc, 530 SourceLocation EqualLoc, 531 bool AllowExplicitConvs = false) { 532 return InitializationKind(IK_Copy, 533 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal, 534 InitLoc, EqualLoc, EqualLoc); 535 } 536 537 /// \brief Create a default initialization. CreateDefault(SourceLocation InitLoc)538 static InitializationKind CreateDefault(SourceLocation InitLoc) { 539 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc); 540 } 541 542 /// \brief Create a value initialization. 543 static InitializationKind CreateValue(SourceLocation InitLoc, 544 SourceLocation LParenLoc, 545 SourceLocation RParenLoc, 546 bool isImplicit = false) { 547 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal, 548 InitLoc, LParenLoc, RParenLoc); 549 } 550 551 /// \brief Determine the initialization kind. getKind()552 InitKind getKind() const { 553 return Kind; 554 } 555 556 /// \brief Determine whether this initialization is an explicit cast. isExplicitCast()557 bool isExplicitCast() const { 558 return Context >= IC_StaticCast; 559 } 560 561 /// \brief Determine whether this initialization is a C-style cast. isCStyleOrFunctionalCast()562 bool isCStyleOrFunctionalCast() const { 563 return Context >= IC_CStyleCast; 564 } 565 566 /// \brief Determine whether this is a C-style cast. isCStyleCast()567 bool isCStyleCast() const { 568 return Context == IC_CStyleCast; 569 } 570 571 /// \brief Determine whether this is a functional-style cast. isFunctionalCast()572 bool isFunctionalCast() const { 573 return Context == IC_FunctionalCast; 574 } 575 576 /// \brief Determine whether this initialization is an implicit 577 /// value-initialization, e.g., as occurs during aggregate 578 /// initialization. isImplicitValueInit()579 bool isImplicitValueInit() const { return Context == IC_Implicit; } 580 581 /// \brief Retrieve the location at which initialization is occurring. getLocation()582 SourceLocation getLocation() const { return Locations[0]; } 583 584 /// \brief Retrieve the source range that covers the initialization. getRange()585 SourceRange getRange() const { 586 return SourceRange(Locations[0], Locations[2]); 587 } 588 589 /// \brief Retrieve the location of the equal sign for copy initialization 590 /// (if present). getEqualLoc()591 SourceLocation getEqualLoc() const { 592 assert(Kind == IK_Copy && "Only copy initialization has an '='"); 593 return Locations[1]; 594 } 595 isCopyInit()596 bool isCopyInit() const { return Kind == IK_Copy; } 597 598 /// \brief Retrieve whether this initialization allows the use of explicit 599 /// constructors. AllowExplicit()600 bool AllowExplicit() const { return !isCopyInit(); } 601 602 /// \brief Retrieve whether this initialization allows the use of explicit 603 /// conversion functions when binding a reference. If the reference is the 604 /// first parameter in a copy or move constructor, such conversions are 605 /// permitted even though we are performing copy-initialization. allowExplicitConversionFunctionsInRefBinding()606 bool allowExplicitConversionFunctionsInRefBinding() const { 607 return !isCopyInit() || Context == IC_ExplicitConvs; 608 } 609 610 /// \brief Retrieve the source range containing the locations of the open 611 /// and closing parentheses for value and direct initializations. getParenRange()612 SourceRange getParenRange() const { 613 assert((Kind == IK_Direct || Kind == IK_Value) && 614 "Only direct- and value-initialization have parentheses"); 615 return SourceRange(Locations[1], Locations[2]); 616 } 617 }; 618 619 /// \brief Describes the sequence of initializations required to initialize 620 /// a given object or reference with a set of arguments. 621 class InitializationSequence { 622 public: 623 /// \brief Describes the kind of initialization sequence computed. 624 enum SequenceKind { 625 /// \brief A failed initialization sequence. The failure kind tells what 626 /// happened. 627 FailedSequence = 0, 628 629 /// \brief A dependent initialization, which could not be 630 /// type-checked due to the presence of dependent types or 631 /// dependently-typed expressions. 632 DependentSequence, 633 634 /// \brief A normal sequence. 635 NormalSequence 636 }; 637 638 /// \brief Describes the kind of a particular step in an initialization 639 /// sequence. 640 enum StepKind { 641 /// \brief Resolve the address of an overloaded function to a specific 642 /// function declaration. 643 SK_ResolveAddressOfOverloadedFunction, 644 /// \brief Perform a derived-to-base cast, producing an rvalue. 645 SK_CastDerivedToBaseRValue, 646 /// \brief Perform a derived-to-base cast, producing an xvalue. 647 SK_CastDerivedToBaseXValue, 648 /// \brief Perform a derived-to-base cast, producing an lvalue. 649 SK_CastDerivedToBaseLValue, 650 /// \brief Reference binding to an lvalue. 651 SK_BindReference, 652 /// \brief Reference binding to a temporary. 653 SK_BindReferenceToTemporary, 654 /// \brief An optional copy of a temporary object to another 655 /// temporary object, which is permitted (but not required) by 656 /// C++98/03 but not C++0x. 657 SK_ExtraneousCopyToTemporary, 658 /// \brief Perform a user-defined conversion, either via a conversion 659 /// function or via a constructor. 660 SK_UserConversion, 661 /// \brief Perform a qualification conversion, producing an rvalue. 662 SK_QualificationConversionRValue, 663 /// \brief Perform a qualification conversion, producing an xvalue. 664 SK_QualificationConversionXValue, 665 /// \brief Perform a qualification conversion, producing an lvalue. 666 SK_QualificationConversionLValue, 667 /// \brief Perform a conversion adding _Atomic to a type. 668 SK_AtomicConversion, 669 /// \brief Perform a load from a glvalue, producing an rvalue. 670 SK_LValueToRValue, 671 /// \brief Perform an implicit conversion sequence. 672 SK_ConversionSequence, 673 /// \brief Perform an implicit conversion sequence without narrowing. 674 SK_ConversionSequenceNoNarrowing, 675 /// \brief Perform list-initialization without a constructor. 676 SK_ListInitialization, 677 /// \brief Unwrap the single-element initializer list for a reference. 678 SK_UnwrapInitList, 679 /// \brief Rewrap the single-element initializer list for a reference. 680 SK_RewrapInitList, 681 /// \brief Perform initialization via a constructor. 682 SK_ConstructorInitialization, 683 /// \brief Perform initialization via a constructor, taking arguments from 684 /// a single InitListExpr. 685 SK_ConstructorInitializationFromList, 686 /// \brief Zero-initialize the object 687 SK_ZeroInitialization, 688 /// \brief C assignment 689 SK_CAssignment, 690 /// \brief Initialization by string 691 SK_StringInit, 692 /// \brief An initialization that "converts" an Objective-C object 693 /// (not a point to an object) to another Objective-C object type. 694 SK_ObjCObjectConversion, 695 /// \brief Array initialization (from an array rvalue). 696 /// This is a GNU C extension. 697 SK_ArrayInit, 698 /// \brief Array initialization from a parenthesized initializer list. 699 /// This is a GNU C++ extension. 700 SK_ParenthesizedArrayInit, 701 /// \brief Pass an object by indirect copy-and-restore. 702 SK_PassByIndirectCopyRestore, 703 /// \brief Pass an object by indirect restore. 704 SK_PassByIndirectRestore, 705 /// \brief Produce an Objective-C object pointer. 706 SK_ProduceObjCObject, 707 /// \brief Construct a std::initializer_list from an initializer list. 708 SK_StdInitializerList, 709 /// \brief Perform initialization via a constructor taking a single 710 /// std::initializer_list argument. 711 SK_StdInitializerListConstructorCall, 712 /// \brief Initialize an OpenCL sampler from an integer. 713 SK_OCLSamplerInit, 714 /// \brief Passing zero to a function where OpenCL event_t is expected. 715 SK_OCLZeroEvent 716 }; 717 718 /// \brief A single step in the initialization sequence. 719 class Step { 720 public: 721 /// \brief The kind of conversion or initialization step we are taking. 722 StepKind Kind; 723 724 // \brief The type that results from this initialization. 725 QualType Type; 726 727 struct F { 728 bool HadMultipleCandidates; 729 FunctionDecl *Function; 730 DeclAccessPair FoundDecl; 731 }; 732 733 union { 734 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind == 735 /// SK_UserConversion, the function that the expression should be 736 /// resolved to or the conversion function to call, respectively. 737 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction, 738 /// the constructor to be called. 739 /// 740 /// Always a FunctionDecl, plus a Boolean flag telling if it was 741 /// selected from an overloaded set having size greater than 1. 742 /// For conversion decls, the naming class is the source type. 743 /// For construct decls, the naming class is the target type. 744 struct F Function; 745 746 /// \brief When Kind = SK_ConversionSequence, the implicit conversion 747 /// sequence. 748 ImplicitConversionSequence *ICS; 749 750 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the 751 /// wrapping list. 752 InitListExpr *WrappingSyntacticList; 753 }; 754 755 void Destroy(); 756 }; 757 758 private: 759 /// \brief The kind of initialization sequence computed. 760 enum SequenceKind SequenceKind; 761 762 /// \brief Steps taken by this initialization. 763 SmallVector<Step, 4> Steps; 764 765 public: 766 /// \brief Describes why initialization failed. 767 enum FailureKind { 768 /// \brief Too many initializers provided for a reference. 769 FK_TooManyInitsForReference, 770 /// \brief Array must be initialized with an initializer list. 771 FK_ArrayNeedsInitList, 772 /// \brief Array must be initialized with an initializer list or a 773 /// string literal. 774 FK_ArrayNeedsInitListOrStringLiteral, 775 /// \brief Array must be initialized with an initializer list or a 776 /// wide string literal. 777 FK_ArrayNeedsInitListOrWideStringLiteral, 778 /// \brief Initializing a wide char array with narrow string literal. 779 FK_NarrowStringIntoWideCharArray, 780 /// \brief Initializing char array with wide string literal. 781 FK_WideStringIntoCharArray, 782 /// \brief Initializing wide char array with incompatible wide string 783 /// literal. 784 FK_IncompatWideStringIntoWideChar, 785 /// \brief Array type mismatch. 786 FK_ArrayTypeMismatch, 787 /// \brief Non-constant array initializer 788 FK_NonConstantArrayInit, 789 /// \brief Cannot resolve the address of an overloaded function. 790 FK_AddressOfOverloadFailed, 791 /// \brief Overloading due to reference initialization failed. 792 FK_ReferenceInitOverloadFailed, 793 /// \brief Non-const lvalue reference binding to a temporary. 794 FK_NonConstLValueReferenceBindingToTemporary, 795 /// \brief Non-const lvalue reference binding to an lvalue of unrelated 796 /// type. 797 FK_NonConstLValueReferenceBindingToUnrelated, 798 /// \brief Rvalue reference binding to an lvalue. 799 FK_RValueReferenceBindingToLValue, 800 /// \brief Reference binding drops qualifiers. 801 FK_ReferenceInitDropsQualifiers, 802 /// \brief Reference binding failed. 803 FK_ReferenceInitFailed, 804 /// \brief Implicit conversion failed. 805 FK_ConversionFailed, 806 /// \brief Implicit conversion failed. 807 FK_ConversionFromPropertyFailed, 808 /// \brief Too many initializers for scalar 809 FK_TooManyInitsForScalar, 810 /// \brief Reference initialization from an initializer list 811 FK_ReferenceBindingToInitList, 812 /// \brief Initialization of some unused destination type with an 813 /// initializer list. 814 FK_InitListBadDestinationType, 815 /// \brief Overloading for a user-defined conversion failed. 816 FK_UserConversionOverloadFailed, 817 /// \brief Overloading for initialization by constructor failed. 818 FK_ConstructorOverloadFailed, 819 /// \brief Overloading for list-initialization by constructor failed. 820 FK_ListConstructorOverloadFailed, 821 /// \brief Default-initialization of a 'const' object. 822 FK_DefaultInitOfConst, 823 /// \brief Initialization of an incomplete type. 824 FK_Incomplete, 825 /// \brief Variable-length array must not have an initializer. 826 FK_VariableLengthArrayHasInitializer, 827 /// \brief List initialization failed at some point. 828 FK_ListInitializationFailed, 829 /// \brief Initializer has a placeholder type which cannot be 830 /// resolved by initialization. 831 FK_PlaceholderType, 832 /// \brief Trying to take the address of a function that doesn't support 833 /// having its address taken. 834 FK_AddressOfUnaddressableFunction, 835 /// \brief List-copy-initialization chose an explicit constructor. 836 FK_ExplicitConstructor 837 }; 838 839 private: 840 /// \brief The reason why initialization failed. 841 FailureKind Failure; 842 843 /// \brief The failed result of overload resolution. 844 OverloadingResult FailedOverloadResult; 845 846 /// \brief The candidate set created when initialization failed. 847 OverloadCandidateSet FailedCandidateSet; 848 849 /// \brief The incomplete type that caused a failure. 850 QualType FailedIncompleteType; 851 852 /// \brief The fixit that needs to be applied to make this initialization 853 /// succeed. 854 std::string ZeroInitializationFixit; 855 SourceLocation ZeroInitializationFixitLoc; 856 857 public: 858 /// \brief Call for initializations are invalid but that would be valid 859 /// zero initialzations if Fixit was applied. SetZeroInitializationFixit(const std::string & Fixit,SourceLocation L)860 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) { 861 ZeroInitializationFixit = Fixit; 862 ZeroInitializationFixitLoc = L; 863 } 864 865 private: 866 867 /// \brief Prints a follow-up note that highlights the location of 868 /// the initialized entity, if it's remote. 869 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity); 870 871 public: 872 /// \brief Try to perform initialization of the given entity, creating a 873 /// record of the steps required to perform the initialization. 874 /// 875 /// The generated initialization sequence will either contain enough 876 /// information to diagnose 877 /// 878 /// \param S the semantic analysis object. 879 /// 880 /// \param Entity the entity being initialized. 881 /// 882 /// \param Kind the kind of initialization being performed. 883 /// 884 /// \param Args the argument(s) provided for initialization. 885 /// 886 /// \param TopLevelOfInitList true if we are initializing from an expression 887 /// at the top level inside an initializer list. This disallows 888 /// narrowing conversions in C++11 onwards. 889 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable 890 /// as invalid. 891 InitializationSequence(Sema &S, 892 const InitializedEntity &Entity, 893 const InitializationKind &Kind, 894 MultiExprArg Args, 895 bool TopLevelOfInitList = false, 896 bool TreatUnavailableAsInvalid = true); 897 void InitializeFrom(Sema &S, const InitializedEntity &Entity, 898 const InitializationKind &Kind, MultiExprArg Args, 899 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid); 900 901 ~InitializationSequence(); 902 903 /// \brief Perform the actual initialization of the given entity based on 904 /// the computed initialization sequence. 905 /// 906 /// \param S the semantic analysis object. 907 /// 908 /// \param Entity the entity being initialized. 909 /// 910 /// \param Kind the kind of initialization being performed. 911 /// 912 /// \param Args the argument(s) provided for initialization, ownership of 913 /// which is transferred into the routine. 914 /// 915 /// \param ResultType if non-NULL, will be set to the type of the 916 /// initialized object, which is the type of the declaration in most 917 /// cases. However, when the initialized object is a variable of 918 /// incomplete array type and the initializer is an initializer 919 /// list, this type will be set to the completed array type. 920 /// 921 /// \returns an expression that performs the actual object initialization, if 922 /// the initialization is well-formed. Otherwise, emits diagnostics 923 /// and returns an invalid expression. 924 ExprResult Perform(Sema &S, 925 const InitializedEntity &Entity, 926 const InitializationKind &Kind, 927 MultiExprArg Args, 928 QualType *ResultType = nullptr); 929 930 /// \brief Diagnose an potentially-invalid initialization sequence. 931 /// 932 /// \returns true if the initialization sequence was ill-formed, 933 /// false otherwise. 934 bool Diagnose(Sema &S, 935 const InitializedEntity &Entity, 936 const InitializationKind &Kind, 937 ArrayRef<Expr *> Args); 938 939 /// \brief Determine the kind of initialization sequence computed. getKind()940 enum SequenceKind getKind() const { return SequenceKind; } 941 942 /// \brief Set the kind of sequence computed. setSequenceKind(enum SequenceKind SK)943 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; } 944 945 /// \brief Determine whether the initialization sequence is valid. 946 explicit operator bool() const { return !Failed(); } 947 948 /// \brief Determine whether the initialization sequence is invalid. Failed()949 bool Failed() const { return SequenceKind == FailedSequence; } 950 951 typedef SmallVectorImpl<Step>::const_iterator step_iterator; step_begin()952 step_iterator step_begin() const { return Steps.begin(); } step_end()953 step_iterator step_end() const { return Steps.end(); } 954 955 typedef llvm::iterator_range<step_iterator> step_range; steps()956 step_range steps() const { return {step_begin(), step_end()}; } 957 958 /// \brief Determine whether this initialization is a direct reference 959 /// binding (C++ [dcl.init.ref]). 960 bool isDirectReferenceBinding() const; 961 962 /// \brief Determine whether this initialization failed due to an ambiguity. 963 bool isAmbiguous() const; 964 965 /// \brief Determine whether this initialization is direct call to a 966 /// constructor. 967 bool isConstructorInitialization() const; 968 969 /// \brief Returns whether the last step in this initialization sequence is a 970 /// narrowing conversion, defined by C++0x [dcl.init.list]p7. 971 /// 972 /// If this function returns true, *isInitializerConstant will be set to 973 /// describe whether *Initializer was a constant expression. If 974 /// *isInitializerConstant is set to true, *ConstantValue will be set to the 975 /// evaluated value of *Initializer. 976 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer, 977 bool *isInitializerConstant, 978 APValue *ConstantValue) const; 979 980 /// \brief Add a new step in the initialization that resolves the address 981 /// of an overloaded function to a specific function declaration. 982 /// 983 /// \param Function the function to which the overloaded function reference 984 /// resolves. 985 void AddAddressOverloadResolutionStep(FunctionDecl *Function, 986 DeclAccessPair Found, 987 bool HadMultipleCandidates); 988 989 /// \brief Add a new step in the initialization that performs a derived-to- 990 /// base cast. 991 /// 992 /// \param BaseType the base type to which we will be casting. 993 /// 994 /// \param Category Indicates whether the result will be treated as an 995 /// rvalue, an xvalue, or an lvalue. 996 void AddDerivedToBaseCastStep(QualType BaseType, 997 ExprValueKind Category); 998 999 /// \brief Add a new step binding a reference to an object. 1000 /// 1001 /// \param BindingTemporary True if we are binding a reference to a temporary 1002 /// object (thereby extending its lifetime); false if we are binding to an 1003 /// lvalue or an lvalue treated as an rvalue. 1004 void AddReferenceBindingStep(QualType T, bool BindingTemporary); 1005 1006 /// \brief Add a new step that makes an extraneous copy of the input 1007 /// to a temporary of the same class type. 1008 /// 1009 /// This extraneous copy only occurs during reference binding in 1010 /// C++98/03, where we are permitted (but not required) to introduce 1011 /// an extra copy. At a bare minimum, we must check that we could 1012 /// call the copy constructor, and produce a diagnostic if the copy 1013 /// constructor is inaccessible or no copy constructor matches. 1014 // 1015 /// \param T The type of the temporary being created. 1016 void AddExtraneousCopyToTemporary(QualType T); 1017 1018 /// \brief Add a new step invoking a conversion function, which is either 1019 /// a constructor or a conversion function. 1020 void AddUserConversionStep(FunctionDecl *Function, 1021 DeclAccessPair FoundDecl, 1022 QualType T, 1023 bool HadMultipleCandidates); 1024 1025 /// \brief Add a new step that performs a qualification conversion to the 1026 /// given type. 1027 void AddQualificationConversionStep(QualType Ty, 1028 ExprValueKind Category); 1029 1030 /// \brief Add a new step that performs conversion from non-atomic to atomic 1031 /// type. 1032 void AddAtomicConversionStep(QualType Ty); 1033 1034 /// \brief Add a new step that performs a load of the given type. 1035 /// 1036 /// Although the term "LValueToRValue" is conventional, this applies to both 1037 /// lvalues and xvalues. 1038 void AddLValueToRValueStep(QualType Ty); 1039 1040 /// \brief Add a new step that applies an implicit conversion sequence. 1041 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, 1042 QualType T, bool TopLevelOfInitList = false); 1043 1044 /// \brief Add a list-initialization step. 1045 void AddListInitializationStep(QualType T); 1046 1047 /// \brief Add a constructor-initialization step. 1048 /// 1049 /// \param FromInitList The constructor call is syntactically an initializer 1050 /// list. 1051 /// \param AsInitList The constructor is called as an init list constructor. 1052 void AddConstructorInitializationStep(DeclAccessPair FoundDecl, 1053 CXXConstructorDecl *Constructor, 1054 QualType T, 1055 bool HadMultipleCandidates, 1056 bool FromInitList, bool AsInitList); 1057 1058 /// \brief Add a zero-initialization step. 1059 void AddZeroInitializationStep(QualType T); 1060 1061 /// \brief Add a C assignment step. 1062 // 1063 // FIXME: It isn't clear whether this should ever be needed; 1064 // ideally, we would handle everything needed in C in the common 1065 // path. However, that isn't the case yet. 1066 void AddCAssignmentStep(QualType T); 1067 1068 /// \brief Add a string init step. 1069 void AddStringInitStep(QualType T); 1070 1071 /// \brief Add an Objective-C object conversion step, which is 1072 /// always a no-op. 1073 void AddObjCObjectConversionStep(QualType T); 1074 1075 /// \brief Add an array initialization step. 1076 void AddArrayInitStep(QualType T); 1077 1078 /// \brief Add a parenthesized array initialization step. 1079 void AddParenthesizedArrayInitStep(QualType T); 1080 1081 /// \brief Add a step to pass an object by indirect copy-restore. 1082 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy); 1083 1084 /// \brief Add a step to "produce" an Objective-C object (by 1085 /// retaining it). 1086 void AddProduceObjCObjectStep(QualType T); 1087 1088 /// \brief Add a step to construct a std::initializer_list object from an 1089 /// initializer list. 1090 void AddStdInitializerListConstructionStep(QualType T); 1091 1092 /// \brief Add a step to initialize an OpenCL sampler from an integer 1093 /// constant. 1094 void AddOCLSamplerInitStep(QualType T); 1095 1096 /// \brief Add a step to initialize an OpenCL event_t from a NULL 1097 /// constant. 1098 void AddOCLZeroEventStep(QualType T); 1099 1100 /// \brief Add steps to unwrap a initializer list for a reference around a 1101 /// single element and rewrap it at the end. 1102 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic); 1103 1104 /// \brief Note that this initialization sequence failed. SetFailed(FailureKind Failure)1105 void SetFailed(FailureKind Failure) { 1106 SequenceKind = FailedSequence; 1107 this->Failure = Failure; 1108 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && 1109 "Incomplete type failure requires a type!"); 1110 } 1111 1112 /// \brief Note that this initialization sequence failed due to failed 1113 /// overload resolution. 1114 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result); 1115 1116 /// \brief Retrieve a reference to the candidate set when overload 1117 /// resolution fails. getFailedCandidateSet()1118 OverloadCandidateSet &getFailedCandidateSet() { 1119 return FailedCandidateSet; 1120 } 1121 1122 /// \brief Get the overloading result, for when the initialization 1123 /// sequence failed due to a bad overload. getFailedOverloadResult()1124 OverloadingResult getFailedOverloadResult() const { 1125 return FailedOverloadResult; 1126 } 1127 1128 /// \brief Note that this initialization sequence failed due to an 1129 /// incomplete type. setIncompleteTypeFailure(QualType IncompleteType)1130 void setIncompleteTypeFailure(QualType IncompleteType) { 1131 FailedIncompleteType = IncompleteType; 1132 SetFailed(FK_Incomplete); 1133 } 1134 1135 /// \brief Determine why initialization failed. getFailureKind()1136 FailureKind getFailureKind() const { 1137 assert(Failed() && "Not an initialization failure!"); 1138 return Failure; 1139 } 1140 1141 /// \brief Dump a representation of this initialization sequence to 1142 /// the given stream, for debugging purposes. 1143 void dump(raw_ostream &OS) const; 1144 1145 /// \brief Dump a representation of this initialization sequence to 1146 /// standard error, for debugging purposes. 1147 void dump() const; 1148 }; 1149 1150 } // end namespace clang 1151 1152 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H 1153