1 //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides supporting data types for initialization of objects.
12 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
14 #define LLVM_CLANG_SEMA_INITIALIZATION_H
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Type.h"
19 #include "clang/AST/UnresolvedSet.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Sema/Overload.h"
22 #include "clang/Sema/Ownership.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallVector.h"
29 class CXXBaseSpecifier;
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
85 /// \brief The kind of entity being initialized.
88 /// \brief If non-NULL, the parent entity in which this
89 /// initialization occurs.
90 const InitializedEntity *Parent;
92 /// \brief The type of the object or reference being initialized.
96 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
97 /// location of the 'return', 'throw', or 'new' keyword,
98 /// respectively. When Kind == EK_Temporary, the location where
99 /// the temporary is being created.
102 /// \brief Whether the entity being initialized may end up using the
103 /// named return value optimization (NRVO).
108 /// \brief The variable being captured by an EK_LambdaCapture.
111 /// \brief The source location at which the capture occurs.
116 /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
117 /// FieldDecl, respectively.
118 DeclaratorDecl *VariableOrMember;
120 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
121 /// low bit indicating whether the parameter is "consumed".
124 /// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
125 /// source information for the temporary.
126 TypeSourceInfo *TypeInfo;
128 struct LN LocAndNRVO;
130 /// \brief When Kind == EK_Base, the base specifier that provides the
131 /// base class. The lower bit specifies whether the base is an inherited
135 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
136 /// EK_ComplexElement, the index of the array or vector element being
143 InitializedEntity() { }
145 /// \brief Create the initialization entity for a variable.
146 InitializedEntity(VarDecl *Var)
147 : Kind(EK_Variable), Parent(0), Type(Var->getType()),
148 VariableOrMember(Var) { }
150 /// \brief Create the initialization entity for the result of a
151 /// function, throwing an object, performing an explicit cast, or
152 /// initializing a parameter for which there is no declaration.
153 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
155 : Kind(Kind), Parent(0), Type(Type)
157 LocAndNRVO.Location = Loc.getRawEncoding();
158 LocAndNRVO.NRVO = NRVO;
161 /// \brief Create the initialization entity for a member subobject.
162 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent)
163 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
164 VariableOrMember(Member) { }
166 /// \brief Create the initialization entity for an array element.
167 InitializedEntity(ASTContext &Context, unsigned Index,
168 const InitializedEntity &Parent);
170 /// \brief Create the initialization entity for a lambda capture.
171 InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
172 : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType())
175 Capture.Location = Loc.getRawEncoding();
179 /// \brief Create the initialization entity for a variable.
180 static InitializedEntity InitializeVariable(VarDecl *Var) {
181 return InitializedEntity(Var);
184 /// \brief Create the initialization entity for a parameter.
185 static InitializedEntity InitializeParameter(ASTContext &Context,
187 return InitializeParameter(Context, Parm, Parm->getType());
190 /// \brief Create the initialization entity for a parameter, but use
192 static InitializedEntity InitializeParameter(ASTContext &Context,
195 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
196 Parm->hasAttr<NSConsumedAttr>());
198 InitializedEntity Entity;
199 Entity.Kind = EK_Parameter;
201 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
204 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
208 /// \brief Create the initialization entity for a parameter that is
209 /// only known by its type.
210 static InitializedEntity InitializeParameter(ASTContext &Context,
213 InitializedEntity Entity;
214 Entity.Kind = EK_Parameter;
215 Entity.Type = Context.getVariableArrayDecayedType(Type);
217 Entity.Parameter = (Consumed);
221 /// \brief Create the initialization entity for the result of a function.
222 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
223 QualType Type, bool NRVO) {
224 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
227 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
228 QualType Type, bool NRVO) {
229 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
232 /// \brief Create the initialization entity for an exception object.
233 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
234 QualType Type, bool NRVO) {
235 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
238 /// \brief Create the initialization entity for an object allocated via new.
239 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
240 return InitializedEntity(EK_New, NewLoc, Type);
243 /// \brief Create the initialization entity for a temporary.
244 static InitializedEntity InitializeTemporary(QualType Type) {
245 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
250 /// \brief Create the initialization entity for a temporary.
251 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
252 InitializedEntity Result(EK_Temporary, SourceLocation(),
253 TypeInfo->getType());
254 Result.TypeInfo = TypeInfo;
258 /// \brief Create the initialization entity for a base class subobject.
259 static InitializedEntity InitializeBase(ASTContext &Context,
260 CXXBaseSpecifier *Base,
261 bool IsInheritedVirtualBase);
263 /// \brief Create the initialization entity for a delegated constructor.
264 static InitializedEntity InitializeDelegation(QualType Type) {
265 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
268 /// \brief Create the initialization entity for a member subobject.
269 static InitializedEntity InitializeMember(FieldDecl *Member,
270 const InitializedEntity *Parent = 0) {
271 return InitializedEntity(Member, Parent);
274 /// \brief Create the initialization entity for a member subobject.
275 static InitializedEntity InitializeMember(IndirectFieldDecl *Member,
276 const InitializedEntity *Parent = 0) {
277 return InitializedEntity(Member->getAnonField(), Parent);
280 /// \brief Create the initialization entity for an array element.
281 static InitializedEntity InitializeElement(ASTContext &Context,
283 const InitializedEntity &Parent) {
284 return InitializedEntity(Context, Index, Parent);
287 /// \brief Create the initialization entity for a lambda capture.
288 static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
290 SourceLocation Loc) {
291 return InitializedEntity(Var, Field, Loc);
294 /// \brief Create the entity for a compound literal initializer.
295 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
296 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
298 Result.TypeInfo = TSI;
303 /// \brief Determine the kind of initialization.
304 EntityKind getKind() const { return Kind; }
306 /// \brief Retrieve the parent of the entity being initialized, when
307 /// the initialization itself is occurring within the context of a
308 /// larger initialization.
309 const InitializedEntity *getParent() const { return Parent; }
311 /// \brief Retrieve type being initialized.
312 QualType getType() const { return Type; }
314 /// \brief Retrieve complete type-source information for the object being
315 /// constructed, if known.
316 TypeSourceInfo *getTypeSourceInfo() const {
317 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
323 /// \brief Retrieve the name of the entity being initialized.
324 DeclarationName getName() const;
326 /// \brief Retrieve the variable, parameter, or field being
328 DeclaratorDecl *getDecl() const;
330 /// \brief Determine whether this initialization allows the named return
331 /// value optimization, which also applies to thrown objects.
332 bool allowsNRVO() const;
334 /// \brief Determine whether this initialization consumes the
336 bool isParameterConsumed() const {
337 assert(getKind() == EK_Parameter && "Not a parameter");
338 return (Parameter & 1);
341 /// \brief Retrieve the base specifier.
342 CXXBaseSpecifier *getBaseSpecifier() const {
343 assert(getKind() == EK_Base && "Not a base specifier");
344 return reinterpret_cast<CXXBaseSpecifier *>(Base & ~0x1);
347 /// \brief Return whether the base is an inherited virtual base.
348 bool isInheritedVirtualBase() const {
349 assert(getKind() == EK_Base && "Not a base specifier");
353 /// \brief Determine the location of the 'return' keyword when initializing
354 /// the result of a function call.
355 SourceLocation getReturnLoc() const {
356 assert(getKind() == EK_Result && "No 'return' location!");
357 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
360 /// \brief Determine the location of the 'throw' keyword when initializing
361 /// an exception object.
362 SourceLocation getThrowLoc() const {
363 assert(getKind() == EK_Exception && "No 'throw' location!");
364 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
367 /// \brief If this is already the initializer for an array or vector
368 /// element, sets the element index.
369 void setElementIndex(unsigned Index) {
370 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
371 getKind() == EK_ComplexElement);
375 /// \brief Retrieve the variable for a captured variable in a lambda.
376 VarDecl *getCapturedVar() const {
377 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
381 /// \brief Determine the location of the capture when initializing
382 /// field from a captured variable in a lambda.
383 SourceLocation getCaptureLoc() const {
384 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
385 return SourceLocation::getFromRawEncoding(Capture.Location);
389 /// \brief Describes the kind of initialization being performed, along with
390 /// location information for tokens related to the initialization (equal sign,
392 class InitializationKind {
394 /// \brief The kind of initialization being performed.
396 IK_Direct, ///< Direct initialization
397 IK_DirectList, ///< Direct list-initialization
398 IK_Copy, ///< Copy initialization
399 IK_Default, ///< Default initialization
400 IK_Value ///< Value initialization
404 /// \brief The context of the initialization.
406 IC_Normal, ///< Normal context
407 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
408 IC_Implicit, ///< Implicit context (value initialization)
409 IC_StaticCast, ///< Static cast context
410 IC_CStyleCast, ///< C-style cast context
411 IC_FunctionalCast ///< Functional cast context
414 /// \brief The kind of initialization being performed.
417 /// \brief The context of the initialization.
418 InitContext Context : 8;
420 /// \brief The source locations involved in the initialization.
421 SourceLocation Locations[3];
423 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
424 SourceLocation Loc2, SourceLocation Loc3)
425 : Kind(Kind), Context(Context)
433 /// \brief Create a direct initialization.
434 static InitializationKind CreateDirect(SourceLocation InitLoc,
435 SourceLocation LParenLoc,
436 SourceLocation RParenLoc) {
437 return InitializationKind(IK_Direct, IC_Normal,
438 InitLoc, LParenLoc, RParenLoc);
441 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
442 return InitializationKind(IK_DirectList, IC_Normal,
443 InitLoc, InitLoc, InitLoc);
446 /// \brief Create a direct initialization due to a cast that isn't a C-style
447 /// or functional cast.
448 static InitializationKind CreateCast(SourceRange TypeRange) {
449 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
450 TypeRange.getBegin(), TypeRange.getEnd());
453 /// \brief Create a direct initialization for a C-style cast.
454 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
455 SourceRange TypeRange,
457 // C++ cast syntax doesn't permit init lists, but C compound literals are
459 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
460 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
464 /// \brief Create a direct initialization for a functional cast.
465 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
467 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
468 IC_FunctionalCast, TypeRange.getBegin(),
469 TypeRange.getBegin(), TypeRange.getEnd());
472 /// \brief Create a copy initialization.
473 static InitializationKind CreateCopy(SourceLocation InitLoc,
474 SourceLocation EqualLoc,
475 bool AllowExplicitConvs = false) {
476 return InitializationKind(IK_Copy,
477 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
478 InitLoc, EqualLoc, EqualLoc);
481 /// \brief Create a default initialization.
482 static InitializationKind CreateDefault(SourceLocation InitLoc) {
483 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
486 /// \brief Create a value initialization.
487 static InitializationKind CreateValue(SourceLocation InitLoc,
488 SourceLocation LParenLoc,
489 SourceLocation RParenLoc,
490 bool isImplicit = false) {
491 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
492 InitLoc, LParenLoc, RParenLoc);
495 /// \brief Determine the initialization kind.
496 InitKind getKind() const {
500 /// \brief Determine whether this initialization is an explicit cast.
501 bool isExplicitCast() const {
502 return Context >= IC_StaticCast;
505 /// \brief Determine whether this initialization is a C-style cast.
506 bool isCStyleOrFunctionalCast() const {
507 return Context >= IC_CStyleCast;
510 /// \brief Determine whether this is a C-style cast.
511 bool isCStyleCast() const {
512 return Context == IC_CStyleCast;
515 /// \brief Determine whether this is a functional-style cast.
516 bool isFunctionalCast() const {
517 return Context == IC_FunctionalCast;
520 /// \brief Determine whether this initialization is an implicit
521 /// value-initialization, e.g., as occurs during aggregate
523 bool isImplicitValueInit() const { return Context == IC_Implicit; }
525 /// \brief Retrieve the location at which initialization is occurring.
526 SourceLocation getLocation() const { return Locations[0]; }
528 /// \brief Retrieve the source range that covers the initialization.
529 SourceRange getRange() const {
530 return SourceRange(Locations[0], Locations[2]);
533 /// \brief Retrieve the location of the equal sign for copy initialization
535 SourceLocation getEqualLoc() const {
536 assert(Kind == IK_Copy && "Only copy initialization has an '='");
540 bool isCopyInit() const { return Kind == IK_Copy; }
542 /// \brief Retrieve whether this initialization allows the use of explicit
544 bool AllowExplicit() const { return !isCopyInit(); }
546 /// \brief Retrieve whether this initialization allows the use of explicit
547 /// conversion functions.
548 bool allowExplicitConversionFunctions() const {
549 return !isCopyInit() || Context == IC_ExplicitConvs;
552 /// \brief Retrieve the source range containing the locations of the open
553 /// and closing parentheses for value and direct initializations.
554 SourceRange getParenRange() const {
555 assert((Kind == IK_Direct || Kind == IK_Value) &&
556 "Only direct- and value-initialization have parentheses");
557 return SourceRange(Locations[1], Locations[2]);
561 /// \brief Describes the sequence of initializations required to initialize
562 /// a given object or reference with a set of arguments.
563 class InitializationSequence {
565 /// \brief Describes the kind of initialization sequence computed.
567 /// \brief A failed initialization sequence. The failure kind tells what
571 /// \brief A dependent initialization, which could not be
572 /// type-checked due to the presence of dependent types or
573 /// dependently-typed expressions.
576 /// \brief A normal sequence.
580 /// \brief Describes the kind of a particular step in an initialization
583 /// \brief Resolve the address of an overloaded function to a specific
584 /// function declaration.
585 SK_ResolveAddressOfOverloadedFunction,
586 /// \brief Perform a derived-to-base cast, producing an rvalue.
587 SK_CastDerivedToBaseRValue,
588 /// \brief Perform a derived-to-base cast, producing an xvalue.
589 SK_CastDerivedToBaseXValue,
590 /// \brief Perform a derived-to-base cast, producing an lvalue.
591 SK_CastDerivedToBaseLValue,
592 /// \brief Reference binding to an lvalue.
594 /// \brief Reference binding to a temporary.
595 SK_BindReferenceToTemporary,
596 /// \brief An optional copy of a temporary object to another
597 /// temporary object, which is permitted (but not required) by
598 /// C++98/03 but not C++0x.
599 SK_ExtraneousCopyToTemporary,
600 /// \brief Perform a user-defined conversion, either via a conversion
601 /// function or via a constructor.
603 /// \brief Perform a qualification conversion, producing an rvalue.
604 SK_QualificationConversionRValue,
605 /// \brief Perform a qualification conversion, producing an xvalue.
606 SK_QualificationConversionXValue,
607 /// \brief Perform a qualification conversion, producing an lvalue.
608 SK_QualificationConversionLValue,
609 /// \brief Perform a load from a glvalue, producing an rvalue.
611 /// \brief Perform an implicit conversion sequence.
612 SK_ConversionSequence,
613 /// \brief Perform list-initialization without a constructor
614 SK_ListInitialization,
615 /// \brief Perform list-initialization with a constructor.
616 SK_ListConstructorCall,
617 /// \brief Unwrap the single-element initializer list for a reference.
619 /// \brief Rewrap the single-element initializer list for a reference.
621 /// \brief Perform initialization via a constructor.
622 SK_ConstructorInitialization,
623 /// \brief Zero-initialize the object
624 SK_ZeroInitialization,
625 /// \brief C assignment
627 /// \brief Initialization by string
629 /// \brief An initialization that "converts" an Objective-C object
630 /// (not a point to an object) to another Objective-C object type.
631 SK_ObjCObjectConversion,
632 /// \brief Array initialization (from an array rvalue).
633 /// This is a GNU C extension.
635 /// \brief Array initialization from a parenthesized initializer list.
636 /// This is a GNU C++ extension.
637 SK_ParenthesizedArrayInit,
638 /// \brief Pass an object by indirect copy-and-restore.
639 SK_PassByIndirectCopyRestore,
640 /// \brief Pass an object by indirect restore.
641 SK_PassByIndirectRestore,
642 /// \brief Produce an Objective-C object pointer.
643 SK_ProduceObjCObject,
644 /// \brief Construct a std::initializer_list from an initializer list.
645 SK_StdInitializerList,
646 /// \brief Initialize an OpenCL sampler from an integer.
648 /// \brief Passing zero to a function where OpenCL event_t is expected.
652 /// \brief A single step in the initialization sequence.
655 /// \brief The kind of conversion or initialization step we are taking.
658 // \brief The type that results from this initialization.
662 bool HadMultipleCandidates;
663 FunctionDecl *Function;
664 DeclAccessPair FoundDecl;
668 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
669 /// SK_UserConversion, the function that the expression should be
670 /// resolved to or the conversion function to call, respectively.
671 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
672 /// the constructor to be called.
674 /// Always a FunctionDecl, plus a Boolean flag telling if it was
675 /// selected from an overloaded set having size greater than 1.
676 /// For conversion decls, the naming class is the source type.
677 /// For construct decls, the naming class is the target type.
680 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
682 ImplicitConversionSequence *ICS;
684 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
686 InitListExpr *WrappingSyntacticList;
693 /// \brief The kind of initialization sequence computed.
694 enum SequenceKind SequenceKind;
696 /// \brief Steps taken by this initialization.
697 SmallVector<Step, 4> Steps;
700 /// \brief Describes why initialization failed.
702 /// \brief Too many initializers provided for a reference.
703 FK_TooManyInitsForReference,
704 /// \brief Array must be initialized with an initializer list.
705 FK_ArrayNeedsInitList,
706 /// \brief Array must be initialized with an initializer list or a
708 FK_ArrayNeedsInitListOrStringLiteral,
709 /// \brief Array type mismatch.
710 FK_ArrayTypeMismatch,
711 /// \brief Non-constant array initializer
712 FK_NonConstantArrayInit,
713 /// \brief Cannot resolve the address of an overloaded function.
714 FK_AddressOfOverloadFailed,
715 /// \brief Overloading due to reference initialization failed.
716 FK_ReferenceInitOverloadFailed,
717 /// \brief Non-const lvalue reference binding to a temporary.
718 FK_NonConstLValueReferenceBindingToTemporary,
719 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
721 FK_NonConstLValueReferenceBindingToUnrelated,
722 /// \brief Rvalue reference binding to an lvalue.
723 FK_RValueReferenceBindingToLValue,
724 /// \brief Reference binding drops qualifiers.
725 FK_ReferenceInitDropsQualifiers,
726 /// \brief Reference binding failed.
727 FK_ReferenceInitFailed,
728 /// \brief Implicit conversion failed.
730 /// \brief Implicit conversion failed.
731 FK_ConversionFromPropertyFailed,
732 /// \brief Too many initializers for scalar
733 FK_TooManyInitsForScalar,
734 /// \brief Reference initialization from an initializer list
735 FK_ReferenceBindingToInitList,
736 /// \brief Initialization of some unused destination type with an
737 /// initializer list.
738 FK_InitListBadDestinationType,
739 /// \brief Overloading for a user-defined conversion failed.
740 FK_UserConversionOverloadFailed,
741 /// \brief Overloading for initialization by constructor failed.
742 FK_ConstructorOverloadFailed,
743 /// \brief Overloading for list-initialization by constructor failed.
744 FK_ListConstructorOverloadFailed,
745 /// \brief Default-initialization of a 'const' object.
746 FK_DefaultInitOfConst,
747 /// \brief Initialization of an incomplete type.
749 /// \brief Variable-length array must not have an initializer.
750 FK_VariableLengthArrayHasInitializer,
751 /// \brief List initialization failed at some point.
752 FK_ListInitializationFailed,
753 /// \brief Initializer has a placeholder type which cannot be
754 /// resolved by initialization.
756 /// \brief Failed to initialize a std::initializer_list because copy
757 /// construction of some element failed.
758 FK_InitListElementCopyFailure,
759 /// \brief List-copy-initialization chose an explicit constructor.
760 FK_ExplicitConstructor
764 /// \brief The reason why initialization failed.
767 /// \brief The failed result of overload resolution.
768 OverloadingResult FailedOverloadResult;
770 /// \brief The candidate set created when initialization failed.
771 OverloadCandidateSet FailedCandidateSet;
773 /// \brief The incomplete type that caused a failure.
774 QualType FailedIncompleteType;
776 /// \brief Prints a follow-up note that highlights the location of
777 /// the initialized entity, if it's remote.
778 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
781 /// \brief Try to perform initialization of the given entity, creating a
782 /// record of the steps required to perform the initialization.
784 /// The generated initialization sequence will either contain enough
785 /// information to diagnose
787 /// \param S the semantic analysis object.
789 /// \param Entity the entity being initialized.
791 /// \param Kind the kind of initialization being performed.
793 /// \param Args the argument(s) provided for initialization.
794 InitializationSequence(Sema &S,
795 const InitializedEntity &Entity,
796 const InitializationKind &Kind,
799 ~InitializationSequence();
801 /// \brief Perform the actual initialization of the given entity based on
802 /// the computed initialization sequence.
804 /// \param S the semantic analysis object.
806 /// \param Entity the entity being initialized.
808 /// \param Kind the kind of initialization being performed.
810 /// \param Args the argument(s) provided for initialization, ownership of
811 /// which is transferred into the routine.
813 /// \param ResultType if non-NULL, will be set to the type of the
814 /// initialized object, which is the type of the declaration in most
815 /// cases. However, when the initialized object is a variable of
816 /// incomplete array type and the initializer is an initializer
817 /// list, this type will be set to the completed array type.
819 /// \returns an expression that performs the actual object initialization, if
820 /// the initialization is well-formed. Otherwise, emits diagnostics
821 /// and returns an invalid expression.
822 ExprResult Perform(Sema &S,
823 const InitializedEntity &Entity,
824 const InitializationKind &Kind,
826 QualType *ResultType = 0);
828 /// \brief Diagnose an potentially-invalid initialization sequence.
830 /// \returns true if the initialization sequence was ill-formed,
832 bool Diagnose(Sema &S,
833 const InitializedEntity &Entity,
834 const InitializationKind &Kind,
835 ArrayRef<Expr *> Args);
837 /// \brief Determine the kind of initialization sequence computed.
838 enum SequenceKind getKind() const { return SequenceKind; }
840 /// \brief Set the kind of sequence computed.
841 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
843 /// \brief Determine whether the initialization sequence is valid.
844 operator bool() const { return !Failed(); }
846 /// \brief Determine whether the initialization sequence is invalid.
847 bool Failed() const { return SequenceKind == FailedSequence; }
849 typedef SmallVector<Step, 4>::const_iterator step_iterator;
850 step_iterator step_begin() const { return Steps.begin(); }
851 step_iterator step_end() const { return Steps.end(); }
853 /// \brief Determine whether this initialization is a direct reference
854 /// binding (C++ [dcl.init.ref]).
855 bool isDirectReferenceBinding() const;
857 /// \brief Determine whether this initialization failed due to an ambiguity.
858 bool isAmbiguous() const;
860 /// \brief Determine whether this initialization is direct call to a
862 bool isConstructorInitialization() const;
864 /// \brief Returns whether the last step in this initialization sequence is a
865 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
867 /// If this function returns true, *isInitializerConstant will be set to
868 /// describe whether *Initializer was a constant expression. If
869 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
870 /// evaluated value of *Initializer.
871 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
872 bool *isInitializerConstant,
873 APValue *ConstantValue) const;
875 /// \brief Add a new step in the initialization that resolves the address
876 /// of an overloaded function to a specific function declaration.
878 /// \param Function the function to which the overloaded function reference
880 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
881 DeclAccessPair Found,
882 bool HadMultipleCandidates);
884 /// \brief Add a new step in the initialization that performs a derived-to-
887 /// \param BaseType the base type to which we will be casting.
889 /// \param Category Indicates whether the result will be treated as an
890 /// rvalue, an xvalue, or an lvalue.
891 void AddDerivedToBaseCastStep(QualType BaseType,
892 ExprValueKind Category);
894 /// \brief Add a new step binding a reference to an object.
896 /// \param BindingTemporary True if we are binding a reference to a temporary
897 /// object (thereby extending its lifetime); false if we are binding to an
898 /// lvalue or an lvalue treated as an rvalue.
899 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
901 /// \brief Add a new step that makes an extraneous copy of the input
902 /// to a temporary of the same class type.
904 /// This extraneous copy only occurs during reference binding in
905 /// C++98/03, where we are permitted (but not required) to introduce
906 /// an extra copy. At a bare minimum, we must check that we could
907 /// call the copy constructor, and produce a diagnostic if the copy
908 /// constructor is inaccessible or no copy constructor matches.
910 /// \param T The type of the temporary being created.
911 void AddExtraneousCopyToTemporary(QualType T);
913 /// \brief Add a new step invoking a conversion function, which is either
914 /// a constructor or a conversion function.
915 void AddUserConversionStep(FunctionDecl *Function,
916 DeclAccessPair FoundDecl,
918 bool HadMultipleCandidates);
920 /// \brief Add a new step that performs a qualification conversion to the
922 void AddQualificationConversionStep(QualType Ty,
923 ExprValueKind Category);
925 /// \brief Add a new step that performs a load of the given type.
927 /// Although the term "LValueToRValue" is conventional, this applies to both
928 /// lvalues and xvalues.
929 void AddLValueToRValueStep(QualType Ty);
931 /// \brief Add a new step that applies an implicit conversion sequence.
932 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
935 /// \brief Add a list-initialization step.
936 void AddListInitializationStep(QualType T);
938 /// \brief Add a constructor-initialization step.
940 /// \param FromInitList The constructor call is syntactically an initializer
942 /// \param AsInitList The constructor is called as an init list constructor.
943 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
944 AccessSpecifier Access,
946 bool HadMultipleCandidates,
947 bool FromInitList, bool AsInitList);
949 /// \brief Add a zero-initialization step.
950 void AddZeroInitializationStep(QualType T);
952 /// \brief Add a C assignment step.
954 // FIXME: It isn't clear whether this should ever be needed;
955 // ideally, we would handle everything needed in C in the common
956 // path. However, that isn't the case yet.
957 void AddCAssignmentStep(QualType T);
959 /// \brief Add a string init step.
960 void AddStringInitStep(QualType T);
962 /// \brief Add an Objective-C object conversion step, which is
964 void AddObjCObjectConversionStep(QualType T);
966 /// \brief Add an array initialization step.
967 void AddArrayInitStep(QualType T);
969 /// \brief Add a parenthesized array initialization step.
970 void AddParenthesizedArrayInitStep(QualType T);
972 /// \brief Add a step to pass an object by indirect copy-restore.
973 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
975 /// \brief Add a step to "produce" an Objective-C object (by
977 void AddProduceObjCObjectStep(QualType T);
979 /// \brief Add a step to construct a std::initializer_list object from an
980 /// initializer list.
981 void AddStdInitializerListConstructionStep(QualType T);
983 /// \brief Add a step to initialize an OpenCL sampler from an integer
985 void AddOCLSamplerInitStep(QualType T);
987 /// \brief Add a step to initialize an OpenCL event_t from a NULL
989 void AddOCLZeroEventStep(QualType T);
991 /// \brief Add steps to unwrap a initializer list for a reference around a
992 /// single element and rewrap it at the end.
993 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
995 /// \brief Note that this initialization sequence failed.
996 void SetFailed(FailureKind Failure) {
997 SequenceKind = FailedSequence;
998 this->Failure = Failure;
999 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1000 "Incomplete type failure requires a type!");
1003 /// \brief Note that this initialization sequence failed due to failed
1004 /// overload resolution.
1005 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1007 /// \brief Retrieve a reference to the candidate set when overload
1008 /// resolution fails.
1009 OverloadCandidateSet &getFailedCandidateSet() {
1010 return FailedCandidateSet;
1013 /// \brief Get the overloading result, for when the initialization
1014 /// sequence failed due to a bad overload.
1015 OverloadingResult getFailedOverloadResult() const {
1016 return FailedOverloadResult;
1019 /// \brief Note that this initialization sequence failed due to an
1020 /// incomplete type.
1021 void setIncompleteTypeFailure(QualType IncompleteType) {
1022 FailedIncompleteType = IncompleteType;
1023 SetFailed(FK_Incomplete);
1026 /// \brief Determine why initialization failed.
1027 FailureKind getFailureKind() const {
1028 assert(Failed() && "Not an initialization failure!");
1032 /// \brief Dump a representation of this initialization sequence to
1033 /// the given stream, for debugging purposes.
1034 void dump(raw_ostream &OS) const;
1036 /// \brief Dump a representation of this initialization sequence to
1037 /// standard error, for debugging purposes.
1041 } // end namespace clang
1043 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H