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 /// \brief The entity being initialized is the real or imaginary part of a
76 /// \brief The entity being initialized is the field that captures a
77 /// variable in a lambda.
79 /// \brief The entity being initialized is the initializer for a compound
81 EK_CompoundLiteralInit,
82 /// \brief The entity being implicitly initialized back to the formal
85 /// \brief The entity being initialized is a function parameter; function
86 /// is member of group of audited CF APIs.
87 EK_Parameter_CF_Audited,
88 /// \brief The entity being initialized is a structured binding of a
89 /// decomposition declaration.
92 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
93 // enum as an index for its first %select. When modifying this list,
94 // that diagnostic text needs to be updated as well.
98 /// \brief The kind of entity being initialized.
101 /// \brief If non-NULL, the parent entity in which this
102 /// initialization occurs.
103 const InitializedEntity *Parent;
105 /// \brief The type of the object or reference being initialized.
108 /// \brief The mangling number for the next reference temporary to be created.
109 mutable unsigned ManglingNumber;
112 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
113 /// location of the 'return', 'throw', or 'new' keyword,
114 /// respectively. When Kind == EK_Temporary, the location where
115 /// the temporary is being created.
118 /// \brief Whether the entity being initialized may end up using the
119 /// named return value optimization (NRVO).
124 /// \brief The VarDecl, FieldDecl, or BindingDecl being initialized.
125 ValueDecl *VariableOrMember;
127 /// \brief When Kind == EK_Member, whether this is an implicit member
128 /// initialization in a copy or move constructor. These can perform array
130 bool IsImplicitFieldInit;
134 /// \brief The name of the variable being captured by an EK_LambdaCapture.
135 IdentifierInfo *VarID;
137 /// \brief The source location at which the capture occurs.
142 /// \brief When Kind == EK_Variable, EK_Member or EK_Binding, the variable.
145 /// \brief When Kind == EK_RelatedResult, the ObjectiveC method where
146 /// result type was implicitly changed to accommodate ARC semantics.
147 ObjCMethodDecl *MethodDecl;
149 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
150 /// low bit indicating whether the parameter is "consumed".
153 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
154 /// source information for the temporary.
155 TypeSourceInfo *TypeInfo;
157 struct LN LocAndNRVO;
159 /// \brief When Kind == EK_Base, the base specifier that provides the
160 /// base class. The lower bit specifies whether the base is an inherited
164 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
165 /// EK_ComplexElement, the index of the array or vector element being
172 InitializedEntity() : ManglingNumber(0) {}
174 /// \brief Create the initialization entity for a variable.
175 InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
176 : Kind(EK), Parent(nullptr), Type(Var->getType()),
177 ManglingNumber(0), Variable{Var, false} { }
179 /// \brief Create the initialization entity for the result of a
180 /// function, throwing an object, performing an explicit cast, or
181 /// initializing a parameter for which there is no declaration.
182 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
184 : Kind(Kind), Parent(nullptr), Type(Type), ManglingNumber(0)
186 LocAndNRVO.Location = Loc.getRawEncoding();
187 LocAndNRVO.NRVO = NRVO;
190 /// \brief Create the initialization entity for a member subobject.
191 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
193 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
194 ManglingNumber(0), Variable{Member, Implicit} {
197 /// \brief Create the initialization entity for an array element.
198 InitializedEntity(ASTContext &Context, unsigned Index,
199 const InitializedEntity &Parent);
201 /// \brief Create the initialization entity for a lambda capture.
202 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
203 : Kind(EK_LambdaCapture), Parent(nullptr), Type(FieldType),
206 Capture.VarID = VarID;
207 Capture.Location = Loc.getRawEncoding();
211 /// \brief Create the initialization entity for a variable.
212 static InitializedEntity InitializeVariable(VarDecl *Var) {
213 return InitializedEntity(Var);
216 /// \brief Create the initialization entity for a parameter.
217 static InitializedEntity InitializeParameter(ASTContext &Context,
218 const ParmVarDecl *Parm) {
219 return InitializeParameter(Context, Parm, Parm->getType());
222 /// \brief Create the initialization entity for a parameter, but use
224 static InitializedEntity InitializeParameter(ASTContext &Context,
225 const ParmVarDecl *Parm,
227 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
228 Parm->hasAttr<NSConsumedAttr>());
230 InitializedEntity Entity;
231 Entity.Kind = EK_Parameter;
233 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
234 Entity.Parent = nullptr;
236 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
240 /// \brief Create the initialization entity for a parameter that is
241 /// only known by its type.
242 static InitializedEntity InitializeParameter(ASTContext &Context,
245 InitializedEntity Entity;
246 Entity.Kind = EK_Parameter;
247 Entity.Type = Context.getVariableArrayDecayedType(Type);
248 Entity.Parent = nullptr;
249 Entity.Parameter = (Consumed);
253 /// \brief Create the initialization entity for the result of a function.
254 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
255 QualType Type, bool NRVO) {
256 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
259 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
260 QualType Type, bool NRVO) {
261 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
264 /// \brief Create the initialization entity for an exception object.
265 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
266 QualType Type, bool NRVO) {
267 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
270 /// \brief Create the initialization entity for an object allocated via new.
271 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
272 return InitializedEntity(EK_New, NewLoc, Type);
275 /// \brief Create the initialization entity for a temporary.
276 static InitializedEntity InitializeTemporary(QualType Type) {
277 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
278 Result.TypeInfo = nullptr;
282 /// \brief Create the initialization entity for a temporary.
283 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
284 InitializedEntity Result(EK_Temporary, SourceLocation(),
285 TypeInfo->getType());
286 Result.TypeInfo = TypeInfo;
290 /// \brief Create the initialization entity for a related result.
291 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
293 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
294 Result.MethodDecl = MD;
299 /// \brief Create the initialization entity for a base class subobject.
300 static InitializedEntity
301 InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base,
302 bool IsInheritedVirtualBase,
303 const InitializedEntity *Parent = nullptr);
305 /// \brief Create the initialization entity for a delegated constructor.
306 static InitializedEntity InitializeDelegation(QualType Type) {
307 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
310 /// \brief Create the initialization entity for a member subobject.
311 static InitializedEntity
312 InitializeMember(FieldDecl *Member,
313 const InitializedEntity *Parent = nullptr,
314 bool Implicit = false) {
315 return InitializedEntity(Member, Parent, Implicit);
318 /// \brief Create the initialization entity for a member subobject.
319 static InitializedEntity
320 InitializeMember(IndirectFieldDecl *Member,
321 const InitializedEntity *Parent = nullptr,
322 bool Implicit = false) {
323 return InitializedEntity(Member->getAnonField(), Parent, Implicit);
326 /// \brief Create the initialization entity for an array element.
327 static InitializedEntity InitializeElement(ASTContext &Context,
329 const InitializedEntity &Parent) {
330 return InitializedEntity(Context, Index, Parent);
333 /// \brief Create the initialization entity for a structured binding.
334 static InitializedEntity InitializeBinding(VarDecl *Binding) {
335 return InitializedEntity(Binding, EK_Binding);
338 /// \brief Create the initialization entity for a lambda capture.
339 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
341 SourceLocation Loc) {
342 return InitializedEntity(VarID, FieldType, Loc);
345 /// \brief Create the entity for a compound literal initializer.
346 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
347 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
349 Result.TypeInfo = TSI;
354 /// \brief Determine the kind of initialization.
355 EntityKind getKind() const { return Kind; }
357 /// \brief Retrieve the parent of the entity being initialized, when
358 /// the initialization itself is occurring within the context of a
359 /// larger initialization.
360 const InitializedEntity *getParent() const { return Parent; }
362 /// \brief Retrieve type being initialized.
363 QualType getType() const { return Type; }
365 /// \brief Retrieve complete type-source information for the object being
366 /// constructed, if known.
367 TypeSourceInfo *getTypeSourceInfo() const {
368 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
374 /// \brief Retrieve the name of the entity being initialized.
375 DeclarationName getName() const;
377 /// \brief Retrieve the variable, parameter, or field being
379 ValueDecl *getDecl() const;
381 /// \brief Retrieve the ObjectiveC method being initialized.
382 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
384 /// \brief Determine whether this initialization allows the named return
385 /// value optimization, which also applies to thrown objects.
386 bool allowsNRVO() const;
388 bool isParameterKind() const {
389 return (getKind() == EK_Parameter ||
390 getKind() == EK_Parameter_CF_Audited);
392 /// \brief Determine whether this initialization consumes the
394 bool isParameterConsumed() const {
395 assert(isParameterKind() && "Not a parameter");
396 return (Parameter & 1);
399 /// \brief Retrieve the base specifier.
400 const CXXBaseSpecifier *getBaseSpecifier() const {
401 assert(getKind() == EK_Base && "Not a base specifier");
402 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
405 /// \brief Return whether the base is an inherited virtual base.
406 bool isInheritedVirtualBase() const {
407 assert(getKind() == EK_Base && "Not a base specifier");
411 /// \brief Determine whether this is an array new with an unknown bound.
412 bool isVariableLengthArrayNew() const {
413 return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>(
414 getType()->getAsArrayTypeUnsafe());
417 /// \brief Is this the implicit initialization of a member of a class from
418 /// a defaulted constructor?
419 bool isImplicitMemberInitializer() const {
420 return getKind() == EK_Member && Variable.IsImplicitFieldInit;
423 /// \brief Determine the location of the 'return' keyword when initializing
424 /// the result of a function call.
425 SourceLocation getReturnLoc() const {
426 assert(getKind() == EK_Result && "No 'return' location!");
427 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
430 /// \brief Determine the location of the 'throw' keyword when initializing
431 /// an exception object.
432 SourceLocation getThrowLoc() const {
433 assert(getKind() == EK_Exception && "No 'throw' location!");
434 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
437 /// \brief If this is an array, vector, or complex number element, get the
439 unsigned getElementIndex() const {
440 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
441 getKind() == EK_ComplexElement);
444 /// \brief If this is already the initializer for an array or vector
445 /// element, sets the element index.
446 void setElementIndex(unsigned Index) {
447 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
448 getKind() == EK_ComplexElement);
451 /// \brief For a lambda capture, return the capture's name.
452 StringRef getCapturedVarName() const {
453 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
454 return Capture.VarID->getName();
456 /// \brief Determine the location of the capture when initializing
457 /// field from a captured variable in a lambda.
458 SourceLocation getCaptureLoc() const {
459 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
460 return SourceLocation::getFromRawEncoding(Capture.Location);
463 void setParameterCFAudited() {
464 Kind = EK_Parameter_CF_Audited;
467 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
469 /// Dump a representation of the initialized entity to standard error,
470 /// for debugging purposes.
474 unsigned dumpImpl(raw_ostream &OS) const;
477 /// \brief Describes the kind of initialization being performed, along with
478 /// location information for tokens related to the initialization (equal sign,
480 class InitializationKind {
482 /// \brief The kind of initialization being performed.
484 IK_Direct, ///< Direct initialization
485 IK_DirectList, ///< Direct list-initialization
486 IK_Copy, ///< Copy initialization
487 IK_Default, ///< Default initialization
488 IK_Value ///< Value initialization
492 /// \brief The context of the initialization.
494 IC_Normal, ///< Normal context
495 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
496 IC_Implicit, ///< Implicit context (value initialization)
497 IC_StaticCast, ///< Static cast context
498 IC_CStyleCast, ///< C-style cast context
499 IC_FunctionalCast ///< Functional cast context
502 /// \brief The kind of initialization being performed.
505 /// \brief The context of the initialization.
506 InitContext Context : 8;
508 /// \brief The source locations involved in the initialization.
509 SourceLocation Locations[3];
511 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
512 SourceLocation Loc2, SourceLocation Loc3)
513 : Kind(Kind), Context(Context)
521 /// \brief Create a direct initialization.
522 static InitializationKind CreateDirect(SourceLocation InitLoc,
523 SourceLocation LParenLoc,
524 SourceLocation RParenLoc) {
525 return InitializationKind(IK_Direct, IC_Normal,
526 InitLoc, LParenLoc, RParenLoc);
529 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
530 return InitializationKind(IK_DirectList, IC_Normal,
531 InitLoc, InitLoc, InitLoc);
534 /// \brief Create a direct initialization due to a cast that isn't a C-style
535 /// or functional cast.
536 static InitializationKind CreateCast(SourceRange TypeRange) {
537 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
538 TypeRange.getBegin(), TypeRange.getEnd());
541 /// \brief Create a direct initialization for a C-style cast.
542 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
543 SourceRange TypeRange,
545 // C++ cast syntax doesn't permit init lists, but C compound literals are
547 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
548 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
552 /// \brief Create a direct initialization for a functional cast.
553 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
555 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
556 IC_FunctionalCast, TypeRange.getBegin(),
557 TypeRange.getBegin(), TypeRange.getEnd());
560 /// \brief Create a copy initialization.
561 static InitializationKind CreateCopy(SourceLocation InitLoc,
562 SourceLocation EqualLoc,
563 bool AllowExplicitConvs = false) {
564 return InitializationKind(IK_Copy,
565 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
566 InitLoc, EqualLoc, EqualLoc);
569 /// \brief Create a default initialization.
570 static InitializationKind CreateDefault(SourceLocation InitLoc) {
571 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
574 /// \brief Create a value initialization.
575 static InitializationKind CreateValue(SourceLocation InitLoc,
576 SourceLocation LParenLoc,
577 SourceLocation RParenLoc,
578 bool isImplicit = false) {
579 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
580 InitLoc, LParenLoc, RParenLoc);
583 /// \brief Determine the initialization kind.
584 InitKind getKind() const {
588 /// \brief Determine whether this initialization is an explicit cast.
589 bool isExplicitCast() const {
590 return Context >= IC_StaticCast;
593 /// \brief Determine whether this initialization is a C-style cast.
594 bool isCStyleOrFunctionalCast() const {
595 return Context >= IC_CStyleCast;
598 /// \brief Determine whether this is a C-style cast.
599 bool isCStyleCast() const {
600 return Context == IC_CStyleCast;
603 /// \brief Determine whether this is a functional-style cast.
604 bool isFunctionalCast() const {
605 return Context == IC_FunctionalCast;
608 /// \brief Determine whether this initialization is an implicit
609 /// value-initialization, e.g., as occurs during aggregate
611 bool isImplicitValueInit() const { return Context == IC_Implicit; }
613 /// \brief Retrieve the location at which initialization is occurring.
614 SourceLocation getLocation() const { return Locations[0]; }
616 /// \brief Retrieve the source range that covers the initialization.
617 SourceRange getRange() const {
618 return SourceRange(Locations[0], Locations[2]);
621 /// \brief Retrieve the location of the equal sign for copy initialization
623 SourceLocation getEqualLoc() const {
624 assert(Kind == IK_Copy && "Only copy initialization has an '='");
628 bool isCopyInit() const { return Kind == IK_Copy; }
630 /// \brief Retrieve whether this initialization allows the use of explicit
632 bool AllowExplicit() const { return !isCopyInit(); }
634 /// \brief Retrieve whether this initialization allows the use of explicit
635 /// conversion functions when binding a reference. If the reference is the
636 /// first parameter in a copy or move constructor, such conversions are
637 /// permitted even though we are performing copy-initialization.
638 bool allowExplicitConversionFunctionsInRefBinding() const {
639 return !isCopyInit() || Context == IC_ExplicitConvs;
642 /// \brief Retrieve the source range containing the locations of the open
643 /// and closing parentheses for value and direct initializations.
644 SourceRange getParenRange() const {
645 assert((Kind == IK_Direct || Kind == IK_Value) &&
646 "Only direct- and value-initialization have parentheses");
647 return SourceRange(Locations[1], Locations[2]);
651 /// \brief Describes the sequence of initializations required to initialize
652 /// a given object or reference with a set of arguments.
653 class InitializationSequence {
655 /// \brief Describes the kind of initialization sequence computed.
657 /// \brief A failed initialization sequence. The failure kind tells what
661 /// \brief A dependent initialization, which could not be
662 /// type-checked due to the presence of dependent types or
663 /// dependently-typed expressions.
666 /// \brief A normal sequence.
670 /// \brief Describes the kind of a particular step in an initialization
673 /// \brief Resolve the address of an overloaded function to a specific
674 /// function declaration.
675 SK_ResolveAddressOfOverloadedFunction,
676 /// \brief Perform a derived-to-base cast, producing an rvalue.
677 SK_CastDerivedToBaseRValue,
678 /// \brief Perform a derived-to-base cast, producing an xvalue.
679 SK_CastDerivedToBaseXValue,
680 /// \brief Perform a derived-to-base cast, producing an lvalue.
681 SK_CastDerivedToBaseLValue,
682 /// \brief Reference binding to an lvalue.
684 /// \brief Reference binding to a temporary.
685 SK_BindReferenceToTemporary,
686 /// \brief An optional copy of a temporary object to another
687 /// temporary object, which is permitted (but not required) by
688 /// C++98/03 but not C++0x.
689 SK_ExtraneousCopyToTemporary,
690 /// \brief Direct-initialization from a reference-related object in the
691 /// final stage of class copy-initialization.
693 /// \brief Perform a user-defined conversion, either via a conversion
694 /// function or via a constructor.
696 /// \brief Perform a qualification conversion, producing an rvalue.
697 SK_QualificationConversionRValue,
698 /// \brief Perform a qualification conversion, producing an xvalue.
699 SK_QualificationConversionXValue,
700 /// \brief Perform a qualification conversion, producing an lvalue.
701 SK_QualificationConversionLValue,
702 /// \brief Perform a conversion adding _Atomic to a type.
704 /// \brief Perform a load from a glvalue, producing an rvalue.
706 /// \brief Perform an implicit conversion sequence.
707 SK_ConversionSequence,
708 /// \brief Perform an implicit conversion sequence without narrowing.
709 SK_ConversionSequenceNoNarrowing,
710 /// \brief Perform list-initialization without a constructor.
711 SK_ListInitialization,
712 /// \brief Unwrap the single-element initializer list for a reference.
714 /// \brief Rewrap the single-element initializer list for a reference.
716 /// \brief Perform initialization via a constructor.
717 SK_ConstructorInitialization,
718 /// \brief Perform initialization via a constructor, taking arguments from
719 /// a single InitListExpr.
720 SK_ConstructorInitializationFromList,
721 /// \brief Zero-initialize the object
722 SK_ZeroInitialization,
723 /// \brief C assignment
725 /// \brief Initialization by string
727 /// \brief An initialization that "converts" an Objective-C object
728 /// (not a point to an object) to another Objective-C object type.
729 SK_ObjCObjectConversion,
730 /// \brief Array indexing for initialization by elementwise copy.
732 /// \brief Array initialization by elementwise copy.
734 /// \brief Array initialization (from an array rvalue).
736 /// \brief Array initialization (from an array rvalue) as a GNU extension.
738 /// \brief Array initialization from a parenthesized initializer list.
739 /// This is a GNU C++ extension.
740 SK_ParenthesizedArrayInit,
741 /// \brief Pass an object by indirect copy-and-restore.
742 SK_PassByIndirectCopyRestore,
743 /// \brief Pass an object by indirect restore.
744 SK_PassByIndirectRestore,
745 /// \brief Produce an Objective-C object pointer.
746 SK_ProduceObjCObject,
747 /// \brief Construct a std::initializer_list from an initializer list.
748 SK_StdInitializerList,
749 /// \brief Perform initialization via a constructor taking a single
750 /// std::initializer_list argument.
751 SK_StdInitializerListConstructorCall,
752 /// \brief Initialize an OpenCL sampler from an integer.
754 /// \brief Initialize queue_t from 0.
756 /// \brief Passing zero to a function where OpenCL event_t is expected.
760 /// \brief A single step in the initialization sequence.
763 /// \brief The kind of conversion or initialization step we are taking.
766 // \brief The type that results from this initialization.
770 bool HadMultipleCandidates;
771 FunctionDecl *Function;
772 DeclAccessPair FoundDecl;
776 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
777 /// SK_UserConversion, the function that the expression should be
778 /// resolved to or the conversion function to call, respectively.
779 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
780 /// the constructor to be called.
782 /// Always a FunctionDecl, plus a Boolean flag telling if it was
783 /// selected from an overloaded set having size greater than 1.
784 /// For conversion decls, the naming class is the source type.
785 /// For construct decls, the naming class is the target type.
788 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
790 ImplicitConversionSequence *ICS;
792 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
794 InitListExpr *WrappingSyntacticList;
801 /// \brief The kind of initialization sequence computed.
802 enum SequenceKind SequenceKind;
804 /// \brief Steps taken by this initialization.
805 SmallVector<Step, 4> Steps;
808 /// \brief Describes why initialization failed.
810 /// \brief Too many initializers provided for a reference.
811 FK_TooManyInitsForReference,
812 /// \brief Array must be initialized with an initializer list.
813 FK_ArrayNeedsInitList,
814 /// \brief Array must be initialized with an initializer list or a
816 FK_ArrayNeedsInitListOrStringLiteral,
817 /// \brief Array must be initialized with an initializer list or a
818 /// wide string literal.
819 FK_ArrayNeedsInitListOrWideStringLiteral,
820 /// \brief Initializing a wide char array with narrow string literal.
821 FK_NarrowStringIntoWideCharArray,
822 /// \brief Initializing char array with wide string literal.
823 FK_WideStringIntoCharArray,
824 /// \brief Initializing wide char array with incompatible wide string
826 FK_IncompatWideStringIntoWideChar,
827 /// \brief Array type mismatch.
828 FK_ArrayTypeMismatch,
829 /// \brief Non-constant array initializer
830 FK_NonConstantArrayInit,
831 /// \brief Cannot resolve the address of an overloaded function.
832 FK_AddressOfOverloadFailed,
833 /// \brief Overloading due to reference initialization failed.
834 FK_ReferenceInitOverloadFailed,
835 /// \brief Non-const lvalue reference binding to a temporary.
836 FK_NonConstLValueReferenceBindingToTemporary,
837 /// \brief Non-const lvalue reference binding to a bit-field.
838 FK_NonConstLValueReferenceBindingToBitfield,
839 /// \brief Non-const lvalue reference binding to a vector element.
840 FK_NonConstLValueReferenceBindingToVectorElement,
841 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
843 FK_NonConstLValueReferenceBindingToUnrelated,
844 /// \brief Rvalue reference binding to an lvalue.
845 FK_RValueReferenceBindingToLValue,
846 /// \brief Reference binding drops qualifiers.
847 FK_ReferenceInitDropsQualifiers,
848 /// \brief Reference binding failed.
849 FK_ReferenceInitFailed,
850 /// \brief Implicit conversion failed.
852 /// \brief Implicit conversion failed.
853 FK_ConversionFromPropertyFailed,
854 /// \brief Too many initializers for scalar
855 FK_TooManyInitsForScalar,
856 /// \brief Reference initialization from an initializer list
857 FK_ReferenceBindingToInitList,
858 /// \brief Initialization of some unused destination type with an
859 /// initializer list.
860 FK_InitListBadDestinationType,
861 /// \brief Overloading for a user-defined conversion failed.
862 FK_UserConversionOverloadFailed,
863 /// \brief Overloading for initialization by constructor failed.
864 FK_ConstructorOverloadFailed,
865 /// \brief Overloading for list-initialization by constructor failed.
866 FK_ListConstructorOverloadFailed,
867 /// \brief Default-initialization of a 'const' object.
868 FK_DefaultInitOfConst,
869 /// \brief Initialization of an incomplete type.
871 /// \brief Variable-length array must not have an initializer.
872 FK_VariableLengthArrayHasInitializer,
873 /// \brief List initialization failed at some point.
874 FK_ListInitializationFailed,
875 /// \brief Initializer has a placeholder type which cannot be
876 /// resolved by initialization.
878 /// \brief Trying to take the address of a function that doesn't support
879 /// having its address taken.
880 FK_AddressOfUnaddressableFunction,
881 /// \brief List-copy-initialization chose an explicit constructor.
882 FK_ExplicitConstructor
886 /// \brief The reason why initialization failed.
889 /// \brief The failed result of overload resolution.
890 OverloadingResult FailedOverloadResult;
892 /// \brief The candidate set created when initialization failed.
893 OverloadCandidateSet FailedCandidateSet;
895 /// \brief The incomplete type that caused a failure.
896 QualType FailedIncompleteType;
898 /// \brief The fixit that needs to be applied to make this initialization
900 std::string ZeroInitializationFixit;
901 SourceLocation ZeroInitializationFixitLoc;
904 /// \brief Call for initializations are invalid but that would be valid
905 /// zero initialzations if Fixit was applied.
906 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
907 ZeroInitializationFixit = Fixit;
908 ZeroInitializationFixitLoc = L;
913 /// \brief Prints a follow-up note that highlights the location of
914 /// the initialized entity, if it's remote.
915 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
918 /// \brief Try to perform initialization of the given entity, creating a
919 /// record of the steps required to perform the initialization.
921 /// The generated initialization sequence will either contain enough
922 /// information to diagnose
924 /// \param S the semantic analysis object.
926 /// \param Entity the entity being initialized.
928 /// \param Kind the kind of initialization being performed.
930 /// \param Args the argument(s) provided for initialization.
932 /// \param TopLevelOfInitList true if we are initializing from an expression
933 /// at the top level inside an initializer list. This disallows
934 /// narrowing conversions in C++11 onwards.
935 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
937 InitializationSequence(Sema &S,
938 const InitializedEntity &Entity,
939 const InitializationKind &Kind,
941 bool TopLevelOfInitList = false,
942 bool TreatUnavailableAsInvalid = true);
943 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
944 const InitializationKind &Kind, MultiExprArg Args,
945 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
947 ~InitializationSequence();
949 /// \brief Perform the actual initialization of the given entity based on
950 /// the computed initialization sequence.
952 /// \param S the semantic analysis object.
954 /// \param Entity the entity being initialized.
956 /// \param Kind the kind of initialization being performed.
958 /// \param Args the argument(s) provided for initialization, ownership of
959 /// which is transferred into the routine.
961 /// \param ResultType if non-NULL, will be set to the type of the
962 /// initialized object, which is the type of the declaration in most
963 /// cases. However, when the initialized object is a variable of
964 /// incomplete array type and the initializer is an initializer
965 /// list, this type will be set to the completed array type.
967 /// \returns an expression that performs the actual object initialization, if
968 /// the initialization is well-formed. Otherwise, emits diagnostics
969 /// and returns an invalid expression.
970 ExprResult Perform(Sema &S,
971 const InitializedEntity &Entity,
972 const InitializationKind &Kind,
974 QualType *ResultType = nullptr);
976 /// \brief Diagnose an potentially-invalid initialization sequence.
978 /// \returns true if the initialization sequence was ill-formed,
980 bool Diagnose(Sema &S,
981 const InitializedEntity &Entity,
982 const InitializationKind &Kind,
983 ArrayRef<Expr *> Args);
985 /// \brief Determine the kind of initialization sequence computed.
986 enum SequenceKind getKind() const { return SequenceKind; }
988 /// \brief Set the kind of sequence computed.
989 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
991 /// \brief Determine whether the initialization sequence is valid.
992 explicit operator bool() const { return !Failed(); }
994 /// \brief Determine whether the initialization sequence is invalid.
995 bool Failed() const { return SequenceKind == FailedSequence; }
997 typedef SmallVectorImpl<Step>::const_iterator step_iterator;
998 step_iterator step_begin() const { return Steps.begin(); }
999 step_iterator step_end() const { return Steps.end(); }
1001 typedef llvm::iterator_range<step_iterator> step_range;
1002 step_range steps() const { return {step_begin(), step_end()}; }
1004 /// \brief Determine whether this initialization is a direct reference
1005 /// binding (C++ [dcl.init.ref]).
1006 bool isDirectReferenceBinding() const;
1008 /// \brief Determine whether this initialization failed due to an ambiguity.
1009 bool isAmbiguous() const;
1011 /// \brief Determine whether this initialization is direct call to a
1013 bool isConstructorInitialization() const;
1015 /// \brief Returns whether the last step in this initialization sequence is a
1016 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
1018 /// If this function returns true, *isInitializerConstant will be set to
1019 /// describe whether *Initializer was a constant expression. If
1020 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
1021 /// evaluated value of *Initializer.
1022 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
1023 bool *isInitializerConstant,
1024 APValue *ConstantValue) const;
1026 /// \brief Add a new step in the initialization that resolves the address
1027 /// of an overloaded function to a specific function declaration.
1029 /// \param Function the function to which the overloaded function reference
1031 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
1032 DeclAccessPair Found,
1033 bool HadMultipleCandidates);
1035 /// \brief Add a new step in the initialization that performs a derived-to-
1038 /// \param BaseType the base type to which we will be casting.
1040 /// \param Category Indicates whether the result will be treated as an
1041 /// rvalue, an xvalue, or an lvalue.
1042 void AddDerivedToBaseCastStep(QualType BaseType,
1043 ExprValueKind Category);
1045 /// \brief Add a new step binding a reference to an object.
1047 /// \param BindingTemporary True if we are binding a reference to a temporary
1048 /// object (thereby extending its lifetime); false if we are binding to an
1049 /// lvalue or an lvalue treated as an rvalue.
1050 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1052 /// \brief Add a new step that makes an extraneous copy of the input
1053 /// to a temporary of the same class type.
1055 /// This extraneous copy only occurs during reference binding in
1056 /// C++98/03, where we are permitted (but not required) to introduce
1057 /// an extra copy. At a bare minimum, we must check that we could
1058 /// call the copy constructor, and produce a diagnostic if the copy
1059 /// constructor is inaccessible or no copy constructor matches.
1061 /// \param T The type of the temporary being created.
1062 void AddExtraneousCopyToTemporary(QualType T);
1064 /// \brief Add a new step that makes a copy of the input to an object of
1065 /// the given type, as the final step in class copy-initialization.
1066 void AddFinalCopy(QualType T);
1068 /// \brief Add a new step invoking a conversion function, which is either
1069 /// a constructor or a conversion function.
1070 void AddUserConversionStep(FunctionDecl *Function,
1071 DeclAccessPair FoundDecl,
1073 bool HadMultipleCandidates);
1075 /// \brief Add a new step that performs a qualification conversion to the
1077 void AddQualificationConversionStep(QualType Ty,
1078 ExprValueKind Category);
1080 /// \brief Add a new step that performs conversion from non-atomic to atomic
1082 void AddAtomicConversionStep(QualType Ty);
1084 /// \brief Add a new step that performs a load of the given type.
1086 /// Although the term "LValueToRValue" is conventional, this applies to both
1087 /// lvalues and xvalues.
1088 void AddLValueToRValueStep(QualType Ty);
1090 /// \brief Add a new step that applies an implicit conversion sequence.
1091 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1092 QualType T, bool TopLevelOfInitList = false);
1094 /// \brief Add a list-initialization step.
1095 void AddListInitializationStep(QualType T);
1097 /// \brief Add a constructor-initialization step.
1099 /// \param FromInitList The constructor call is syntactically an initializer
1101 /// \param AsInitList The constructor is called as an init list constructor.
1102 void AddConstructorInitializationStep(DeclAccessPair FoundDecl,
1103 CXXConstructorDecl *Constructor,
1105 bool HadMultipleCandidates,
1106 bool FromInitList, bool AsInitList);
1108 /// \brief Add a zero-initialization step.
1109 void AddZeroInitializationStep(QualType T);
1111 /// \brief Add a C assignment step.
1113 // FIXME: It isn't clear whether this should ever be needed;
1114 // ideally, we would handle everything needed in C in the common
1115 // path. However, that isn't the case yet.
1116 void AddCAssignmentStep(QualType T);
1118 /// \brief Add a string init step.
1119 void AddStringInitStep(QualType T);
1121 /// \brief Add an Objective-C object conversion step, which is
1123 void AddObjCObjectConversionStep(QualType T);
1125 /// \brief Add an array initialization loop step.
1126 void AddArrayInitLoopStep(QualType T, QualType EltTy);
1128 /// \brief Add an array initialization step.
1129 void AddArrayInitStep(QualType T, bool IsGNUExtension);
1131 /// \brief Add a parenthesized array initialization step.
1132 void AddParenthesizedArrayInitStep(QualType T);
1134 /// \brief Add a step to pass an object by indirect copy-restore.
1135 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1137 /// \brief Add a step to "produce" an Objective-C object (by
1139 void AddProduceObjCObjectStep(QualType T);
1141 /// \brief Add a step to construct a std::initializer_list object from an
1142 /// initializer list.
1143 void AddStdInitializerListConstructionStep(QualType T);
1145 /// \brief Add a step to initialize an OpenCL sampler from an integer
1147 void AddOCLSamplerInitStep(QualType T);
1149 /// \brief Add a step to initialize an OpenCL event_t from a NULL
1151 void AddOCLZeroEventStep(QualType T);
1153 /// \brief Add a step to initialize an OpenCL queue_t from 0.
1154 void AddOCLZeroQueueStep(QualType T);
1156 /// \brief Add steps to unwrap a initializer list for a reference around a
1157 /// single element and rewrap it at the end.
1158 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1160 /// \brief Note that this initialization sequence failed.
1161 void SetFailed(FailureKind Failure) {
1162 SequenceKind = FailedSequence;
1163 this->Failure = Failure;
1164 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1165 "Incomplete type failure requires a type!");
1168 /// \brief Note that this initialization sequence failed due to failed
1169 /// overload resolution.
1170 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1172 /// \brief Retrieve a reference to the candidate set when overload
1173 /// resolution fails.
1174 OverloadCandidateSet &getFailedCandidateSet() {
1175 return FailedCandidateSet;
1178 /// \brief Get the overloading result, for when the initialization
1179 /// sequence failed due to a bad overload.
1180 OverloadingResult getFailedOverloadResult() const {
1181 return FailedOverloadResult;
1184 /// \brief Note that this initialization sequence failed due to an
1185 /// incomplete type.
1186 void setIncompleteTypeFailure(QualType IncompleteType) {
1187 FailedIncompleteType = IncompleteType;
1188 SetFailed(FK_Incomplete);
1191 /// \brief Determine why initialization failed.
1192 FailureKind getFailureKind() const {
1193 assert(Failed() && "Not an initialization failure!");
1197 /// \brief Dump a representation of this initialization sequence to
1198 /// the given stream, for debugging purposes.
1199 void dump(raw_ostream &OS) const;
1201 /// \brief Dump a representation of this initialization sequence to
1202 /// standard error, for debugging purposes.
1206 } // end namespace clang
1208 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H