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