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