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