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 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
15 #define LLVM_CLANG_SEMA_INITIALIZATION_H
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/DeclarationName.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/IdentifierTable.h"
25 #include "clang/Basic/LLVM.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/SourceLocation.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Sema/Overload.h"
30 #include "clang/Sema/Ownership.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Support/Casting.h"
43 class CXXBaseSpecifier;
44 class CXXConstructorDecl;
48 /// Describes an entity that is being initialized.
49 class alignas(8) InitializedEntity {
51 /// Specifies the kind of entity being initialized.
53 /// The entity being initialized is a variable.
56 /// The entity being initialized is a function parameter.
59 /// The entity being initialized is the result of a function call.
62 /// The entity being initialized is the result of a statement expression.
65 /// The entity being initialized is an exception object that
69 /// The entity being initialized is a non-static data member
73 /// The entity being initialized is an element of an array.
76 /// The entity being initialized is an object (or array of
77 /// objects) allocated via new.
80 /// The entity being initialized is a temporary object.
83 /// The entity being initialized is a base member subobject.
86 /// The initialization is being done by a delegating constructor.
89 /// The entity being initialized is an element of a vector.
93 /// The entity being initialized is a field of block descriptor for
94 /// the copied-in c++ object.
97 /// The entity being initialized is a field of block descriptor for the
98 /// copied-in lambda object that's used in the lambda to block conversion.
99 EK_LambdaToBlockConversionBlockElement,
101 /// The entity being initialized is the real or imaginary part of a
105 /// The entity being initialized is the field that captures a
106 /// variable in a lambda.
109 /// The entity being initialized is the initializer for a compound
111 EK_CompoundLiteralInit,
113 /// The entity being implicitly initialized back to the formal
117 /// The entity being initialized is a function parameter; function
118 /// is member of group of audited CF APIs.
119 EK_Parameter_CF_Audited,
121 /// The entity being initialized is a structured binding of a
122 /// decomposition declaration.
125 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
126 // enum as an index for its first %select. When modifying this list,
127 // that diagnostic text needs to be updated as well.
131 /// The kind of entity being initialized.
134 /// If non-NULL, the parent entity in which this
135 /// initialization occurs.
136 const InitializedEntity *Parent = nullptr;
138 /// The type of the object or reference being initialized.
141 /// The mangling number for the next reference temporary to be created.
142 mutable unsigned ManglingNumber = 0;
145 /// When Kind == EK_Result, EK_Exception, EK_New, the
146 /// location of the 'return', 'throw', or 'new' keyword,
147 /// respectively. When Kind == EK_Temporary, the location where
148 /// the temporary is being created.
151 /// Whether the entity being initialized may end up using the
152 /// named return value optimization (NRVO).
157 /// The VarDecl, FieldDecl, or BindingDecl being initialized.
158 ValueDecl *VariableOrMember;
160 /// When Kind == EK_Member, whether this is an implicit member
161 /// initialization in a copy or move constructor. These can perform array
163 bool IsImplicitFieldInit;
165 /// When Kind == EK_Member, whether this is the initial initialization
166 /// check for a default member initializer.
167 bool IsDefaultMemberInit;
171 /// The name of the variable being captured by an EK_LambdaCapture.
172 IdentifierInfo *VarID;
174 /// The source location at which the capture occurs.
179 /// When Kind == EK_Variable, EK_Member or EK_Binding, the variable.
182 /// When Kind == EK_RelatedResult, the ObjectiveC method where
183 /// result type was implicitly changed to accommodate ARC semantics.
184 ObjCMethodDecl *MethodDecl;
186 /// When Kind == EK_Parameter, the ParmVarDecl, with the
187 /// low bit indicating whether the parameter is "consumed".
190 /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
191 /// source information for the temporary.
192 TypeSourceInfo *TypeInfo;
194 struct LN LocAndNRVO;
196 /// When Kind == EK_Base, the base specifier that provides the
197 /// base class. The lower bit specifies whether the base is an inherited
201 /// When Kind == EK_ArrayElement, EK_VectorElement, or
202 /// EK_ComplexElement, the index of the array or vector element being
209 InitializedEntity() = default;
211 /// Create the initialization entity for a variable.
212 InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
213 : Kind(EK), Type(Var->getType()), Variable{Var, false, false} {}
215 /// Create the initialization entity for the result of a
216 /// function, throwing an object, performing an explicit cast, or
217 /// initializing a parameter for which there is no declaration.
218 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
220 : Kind(Kind), Type(Type) {
221 LocAndNRVO.Location = Loc.getRawEncoding();
222 LocAndNRVO.NRVO = NRVO;
225 /// Create the initialization entity for a member subobject.
226 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
227 bool Implicit, bool DefaultMemberInit)
228 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
229 Variable{Member, Implicit, DefaultMemberInit} {}
231 /// Create the initialization entity for an array element.
232 InitializedEntity(ASTContext &Context, unsigned Index,
233 const InitializedEntity &Parent);
235 /// Create the initialization entity for a lambda capture.
236 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
237 : Kind(EK_LambdaCapture), Type(FieldType) {
238 Capture.VarID = VarID;
239 Capture.Location = Loc.getRawEncoding();
243 /// Create the initialization entity for a variable.
244 static InitializedEntity InitializeVariable(VarDecl *Var) {
245 return InitializedEntity(Var);
248 /// Create the initialization entity for a parameter.
249 static InitializedEntity InitializeParameter(ASTContext &Context,
250 const ParmVarDecl *Parm) {
251 return InitializeParameter(Context, Parm, Parm->getType());
254 /// Create the initialization entity for a parameter, but use
256 static InitializedEntity InitializeParameter(ASTContext &Context,
257 const ParmVarDecl *Parm,
259 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
260 Parm->hasAttr<NSConsumedAttr>());
262 InitializedEntity Entity;
263 Entity.Kind = EK_Parameter;
265 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
266 Entity.Parent = nullptr;
268 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
272 /// Create the initialization entity for a parameter that is
273 /// only known by its type.
274 static InitializedEntity InitializeParameter(ASTContext &Context,
277 InitializedEntity Entity;
278 Entity.Kind = EK_Parameter;
279 Entity.Type = Context.getVariableArrayDecayedType(Type);
280 Entity.Parent = nullptr;
281 Entity.Parameter = (Consumed);
285 /// Create the initialization entity for the result of a function.
286 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
287 QualType Type, bool NRVO) {
288 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
291 static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc,
293 return InitializedEntity(EK_StmtExprResult, ReturnLoc, Type);
296 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
297 QualType Type, bool NRVO) {
298 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
301 static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
302 QualType Type, bool NRVO) {
303 return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
304 BlockVarLoc, Type, NRVO);
307 /// Create the initialization entity for an exception object.
308 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
309 QualType Type, bool NRVO) {
310 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
313 /// Create the initialization entity for an object allocated via new.
314 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
315 return InitializedEntity(EK_New, NewLoc, Type);
318 /// Create the initialization entity for a temporary.
319 static InitializedEntity InitializeTemporary(QualType Type) {
320 return InitializeTemporary(nullptr, Type);
323 /// Create the initialization entity for a temporary.
324 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
325 return InitializeTemporary(TypeInfo, TypeInfo->getType());
328 /// Create the initialization entity for a temporary.
329 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo,
331 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
332 Result.TypeInfo = TypeInfo;
336 /// Create the initialization entity for a related result.
337 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
339 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
340 Result.MethodDecl = MD;
344 /// Create the initialization entity for a base class subobject.
345 static InitializedEntity
346 InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base,
347 bool IsInheritedVirtualBase,
348 const InitializedEntity *Parent = nullptr);
350 /// Create the initialization entity for a delegated constructor.
351 static InitializedEntity InitializeDelegation(QualType Type) {
352 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
355 /// Create the initialization entity for a member subobject.
356 static InitializedEntity
357 InitializeMember(FieldDecl *Member,
358 const InitializedEntity *Parent = nullptr,
359 bool Implicit = false) {
360 return InitializedEntity(Member, Parent, Implicit, false);
363 /// Create the initialization entity for a member subobject.
364 static InitializedEntity
365 InitializeMember(IndirectFieldDecl *Member,
366 const InitializedEntity *Parent = nullptr,
367 bool Implicit = false) {
368 return InitializedEntity(Member->getAnonField(), Parent, Implicit, false);
371 /// Create the initialization entity for a default member initializer.
372 static InitializedEntity
373 InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member) {
374 return InitializedEntity(Member, nullptr, false, true);
377 /// Create the initialization entity for an array element.
378 static InitializedEntity InitializeElement(ASTContext &Context,
380 const InitializedEntity &Parent) {
381 return InitializedEntity(Context, Index, Parent);
384 /// Create the initialization entity for a structured binding.
385 static InitializedEntity InitializeBinding(VarDecl *Binding) {
386 return InitializedEntity(Binding, EK_Binding);
389 /// Create the initialization entity for a lambda capture.
390 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
392 SourceLocation Loc) {
393 return InitializedEntity(VarID, FieldType, Loc);
396 /// Create the entity for a compound literal initializer.
397 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
398 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
400 Result.TypeInfo = TSI;
404 /// Determine the kind of initialization.
405 EntityKind getKind() const { return Kind; }
407 /// Retrieve the parent of the entity being initialized, when
408 /// the initialization itself is occurring within the context of a
409 /// larger initialization.
410 const InitializedEntity *getParent() const { return Parent; }
412 /// Retrieve type being initialized.
413 QualType getType() const { return Type; }
415 /// Retrieve complete type-source information for the object being
416 /// constructed, if known.
417 TypeSourceInfo *getTypeSourceInfo() const {
418 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
424 /// Retrieve the name of the entity being initialized.
425 DeclarationName getName() const;
427 /// Retrieve the variable, parameter, or field being
429 ValueDecl *getDecl() const;
431 /// Retrieve the ObjectiveC method being initialized.
432 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
434 /// Determine whether this initialization allows the named return
435 /// value optimization, which also applies to thrown objects.
436 bool allowsNRVO() const;
438 bool isParameterKind() const {
439 return (getKind() == EK_Parameter ||
440 getKind() == EK_Parameter_CF_Audited);
443 /// Determine whether this initialization consumes the
445 bool isParameterConsumed() const {
446 assert(isParameterKind() && "Not a parameter");
447 return (Parameter & 1);
450 /// Retrieve the base specifier.
451 const CXXBaseSpecifier *getBaseSpecifier() const {
452 assert(getKind() == EK_Base && "Not a base specifier");
453 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
456 /// Return whether the base is an inherited virtual base.
457 bool isInheritedVirtualBase() const {
458 assert(getKind() == EK_Base && "Not a base specifier");
462 /// Determine whether this is an array new with an unknown bound.
463 bool isVariableLengthArrayNew() const {
464 return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>(
465 getType()->getAsArrayTypeUnsafe());
468 /// Is this the implicit initialization of a member of a class from
469 /// a defaulted constructor?
470 bool isImplicitMemberInitializer() const {
471 return getKind() == EK_Member && Variable.IsImplicitFieldInit;
474 /// Is this the default member initializer of a member (specified inside
475 /// the class definition)?
476 bool isDefaultMemberInitializer() const {
477 return getKind() == EK_Member && Variable.IsDefaultMemberInit;
480 /// Determine the location of the 'return' keyword when initializing
481 /// the result of a function call.
482 SourceLocation getReturnLoc() const {
483 assert(getKind() == EK_Result && "No 'return' location!");
484 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
487 /// Determine the location of the 'throw' keyword when initializing
488 /// an exception object.
489 SourceLocation getThrowLoc() const {
490 assert(getKind() == EK_Exception && "No 'throw' location!");
491 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
494 /// If this is an array, vector, or complex number element, get the
496 unsigned getElementIndex() const {
497 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
498 getKind() == EK_ComplexElement);
502 /// If this is already the initializer for an array or vector
503 /// element, sets the element index.
504 void setElementIndex(unsigned Index) {
505 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
506 getKind() == EK_ComplexElement);
510 /// For a lambda capture, return the capture's name.
511 StringRef getCapturedVarName() const {
512 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
513 return Capture.VarID->getName();
516 /// Determine the location of the capture when initializing
517 /// field from a captured variable in a lambda.
518 SourceLocation getCaptureLoc() const {
519 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
520 return SourceLocation::getFromRawEncoding(Capture.Location);
523 void setParameterCFAudited() {
524 Kind = EK_Parameter_CF_Audited;
527 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
529 /// Dump a representation of the initialized entity to standard error,
530 /// for debugging purposes.
534 unsigned dumpImpl(raw_ostream &OS) const;
537 /// Describes the kind of initialization being performed, along with
538 /// location information for tokens related to the initialization (equal sign,
540 class InitializationKind {
542 /// The kind of initialization being performed.
544 /// Direct initialization
547 /// Direct list-initialization
550 /// Copy initialization
553 /// Default initialization
556 /// Value initialization
561 /// The context of the initialization.
566 /// Normal context, but allows explicit conversion functionss
569 /// Implicit context (value initialization)
572 /// Static cast context
575 /// C-style cast context
578 /// Functional cast context
582 /// The kind of initialization being performed.
585 /// The context of the initialization.
586 InitContext Context : 8;
588 /// The source locations involved in the initialization.
589 SourceLocation Locations[3];
591 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
592 SourceLocation Loc2, SourceLocation Loc3)
593 : Kind(Kind), Context(Context) {
600 /// Create a direct initialization.
601 static InitializationKind CreateDirect(SourceLocation InitLoc,
602 SourceLocation LParenLoc,
603 SourceLocation RParenLoc) {
604 return InitializationKind(IK_Direct, IC_Normal,
605 InitLoc, LParenLoc, RParenLoc);
608 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
609 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc,
613 static InitializationKind CreateDirectList(SourceLocation InitLoc,
614 SourceLocation LBraceLoc,
615 SourceLocation RBraceLoc) {
616 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc,
620 /// Create a direct initialization due to a cast that isn't a C-style
621 /// or functional cast.
622 static InitializationKind CreateCast(SourceRange TypeRange) {
623 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
624 TypeRange.getBegin(), TypeRange.getEnd());
627 /// Create a direct initialization for a C-style cast.
628 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
629 SourceRange TypeRange,
631 // C++ cast syntax doesn't permit init lists, but C compound literals are
633 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
634 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
638 /// Create a direct initialization for a functional cast.
639 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
641 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
642 IC_FunctionalCast, TypeRange.getBegin(),
643 TypeRange.getBegin(), TypeRange.getEnd());
646 /// Create a copy initialization.
647 static InitializationKind CreateCopy(SourceLocation InitLoc,
648 SourceLocation EqualLoc,
649 bool AllowExplicitConvs = false) {
650 return InitializationKind(IK_Copy,
651 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
652 InitLoc, EqualLoc, EqualLoc);
655 /// Create a default initialization.
656 static InitializationKind CreateDefault(SourceLocation InitLoc) {
657 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
660 /// Create a value initialization.
661 static InitializationKind CreateValue(SourceLocation InitLoc,
662 SourceLocation LParenLoc,
663 SourceLocation RParenLoc,
664 bool isImplicit = false) {
665 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
666 InitLoc, LParenLoc, RParenLoc);
669 /// Create an initialization from an initializer (which, for direct
670 /// initialization from a parenthesized list, will be a ParenListExpr).
671 static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit,
673 if (!Init) return CreateDefault(Loc);
675 return CreateCopy(Loc, Init->getBeginLoc());
676 if (isa<InitListExpr>(Init))
677 return CreateDirectList(Loc, Init->getBeginLoc(), Init->getEndLoc());
678 return CreateDirect(Loc, Init->getBeginLoc(), Init->getEndLoc());
681 /// Determine the initialization kind.
682 InitKind getKind() const {
686 /// Determine whether this initialization is an explicit cast.
687 bool isExplicitCast() const {
688 return Context >= IC_StaticCast;
691 /// Determine whether this initialization is a C-style cast.
692 bool isCStyleOrFunctionalCast() const {
693 return Context >= IC_CStyleCast;
696 /// Determine whether this is a C-style cast.
697 bool isCStyleCast() const {
698 return Context == IC_CStyleCast;
701 /// Determine whether this is a functional-style cast.
702 bool isFunctionalCast() const {
703 return Context == IC_FunctionalCast;
706 /// Determine whether this initialization is an implicit
707 /// value-initialization, e.g., as occurs during aggregate
709 bool isImplicitValueInit() const { return Context == IC_Implicit; }
711 /// Retrieve the location at which initialization is occurring.
712 SourceLocation getLocation() const { return Locations[0]; }
714 /// Retrieve the source range that covers the initialization.
715 SourceRange getRange() const {
716 return SourceRange(Locations[0], Locations[2]);
719 /// Retrieve the location of the equal sign for copy initialization
721 SourceLocation getEqualLoc() const {
722 assert(Kind == IK_Copy && "Only copy initialization has an '='");
726 bool isCopyInit() const { return Kind == IK_Copy; }
728 /// Retrieve whether this initialization allows the use of explicit
730 bool AllowExplicit() const { return !isCopyInit(); }
732 /// Retrieve whether this initialization allows the use of explicit
733 /// conversion functions when binding a reference. If the reference is the
734 /// first parameter in a copy or move constructor, such conversions are
735 /// permitted even though we are performing copy-initialization.
736 bool allowExplicitConversionFunctionsInRefBinding() const {
737 return !isCopyInit() || Context == IC_ExplicitConvs;
740 /// Determine whether this initialization has a source range containing the
741 /// locations of open and closing parentheses or braces.
742 bool hasParenOrBraceRange() const {
743 return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList;
746 /// Retrieve the source range containing the locations of the open
747 /// and closing parentheses or braces for value, direct, and direct list
749 SourceRange getParenOrBraceRange() const {
750 assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "
751 "initialization have parentheses or "
753 return SourceRange(Locations[1], Locations[2]);
757 /// Describes the sequence of initializations required to initialize
758 /// a given object or reference with a set of arguments.
759 class InitializationSequence {
761 /// Describes the kind of initialization sequence computed.
763 /// A failed initialization sequence. The failure kind tells what
767 /// A dependent initialization, which could not be
768 /// type-checked due to the presence of dependent types or
769 /// dependently-typed expressions.
772 /// A normal sequence.
776 /// Describes the kind of a particular step in an initialization
779 /// Resolve the address of an overloaded function to a specific
780 /// function declaration.
781 SK_ResolveAddressOfOverloadedFunction,
783 /// Perform a derived-to-base cast, producing an rvalue.
784 SK_CastDerivedToBaseRValue,
786 /// Perform a derived-to-base cast, producing an xvalue.
787 SK_CastDerivedToBaseXValue,
789 /// Perform a derived-to-base cast, producing an lvalue.
790 SK_CastDerivedToBaseLValue,
792 /// Reference binding to an lvalue.
795 /// Reference binding to a temporary.
796 SK_BindReferenceToTemporary,
798 /// An optional copy of a temporary object to another
799 /// temporary object, which is permitted (but not required) by
800 /// C++98/03 but not C++0x.
801 SK_ExtraneousCopyToTemporary,
803 /// Direct-initialization from a reference-related object in the
804 /// final stage of class copy-initialization.
807 /// Perform a user-defined conversion, either via a conversion
808 /// function or via a constructor.
811 /// Perform a qualification conversion, producing an rvalue.
812 SK_QualificationConversionRValue,
814 /// Perform a qualification conversion, producing an xvalue.
815 SK_QualificationConversionXValue,
817 /// Perform a qualification conversion, producing an lvalue.
818 SK_QualificationConversionLValue,
820 /// Perform a conversion adding _Atomic to a type.
823 /// Perform a load from a glvalue, producing an rvalue.
826 /// Perform an implicit conversion sequence.
827 SK_ConversionSequence,
829 /// Perform an implicit conversion sequence without narrowing.
830 SK_ConversionSequenceNoNarrowing,
832 /// Perform list-initialization without a constructor.
833 SK_ListInitialization,
835 /// Unwrap the single-element initializer list for a reference.
838 /// Rewrap the single-element initializer list for a reference.
841 /// Perform initialization via a constructor.
842 SK_ConstructorInitialization,
844 /// Perform initialization via a constructor, taking arguments from
845 /// a single InitListExpr.
846 SK_ConstructorInitializationFromList,
848 /// Zero-initialize the object
849 SK_ZeroInitialization,
854 /// Initialization by string
857 /// An initialization that "converts" an Objective-C object
858 /// (not a point to an object) to another Objective-C object type.
859 SK_ObjCObjectConversion,
861 /// Array indexing for initialization by elementwise copy.
864 /// Array initialization by elementwise copy.
867 /// Array initialization (from an array rvalue).
870 /// Array initialization (from an array rvalue) as a GNU extension.
873 /// Array initialization from a parenthesized initializer list.
874 /// This is a GNU C++ extension.
875 SK_ParenthesizedArrayInit,
877 /// Pass an object by indirect copy-and-restore.
878 SK_PassByIndirectCopyRestore,
880 /// Pass an object by indirect restore.
881 SK_PassByIndirectRestore,
883 /// Produce an Objective-C object pointer.
884 SK_ProduceObjCObject,
886 /// Construct a std::initializer_list from an initializer list.
887 SK_StdInitializerList,
889 /// Perform initialization via a constructor taking a single
890 /// std::initializer_list argument.
891 SK_StdInitializerListConstructorCall,
893 /// Initialize an OpenCL sampler from an integer.
896 /// Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero
900 /// A single step in the initialization sequence.
903 /// The kind of conversion or initialization step we are taking.
906 // The type that results from this initialization.
910 bool HadMultipleCandidates;
911 FunctionDecl *Function;
912 DeclAccessPair FoundDecl;
916 /// When Kind == SK_ResolvedOverloadedFunction or Kind ==
917 /// SK_UserConversion, the function that the expression should be
918 /// resolved to or the conversion function to call, respectively.
919 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
920 /// the constructor to be called.
922 /// Always a FunctionDecl, plus a Boolean flag telling if it was
923 /// selected from an overloaded set having size greater than 1.
924 /// For conversion decls, the naming class is the source type.
925 /// For construct decls, the naming class is the target type.
928 /// When Kind = SK_ConversionSequence, the implicit conversion
930 ImplicitConversionSequence *ICS;
932 /// When Kind = SK_RewrapInitList, the syntactic form of the
934 InitListExpr *WrappingSyntacticList;
941 /// The kind of initialization sequence computed.
942 enum SequenceKind SequenceKind;
944 /// Steps taken by this initialization.
945 SmallVector<Step, 4> Steps;
948 /// Describes why initialization failed.
950 /// Too many initializers provided for a reference.
951 FK_TooManyInitsForReference,
953 /// Reference initialized from a parenthesized initializer list.
954 FK_ParenthesizedListInitForReference,
956 /// Array must be initialized with an initializer list.
957 FK_ArrayNeedsInitList,
959 /// Array must be initialized with an initializer list or a
961 FK_ArrayNeedsInitListOrStringLiteral,
963 /// Array must be initialized with an initializer list or a
964 /// wide string literal.
965 FK_ArrayNeedsInitListOrWideStringLiteral,
967 /// Initializing a wide char array with narrow string literal.
968 FK_NarrowStringIntoWideCharArray,
970 /// Initializing char array with wide string literal.
971 FK_WideStringIntoCharArray,
973 /// Initializing wide char array with incompatible wide string
975 FK_IncompatWideStringIntoWideChar,
977 /// Initializing char8_t array with plain string literal.
978 FK_PlainStringIntoUTF8Char,
980 /// Initializing char array with UTF-8 string literal.
981 FK_UTF8StringIntoPlainChar,
983 /// Array type mismatch.
984 FK_ArrayTypeMismatch,
986 /// Non-constant array initializer
987 FK_NonConstantArrayInit,
989 /// Cannot resolve the address of an overloaded function.
990 FK_AddressOfOverloadFailed,
992 /// Overloading due to reference initialization failed.
993 FK_ReferenceInitOverloadFailed,
995 /// Non-const lvalue reference binding to a temporary.
996 FK_NonConstLValueReferenceBindingToTemporary,
998 /// Non-const lvalue reference binding to a bit-field.
999 FK_NonConstLValueReferenceBindingToBitfield,
1001 /// Non-const lvalue reference binding to a vector element.
1002 FK_NonConstLValueReferenceBindingToVectorElement,
1004 /// Non-const lvalue reference binding to an lvalue of unrelated
1006 FK_NonConstLValueReferenceBindingToUnrelated,
1008 /// Rvalue reference binding to an lvalue.
1009 FK_RValueReferenceBindingToLValue,
1011 /// Reference binding drops qualifiers.
1012 FK_ReferenceInitDropsQualifiers,
1014 /// Reference binding failed.
1015 FK_ReferenceInitFailed,
1017 /// Implicit conversion failed.
1018 FK_ConversionFailed,
1020 /// Implicit conversion failed.
1021 FK_ConversionFromPropertyFailed,
1023 /// Too many initializers for scalar
1024 FK_TooManyInitsForScalar,
1026 /// Scalar initialized from a parenthesized initializer list.
1027 FK_ParenthesizedListInitForScalar,
1029 /// Reference initialization from an initializer list
1030 FK_ReferenceBindingToInitList,
1032 /// Initialization of some unused destination type with an
1033 /// initializer list.
1034 FK_InitListBadDestinationType,
1036 /// Overloading for a user-defined conversion failed.
1037 FK_UserConversionOverloadFailed,
1039 /// Overloading for initialization by constructor failed.
1040 FK_ConstructorOverloadFailed,
1042 /// Overloading for list-initialization by constructor failed.
1043 FK_ListConstructorOverloadFailed,
1045 /// Default-initialization of a 'const' object.
1046 FK_DefaultInitOfConst,
1048 /// Initialization of an incomplete type.
1051 /// Variable-length array must not have an initializer.
1052 FK_VariableLengthArrayHasInitializer,
1054 /// List initialization failed at some point.
1055 FK_ListInitializationFailed,
1057 /// Initializer has a placeholder type which cannot be
1058 /// resolved by initialization.
1061 /// Trying to take the address of a function that doesn't support
1062 /// having its address taken.
1063 FK_AddressOfUnaddressableFunction,
1065 /// List-copy-initialization chose an explicit constructor.
1066 FK_ExplicitConstructor,
1070 /// The reason why initialization failed.
1071 FailureKind Failure;
1073 /// The failed result of overload resolution.
1074 OverloadingResult FailedOverloadResult;
1076 /// The candidate set created when initialization failed.
1077 OverloadCandidateSet FailedCandidateSet;
1079 /// The incomplete type that caused a failure.
1080 QualType FailedIncompleteType;
1082 /// The fixit that needs to be applied to make this initialization
1084 std::string ZeroInitializationFixit;
1085 SourceLocation ZeroInitializationFixitLoc;
1088 /// Call for initializations are invalid but that would be valid
1089 /// zero initialzations if Fixit was applied.
1090 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
1091 ZeroInitializationFixit = Fixit;
1092 ZeroInitializationFixitLoc = L;
1096 /// Prints a follow-up note that highlights the location of
1097 /// the initialized entity, if it's remote.
1098 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
1101 /// Try to perform initialization of the given entity, creating a
1102 /// record of the steps required to perform the initialization.
1104 /// The generated initialization sequence will either contain enough
1105 /// information to diagnose
1107 /// \param S the semantic analysis object.
1109 /// \param Entity the entity being initialized.
1111 /// \param Kind the kind of initialization being performed.
1113 /// \param Args the argument(s) provided for initialization.
1115 /// \param TopLevelOfInitList true if we are initializing from an expression
1116 /// at the top level inside an initializer list. This disallows
1117 /// narrowing conversions in C++11 onwards.
1118 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
1120 InitializationSequence(Sema &S,
1121 const InitializedEntity &Entity,
1122 const InitializationKind &Kind,
1124 bool TopLevelOfInitList = false,
1125 bool TreatUnavailableAsInvalid = true);
1126 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
1127 const InitializationKind &Kind, MultiExprArg Args,
1128 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
1130 ~InitializationSequence();
1132 /// Perform the actual initialization of the given entity based on
1133 /// the computed initialization sequence.
1135 /// \param S the semantic analysis object.
1137 /// \param Entity the entity being initialized.
1139 /// \param Kind the kind of initialization being performed.
1141 /// \param Args the argument(s) provided for initialization, ownership of
1142 /// which is transferred into the routine.
1144 /// \param ResultType if non-NULL, will be set to the type of the
1145 /// initialized object, which is the type of the declaration in most
1146 /// cases. However, when the initialized object is a variable of
1147 /// incomplete array type and the initializer is an initializer
1148 /// list, this type will be set to the completed array type.
1150 /// \returns an expression that performs the actual object initialization, if
1151 /// the initialization is well-formed. Otherwise, emits diagnostics
1152 /// and returns an invalid expression.
1153 ExprResult Perform(Sema &S,
1154 const InitializedEntity &Entity,
1155 const InitializationKind &Kind,
1157 QualType *ResultType = nullptr);
1159 /// Diagnose an potentially-invalid initialization sequence.
1161 /// \returns true if the initialization sequence was ill-formed,
1162 /// false otherwise.
1163 bool Diagnose(Sema &S,
1164 const InitializedEntity &Entity,
1165 const InitializationKind &Kind,
1166 ArrayRef<Expr *> Args);
1168 /// Determine the kind of initialization sequence computed.
1169 enum SequenceKind getKind() const { return SequenceKind; }
1171 /// Set the kind of sequence computed.
1172 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
1174 /// Determine whether the initialization sequence is valid.
1175 explicit operator bool() const { return !Failed(); }
1177 /// Determine whether the initialization sequence is invalid.
1178 bool Failed() const { return SequenceKind == FailedSequence; }
1180 using step_iterator = SmallVectorImpl<Step>::const_iterator;
1182 step_iterator step_begin() const { return Steps.begin(); }
1183 step_iterator step_end() const { return Steps.end(); }
1185 using step_range = llvm::iterator_range<step_iterator>;
1187 step_range steps() const { return {step_begin(), step_end()}; }
1189 /// Determine whether this initialization is a direct reference
1190 /// binding (C++ [dcl.init.ref]).
1191 bool isDirectReferenceBinding() const;
1193 /// Determine whether this initialization failed due to an ambiguity.
1194 bool isAmbiguous() const;
1196 /// Determine whether this initialization is direct call to a
1198 bool isConstructorInitialization() const;
1200 /// Returns whether the last step in this initialization sequence is a
1201 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
1203 /// If this function returns true, *isInitializerConstant will be set to
1204 /// describe whether *Initializer was a constant expression. If
1205 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
1206 /// evaluated value of *Initializer.
1207 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
1208 bool *isInitializerConstant,
1209 APValue *ConstantValue) const;
1211 /// Add a new step in the initialization that resolves the address
1212 /// of an overloaded function to a specific function declaration.
1214 /// \param Function the function to which the overloaded function reference
1216 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
1217 DeclAccessPair Found,
1218 bool HadMultipleCandidates);
1220 /// Add a new step in the initialization that performs a derived-to-
1223 /// \param BaseType the base type to which we will be casting.
1225 /// \param Category Indicates whether the result will be treated as an
1226 /// rvalue, an xvalue, or an lvalue.
1227 void AddDerivedToBaseCastStep(QualType BaseType,
1228 ExprValueKind Category);
1230 /// Add a new step binding a reference to an object.
1232 /// \param BindingTemporary True if we are binding a reference to a temporary
1233 /// object (thereby extending its lifetime); false if we are binding to an
1234 /// lvalue or an lvalue treated as an rvalue.
1235 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1237 /// Add a new step that makes an extraneous copy of the input
1238 /// to a temporary of the same class type.
1240 /// This extraneous copy only occurs during reference binding in
1241 /// C++98/03, where we are permitted (but not required) to introduce
1242 /// an extra copy. At a bare minimum, we must check that we could
1243 /// call the copy constructor, and produce a diagnostic if the copy
1244 /// constructor is inaccessible or no copy constructor matches.
1246 /// \param T The type of the temporary being created.
1247 void AddExtraneousCopyToTemporary(QualType T);
1249 /// Add a new step that makes a copy of the input to an object of
1250 /// the given type, as the final step in class copy-initialization.
1251 void AddFinalCopy(QualType T);
1253 /// Add a new step invoking a conversion function, which is either
1254 /// a constructor or a conversion function.
1255 void AddUserConversionStep(FunctionDecl *Function,
1256 DeclAccessPair FoundDecl,
1258 bool HadMultipleCandidates);
1260 /// Add a new step that performs a qualification conversion to the
1262 void AddQualificationConversionStep(QualType Ty,
1263 ExprValueKind Category);
1265 /// Add a new step that performs conversion from non-atomic to atomic
1267 void AddAtomicConversionStep(QualType Ty);
1269 /// Add a new step that performs a load of the given type.
1271 /// Although the term "LValueToRValue" is conventional, this applies to both
1272 /// lvalues and xvalues.
1273 void AddLValueToRValueStep(QualType Ty);
1275 /// Add a new step that applies an implicit conversion sequence.
1276 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1277 QualType T, bool TopLevelOfInitList = false);
1279 /// Add a list-initialization step.
1280 void AddListInitializationStep(QualType T);
1282 /// Add a constructor-initialization step.
1284 /// \param FromInitList The constructor call is syntactically an initializer
1286 /// \param AsInitList The constructor is called as an init list constructor.
1287 void AddConstructorInitializationStep(DeclAccessPair FoundDecl,
1288 CXXConstructorDecl *Constructor,
1290 bool HadMultipleCandidates,
1291 bool FromInitList, bool AsInitList);
1293 /// Add a zero-initialization step.
1294 void AddZeroInitializationStep(QualType T);
1296 /// Add a C assignment step.
1298 // FIXME: It isn't clear whether this should ever be needed;
1299 // ideally, we would handle everything needed in C in the common
1300 // path. However, that isn't the case yet.
1301 void AddCAssignmentStep(QualType T);
1303 /// Add a string init step.
1304 void AddStringInitStep(QualType T);
1306 /// Add an Objective-C object conversion step, which is
1308 void AddObjCObjectConversionStep(QualType T);
1310 /// Add an array initialization loop step.
1311 void AddArrayInitLoopStep(QualType T, QualType EltTy);
1313 /// Add an array initialization step.
1314 void AddArrayInitStep(QualType T, bool IsGNUExtension);
1316 /// Add a parenthesized array initialization step.
1317 void AddParenthesizedArrayInitStep(QualType T);
1319 /// Add a step to pass an object by indirect copy-restore.
1320 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1322 /// Add a step to "produce" an Objective-C object (by
1324 void AddProduceObjCObjectStep(QualType T);
1326 /// Add a step to construct a std::initializer_list object from an
1327 /// initializer list.
1328 void AddStdInitializerListConstructionStep(QualType T);
1330 /// Add a step to initialize an OpenCL sampler from an integer
1332 void AddOCLSamplerInitStep(QualType T);
1334 /// Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.)
1335 /// from a zero constant.
1336 void AddOCLZeroOpaqueTypeStep(QualType T);
1338 /// Add a step to initialize by zero types defined in the
1339 /// cl_intel_device_side_avc_motion_estimation OpenCL extension
1340 void AddOCLIntelSubgroupAVCZeroInitStep(QualType T);
1342 /// Add steps to unwrap a initializer list for a reference around a
1343 /// single element and rewrap it at the end.
1344 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1346 /// Note that this initialization sequence failed.
1347 void SetFailed(FailureKind Failure) {
1348 SequenceKind = FailedSequence;
1349 this->Failure = Failure;
1350 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1351 "Incomplete type failure requires a type!");
1354 /// Note that this initialization sequence failed due to failed
1355 /// overload resolution.
1356 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1358 /// Retrieve a reference to the candidate set when overload
1359 /// resolution fails.
1360 OverloadCandidateSet &getFailedCandidateSet() {
1361 return FailedCandidateSet;
1364 /// Get the overloading result, for when the initialization
1365 /// sequence failed due to a bad overload.
1366 OverloadingResult getFailedOverloadResult() const {
1367 return FailedOverloadResult;
1370 /// Note that this initialization sequence failed due to an
1371 /// incomplete type.
1372 void setIncompleteTypeFailure(QualType IncompleteType) {
1373 FailedIncompleteType = IncompleteType;
1374 SetFailed(FK_Incomplete);
1377 /// Determine why initialization failed.
1378 FailureKind getFailureKind() const {
1379 assert(Failed() && "Not an initialization failure!");
1383 /// Dump a representation of this initialization sequence to
1384 /// the given stream, for debugging purposes.
1385 void dump(raw_ostream &OS) const;
1387 /// Dump a representation of this initialization sequence to
1388 /// standard error, for debugging purposes.
1392 } // namespace clang
1394 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H