1 //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides supporting data types for initialization of objects.
12 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
14 #define LLVM_CLANG_SEMA_INITIALIZATION_H
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"
29 class CXXBaseSpecifier;
40 /// \brief Describes an entity that is being initialized.
41 class InitializedEntity {
43 /// \brief Specifies the kind of entity being initialized.
45 /// \brief The entity being initialized is a variable.
47 /// \brief The entity being initialized is a function parameter.
49 /// \brief The entity being initialized is the result of a function call.
51 /// \brief The entity being initialized is an exception object that
54 /// \brief The entity being initialized is a non-static data member
57 /// \brief The entity being initialized is an element of an array.
59 /// \brief The entity being initialized is an object (or array of
60 /// objects) allocated via new.
62 /// \brief The entity being initialized is a temporary object.
64 /// \brief The entity being initialized is a base member subobject.
66 /// \brief The initialization is being done by a delegating constructor.
68 /// \brief The entity being initialized is an element of a vector.
71 /// \brief The entity being initialized is a field of block descriptor for
72 /// the copied-in c++ object.
74 /// \brief The entity being initialized is the real or imaginary part of a
77 /// \brief The entity being initialized is the field that captures a
78 /// variable in a lambda.
80 /// \brief The entity being initialized is the initializer for a compound
82 EK_CompoundLiteralInit,
83 /// \brief The entity being implicitly initialized back to the formal
86 /// \brief The entity being initialized is a function parameter; function
87 /// is member of group of audited CF APIs.
88 EK_Parameter_CF_Audited
90 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
91 // enum as an index for its first %select. When modifying this list,
92 // that diagnostic text needs to be updated as well.
96 /// \brief The kind of entity being initialized.
99 /// \brief If non-NULL, the parent entity in which this
100 /// initialization occurs.
101 const InitializedEntity *Parent;
103 /// \brief The type of the object or reference being initialized.
106 /// \brief The mangling number for the next reference temporary to be created.
107 mutable unsigned ManglingNumber;
110 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
111 /// location of the 'return', 'throw', or 'new' keyword,
112 /// respectively. When Kind == EK_Temporary, the location where
113 /// the temporary is being created.
116 /// \brief Whether the entity being initialized may end up using the
117 /// named return value optimization (NRVO).
122 /// \brief The name of the variable being captured by an EK_LambdaCapture.
123 IdentifierInfo *VarID;
125 /// \brief The source location at which the capture occurs.
130 /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
131 /// FieldDecl, respectively.
132 DeclaratorDecl *VariableOrMember;
134 /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where
135 /// result type was implicitly changed to accommodate ARC semantics.
136 ObjCMethodDecl *MethodDecl;
138 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
139 /// low bit indicating whether the parameter is "consumed".
142 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
143 /// source information for the temporary.
144 TypeSourceInfo *TypeInfo;
146 struct LN LocAndNRVO;
148 /// \brief When Kind == EK_Base, the base specifier that provides the
149 /// base class. The lower bit specifies whether the base is an inherited
153 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
154 /// EK_ComplexElement, the index of the array or vector element being
161 InitializedEntity() : ManglingNumber(0) {}
163 /// \brief Create the initialization entity for a variable.
164 InitializedEntity(VarDecl *Var)
165 : Kind(EK_Variable), Parent(nullptr), Type(Var->getType()),
166 ManglingNumber(0), VariableOrMember(Var) { }
168 /// \brief Create the initialization entity for the result of a
169 /// function, throwing an object, performing an explicit cast, or
170 /// initializing a parameter for which there is no declaration.
171 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
173 : Kind(Kind), Parent(nullptr), Type(Type), ManglingNumber(0)
175 LocAndNRVO.Location = Loc.getRawEncoding();
176 LocAndNRVO.NRVO = NRVO;
179 /// \brief Create the initialization entity for a member subobject.
180 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent)
181 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
182 ManglingNumber(0), VariableOrMember(Member) { }
184 /// \brief Create the initialization entity for an array element.
185 InitializedEntity(ASTContext &Context, unsigned Index,
186 const InitializedEntity &Parent);
188 /// \brief Create the initialization entity for a lambda capture.
189 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
190 : Kind(EK_LambdaCapture), Parent(nullptr), Type(FieldType),
193 Capture.VarID = VarID;
194 Capture.Location = Loc.getRawEncoding();
198 /// \brief Create the initialization entity for a variable.
199 static InitializedEntity InitializeVariable(VarDecl *Var) {
200 return InitializedEntity(Var);
203 /// \brief Create the initialization entity for a parameter.
204 static InitializedEntity InitializeParameter(ASTContext &Context,
206 return InitializeParameter(Context, Parm, Parm->getType());
209 /// \brief Create the initialization entity for a parameter, but use
211 static InitializedEntity InitializeParameter(ASTContext &Context,
214 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
215 Parm->hasAttr<NSConsumedAttr>());
217 InitializedEntity Entity;
218 Entity.Kind = EK_Parameter;
220 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
221 Entity.Parent = nullptr;
223 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
227 /// \brief Create the initialization entity for a parameter that is
228 /// only known by its type.
229 static InitializedEntity InitializeParameter(ASTContext &Context,
232 InitializedEntity Entity;
233 Entity.Kind = EK_Parameter;
234 Entity.Type = Context.getVariableArrayDecayedType(Type);
235 Entity.Parent = nullptr;
236 Entity.Parameter = (Consumed);
240 /// \brief Create the initialization entity for the result of a function.
241 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
242 QualType Type, bool NRVO) {
243 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
246 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
247 QualType Type, bool NRVO) {
248 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
251 /// \brief Create the initialization entity for an exception object.
252 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
253 QualType Type, bool NRVO) {
254 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
257 /// \brief Create the initialization entity for an object allocated via new.
258 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
259 return InitializedEntity(EK_New, NewLoc, Type);
262 /// \brief Create the initialization entity for a temporary.
263 static InitializedEntity InitializeTemporary(QualType Type) {
264 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
265 Result.TypeInfo = nullptr;
269 /// \brief Create the initialization entity for a temporary.
270 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
271 InitializedEntity Result(EK_Temporary, SourceLocation(),
272 TypeInfo->getType());
273 Result.TypeInfo = TypeInfo;
277 /// \brief Create the initialization entity for a related result.
278 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
280 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
281 Result.MethodDecl = MD;
286 /// \brief Create the initialization entity for a base class subobject.
287 static InitializedEntity InitializeBase(ASTContext &Context,
288 const CXXBaseSpecifier *Base,
289 bool IsInheritedVirtualBase);
291 /// \brief Create the initialization entity for a delegated constructor.
292 static InitializedEntity InitializeDelegation(QualType Type) {
293 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
296 /// \brief Create the initialization entity for a member subobject.
297 static InitializedEntity
298 InitializeMember(FieldDecl *Member,
299 const InitializedEntity *Parent = nullptr) {
300 return InitializedEntity(Member, Parent);
303 /// \brief Create the initialization entity for a member subobject.
304 static InitializedEntity
305 InitializeMember(IndirectFieldDecl *Member,
306 const InitializedEntity *Parent = nullptr) {
307 return InitializedEntity(Member->getAnonField(), Parent);
310 /// \brief Create the initialization entity for an array element.
311 static InitializedEntity InitializeElement(ASTContext &Context,
313 const InitializedEntity &Parent) {
314 return InitializedEntity(Context, Index, Parent);
317 /// \brief Create the initialization entity for a lambda capture.
318 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
320 SourceLocation Loc) {
321 return InitializedEntity(VarID, FieldType, Loc);
324 /// \brief Create the entity for a compound literal initializer.
325 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
326 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
328 Result.TypeInfo = TSI;
333 /// \brief Determine the kind of initialization.
334 EntityKind getKind() const { return Kind; }
336 /// \brief Retrieve the parent of the entity being initialized, when
337 /// the initialization itself is occurring within the context of a
338 /// larger initialization.
339 const InitializedEntity *getParent() const { return Parent; }
341 /// \brief Retrieve type being initialized.
342 QualType getType() const { return Type; }
344 /// \brief Retrieve complete type-source information for the object being
345 /// constructed, if known.
346 TypeSourceInfo *getTypeSourceInfo() const {
347 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
353 /// \brief Retrieve the name of the entity being initialized.
354 DeclarationName getName() const;
356 /// \brief Retrieve the variable, parameter, or field being
358 DeclaratorDecl *getDecl() const;
360 /// \brief Retrieve the ObjectiveC method being initialized.
361 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
363 /// \brief Determine whether this initialization allows the named return
364 /// value optimization, which also applies to thrown objects.
365 bool allowsNRVO() const;
367 bool isParameterKind() const {
368 return (getKind() == EK_Parameter ||
369 getKind() == EK_Parameter_CF_Audited);
371 /// \brief Determine whether this initialization consumes the
373 bool isParameterConsumed() const {
374 assert(isParameterKind() && "Not a parameter");
375 return (Parameter & 1);
378 /// \brief Retrieve the base specifier.
379 const CXXBaseSpecifier *getBaseSpecifier() const {
380 assert(getKind() == EK_Base && "Not a base specifier");
381 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
384 /// \brief Return whether the base is an inherited virtual base.
385 bool isInheritedVirtualBase() const {
386 assert(getKind() == EK_Base && "Not a base specifier");
390 /// \brief Determine the location of the 'return' keyword when initializing
391 /// the result of a function call.
392 SourceLocation getReturnLoc() const {
393 assert(getKind() == EK_Result && "No 'return' location!");
394 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
397 /// \brief Determine the location of the 'throw' keyword when initializing
398 /// an exception object.
399 SourceLocation getThrowLoc() const {
400 assert(getKind() == EK_Exception && "No 'throw' location!");
401 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
404 /// \brief If this is an array, vector, or complex number element, get the
406 unsigned getElementIndex() const {
407 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
408 getKind() == EK_ComplexElement);
411 /// \brief If this is already the initializer for an array or vector
412 /// element, sets the element index.
413 void setElementIndex(unsigned Index) {
414 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
415 getKind() == EK_ComplexElement);
418 /// \brief For a lambda capture, return the capture's name.
419 StringRef getCapturedVarName() const {
420 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
421 return Capture.VarID->getName();
423 /// \brief Determine the location of the capture when initializing
424 /// field from a captured variable in a lambda.
425 SourceLocation getCaptureLoc() const {
426 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
427 return SourceLocation::getFromRawEncoding(Capture.Location);
430 void setParameterCFAudited() {
431 Kind = EK_Parameter_CF_Audited;
434 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
436 /// Dump a representation of the initialized entity to standard error,
437 /// for debugging purposes.
441 unsigned dumpImpl(raw_ostream &OS) const;
444 /// \brief Describes the kind of initialization being performed, along with
445 /// location information for tokens related to the initialization (equal sign,
447 class InitializationKind {
449 /// \brief The kind of initialization being performed.
451 IK_Direct, ///< Direct initialization
452 IK_DirectList, ///< Direct list-initialization
453 IK_Copy, ///< Copy initialization
454 IK_Default, ///< Default initialization
455 IK_Value ///< Value initialization
459 /// \brief The context of the initialization.
461 IC_Normal, ///< Normal context
462 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
463 IC_Implicit, ///< Implicit context (value initialization)
464 IC_StaticCast, ///< Static cast context
465 IC_CStyleCast, ///< C-style cast context
466 IC_FunctionalCast ///< Functional cast context
469 /// \brief The kind of initialization being performed.
472 /// \brief The context of the initialization.
473 InitContext Context : 8;
475 /// \brief The source locations involved in the initialization.
476 SourceLocation Locations[3];
478 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
479 SourceLocation Loc2, SourceLocation Loc3)
480 : Kind(Kind), Context(Context)
488 /// \brief Create a direct initialization.
489 static InitializationKind CreateDirect(SourceLocation InitLoc,
490 SourceLocation LParenLoc,
491 SourceLocation RParenLoc) {
492 return InitializationKind(IK_Direct, IC_Normal,
493 InitLoc, LParenLoc, RParenLoc);
496 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
497 return InitializationKind(IK_DirectList, IC_Normal,
498 InitLoc, InitLoc, InitLoc);
501 /// \brief Create a direct initialization due to a cast that isn't a C-style
502 /// or functional cast.
503 static InitializationKind CreateCast(SourceRange TypeRange) {
504 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
505 TypeRange.getBegin(), TypeRange.getEnd());
508 /// \brief Create a direct initialization for a C-style cast.
509 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
510 SourceRange TypeRange,
512 // C++ cast syntax doesn't permit init lists, but C compound literals are
514 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
515 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
519 /// \brief Create a direct initialization for a functional cast.
520 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
522 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
523 IC_FunctionalCast, TypeRange.getBegin(),
524 TypeRange.getBegin(), TypeRange.getEnd());
527 /// \brief Create a copy initialization.
528 static InitializationKind CreateCopy(SourceLocation InitLoc,
529 SourceLocation EqualLoc,
530 bool AllowExplicitConvs = false) {
531 return InitializationKind(IK_Copy,
532 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
533 InitLoc, EqualLoc, EqualLoc);
536 /// \brief Create a default initialization.
537 static InitializationKind CreateDefault(SourceLocation InitLoc) {
538 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
541 /// \brief Create a value initialization.
542 static InitializationKind CreateValue(SourceLocation InitLoc,
543 SourceLocation LParenLoc,
544 SourceLocation RParenLoc,
545 bool isImplicit = false) {
546 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
547 InitLoc, LParenLoc, RParenLoc);
550 /// \brief Determine the initialization kind.
551 InitKind getKind() const {
555 /// \brief Determine whether this initialization is an explicit cast.
556 bool isExplicitCast() const {
557 return Context >= IC_StaticCast;
560 /// \brief Determine whether this initialization is a C-style cast.
561 bool isCStyleOrFunctionalCast() const {
562 return Context >= IC_CStyleCast;
565 /// \brief Determine whether this is a C-style cast.
566 bool isCStyleCast() const {
567 return Context == IC_CStyleCast;
570 /// \brief Determine whether this is a functional-style cast.
571 bool isFunctionalCast() const {
572 return Context == IC_FunctionalCast;
575 /// \brief Determine whether this initialization is an implicit
576 /// value-initialization, e.g., as occurs during aggregate
578 bool isImplicitValueInit() const { return Context == IC_Implicit; }
580 /// \brief Retrieve the location at which initialization is occurring.
581 SourceLocation getLocation() const { return Locations[0]; }
583 /// \brief Retrieve the source range that covers the initialization.
584 SourceRange getRange() const {
585 return SourceRange(Locations[0], Locations[2]);
588 /// \brief Retrieve the location of the equal sign for copy initialization
590 SourceLocation getEqualLoc() const {
591 assert(Kind == IK_Copy && "Only copy initialization has an '='");
595 bool isCopyInit() const { return Kind == IK_Copy; }
597 /// \brief Retrieve whether this initialization allows the use of explicit
599 bool AllowExplicit() const { return !isCopyInit(); }
601 /// \brief Retrieve whether this initialization allows the use of explicit
602 /// conversion functions when binding a reference. If the reference is the
603 /// first parameter in a copy or move constructor, such conversions are
604 /// permitted even though we are performing copy-initialization.
605 bool allowExplicitConversionFunctionsInRefBinding() const {
606 return !isCopyInit() || Context == IC_ExplicitConvs;
609 /// \brief Retrieve the source range containing the locations of the open
610 /// and closing parentheses for value and direct initializations.
611 SourceRange getParenRange() const {
612 assert((Kind == IK_Direct || Kind == IK_Value) &&
613 "Only direct- and value-initialization have parentheses");
614 return SourceRange(Locations[1], Locations[2]);
618 /// \brief Describes the sequence of initializations required to initialize
619 /// a given object or reference with a set of arguments.
620 class InitializationSequence {
622 /// \brief Describes the kind of initialization sequence computed.
624 /// \brief A failed initialization sequence. The failure kind tells what
628 /// \brief A dependent initialization, which could not be
629 /// type-checked due to the presence of dependent types or
630 /// dependently-typed expressions.
633 /// \brief A normal sequence.
637 /// \brief Describes the kind of a particular step in an initialization
640 /// \brief Resolve the address of an overloaded function to a specific
641 /// function declaration.
642 SK_ResolveAddressOfOverloadedFunction,
643 /// \brief Perform a derived-to-base cast, producing an rvalue.
644 SK_CastDerivedToBaseRValue,
645 /// \brief Perform a derived-to-base cast, producing an xvalue.
646 SK_CastDerivedToBaseXValue,
647 /// \brief Perform a derived-to-base cast, producing an lvalue.
648 SK_CastDerivedToBaseLValue,
649 /// \brief Reference binding to an lvalue.
651 /// \brief Reference binding to a temporary.
652 SK_BindReferenceToTemporary,
653 /// \brief An optional copy of a temporary object to another
654 /// temporary object, which is permitted (but not required) by
655 /// C++98/03 but not C++0x.
656 SK_ExtraneousCopyToTemporary,
657 /// \brief Perform a user-defined conversion, either via a conversion
658 /// function or via a constructor.
660 /// \brief Perform a qualification conversion, producing an rvalue.
661 SK_QualificationConversionRValue,
662 /// \brief Perform a qualification conversion, producing an xvalue.
663 SK_QualificationConversionXValue,
664 /// \brief Perform a qualification conversion, producing an lvalue.
665 SK_QualificationConversionLValue,
666 /// \brief Perform a conversion adding _Atomic to a type.
668 /// \brief Perform a load from a glvalue, producing an rvalue.
670 /// \brief Perform an implicit conversion sequence.
671 SK_ConversionSequence,
672 /// \brief Perform an implicit conversion sequence without narrowing.
673 SK_ConversionSequenceNoNarrowing,
674 /// \brief Perform list-initialization without a constructor.
675 SK_ListInitialization,
676 /// \brief Unwrap the single-element initializer list for a reference.
678 /// \brief Rewrap the single-element initializer list for a reference.
680 /// \brief Perform initialization via a constructor.
681 SK_ConstructorInitialization,
682 /// \brief Perform initialization via a constructor, taking arguments from
683 /// a single InitListExpr.
684 SK_ConstructorInitializationFromList,
685 /// \brief Zero-initialize the object
686 SK_ZeroInitialization,
687 /// \brief C assignment
689 /// \brief Initialization by string
691 /// \brief An initialization that "converts" an Objective-C object
692 /// (not a point to an object) to another Objective-C object type.
693 SK_ObjCObjectConversion,
694 /// \brief Array initialization (from an array rvalue).
695 /// This is a GNU C extension.
697 /// \brief Array initialization from a parenthesized initializer list.
698 /// This is a GNU C++ extension.
699 SK_ParenthesizedArrayInit,
700 /// \brief Pass an object by indirect copy-and-restore.
701 SK_PassByIndirectCopyRestore,
702 /// \brief Pass an object by indirect restore.
703 SK_PassByIndirectRestore,
704 /// \brief Produce an Objective-C object pointer.
705 SK_ProduceObjCObject,
706 /// \brief Construct a std::initializer_list from an initializer list.
707 SK_StdInitializerList,
708 /// \brief Perform initialization via a constructor taking a single
709 /// std::initializer_list argument.
710 SK_StdInitializerListConstructorCall,
711 /// \brief Initialize an OpenCL sampler from an integer.
713 /// \brief Passing zero to a function where OpenCL event_t is expected.
717 /// \brief A single step in the initialization sequence.
720 /// \brief The kind of conversion or initialization step we are taking.
723 // \brief The type that results from this initialization.
727 bool HadMultipleCandidates;
728 FunctionDecl *Function;
729 DeclAccessPair FoundDecl;
733 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
734 /// SK_UserConversion, the function that the expression should be
735 /// resolved to or the conversion function to call, respectively.
736 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
737 /// the constructor to be called.
739 /// Always a FunctionDecl, plus a Boolean flag telling if it was
740 /// selected from an overloaded set having size greater than 1.
741 /// For conversion decls, the naming class is the source type.
742 /// For construct decls, the naming class is the target type.
745 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
747 ImplicitConversionSequence *ICS;
749 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
751 InitListExpr *WrappingSyntacticList;
758 /// \brief The kind of initialization sequence computed.
759 enum SequenceKind SequenceKind;
761 /// \brief Steps taken by this initialization.
762 SmallVector<Step, 4> Steps;
765 /// \brief Describes why initialization failed.
767 /// \brief Too many initializers provided for a reference.
768 FK_TooManyInitsForReference,
769 /// \brief Array must be initialized with an initializer list.
770 FK_ArrayNeedsInitList,
771 /// \brief Array must be initialized with an initializer list or a
773 FK_ArrayNeedsInitListOrStringLiteral,
774 /// \brief Array must be initialized with an initializer list or a
775 /// wide string literal.
776 FK_ArrayNeedsInitListOrWideStringLiteral,
777 /// \brief Initializing a wide char array with narrow string literal.
778 FK_NarrowStringIntoWideCharArray,
779 /// \brief Initializing char array with wide string literal.
780 FK_WideStringIntoCharArray,
781 /// \brief Initializing wide char array with incompatible wide string
783 FK_IncompatWideStringIntoWideChar,
784 /// \brief Array type mismatch.
785 FK_ArrayTypeMismatch,
786 /// \brief Non-constant array initializer
787 FK_NonConstantArrayInit,
788 /// \brief Cannot resolve the address of an overloaded function.
789 FK_AddressOfOverloadFailed,
790 /// \brief Overloading due to reference initialization failed.
791 FK_ReferenceInitOverloadFailed,
792 /// \brief Non-const lvalue reference binding to a temporary.
793 FK_NonConstLValueReferenceBindingToTemporary,
794 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
796 FK_NonConstLValueReferenceBindingToUnrelated,
797 /// \brief Rvalue reference binding to an lvalue.
798 FK_RValueReferenceBindingToLValue,
799 /// \brief Reference binding drops qualifiers.
800 FK_ReferenceInitDropsQualifiers,
801 /// \brief Reference binding failed.
802 FK_ReferenceInitFailed,
803 /// \brief Implicit conversion failed.
805 /// \brief Implicit conversion failed.
806 FK_ConversionFromPropertyFailed,
807 /// \brief Too many initializers for scalar
808 FK_TooManyInitsForScalar,
809 /// \brief Reference initialization from an initializer list
810 FK_ReferenceBindingToInitList,
811 /// \brief Initialization of some unused destination type with an
812 /// initializer list.
813 FK_InitListBadDestinationType,
814 /// \brief Overloading for a user-defined conversion failed.
815 FK_UserConversionOverloadFailed,
816 /// \brief Overloading for initialization by constructor failed.
817 FK_ConstructorOverloadFailed,
818 /// \brief Overloading for list-initialization by constructor failed.
819 FK_ListConstructorOverloadFailed,
820 /// \brief Default-initialization of a 'const' object.
821 FK_DefaultInitOfConst,
822 /// \brief Initialization of an incomplete type.
824 /// \brief Variable-length array must not have an initializer.
825 FK_VariableLengthArrayHasInitializer,
826 /// \brief List initialization failed at some point.
827 FK_ListInitializationFailed,
828 /// \brief Initializer has a placeholder type which cannot be
829 /// resolved by initialization.
831 /// \brief Trying to take the address of a function that doesn't support
832 /// having its address taken.
833 FK_AddressOfUnaddressableFunction,
834 /// \brief List-copy-initialization chose an explicit constructor.
835 FK_ExplicitConstructor
839 /// \brief The reason why initialization failed.
842 /// \brief The failed result of overload resolution.
843 OverloadingResult FailedOverloadResult;
845 /// \brief The candidate set created when initialization failed.
846 OverloadCandidateSet FailedCandidateSet;
848 /// \brief The incomplete type that caused a failure.
849 QualType FailedIncompleteType;
851 /// \brief The fixit that needs to be applied to make this initialization
853 std::string ZeroInitializationFixit;
854 SourceLocation ZeroInitializationFixitLoc;
857 /// \brief Call for initializations are invalid but that would be valid
858 /// zero initialzations if Fixit was applied.
859 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
860 ZeroInitializationFixit = Fixit;
861 ZeroInitializationFixitLoc = L;
866 /// \brief Prints a follow-up note that highlights the location of
867 /// the initialized entity, if it's remote.
868 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
871 /// \brief Try to perform initialization of the given entity, creating a
872 /// record of the steps required to perform the initialization.
874 /// The generated initialization sequence will either contain enough
875 /// information to diagnose
877 /// \param S the semantic analysis object.
879 /// \param Entity the entity being initialized.
881 /// \param Kind the kind of initialization being performed.
883 /// \param Args the argument(s) provided for initialization.
885 /// \param TopLevelOfInitList true if we are initializing from an expression
886 /// at the top level inside an initializer list. This disallows
887 /// narrowing conversions in C++11 onwards.
888 InitializationSequence(Sema &S,
889 const InitializedEntity &Entity,
890 const InitializationKind &Kind,
892 bool TopLevelOfInitList = false);
893 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
894 const InitializationKind &Kind, MultiExprArg Args,
895 bool TopLevelOfInitList);
897 ~InitializationSequence();
899 /// \brief Perform the actual initialization of the given entity based on
900 /// the computed initialization sequence.
902 /// \param S the semantic analysis object.
904 /// \param Entity the entity being initialized.
906 /// \param Kind the kind of initialization being performed.
908 /// \param Args the argument(s) provided for initialization, ownership of
909 /// which is transferred into the routine.
911 /// \param ResultType if non-NULL, will be set to the type of the
912 /// initialized object, which is the type of the declaration in most
913 /// cases. However, when the initialized object is a variable of
914 /// incomplete array type and the initializer is an initializer
915 /// list, this type will be set to the completed array type.
917 /// \returns an expression that performs the actual object initialization, if
918 /// the initialization is well-formed. Otherwise, emits diagnostics
919 /// and returns an invalid expression.
920 ExprResult Perform(Sema &S,
921 const InitializedEntity &Entity,
922 const InitializationKind &Kind,
924 QualType *ResultType = nullptr);
926 /// \brief Diagnose an potentially-invalid initialization sequence.
928 /// \returns true if the initialization sequence was ill-formed,
930 bool Diagnose(Sema &S,
931 const InitializedEntity &Entity,
932 const InitializationKind &Kind,
933 ArrayRef<Expr *> Args);
935 /// \brief Determine the kind of initialization sequence computed.
936 enum SequenceKind getKind() const { return SequenceKind; }
938 /// \brief Set the kind of sequence computed.
939 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
941 /// \brief Determine whether the initialization sequence is valid.
942 explicit operator bool() const { return !Failed(); }
944 /// \brief Determine whether the initialization sequence is invalid.
945 bool Failed() const { return SequenceKind == FailedSequence; }
947 typedef SmallVectorImpl<Step>::const_iterator step_iterator;
948 step_iterator step_begin() const { return Steps.begin(); }
949 step_iterator step_end() const { return Steps.end(); }
951 /// \brief Determine whether this initialization is a direct reference
952 /// binding (C++ [dcl.init.ref]).
953 bool isDirectReferenceBinding() const;
955 /// \brief Determine whether this initialization failed due to an ambiguity.
956 bool isAmbiguous() const;
958 /// \brief Determine whether this initialization is direct call to a
960 bool isConstructorInitialization() const;
962 /// \brief Returns whether the last step in this initialization sequence is a
963 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
965 /// If this function returns true, *isInitializerConstant will be set to
966 /// describe whether *Initializer was a constant expression. If
967 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
968 /// evaluated value of *Initializer.
969 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
970 bool *isInitializerConstant,
971 APValue *ConstantValue) const;
973 /// \brief Add a new step in the initialization that resolves the address
974 /// of an overloaded function to a specific function declaration.
976 /// \param Function the function to which the overloaded function reference
978 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
979 DeclAccessPair Found,
980 bool HadMultipleCandidates);
982 /// \brief Add a new step in the initialization that performs a derived-to-
985 /// \param BaseType the base type to which we will be casting.
987 /// \param Category Indicates whether the result will be treated as an
988 /// rvalue, an xvalue, or an lvalue.
989 void AddDerivedToBaseCastStep(QualType BaseType,
990 ExprValueKind Category);
992 /// \brief Add a new step binding a reference to an object.
994 /// \param BindingTemporary True if we are binding a reference to a temporary
995 /// object (thereby extending its lifetime); false if we are binding to an
996 /// lvalue or an lvalue treated as an rvalue.
997 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
999 /// \brief Add a new step that makes an extraneous copy of the input
1000 /// to a temporary of the same class type.
1002 /// This extraneous copy only occurs during reference binding in
1003 /// C++98/03, where we are permitted (but not required) to introduce
1004 /// an extra copy. At a bare minimum, we must check that we could
1005 /// call the copy constructor, and produce a diagnostic if the copy
1006 /// constructor is inaccessible or no copy constructor matches.
1008 /// \param T The type of the temporary being created.
1009 void AddExtraneousCopyToTemporary(QualType T);
1011 /// \brief Add a new step invoking a conversion function, which is either
1012 /// a constructor or a conversion function.
1013 void AddUserConversionStep(FunctionDecl *Function,
1014 DeclAccessPair FoundDecl,
1016 bool HadMultipleCandidates);
1018 /// \brief Add a new step that performs a qualification conversion to the
1020 void AddQualificationConversionStep(QualType Ty,
1021 ExprValueKind Category);
1023 /// \brief Add a new step that performs conversion from non-atomic to atomic
1025 void AddAtomicConversionStep(QualType Ty);
1027 /// \brief Add a new step that performs a load of the given type.
1029 /// Although the term "LValueToRValue" is conventional, this applies to both
1030 /// lvalues and xvalues.
1031 void AddLValueToRValueStep(QualType Ty);
1033 /// \brief Add a new step that applies an implicit conversion sequence.
1034 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1035 QualType T, bool TopLevelOfInitList = false);
1037 /// \brief Add a list-initialization step.
1038 void AddListInitializationStep(QualType T);
1040 /// \brief Add a constructor-initialization step.
1042 /// \param FromInitList The constructor call is syntactically an initializer
1044 /// \param AsInitList The constructor is called as an init list constructor.
1045 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
1046 AccessSpecifier Access,
1048 bool HadMultipleCandidates,
1049 bool FromInitList, bool AsInitList);
1051 /// \brief Add a zero-initialization step.
1052 void AddZeroInitializationStep(QualType T);
1054 /// \brief Add a C assignment step.
1056 // FIXME: It isn't clear whether this should ever be needed;
1057 // ideally, we would handle everything needed in C in the common
1058 // path. However, that isn't the case yet.
1059 void AddCAssignmentStep(QualType T);
1061 /// \brief Add a string init step.
1062 void AddStringInitStep(QualType T);
1064 /// \brief Add an Objective-C object conversion step, which is
1066 void AddObjCObjectConversionStep(QualType T);
1068 /// \brief Add an array initialization step.
1069 void AddArrayInitStep(QualType T);
1071 /// \brief Add a parenthesized array initialization step.
1072 void AddParenthesizedArrayInitStep(QualType T);
1074 /// \brief Add a step to pass an object by indirect copy-restore.
1075 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1077 /// \brief Add a step to "produce" an Objective-C object (by
1079 void AddProduceObjCObjectStep(QualType T);
1081 /// \brief Add a step to construct a std::initializer_list object from an
1082 /// initializer list.
1083 void AddStdInitializerListConstructionStep(QualType T);
1085 /// \brief Add a step to initialize an OpenCL sampler from an integer
1087 void AddOCLSamplerInitStep(QualType T);
1089 /// \brief Add a step to initialize an OpenCL event_t from a NULL
1091 void AddOCLZeroEventStep(QualType T);
1093 /// \brief Add steps to unwrap a initializer list for a reference around a
1094 /// single element and rewrap it at the end.
1095 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1097 /// \brief Note that this initialization sequence failed.
1098 void SetFailed(FailureKind Failure) {
1099 SequenceKind = FailedSequence;
1100 this->Failure = Failure;
1101 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1102 "Incomplete type failure requires a type!");
1105 /// \brief Note that this initialization sequence failed due to failed
1106 /// overload resolution.
1107 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1109 /// \brief Retrieve a reference to the candidate set when overload
1110 /// resolution fails.
1111 OverloadCandidateSet &getFailedCandidateSet() {
1112 return FailedCandidateSet;
1115 /// \brief Get the overloading result, for when the initialization
1116 /// sequence failed due to a bad overload.
1117 OverloadingResult getFailedOverloadResult() const {
1118 return FailedOverloadResult;
1121 /// \brief Note that this initialization sequence failed due to an
1122 /// incomplete type.
1123 void setIncompleteTypeFailure(QualType IncompleteType) {
1124 FailedIncompleteType = IncompleteType;
1125 SetFailed(FK_Incomplete);
1128 /// \brief Determine why initialization failed.
1129 FailureKind getFailureKind() const {
1130 assert(Failed() && "Not an initialization failure!");
1134 /// \brief Dump a representation of this initialization sequence to
1135 /// the given stream, for debugging purposes.
1136 void dump(raw_ostream &OS) const;
1138 /// \brief Dump a representation of this initialization sequence to
1139 /// standard error, for debugging purposes.
1143 } // end namespace clang
1145 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H