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/Sema/Ownership.h"
17 #include "clang/Sema/Overload.h"
18 #include "clang/AST/Type.h"
19 #include "clang/AST/UnresolvedSet.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/SmallVector.h"
27 class CXXBaseSpecifier;
37 /// \brief Describes an entity that is being initialized.
38 class InitializedEntity {
40 /// \brief Specifies the kind of entity being initialized.
42 /// \brief The entity being initialized is a variable.
44 /// \brief The entity being initialized is a function parameter.
46 /// \brief The entity being initialized is the result of a function call.
48 /// \brief The entity being initialized is an exception object that
51 /// \brief The entity being initialized is a non-static data member
54 /// \brief The entity being initialized is an element of an array.
56 /// \brief The entity being initialized is an object (or array of
57 /// objects) allocated via new.
59 /// \brief The entity being initialized is a temporary object.
61 /// \brief The entity being initialized is a base member subobject.
63 /// \brief The initialization is being done by a delegating constructor.
65 /// \brief The entity being initialized is an element of a vector.
68 /// \brief The entity being initialized is a field of block descriptor for
69 /// the copied-in c++ object.
71 /// \brief The entity being initialized is the real or imaginary part of a
74 /// \brief The entity being initialized is the field that captures a
75 /// variable in a lambda.
80 /// \brief The kind of entity being initialized.
83 /// \brief If non-NULL, the parent entity in which this
84 /// initialization occurs.
85 const InitializedEntity *Parent;
87 /// \brief The type of the object or reference being initialized.
91 /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
92 /// FieldDecl, respectively.
93 DeclaratorDecl *VariableOrMember;
95 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
96 /// low bit indicating whether the parameter is "consumed".
99 /// \brief When Kind == EK_Temporary, the type source information for
101 TypeSourceInfo *TypeInfo;
104 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
105 /// location of the 'return', 'throw', or 'new' keyword,
106 /// respectively. When Kind == EK_Temporary, the location where
107 /// the temporary is being created.
110 /// \brief Whether the entity being initialized may end up using the
111 /// named return value optimization (NRVO).
115 /// \brief When Kind == EK_Base, the base specifier that provides the
116 /// base class. The lower bit specifies whether the base is an inherited
120 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
121 /// EK_ComplexElement, the index of the array or vector element being
126 /// \brief The variable being captured by an EK_LambdaCapture.
129 /// \brief The source location at which the capture occurs.
134 InitializedEntity() { }
136 /// \brief Create the initialization entity for a variable.
137 InitializedEntity(VarDecl *Var)
138 : Kind(EK_Variable), Parent(0), Type(Var->getType()),
139 VariableOrMember(Var) { }
141 /// \brief Create the initialization entity for the result of a
142 /// function, throwing an object, performing an explicit cast, or
143 /// initializing a parameter for which there is no declaration.
144 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
146 : Kind(Kind), Parent(0), Type(Type)
148 LocAndNRVO.Location = Loc.getRawEncoding();
149 LocAndNRVO.NRVO = NRVO;
152 /// \brief Create the initialization entity for a member subobject.
153 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent)
154 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
155 VariableOrMember(Member) { }
157 /// \brief Create the initialization entity for an array element.
158 InitializedEntity(ASTContext &Context, unsigned Index,
159 const InitializedEntity &Parent);
161 /// \brief Create the initialization entity for a lambda capture.
162 InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
163 : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType())
166 Capture.Location = Loc.getRawEncoding();
170 /// \brief Create the initialization entity for a variable.
171 static InitializedEntity InitializeVariable(VarDecl *Var) {
172 return InitializedEntity(Var);
175 /// \brief Create the initialization entity for a parameter.
176 static InitializedEntity InitializeParameter(ASTContext &Context,
178 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
179 Parm->hasAttr<NSConsumedAttr>());
181 InitializedEntity Entity;
182 Entity.Kind = EK_Parameter;
183 Entity.Type = Context.getVariableArrayDecayedType(
184 Parm->getType().getUnqualifiedType());
187 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
191 /// \brief Create the initialization entity for a parameter that is
192 /// only known by its type.
193 static InitializedEntity InitializeParameter(ASTContext &Context,
196 InitializedEntity Entity;
197 Entity.Kind = EK_Parameter;
198 Entity.Type = Context.getVariableArrayDecayedType(Type);
200 Entity.Parameter = (Consumed);
204 /// \brief Create the initialization entity for the result of a function.
205 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
206 QualType Type, bool NRVO) {
207 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
210 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
211 QualType Type, bool NRVO) {
212 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
215 /// \brief Create the initialization entity for an exception object.
216 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
217 QualType Type, bool NRVO) {
218 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
221 /// \brief Create the initialization entity for an object allocated via new.
222 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
223 return InitializedEntity(EK_New, NewLoc, Type);
226 /// \brief Create the initialization entity for a temporary.
227 static InitializedEntity InitializeTemporary(QualType Type) {
228 return InitializedEntity(EK_Temporary, SourceLocation(), Type);
231 /// \brief Create the initialization entity for a temporary.
232 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
233 InitializedEntity Result(EK_Temporary, SourceLocation(),
234 TypeInfo->getType());
235 Result.TypeInfo = TypeInfo;
239 /// \brief Create the initialization entity for a base class subobject.
240 static InitializedEntity InitializeBase(ASTContext &Context,
241 CXXBaseSpecifier *Base,
242 bool IsInheritedVirtualBase);
244 /// \brief Create the initialization entity for a delegated constructor.
245 static InitializedEntity InitializeDelegation(QualType Type) {
246 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
249 /// \brief Create the initialization entity for a member subobject.
250 static InitializedEntity InitializeMember(FieldDecl *Member,
251 const InitializedEntity *Parent = 0) {
252 return InitializedEntity(Member, Parent);
255 /// \brief Create the initialization entity for a member subobject.
256 static InitializedEntity InitializeMember(IndirectFieldDecl *Member,
257 const InitializedEntity *Parent = 0) {
258 return InitializedEntity(Member->getAnonField(), Parent);
261 /// \brief Create the initialization entity for an array element.
262 static InitializedEntity InitializeElement(ASTContext &Context,
264 const InitializedEntity &Parent) {
265 return InitializedEntity(Context, Index, Parent);
268 /// \brief Create the initialization entity for a lambda capture.
269 static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
271 SourceLocation Loc) {
272 return InitializedEntity(Var, Field, Loc);
275 /// \brief Determine the kind of initialization.
276 EntityKind getKind() const { return Kind; }
278 /// \brief Retrieve the parent of the entity being initialized, when
279 /// the initialization itself is occurring within the context of a
280 /// larger initialization.
281 const InitializedEntity *getParent() const { return Parent; }
283 /// \brief Retrieve type being initialized.
284 QualType getType() const { return Type; }
286 /// \brief Retrieve complete type-source information for the object being
287 /// constructed, if known.
288 TypeSourceInfo *getTypeSourceInfo() const {
289 if (Kind == EK_Temporary)
295 /// \brief Retrieve the name of the entity being initialized.
296 DeclarationName getName() const;
298 /// \brief Retrieve the variable, parameter, or field being
300 DeclaratorDecl *getDecl() const;
302 /// \brief Determine whether this initialization allows the named return
303 /// value optimization, which also applies to thrown objects.
304 bool allowsNRVO() const;
306 /// \brief Determine whether this initialization consumes the
308 bool isParameterConsumed() const {
309 assert(getKind() == EK_Parameter && "Not a parameter");
310 return (Parameter & 1);
313 /// \brief Retrieve the base specifier.
314 CXXBaseSpecifier *getBaseSpecifier() const {
315 assert(getKind() == EK_Base && "Not a base specifier");
316 return reinterpret_cast<CXXBaseSpecifier *>(Base & ~0x1);
319 /// \brief Return whether the base is an inherited virtual base.
320 bool isInheritedVirtualBase() const {
321 assert(getKind() == EK_Base && "Not a base specifier");
325 /// \brief Determine the location of the 'return' keyword when initializing
326 /// the result of a function call.
327 SourceLocation getReturnLoc() const {
328 assert(getKind() == EK_Result && "No 'return' location!");
329 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
332 /// \brief Determine the location of the 'throw' keyword when initializing
333 /// an exception object.
334 SourceLocation getThrowLoc() const {
335 assert(getKind() == EK_Exception && "No 'throw' location!");
336 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
339 /// \brief If this is already the initializer for an array or vector
340 /// element, sets the element index.
341 void setElementIndex(unsigned Index) {
342 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
343 getKind() == EK_ComplexElement);
347 /// \brief Retrieve the variable for a captured variable in a lambda.
348 VarDecl *getCapturedVar() const {
349 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
353 /// \brief Determine the location of the capture when initializing
354 /// field from a captured variable in a lambda.
355 SourceLocation getCaptureLoc() const {
356 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
357 return SourceLocation::getFromRawEncoding(Capture.Location);
361 /// \brief Describes the kind of initialization being performed, along with
362 /// location information for tokens related to the initialization (equal sign,
364 class InitializationKind {
366 /// \brief The kind of initialization being performed.
368 IK_Direct, ///< Direct initialization
369 IK_DirectList, ///< Direct list-initialization
370 IK_Copy, ///< Copy initialization
371 IK_Default, ///< Default initialization
372 IK_Value ///< Value initialization
376 /// \brief The context of the initialization.
378 IC_Normal, ///< Normal context
379 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
380 IC_Implicit, ///< Implicit context (value initialization)
381 IC_StaticCast, ///< Static cast context
382 IC_CStyleCast, ///< C-style cast context
383 IC_FunctionalCast ///< Functional cast context
386 /// \brief The kind of initialization being performed.
389 /// \brief The context of the initialization.
390 InitContext Context : 8;
392 /// \brief The source locations involved in the initialization.
393 SourceLocation Locations[3];
395 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
396 SourceLocation Loc2, SourceLocation Loc3)
397 : Kind(Kind), Context(Context)
405 /// \brief Create a direct initialization.
406 static InitializationKind CreateDirect(SourceLocation InitLoc,
407 SourceLocation LParenLoc,
408 SourceLocation RParenLoc) {
409 return InitializationKind(IK_Direct, IC_Normal,
410 InitLoc, LParenLoc, RParenLoc);
413 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
414 return InitializationKind(IK_DirectList, IC_Normal,
415 InitLoc, InitLoc, InitLoc);
418 /// \brief Create a direct initialization due to a cast that isn't a C-style
419 /// or functional cast.
420 static InitializationKind CreateCast(SourceRange TypeRange) {
421 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
422 TypeRange.getBegin(), TypeRange.getEnd());
425 /// \brief Create a direct initialization for a C-style cast.
426 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
427 SourceRange TypeRange,
429 // C++ cast syntax doesn't permit init lists, but C compound literals are
431 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
432 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
436 /// \brief Create a direct initialization for a functional cast.
437 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
439 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
440 IC_FunctionalCast, TypeRange.getBegin(),
441 TypeRange.getBegin(), TypeRange.getEnd());
444 /// \brief Create a copy initialization.
445 static InitializationKind CreateCopy(SourceLocation InitLoc,
446 SourceLocation EqualLoc,
447 bool AllowExplicitConvs = false) {
448 return InitializationKind(IK_Copy,
449 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
450 InitLoc, EqualLoc, EqualLoc);
453 /// \brief Create a default initialization.
454 static InitializationKind CreateDefault(SourceLocation InitLoc) {
455 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
458 /// \brief Create a value initialization.
459 static InitializationKind CreateValue(SourceLocation InitLoc,
460 SourceLocation LParenLoc,
461 SourceLocation RParenLoc,
462 bool isImplicit = false) {
463 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
464 InitLoc, LParenLoc, RParenLoc);
467 /// \brief Determine the initialization kind.
468 InitKind getKind() const {
472 /// \brief Determine whether this initialization is an explicit cast.
473 bool isExplicitCast() const {
474 return Context >= IC_StaticCast;
477 /// \brief Determine whether this initialization is a C-style cast.
478 bool isCStyleOrFunctionalCast() const {
479 return Context >= IC_CStyleCast;
482 /// \brief Determine whether this is a C-style cast.
483 bool isCStyleCast() const {
484 return Context == IC_CStyleCast;
487 /// \brief Determine whether this is a functional-style cast.
488 bool isFunctionalCast() const {
489 return Context == IC_FunctionalCast;
492 /// \brief Determine whether this initialization is an implicit
493 /// value-initialization, e.g., as occurs during aggregate
495 bool isImplicitValueInit() const { return Context == IC_Implicit; }
497 /// \brief Retrieve the location at which initialization is occurring.
498 SourceLocation getLocation() const { return Locations[0]; }
500 /// \brief Retrieve the source range that covers the initialization.
501 SourceRange getRange() const {
502 return SourceRange(Locations[0], Locations[2]);
505 /// \brief Retrieve the location of the equal sign for copy initialization
507 SourceLocation getEqualLoc() const {
508 assert(Kind == IK_Copy && "Only copy initialization has an '='");
512 bool isCopyInit() const { return Kind == IK_Copy; }
514 /// \brief Retrieve whether this initialization allows the use of explicit
516 bool AllowExplicit() const { return !isCopyInit(); }
518 /// \brief Retrieve whether this initialization allows the use of explicit
519 /// conversion functions.
520 bool allowExplicitConversionFunctions() const {
521 return !isCopyInit() || Context == IC_ExplicitConvs;
524 /// \brief Retrieve the source range containing the locations of the open
525 /// and closing parentheses for value and direct initializations.
526 SourceRange getParenRange() const {
527 assert((Kind == IK_Direct || Kind == IK_Value) &&
528 "Only direct- and value-initialization have parentheses");
529 return SourceRange(Locations[1], Locations[2]);
533 /// \brief Describes the sequence of initializations required to initialize
534 /// a given object or reference with a set of arguments.
535 class InitializationSequence {
537 /// \brief Describes the kind of initialization sequence computed.
539 /// \brief A failed initialization sequence. The failure kind tells what
543 /// \brief A dependent initialization, which could not be
544 /// type-checked due to the presence of dependent types or
545 /// dependently-typed expressions.
548 /// \brief A normal sequence.
552 /// \brief Describes the kind of a particular step in an initialization
555 /// \brief Resolve the address of an overloaded function to a specific
556 /// function declaration.
557 SK_ResolveAddressOfOverloadedFunction,
558 /// \brief Perform a derived-to-base cast, producing an rvalue.
559 SK_CastDerivedToBaseRValue,
560 /// \brief Perform a derived-to-base cast, producing an xvalue.
561 SK_CastDerivedToBaseXValue,
562 /// \brief Perform a derived-to-base cast, producing an lvalue.
563 SK_CastDerivedToBaseLValue,
564 /// \brief Reference binding to an lvalue.
566 /// \brief Reference binding to a temporary.
567 SK_BindReferenceToTemporary,
568 /// \brief An optional copy of a temporary object to another
569 /// temporary object, which is permitted (but not required) by
570 /// C++98/03 but not C++0x.
571 SK_ExtraneousCopyToTemporary,
572 /// \brief Perform a user-defined conversion, either via a conversion
573 /// function or via a constructor.
575 /// \brief Perform a qualification conversion, producing an rvalue.
576 SK_QualificationConversionRValue,
577 /// \brief Perform a qualification conversion, producing an xvalue.
578 SK_QualificationConversionXValue,
579 /// \brief Perform a qualification conversion, producing an lvalue.
580 SK_QualificationConversionLValue,
581 /// \brief Perform an implicit conversion sequence.
582 SK_ConversionSequence,
583 /// \brief Perform list-initialization without a constructor
584 SK_ListInitialization,
585 /// \brief Perform list-initialization with a constructor.
586 SK_ListConstructorCall,
587 /// \brief Unwrap the single-element initializer list for a reference.
589 /// \brief Rewrap the single-element initializer list for a reference.
591 /// \brief Perform initialization via a constructor.
592 SK_ConstructorInitialization,
593 /// \brief Zero-initialize the object
594 SK_ZeroInitialization,
595 /// \brief C assignment
597 /// \brief Initialization by string
599 /// \brief An initialization that "converts" an Objective-C object
600 /// (not a point to an object) to another Objective-C object type.
601 SK_ObjCObjectConversion,
602 /// \brief Array initialization (from an array rvalue).
603 /// This is a GNU C extension.
605 /// \brief Array initialization from a parenthesized initializer list.
606 /// This is a GNU C++ extension.
607 SK_ParenthesizedArrayInit,
608 /// \brief Pass an object by indirect copy-and-restore.
609 SK_PassByIndirectCopyRestore,
610 /// \brief Pass an object by indirect restore.
611 SK_PassByIndirectRestore,
612 /// \brief Produce an Objective-C object pointer.
613 SK_ProduceObjCObject,
614 /// \brief Construct a std::initializer_list from an initializer list.
615 SK_StdInitializerList
618 /// \brief A single step in the initialization sequence.
621 /// \brief The kind of conversion or initialization step we are taking.
624 // \brief The type that results from this initialization.
628 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
629 /// SK_UserConversion, the function that the expression should be
630 /// resolved to or the conversion function to call, respectively.
631 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
632 /// the constructor to be called.
634 /// Always a FunctionDecl, plus a Boolean flag telling if it was
635 /// selected from an overloaded set having size greater than 1.
636 /// For conversion decls, the naming class is the source type.
637 /// For construct decls, the naming class is the target type.
639 bool HadMultipleCandidates;
640 FunctionDecl *Function;
641 DeclAccessPair FoundDecl;
644 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
646 ImplicitConversionSequence *ICS;
648 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
650 InitListExpr *WrappingSyntacticList;
657 /// \brief The kind of initialization sequence computed.
658 enum SequenceKind SequenceKind;
660 /// \brief Steps taken by this initialization.
661 SmallVector<Step, 4> Steps;
664 /// \brief Describes why initialization failed.
666 /// \brief Too many initializers provided for a reference.
667 FK_TooManyInitsForReference,
668 /// \brief Array must be initialized with an initializer list.
669 FK_ArrayNeedsInitList,
670 /// \brief Array must be initialized with an initializer list or a
672 FK_ArrayNeedsInitListOrStringLiteral,
673 /// \brief Array type mismatch.
674 FK_ArrayTypeMismatch,
675 /// \brief Non-constant array initializer
676 FK_NonConstantArrayInit,
677 /// \brief Cannot resolve the address of an overloaded function.
678 FK_AddressOfOverloadFailed,
679 /// \brief Overloading due to reference initialization failed.
680 FK_ReferenceInitOverloadFailed,
681 /// \brief Non-const lvalue reference binding to a temporary.
682 FK_NonConstLValueReferenceBindingToTemporary,
683 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
685 FK_NonConstLValueReferenceBindingToUnrelated,
686 /// \brief Rvalue reference binding to an lvalue.
687 FK_RValueReferenceBindingToLValue,
688 /// \brief Reference binding drops qualifiers.
689 FK_ReferenceInitDropsQualifiers,
690 /// \brief Reference binding failed.
691 FK_ReferenceInitFailed,
692 /// \brief Implicit conversion failed.
694 /// \brief Implicit conversion failed.
695 FK_ConversionFromPropertyFailed,
696 /// \brief Too many initializers for scalar
697 FK_TooManyInitsForScalar,
698 /// \brief Reference initialization from an initializer list
699 FK_ReferenceBindingToInitList,
700 /// \brief Initialization of some unused destination type with an
701 /// initializer list.
702 FK_InitListBadDestinationType,
703 /// \brief Overloading for a user-defined conversion failed.
704 FK_UserConversionOverloadFailed,
705 /// \brief Overloading for initialization by constructor failed.
706 FK_ConstructorOverloadFailed,
707 /// \brief Overloading for list-initialization by constructor failed.
708 FK_ListConstructorOverloadFailed,
709 /// \brief Default-initialization of a 'const' object.
710 FK_DefaultInitOfConst,
711 /// \brief Initialization of an incomplete type.
713 /// \brief Variable-length array must not have an initializer.
714 FK_VariableLengthArrayHasInitializer,
715 /// \brief List initialization failed at some point.
716 FK_ListInitializationFailed,
717 /// \brief Initializer has a placeholder type which cannot be
718 /// resolved by initialization.
720 /// \brief Failed to initialize a std::initializer_list because copy
721 /// construction of some element failed.
722 FK_InitListElementCopyFailure,
723 /// \brief List-copy-initialization chose an explicit constructor.
724 FK_ExplicitConstructor
728 /// \brief The reason why initialization failed.
731 /// \brief The failed result of overload resolution.
732 OverloadingResult FailedOverloadResult;
734 /// \brief The candidate set created when initialization failed.
735 OverloadCandidateSet FailedCandidateSet;
737 /// \brief The incomplete type that caused a failure.
738 QualType FailedIncompleteType;
740 /// \brief Prints a follow-up note that highlights the location of
741 /// the initialized entity, if it's remote.
742 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
745 /// \brief Try to perform initialization of the given entity, creating a
746 /// record of the steps required to perform the initialization.
748 /// The generated initialization sequence will either contain enough
749 /// information to diagnose
751 /// \param S the semantic analysis object.
753 /// \param Entity the entity being initialized.
755 /// \param Kind the kind of initialization being performed.
757 /// \param Args the argument(s) provided for initialization.
759 /// \param NumArgs the number of arguments provided for initialization.
760 InitializationSequence(Sema &S,
761 const InitializedEntity &Entity,
762 const InitializationKind &Kind,
766 ~InitializationSequence();
768 /// \brief Perform the actual initialization of the given entity based on
769 /// the computed initialization sequence.
771 /// \param S the semantic analysis object.
773 /// \param Entity the entity being initialized.
775 /// \param Kind the kind of initialization being performed.
777 /// \param Args the argument(s) provided for initialization, ownership of
778 /// which is transferred into the routine.
780 /// \param ResultType if non-NULL, will be set to the type of the
781 /// initialized object, which is the type of the declaration in most
782 /// cases. However, when the initialized object is a variable of
783 /// incomplete array type and the initializer is an initializer
784 /// list, this type will be set to the completed array type.
786 /// \returns an expression that performs the actual object initialization, if
787 /// the initialization is well-formed. Otherwise, emits diagnostics
788 /// and returns an invalid expression.
789 ExprResult Perform(Sema &S,
790 const InitializedEntity &Entity,
791 const InitializationKind &Kind,
793 QualType *ResultType = 0);
795 /// \brief Diagnose an potentially-invalid initialization sequence.
797 /// \returns true if the initialization sequence was ill-formed,
799 bool Diagnose(Sema &S,
800 const InitializedEntity &Entity,
801 const InitializationKind &Kind,
802 Expr **Args, unsigned NumArgs);
804 /// \brief Determine the kind of initialization sequence computed.
805 enum SequenceKind getKind() const { return SequenceKind; }
807 /// \brief Set the kind of sequence computed.
808 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
810 /// \brief Determine whether the initialization sequence is valid.
811 operator bool() const { return !Failed(); }
813 /// \brief Determine whether the initialization sequence is invalid.
814 bool Failed() const { return SequenceKind == FailedSequence; }
816 typedef SmallVector<Step, 4>::const_iterator step_iterator;
817 step_iterator step_begin() const { return Steps.begin(); }
818 step_iterator step_end() const { return Steps.end(); }
820 /// \brief Determine whether this initialization is a direct reference
821 /// binding (C++ [dcl.init.ref]).
822 bool isDirectReferenceBinding() const;
824 /// \brief Determine whether this initialization failed due to an ambiguity.
825 bool isAmbiguous() const;
827 /// \brief Determine whether this initialization is direct call to a
829 bool isConstructorInitialization() const;
831 /// \brief Returns whether the last step in this initialization sequence is a
832 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
834 /// If this function returns true, *isInitializerConstant will be set to
835 /// describe whether *Initializer was a constant expression. If
836 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
837 /// evaluated value of *Initializer.
838 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
839 bool *isInitializerConstant,
840 APValue *ConstantValue) const;
842 /// \brief Add a new step in the initialization that resolves the address
843 /// of an overloaded function to a specific function declaration.
845 /// \param Function the function to which the overloaded function reference
847 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
848 DeclAccessPair Found,
849 bool HadMultipleCandidates);
851 /// \brief Add a new step in the initialization that performs a derived-to-
854 /// \param BaseType the base type to which we will be casting.
856 /// \param IsLValue true if the result of this cast will be treated as
858 void AddDerivedToBaseCastStep(QualType BaseType,
859 ExprValueKind Category);
861 /// \brief Add a new step binding a reference to an object.
863 /// \param BindingTemporary True if we are binding a reference to a temporary
864 /// object (thereby extending its lifetime); false if we are binding to an
865 /// lvalue or an lvalue treated as an rvalue.
867 /// \param UnnecessaryCopy True if we should check for a copy
868 /// constructor for a completely unnecessary but
869 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
871 /// \brief Add a new step that makes an extraneous copy of the input
872 /// to a temporary of the same class type.
874 /// This extraneous copy only occurs during reference binding in
875 /// C++98/03, where we are permitted (but not required) to introduce
876 /// an extra copy. At a bare minimum, we must check that we could
877 /// call the copy constructor, and produce a diagnostic if the copy
878 /// constructor is inaccessible or no copy constructor matches.
880 /// \param T The type of the temporary being created.
881 void AddExtraneousCopyToTemporary(QualType T);
883 /// \brief Add a new step invoking a conversion function, which is either
884 /// a constructor or a conversion function.
885 void AddUserConversionStep(FunctionDecl *Function,
886 DeclAccessPair FoundDecl,
888 bool HadMultipleCandidates);
890 /// \brief Add a new step that performs a qualification conversion to the
892 void AddQualificationConversionStep(QualType Ty,
893 ExprValueKind Category);
895 /// \brief Add a new step that applies an implicit conversion sequence.
896 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
899 /// \brief Add a list-initialization step.
900 void AddListInitializationStep(QualType T);
902 /// \brief Add a constructor-initialization step.
904 /// \arg FromInitList The constructor call is syntactically an initializer
906 /// \arg AsInitList The constructor is called as an init list constructor.
907 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
908 AccessSpecifier Access,
910 bool HadMultipleCandidates,
911 bool FromInitList, bool AsInitList);
913 /// \brief Add a zero-initialization step.
914 void AddZeroInitializationStep(QualType T);
916 /// \brief Add a C assignment step.
918 // FIXME: It isn't clear whether this should ever be needed;
919 // ideally, we would handle everything needed in C in the common
920 // path. However, that isn't the case yet.
921 void AddCAssignmentStep(QualType T);
923 /// \brief Add a string init step.
924 void AddStringInitStep(QualType T);
926 /// \brief Add an Objective-C object conversion step, which is
928 void AddObjCObjectConversionStep(QualType T);
930 /// \brief Add an array initialization step.
931 void AddArrayInitStep(QualType T);
933 /// \brief Add a parenthesized array initialization step.
934 void AddParenthesizedArrayInitStep(QualType T);
936 /// \brief Add a step to pass an object by indirect copy-restore.
937 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
939 /// \brief Add a step to "produce" an Objective-C object (by
941 void AddProduceObjCObjectStep(QualType T);
943 /// \brief Add a step to construct a std::initializer_list object from an
944 /// initializer list.
945 void AddStdInitializerListConstructionStep(QualType T);
947 /// \brief Add steps to unwrap a initializer list for a reference around a
948 /// single element and rewrap it at the end.
949 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
951 /// \brief Note that this initialization sequence failed.
952 void SetFailed(FailureKind Failure) {
953 SequenceKind = FailedSequence;
954 this->Failure = Failure;
955 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
956 "Incomplete type failure requires a type!");
959 /// \brief Note that this initialization sequence failed due to failed
960 /// overload resolution.
961 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
963 /// \brief Retrieve a reference to the candidate set when overload
964 /// resolution fails.
965 OverloadCandidateSet &getFailedCandidateSet() {
966 return FailedCandidateSet;
969 /// \brief Get the overloading result, for when the initialization
970 /// sequence failed due to a bad overload.
971 OverloadingResult getFailedOverloadResult() const {
972 return FailedOverloadResult;
975 /// \brief Note that this initialization sequence failed due to an
977 void setIncompleteTypeFailure(QualType IncompleteType) {
978 FailedIncompleteType = IncompleteType;
979 SetFailed(FK_Incomplete);
982 /// \brief Determine why initialization failed.
983 FailureKind getFailureKind() const {
984 assert(Failed() && "Not an initialization failure!");
988 /// \brief Dump a representation of this initialization sequence to
989 /// the given stream, for debugging purposes.
990 void dump(raw_ostream &OS) const;
992 /// \brief Dump a representation of this initialization sequence to
993 /// standard error, for debugging purposes.
997 } // end namespace clang
999 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H