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