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/SmallVector.h"
28 class CXXBaseSpecifier;
39 /// \brief Describes an entity that is being initialized.
40 class InitializedEntity {
42 /// \brief Specifies the kind of entity being initialized.
44 /// \brief The entity being initialized is a variable.
46 /// \brief The entity being initialized is a function parameter.
48 /// \brief The entity being initialized is the result of a function call.
50 /// \brief The entity being initialized is an exception object that
53 /// \brief The entity being initialized is a non-static data member
56 /// \brief The entity being initialized is an element of an array.
58 /// \brief The entity being initialized is an object (or array of
59 /// objects) allocated via new.
61 /// \brief The entity being initialized is a temporary object.
63 /// \brief The entity being initialized is a base member subobject.
65 /// \brief The initialization is being done by a delegating constructor.
67 /// \brief The entity being initialized is an element of a vector.
70 /// \brief The entity being initialized is a field of block descriptor for
71 /// the copied-in c++ object.
73 /// The entity being initialized is a field of block descriptor for the
74 /// copied-in lambda object that's used in the lambda to block conversion.
75 EK_LambdaToBlockConversionBlockElement,
76 /// \brief The entity being initialized is the real or imaginary part of a
79 /// \brief The entity being initialized is the field that captures a
80 /// variable in a lambda.
82 /// \brief The entity being initialized is the initializer for a compound
84 EK_CompoundLiteralInit,
85 /// \brief The entity being implicitly initialized back to the formal
88 /// \brief The entity being initialized is a function parameter; function
89 /// is member of group of audited CF APIs.
90 EK_Parameter_CF_Audited,
91 /// \brief The entity being initialized is a structured binding of a
92 /// decomposition declaration.
95 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
96 // enum as an index for its first %select. When modifying this list,
97 // that diagnostic text needs to be updated as well.
101 /// \brief The kind of entity being initialized.
104 /// \brief If non-NULL, the parent entity in which this
105 /// initialization occurs.
106 const InitializedEntity *Parent;
108 /// \brief The type of the object or reference being initialized.
111 /// \brief The mangling number for the next reference temporary to be created.
112 mutable unsigned ManglingNumber;
115 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
116 /// location of the 'return', 'throw', or 'new' keyword,
117 /// respectively. When Kind == EK_Temporary, the location where
118 /// the temporary is being created.
121 /// \brief Whether the entity being initialized may end up using the
122 /// named return value optimization (NRVO).
127 /// \brief The VarDecl, FieldDecl, or BindingDecl being initialized.
128 ValueDecl *VariableOrMember;
130 /// \brief When Kind == EK_Member, whether this is an implicit member
131 /// initialization in a copy or move constructor. These can perform array
133 bool IsImplicitFieldInit;
137 /// \brief The name of the variable being captured by an EK_LambdaCapture.
138 IdentifierInfo *VarID;
140 /// \brief The source location at which the capture occurs.
145 /// \brief When Kind == EK_Variable, EK_Member or EK_Binding, the variable.
148 /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where
149 /// result type was implicitly changed to accommodate ARC semantics.
150 ObjCMethodDecl *MethodDecl;
152 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
153 /// low bit indicating whether the parameter is "consumed".
156 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
157 /// source information for the temporary.
158 TypeSourceInfo *TypeInfo;
160 struct LN LocAndNRVO;
162 /// \brief When Kind == EK_Base, the base specifier that provides the
163 /// base class. The lower bit specifies whether the base is an inherited
167 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
168 /// EK_ComplexElement, the index of the array or vector element being
175 InitializedEntity() : ManglingNumber(0) {}
177 /// \brief Create the initialization entity for a variable.
178 InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
179 : Kind(EK), Parent(nullptr), Type(Var->getType()),
180 ManglingNumber(0), Variable{Var, false} { }
182 /// \brief Create the initialization entity for the result of a
183 /// function, throwing an object, performing an explicit cast, or
184 /// initializing a parameter for which there is no declaration.
185 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
187 : Kind(Kind), Parent(nullptr), Type(Type), ManglingNumber(0)
189 LocAndNRVO.Location = Loc.getRawEncoding();
190 LocAndNRVO.NRVO = NRVO;
193 /// \brief Create the initialization entity for a member subobject.
194 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
196 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
197 ManglingNumber(0), Variable{Member, Implicit} {
200 /// \brief Create the initialization entity for an array element.
201 InitializedEntity(ASTContext &Context, unsigned Index,
202 const InitializedEntity &Parent);
204 /// \brief Create the initialization entity for a lambda capture.
205 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
206 : Kind(EK_LambdaCapture), Parent(nullptr), Type(FieldType),
209 Capture.VarID = VarID;
210 Capture.Location = Loc.getRawEncoding();
214 /// \brief Create the initialization entity for a variable.
215 static InitializedEntity InitializeVariable(VarDecl *Var) {
216 return InitializedEntity(Var);
219 /// \brief Create the initialization entity for a parameter.
220 static InitializedEntity InitializeParameter(ASTContext &Context,
221 const ParmVarDecl *Parm) {
222 return InitializeParameter(Context, Parm, Parm->getType());
225 /// \brief Create the initialization entity for a parameter, but use
227 static InitializedEntity InitializeParameter(ASTContext &Context,
228 const ParmVarDecl *Parm,
230 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
231 Parm->hasAttr<NSConsumedAttr>());
233 InitializedEntity Entity;
234 Entity.Kind = EK_Parameter;
236 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
237 Entity.Parent = nullptr;
239 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
243 /// \brief Create the initialization entity for a parameter that is
244 /// only known by its type.
245 static InitializedEntity InitializeParameter(ASTContext &Context,
248 InitializedEntity Entity;
249 Entity.Kind = EK_Parameter;
250 Entity.Type = Context.getVariableArrayDecayedType(Type);
251 Entity.Parent = nullptr;
252 Entity.Parameter = (Consumed);
256 /// \brief Create the initialization entity for the result of a function.
257 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
258 QualType Type, bool NRVO) {
259 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
262 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
263 QualType Type, bool NRVO) {
264 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
267 static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
268 QualType Type, bool NRVO) {
269 return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
270 BlockVarLoc, Type, NRVO);
273 /// \brief Create the initialization entity for an exception object.
274 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
275 QualType Type, bool NRVO) {
276 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
279 /// \brief Create the initialization entity for an object allocated via new.
280 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
281 return InitializedEntity(EK_New, NewLoc, Type);
284 /// \brief Create the initialization entity for a temporary.
285 static InitializedEntity InitializeTemporary(QualType Type) {
286 return InitializeTemporary(nullptr, Type);
289 /// \brief Create the initialization entity for a temporary.
290 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
291 return InitializeTemporary(TypeInfo, TypeInfo->getType());
294 /// \brief Create the initialization entity for a temporary.
295 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo,
297 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
298 Result.TypeInfo = TypeInfo;
302 /// \brief Create the initialization entity for a related result.
303 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
305 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
306 Result.MethodDecl = MD;
311 /// \brief Create the initialization entity for a base class subobject.
312 static InitializedEntity
313 InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base,
314 bool IsInheritedVirtualBase,
315 const InitializedEntity *Parent = nullptr);
317 /// \brief Create the initialization entity for a delegated constructor.
318 static InitializedEntity InitializeDelegation(QualType Type) {
319 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
322 /// \brief Create the initialization entity for a member subobject.
323 static InitializedEntity
324 InitializeMember(FieldDecl *Member,
325 const InitializedEntity *Parent = nullptr,
326 bool Implicit = false) {
327 return InitializedEntity(Member, Parent, Implicit);
330 /// \brief Create the initialization entity for a member subobject.
331 static InitializedEntity
332 InitializeMember(IndirectFieldDecl *Member,
333 const InitializedEntity *Parent = nullptr,
334 bool Implicit = false) {
335 return InitializedEntity(Member->getAnonField(), Parent, Implicit);
338 /// \brief Create the initialization entity for an array element.
339 static InitializedEntity InitializeElement(ASTContext &Context,
341 const InitializedEntity &Parent) {
342 return InitializedEntity(Context, Index, Parent);
345 /// \brief Create the initialization entity for a structured binding.
346 static InitializedEntity InitializeBinding(VarDecl *Binding) {
347 return InitializedEntity(Binding, EK_Binding);
350 /// \brief Create the initialization entity for a lambda capture.
351 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
353 SourceLocation Loc) {
354 return InitializedEntity(VarID, FieldType, Loc);
357 /// \brief Create the entity for a compound literal initializer.
358 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
359 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
361 Result.TypeInfo = TSI;
366 /// \brief Determine the kind of initialization.
367 EntityKind getKind() const { return Kind; }
369 /// \brief Retrieve the parent of the entity being initialized, when
370 /// the initialization itself is occurring within the context of a
371 /// larger initialization.
372 const InitializedEntity *getParent() const { return Parent; }
374 /// \brief Retrieve type being initialized.
375 QualType getType() const { return Type; }
377 /// \brief Retrieve complete type-source information for the object being
378 /// constructed, if known.
379 TypeSourceInfo *getTypeSourceInfo() const {
380 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
386 /// \brief Retrieve the name of the entity being initialized.
387 DeclarationName getName() const;
389 /// \brief Retrieve the variable, parameter, or field being
391 ValueDecl *getDecl() const;
393 /// \brief Retrieve the ObjectiveC method being initialized.
394 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
396 /// \brief Determine whether this initialization allows the named return
397 /// value optimization, which also applies to thrown objects.
398 bool allowsNRVO() const;
400 bool isParameterKind() const {
401 return (getKind() == EK_Parameter ||
402 getKind() == EK_Parameter_CF_Audited);
404 /// \brief Determine whether this initialization consumes the
406 bool isParameterConsumed() const {
407 assert(isParameterKind() && "Not a parameter");
408 return (Parameter & 1);
411 /// \brief Retrieve the base specifier.
412 const CXXBaseSpecifier *getBaseSpecifier() const {
413 assert(getKind() == EK_Base && "Not a base specifier");
414 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
417 /// \brief Return whether the base is an inherited virtual base.
418 bool isInheritedVirtualBase() const {
419 assert(getKind() == EK_Base && "Not a base specifier");
423 /// \brief Determine whether this is an array new with an unknown bound.
424 bool isVariableLengthArrayNew() const {
425 return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>(
426 getType()->getAsArrayTypeUnsafe());
429 /// \brief Is this the implicit initialization of a member of a class from
430 /// a defaulted constructor?
431 bool isImplicitMemberInitializer() const {
432 return getKind() == EK_Member && Variable.IsImplicitFieldInit;
435 /// \brief Determine the location of the 'return' keyword when initializing
436 /// the result of a function call.
437 SourceLocation getReturnLoc() const {
438 assert(getKind() == EK_Result && "No 'return' location!");
439 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
442 /// \brief Determine the location of the 'throw' keyword when initializing
443 /// an exception object.
444 SourceLocation getThrowLoc() const {
445 assert(getKind() == EK_Exception && "No 'throw' location!");
446 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
449 /// \brief If this is an array, vector, or complex number element, get the
451 unsigned getElementIndex() const {
452 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
453 getKind() == EK_ComplexElement);
456 /// \brief If this is already the initializer for an array or vector
457 /// element, sets the element index.
458 void setElementIndex(unsigned Index) {
459 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
460 getKind() == EK_ComplexElement);
463 /// \brief For a lambda capture, return the capture's name.
464 StringRef getCapturedVarName() const {
465 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
466 return Capture.VarID->getName();
468 /// \brief Determine the location of the capture when initializing
469 /// field from a captured variable in a lambda.
470 SourceLocation getCaptureLoc() const {
471 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
472 return SourceLocation::getFromRawEncoding(Capture.Location);
475 void setParameterCFAudited() {
476 Kind = EK_Parameter_CF_Audited;
479 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
481 /// Dump a representation of the initialized entity to standard error,
482 /// for debugging purposes.
486 unsigned dumpImpl(raw_ostream &OS) const;
489 /// \brief Describes the kind of initialization being performed, along with
490 /// location information for tokens related to the initialization (equal sign,
492 class InitializationKind {
494 /// \brief The kind of initialization being performed.
496 IK_Direct, ///< Direct initialization
497 IK_DirectList, ///< Direct list-initialization
498 IK_Copy, ///< Copy initialization
499 IK_Default, ///< Default initialization
500 IK_Value ///< Value initialization
504 /// \brief The context of the initialization.
506 IC_Normal, ///< Normal context
507 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
508 IC_Implicit, ///< Implicit context (value initialization)
509 IC_StaticCast, ///< Static cast context
510 IC_CStyleCast, ///< C-style cast context
511 IC_FunctionalCast ///< Functional cast context
514 /// \brief The kind of initialization being performed.
517 /// \brief The context of the initialization.
518 InitContext Context : 8;
520 /// \brief The source locations involved in the initialization.
521 SourceLocation Locations[3];
523 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
524 SourceLocation Loc2, SourceLocation Loc3)
525 : Kind(Kind), Context(Context)
533 /// \brief Create a direct initialization.
534 static InitializationKind CreateDirect(SourceLocation InitLoc,
535 SourceLocation LParenLoc,
536 SourceLocation RParenLoc) {
537 return InitializationKind(IK_Direct, IC_Normal,
538 InitLoc, LParenLoc, RParenLoc);
541 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
542 return InitializationKind(IK_DirectList, IC_Normal,
543 InitLoc, InitLoc, InitLoc);
546 /// \brief Create a direct initialization due to a cast that isn't a C-style
547 /// or functional cast.
548 static InitializationKind CreateCast(SourceRange TypeRange) {
549 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
550 TypeRange.getBegin(), TypeRange.getEnd());
553 /// \brief Create a direct initialization for a C-style cast.
554 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
555 SourceRange TypeRange,
557 // C++ cast syntax doesn't permit init lists, but C compound literals are
559 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
560 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
564 /// \brief Create a direct initialization for a functional cast.
565 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
567 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
568 IC_FunctionalCast, TypeRange.getBegin(),
569 TypeRange.getBegin(), TypeRange.getEnd());
572 /// \brief Create a copy initialization.
573 static InitializationKind CreateCopy(SourceLocation InitLoc,
574 SourceLocation EqualLoc,
575 bool AllowExplicitConvs = false) {
576 return InitializationKind(IK_Copy,
577 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
578 InitLoc, EqualLoc, EqualLoc);
581 /// \brief Create a default initialization.
582 static InitializationKind CreateDefault(SourceLocation InitLoc) {
583 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
586 /// \brief Create a value initialization.
587 static InitializationKind CreateValue(SourceLocation InitLoc,
588 SourceLocation LParenLoc,
589 SourceLocation RParenLoc,
590 bool isImplicit = false) {
591 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
592 InitLoc, LParenLoc, RParenLoc);
595 /// \brief Create an initialization from an initializer (which, for direct
596 /// initialization from a parenthesized list, will be a ParenListExpr).
597 static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit,
599 if (!Init) return CreateDefault(Loc);
600 if (!DirectInit) return CreateCopy(Loc, Init->getLocStart());
601 if (isa<InitListExpr>(Init)) return CreateDirectList(Loc);
602 return CreateDirect(Loc, Init->getLocStart(), Init->getLocEnd());
605 /// \brief Determine the initialization kind.
606 InitKind getKind() const {
610 /// \brief Determine whether this initialization is an explicit cast.
611 bool isExplicitCast() const {
612 return Context >= IC_StaticCast;
615 /// \brief Determine whether this initialization is a C-style cast.
616 bool isCStyleOrFunctionalCast() const {
617 return Context >= IC_CStyleCast;
620 /// \brief Determine whether this is a C-style cast.
621 bool isCStyleCast() const {
622 return Context == IC_CStyleCast;
625 /// \brief Determine whether this is a functional-style cast.
626 bool isFunctionalCast() const {
627 return Context == IC_FunctionalCast;
630 /// \brief Determine whether this initialization is an implicit
631 /// value-initialization, e.g., as occurs during aggregate
633 bool isImplicitValueInit() const { return Context == IC_Implicit; }
635 /// \brief Retrieve the location at which initialization is occurring.
636 SourceLocation getLocation() const { return Locations[0]; }
638 /// \brief Retrieve the source range that covers the initialization.
639 SourceRange getRange() const {
640 return SourceRange(Locations[0], Locations[2]);
643 /// \brief Retrieve the location of the equal sign for copy initialization
645 SourceLocation getEqualLoc() const {
646 assert(Kind == IK_Copy && "Only copy initialization has an '='");
650 bool isCopyInit() const { return Kind == IK_Copy; }
652 /// \brief Retrieve whether this initialization allows the use of explicit
654 bool AllowExplicit() const { return !isCopyInit(); }
656 /// \brief Retrieve whether this initialization allows the use of explicit
657 /// conversion functions when binding a reference. If the reference is the
658 /// first parameter in a copy or move constructor, such conversions are
659 /// permitted even though we are performing copy-initialization.
660 bool allowExplicitConversionFunctionsInRefBinding() const {
661 return !isCopyInit() || Context == IC_ExplicitConvs;
664 /// \brief Retrieve the source range containing the locations of the open
665 /// and closing parentheses for value and direct initializations.
666 SourceRange getParenRange() const {
667 assert((Kind == IK_Direct || Kind == IK_Value) &&
668 "Only direct- and value-initialization have parentheses");
669 return SourceRange(Locations[1], Locations[2]);
673 /// \brief Describes the sequence of initializations required to initialize
674 /// a given object or reference with a set of arguments.
675 class InitializationSequence {
677 /// \brief Describes the kind of initialization sequence computed.
679 /// \brief A failed initialization sequence. The failure kind tells what
683 /// \brief A dependent initialization, which could not be
684 /// type-checked due to the presence of dependent types or
685 /// dependently-typed expressions.
688 /// \brief A normal sequence.
692 /// \brief Describes the kind of a particular step in an initialization
695 /// \brief Resolve the address of an overloaded function to a specific
696 /// function declaration.
697 SK_ResolveAddressOfOverloadedFunction,
698 /// \brief Perform a derived-to-base cast, producing an rvalue.
699 SK_CastDerivedToBaseRValue,
700 /// \brief Perform a derived-to-base cast, producing an xvalue.
701 SK_CastDerivedToBaseXValue,
702 /// \brief Perform a derived-to-base cast, producing an lvalue.
703 SK_CastDerivedToBaseLValue,
704 /// \brief Reference binding to an lvalue.
706 /// \brief Reference binding to a temporary.
707 SK_BindReferenceToTemporary,
708 /// \brief An optional copy of a temporary object to another
709 /// temporary object, which is permitted (but not required) by
710 /// C++98/03 but not C++0x.
711 SK_ExtraneousCopyToTemporary,
712 /// \brief Direct-initialization from a reference-related object in the
713 /// final stage of class copy-initialization.
715 /// \brief Perform a user-defined conversion, either via a conversion
716 /// function or via a constructor.
718 /// \brief Perform a qualification conversion, producing an rvalue.
719 SK_QualificationConversionRValue,
720 /// \brief Perform a qualification conversion, producing an xvalue.
721 SK_QualificationConversionXValue,
722 /// \brief Perform a qualification conversion, producing an lvalue.
723 SK_QualificationConversionLValue,
724 /// \brief Perform a conversion adding _Atomic to a type.
726 /// \brief Perform a load from a glvalue, producing an rvalue.
728 /// \brief Perform an implicit conversion sequence.
729 SK_ConversionSequence,
730 /// \brief Perform an implicit conversion sequence without narrowing.
731 SK_ConversionSequenceNoNarrowing,
732 /// \brief Perform list-initialization without a constructor.
733 SK_ListInitialization,
734 /// \brief Unwrap the single-element initializer list for a reference.
736 /// \brief Rewrap the single-element initializer list for a reference.
738 /// \brief Perform initialization via a constructor.
739 SK_ConstructorInitialization,
740 /// \brief Perform initialization via a constructor, taking arguments from
741 /// a single InitListExpr.
742 SK_ConstructorInitializationFromList,
743 /// \brief Zero-initialize the object
744 SK_ZeroInitialization,
745 /// \brief C assignment
747 /// \brief Initialization by string
749 /// \brief An initialization that "converts" an Objective-C object
750 /// (not a point to an object) to another Objective-C object type.
751 SK_ObjCObjectConversion,
752 /// \brief Array indexing for initialization by elementwise copy.
754 /// \brief Array initialization by elementwise copy.
756 /// \brief Array initialization (from an array rvalue).
758 /// \brief Array initialization (from an array rvalue) as a GNU extension.
760 /// \brief Array initialization from a parenthesized initializer list.
761 /// This is a GNU C++ extension.
762 SK_ParenthesizedArrayInit,
763 /// \brief Pass an object by indirect copy-and-restore.
764 SK_PassByIndirectCopyRestore,
765 /// \brief Pass an object by indirect restore.
766 SK_PassByIndirectRestore,
767 /// \brief Produce an Objective-C object pointer.
768 SK_ProduceObjCObject,
769 /// \brief Construct a std::initializer_list from an initializer list.
770 SK_StdInitializerList,
771 /// \brief Perform initialization via a constructor taking a single
772 /// std::initializer_list argument.
773 SK_StdInitializerListConstructorCall,
774 /// \brief Initialize an OpenCL sampler from an integer.
776 /// \brief Initialize queue_t from 0.
778 /// \brief Passing zero to a function where OpenCL event_t is expected.
782 /// \brief A single step in the initialization sequence.
785 /// \brief The kind of conversion or initialization step we are taking.
788 // \brief The type that results from this initialization.
792 bool HadMultipleCandidates;
793 FunctionDecl *Function;
794 DeclAccessPair FoundDecl;
798 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
799 /// SK_UserConversion, the function that the expression should be
800 /// resolved to or the conversion function to call, respectively.
801 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
802 /// the constructor to be called.
804 /// Always a FunctionDecl, plus a Boolean flag telling if it was
805 /// selected from an overloaded set having size greater than 1.
806 /// For conversion decls, the naming class is the source type.
807 /// For construct decls, the naming class is the target type.
810 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
812 ImplicitConversionSequence *ICS;
814 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
816 InitListExpr *WrappingSyntacticList;
823 /// \brief The kind of initialization sequence computed.
824 enum SequenceKind SequenceKind;
826 /// \brief Steps taken by this initialization.
827 SmallVector<Step, 4> Steps;
830 /// \brief Describes why initialization failed.
832 /// \brief Too many initializers provided for a reference.
833 FK_TooManyInitsForReference,
834 /// \brief Reference initialized from a parenthesized initializer list.
835 FK_ParenthesizedListInitForReference,
836 /// \brief Array must be initialized with an initializer list.
837 FK_ArrayNeedsInitList,
838 /// \brief Array must be initialized with an initializer list or a
840 FK_ArrayNeedsInitListOrStringLiteral,
841 /// \brief Array must be initialized with an initializer list or a
842 /// wide string literal.
843 FK_ArrayNeedsInitListOrWideStringLiteral,
844 /// \brief Initializing a wide char array with narrow string literal.
845 FK_NarrowStringIntoWideCharArray,
846 /// \brief Initializing char array with wide string literal.
847 FK_WideStringIntoCharArray,
848 /// \brief Initializing wide char array with incompatible wide string
850 FK_IncompatWideStringIntoWideChar,
851 /// \brief Array type mismatch.
852 FK_ArrayTypeMismatch,
853 /// \brief Non-constant array initializer
854 FK_NonConstantArrayInit,
855 /// \brief Cannot resolve the address of an overloaded function.
856 FK_AddressOfOverloadFailed,
857 /// \brief Overloading due to reference initialization failed.
858 FK_ReferenceInitOverloadFailed,
859 /// \brief Non-const lvalue reference binding to a temporary.
860 FK_NonConstLValueReferenceBindingToTemporary,
861 /// \brief Non-const lvalue reference binding to a bit-field.
862 FK_NonConstLValueReferenceBindingToBitfield,
863 /// \brief Non-const lvalue reference binding to a vector element.
864 FK_NonConstLValueReferenceBindingToVectorElement,
865 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
867 FK_NonConstLValueReferenceBindingToUnrelated,
868 /// \brief Rvalue reference binding to an lvalue.
869 FK_RValueReferenceBindingToLValue,
870 /// \brief Reference binding drops qualifiers.
871 FK_ReferenceInitDropsQualifiers,
872 /// \brief Reference binding failed.
873 FK_ReferenceInitFailed,
874 /// \brief Implicit conversion failed.
876 /// \brief Implicit conversion failed.
877 FK_ConversionFromPropertyFailed,
878 /// \brief Too many initializers for scalar
879 FK_TooManyInitsForScalar,
880 /// \brief Scalar initialized from a parenthesized initializer list.
881 FK_ParenthesizedListInitForScalar,
882 /// \brief Reference initialization from an initializer list
883 FK_ReferenceBindingToInitList,
884 /// \brief Initialization of some unused destination type with an
885 /// initializer list.
886 FK_InitListBadDestinationType,
887 /// \brief Overloading for a user-defined conversion failed.
888 FK_UserConversionOverloadFailed,
889 /// \brief Overloading for initialization by constructor failed.
890 FK_ConstructorOverloadFailed,
891 /// \brief Overloading for list-initialization by constructor failed.
892 FK_ListConstructorOverloadFailed,
893 /// \brief Default-initialization of a 'const' object.
894 FK_DefaultInitOfConst,
895 /// \brief Initialization of an incomplete type.
897 /// \brief Variable-length array must not have an initializer.
898 FK_VariableLengthArrayHasInitializer,
899 /// \brief List initialization failed at some point.
900 FK_ListInitializationFailed,
901 /// \brief Initializer has a placeholder type which cannot be
902 /// resolved by initialization.
904 /// \brief Trying to take the address of a function that doesn't support
905 /// having its address taken.
906 FK_AddressOfUnaddressableFunction,
907 /// \brief List-copy-initialization chose an explicit constructor.
908 FK_ExplicitConstructor,
912 /// \brief The reason why initialization failed.
915 /// \brief The failed result of overload resolution.
916 OverloadingResult FailedOverloadResult;
918 /// \brief The candidate set created when initialization failed.
919 OverloadCandidateSet FailedCandidateSet;
921 /// \brief The incomplete type that caused a failure.
922 QualType FailedIncompleteType;
924 /// \brief The fixit that needs to be applied to make this initialization
926 std::string ZeroInitializationFixit;
927 SourceLocation ZeroInitializationFixitLoc;
930 /// \brief Call for initializations are invalid but that would be valid
931 /// zero initialzations if Fixit was applied.
932 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
933 ZeroInitializationFixit = Fixit;
934 ZeroInitializationFixitLoc = L;
939 /// \brief Prints a follow-up note that highlights the location of
940 /// the initialized entity, if it's remote.
941 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
944 /// \brief Try to perform initialization of the given entity, creating a
945 /// record of the steps required to perform the initialization.
947 /// The generated initialization sequence will either contain enough
948 /// information to diagnose
950 /// \param S the semantic analysis object.
952 /// \param Entity the entity being initialized.
954 /// \param Kind the kind of initialization being performed.
956 /// \param Args the argument(s) provided for initialization.
958 /// \param TopLevelOfInitList true if we are initializing from an expression
959 /// at the top level inside an initializer list. This disallows
960 /// narrowing conversions in C++11 onwards.
961 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
963 InitializationSequence(Sema &S,
964 const InitializedEntity &Entity,
965 const InitializationKind &Kind,
967 bool TopLevelOfInitList = false,
968 bool TreatUnavailableAsInvalid = true);
969 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
970 const InitializationKind &Kind, MultiExprArg Args,
971 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
973 ~InitializationSequence();
975 /// \brief Perform the actual initialization of the given entity based on
976 /// the computed initialization sequence.
978 /// \param S the semantic analysis object.
980 /// \param Entity the entity being initialized.
982 /// \param Kind the kind of initialization being performed.
984 /// \param Args the argument(s) provided for initialization, ownership of
985 /// which is transferred into the routine.
987 /// \param ResultType if non-NULL, will be set to the type of the
988 /// initialized object, which is the type of the declaration in most
989 /// cases. However, when the initialized object is a variable of
990 /// incomplete array type and the initializer is an initializer
991 /// list, this type will be set to the completed array type.
993 /// \returns an expression that performs the actual object initialization, if
994 /// the initialization is well-formed. Otherwise, emits diagnostics
995 /// and returns an invalid expression.
996 ExprResult Perform(Sema &S,
997 const InitializedEntity &Entity,
998 const InitializationKind &Kind,
1000 QualType *ResultType = nullptr);
1002 /// \brief Diagnose an potentially-invalid initialization sequence.
1004 /// \returns true if the initialization sequence was ill-formed,
1005 /// false otherwise.
1006 bool Diagnose(Sema &S,
1007 const InitializedEntity &Entity,
1008 const InitializationKind &Kind,
1009 ArrayRef<Expr *> Args);
1011 /// \brief Determine the kind of initialization sequence computed.
1012 enum SequenceKind getKind() const { return SequenceKind; }
1014 /// \brief Set the kind of sequence computed.
1015 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
1017 /// \brief Determine whether the initialization sequence is valid.
1018 explicit operator bool() const { return !Failed(); }
1020 /// \brief Determine whether the initialization sequence is invalid.
1021 bool Failed() const { return SequenceKind == FailedSequence; }
1023 typedef SmallVectorImpl<Step>::const_iterator step_iterator;
1024 step_iterator step_begin() const { return Steps.begin(); }
1025 step_iterator step_end() const { return Steps.end(); }
1027 typedef llvm::iterator_range<step_iterator> step_range;
1028 step_range steps() const { return {step_begin(), step_end()}; }
1030 /// \brief Determine whether this initialization is a direct reference
1031 /// binding (C++ [dcl.init.ref]).
1032 bool isDirectReferenceBinding() const;
1034 /// \brief Determine whether this initialization failed due to an ambiguity.
1035 bool isAmbiguous() const;
1037 /// \brief Determine whether this initialization is direct call to a
1039 bool isConstructorInitialization() const;
1041 /// \brief Returns whether the last step in this initialization sequence is a
1042 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
1044 /// If this function returns true, *isInitializerConstant will be set to
1045 /// describe whether *Initializer was a constant expression. If
1046 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
1047 /// evaluated value of *Initializer.
1048 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
1049 bool *isInitializerConstant,
1050 APValue *ConstantValue) const;
1052 /// \brief Add a new step in the initialization that resolves the address
1053 /// of an overloaded function to a specific function declaration.
1055 /// \param Function the function to which the overloaded function reference
1057 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
1058 DeclAccessPair Found,
1059 bool HadMultipleCandidates);
1061 /// \brief Add a new step in the initialization that performs a derived-to-
1064 /// \param BaseType the base type to which we will be casting.
1066 /// \param Category Indicates whether the result will be treated as an
1067 /// rvalue, an xvalue, or an lvalue.
1068 void AddDerivedToBaseCastStep(QualType BaseType,
1069 ExprValueKind Category);
1071 /// \brief Add a new step binding a reference to an object.
1073 /// \param BindingTemporary True if we are binding a reference to a temporary
1074 /// object (thereby extending its lifetime); false if we are binding to an
1075 /// lvalue or an lvalue treated as an rvalue.
1076 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1078 /// \brief Add a new step that makes an extraneous copy of the input
1079 /// to a temporary of the same class type.
1081 /// This extraneous copy only occurs during reference binding in
1082 /// C++98/03, where we are permitted (but not required) to introduce
1083 /// an extra copy. At a bare minimum, we must check that we could
1084 /// call the copy constructor, and produce a diagnostic if the copy
1085 /// constructor is inaccessible or no copy constructor matches.
1087 /// \param T The type of the temporary being created.
1088 void AddExtraneousCopyToTemporary(QualType T);
1090 /// \brief Add a new step that makes a copy of the input to an object of
1091 /// the given type, as the final step in class copy-initialization.
1092 void AddFinalCopy(QualType T);
1094 /// \brief Add a new step invoking a conversion function, which is either
1095 /// a constructor or a conversion function.
1096 void AddUserConversionStep(FunctionDecl *Function,
1097 DeclAccessPair FoundDecl,
1099 bool HadMultipleCandidates);
1101 /// \brief Add a new step that performs a qualification conversion to the
1103 void AddQualificationConversionStep(QualType Ty,
1104 ExprValueKind Category);
1106 /// \brief Add a new step that performs conversion from non-atomic to atomic
1108 void AddAtomicConversionStep(QualType Ty);
1110 /// \brief Add a new step that performs a load of the given type.
1112 /// Although the term "LValueToRValue" is conventional, this applies to both
1113 /// lvalues and xvalues.
1114 void AddLValueToRValueStep(QualType Ty);
1116 /// \brief Add a new step that applies an implicit conversion sequence.
1117 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1118 QualType T, bool TopLevelOfInitList = false);
1120 /// \brief Add a list-initialization step.
1121 void AddListInitializationStep(QualType T);
1123 /// \brief Add a constructor-initialization step.
1125 /// \param FromInitList The constructor call is syntactically an initializer
1127 /// \param AsInitList The constructor is called as an init list constructor.
1128 void AddConstructorInitializationStep(DeclAccessPair FoundDecl,
1129 CXXConstructorDecl *Constructor,
1131 bool HadMultipleCandidates,
1132 bool FromInitList, bool AsInitList);
1134 /// \brief Add a zero-initialization step.
1135 void AddZeroInitializationStep(QualType T);
1137 /// \brief Add a C assignment step.
1139 // FIXME: It isn't clear whether this should ever be needed;
1140 // ideally, we would handle everything needed in C in the common
1141 // path. However, that isn't the case yet.
1142 void AddCAssignmentStep(QualType T);
1144 /// \brief Add a string init step.
1145 void AddStringInitStep(QualType T);
1147 /// \brief Add an Objective-C object conversion step, which is
1149 void AddObjCObjectConversionStep(QualType T);
1151 /// \brief Add an array initialization loop step.
1152 void AddArrayInitLoopStep(QualType T, QualType EltTy);
1154 /// \brief Add an array initialization step.
1155 void AddArrayInitStep(QualType T, bool IsGNUExtension);
1157 /// \brief Add a parenthesized array initialization step.
1158 void AddParenthesizedArrayInitStep(QualType T);
1160 /// \brief Add a step to pass an object by indirect copy-restore.
1161 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1163 /// \brief Add a step to "produce" an Objective-C object (by
1165 void AddProduceObjCObjectStep(QualType T);
1167 /// \brief Add a step to construct a std::initializer_list object from an
1168 /// initializer list.
1169 void AddStdInitializerListConstructionStep(QualType T);
1171 /// \brief Add a step to initialize an OpenCL sampler from an integer
1173 void AddOCLSamplerInitStep(QualType T);
1175 /// \brief Add a step to initialize an OpenCL event_t from a NULL
1177 void AddOCLZeroEventStep(QualType T);
1179 /// \brief Add a step to initialize an OpenCL queue_t from 0.
1180 void AddOCLZeroQueueStep(QualType T);
1182 /// \brief Add steps to unwrap a initializer list for a reference around a
1183 /// single element and rewrap it at the end.
1184 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1186 /// \brief Note that this initialization sequence failed.
1187 void SetFailed(FailureKind Failure) {
1188 SequenceKind = FailedSequence;
1189 this->Failure = Failure;
1190 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1191 "Incomplete type failure requires a type!");
1194 /// \brief Note that this initialization sequence failed due to failed
1195 /// overload resolution.
1196 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1198 /// \brief Retrieve a reference to the candidate set when overload
1199 /// resolution fails.
1200 OverloadCandidateSet &getFailedCandidateSet() {
1201 return FailedCandidateSet;
1204 /// \brief Get the overloading result, for when the initialization
1205 /// sequence failed due to a bad overload.
1206 OverloadingResult getFailedOverloadResult() const {
1207 return FailedOverloadResult;
1210 /// \brief Note that this initialization sequence failed due to an
1211 /// incomplete type.
1212 void setIncompleteTypeFailure(QualType IncompleteType) {
1213 FailedIncompleteType = IncompleteType;
1214 SetFailed(FK_Incomplete);
1217 /// \brief Determine why initialization failed.
1218 FailureKind getFailureKind() const {
1219 assert(Failed() && "Not an initialization failure!");
1223 /// \brief Dump a representation of this initialization sequence to
1224 /// the given stream, for debugging purposes.
1225 void dump(raw_ostream &OS) const;
1227 /// \brief Dump a representation of this initialization sequence to
1228 /// standard error, for debugging purposes.
1232 } // end namespace clang
1234 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H