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/ASTContext.h"
19 #include "clang/AST/Type.h"
20 #include "clang/AST/UnresolvedSet.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "llvm/ADT/PointerIntPair.h"
23 #include "llvm/ADT/SmallVector.h"
28 class CXXBaseSpecifier;
38 /// \brief Describes an entity that is being initialized.
39 class InitializedEntity {
41 /// \brief Specifies the kind of entity being initialized.
43 /// \brief The entity being initialized is a variable.
45 /// \brief The entity being initialized is a function parameter.
47 /// \brief The entity being initialized is the result of a function call.
49 /// \brief The entity being initialized is an exception object that
52 /// \brief The entity being initialized is a non-static data member
55 /// \brief The entity being initialized is an element of an array.
57 /// \brief The entity being initialized is an object (or array of
58 /// objects) allocated via new.
60 /// \brief The entity being initialized is a temporary object.
62 /// \brief The entity being initialized is a base member subobject.
64 /// \brief The initialization is being done by a delegating constructor.
66 /// \brief The entity being initialized is an element of a vector.
69 /// \brief The entity being initialized is a field of block descriptor for
70 /// the copied-in c++ object.
72 /// \brief The entity being initialized is the real or imaginary part of a
75 /// \brief The entity being initialized is the field that captures a
76 /// variable in a lambda.
81 /// \brief The kind of entity being initialized.
84 /// \brief If non-NULL, the parent entity in which this
85 /// initialization occurs.
86 const InitializedEntity *Parent;
88 /// \brief The type of the object or reference being initialized.
92 /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
93 /// FieldDecl, respectively.
94 DeclaratorDecl *VariableOrMember;
96 /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
97 /// low bit indicating whether the parameter is "consumed".
100 /// \brief When Kind == EK_Temporary, the type source information for
102 TypeSourceInfo *TypeInfo;
105 /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
106 /// location of the 'return', 'throw', or 'new' keyword,
107 /// respectively. When Kind == EK_Temporary, the location where
108 /// the temporary is being created.
111 /// \brief Whether the entity being initialized may end up using the
112 /// named return value optimization (NRVO).
116 /// \brief When Kind == EK_Base, the base specifier that provides the
117 /// base class. The lower bit specifies whether the base is an inherited
121 /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
122 /// EK_ComplexElement, the index of the array or vector element being
127 /// \brief The variable being captured by an EK_LambdaCapture.
130 /// \brief The source location at which the capture occurs.
135 InitializedEntity() { }
137 /// \brief Create the initialization entity for a variable.
138 InitializedEntity(VarDecl *Var)
139 : Kind(EK_Variable), Parent(0), Type(Var->getType()),
140 VariableOrMember(Var) { }
142 /// \brief Create the initialization entity for the result of a
143 /// function, throwing an object, performing an explicit cast, or
144 /// initializing a parameter for which there is no declaration.
145 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
147 : Kind(Kind), Parent(0), Type(Type)
149 LocAndNRVO.Location = Loc.getRawEncoding();
150 LocAndNRVO.NRVO = NRVO;
153 /// \brief Create the initialization entity for a member subobject.
154 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent)
155 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
156 VariableOrMember(Member) { }
158 /// \brief Create the initialization entity for an array element.
159 InitializedEntity(ASTContext &Context, unsigned Index,
160 const InitializedEntity &Parent);
162 /// \brief Create the initialization entity for a lambda capture.
163 InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
164 : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType())
167 Capture.Location = Loc.getRawEncoding();
171 /// \brief Create the initialization entity for a variable.
172 static InitializedEntity InitializeVariable(VarDecl *Var) {
173 return InitializedEntity(Var);
176 /// \brief Create the initialization entity for a parameter.
177 static InitializedEntity InitializeParameter(ASTContext &Context,
179 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
180 Parm->hasAttr<NSConsumedAttr>());
182 InitializedEntity Entity;
183 Entity.Kind = EK_Parameter;
184 Entity.Type = Context.getVariableArrayDecayedType(
185 Parm->getType().getUnqualifiedType());
188 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
192 /// \brief Create the initialization entity for a parameter that is
193 /// only known by its type.
194 static InitializedEntity InitializeParameter(ASTContext &Context,
197 InitializedEntity Entity;
198 Entity.Kind = EK_Parameter;
199 Entity.Type = Context.getVariableArrayDecayedType(Type);
201 Entity.Parameter = (Consumed);
205 /// \brief Create the initialization entity for the result of a function.
206 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
207 QualType Type, bool NRVO) {
208 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
211 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
212 QualType Type, bool NRVO) {
213 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
216 /// \brief Create the initialization entity for an exception object.
217 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
218 QualType Type, bool NRVO) {
219 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
222 /// \brief Create the initialization entity for an object allocated via new.
223 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
224 return InitializedEntity(EK_New, NewLoc, Type);
227 /// \brief Create the initialization entity for a temporary.
228 static InitializedEntity InitializeTemporary(QualType Type) {
229 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
234 /// \brief Create the initialization entity for a temporary.
235 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
236 InitializedEntity Result(EK_Temporary, SourceLocation(),
237 TypeInfo->getType());
238 Result.TypeInfo = TypeInfo;
242 /// \brief Create the initialization entity for a base class subobject.
243 static InitializedEntity InitializeBase(ASTContext &Context,
244 CXXBaseSpecifier *Base,
245 bool IsInheritedVirtualBase);
247 /// \brief Create the initialization entity for a delegated constructor.
248 static InitializedEntity InitializeDelegation(QualType Type) {
249 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
252 /// \brief Create the initialization entity for a member subobject.
253 static InitializedEntity InitializeMember(FieldDecl *Member,
254 const InitializedEntity *Parent = 0) {
255 return InitializedEntity(Member, Parent);
258 /// \brief Create the initialization entity for a member subobject.
259 static InitializedEntity InitializeMember(IndirectFieldDecl *Member,
260 const InitializedEntity *Parent = 0) {
261 return InitializedEntity(Member->getAnonField(), Parent);
264 /// \brief Create the initialization entity for an array element.
265 static InitializedEntity InitializeElement(ASTContext &Context,
267 const InitializedEntity &Parent) {
268 return InitializedEntity(Context, Index, Parent);
271 /// \brief Create the initialization entity for a lambda capture.
272 static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
274 SourceLocation Loc) {
275 return InitializedEntity(Var, Field, Loc);
278 /// \brief Determine the kind of initialization.
279 EntityKind getKind() const { return Kind; }
281 /// \brief Retrieve the parent of the entity being initialized, when
282 /// the initialization itself is occurring within the context of a
283 /// larger initialization.
284 const InitializedEntity *getParent() const { return Parent; }
286 /// \brief Retrieve type being initialized.
287 QualType getType() const { return Type; }
289 /// \brief Retrieve complete type-source information for the object being
290 /// constructed, if known.
291 TypeSourceInfo *getTypeSourceInfo() const {
292 if (Kind == EK_Temporary)
298 /// \brief Retrieve the name of the entity being initialized.
299 DeclarationName getName() const;
301 /// \brief Retrieve the variable, parameter, or field being
303 DeclaratorDecl *getDecl() const;
305 /// \brief Determine whether this initialization allows the named return
306 /// value optimization, which also applies to thrown objects.
307 bool allowsNRVO() const;
309 /// \brief Determine whether this initialization consumes the
311 bool isParameterConsumed() const {
312 assert(getKind() == EK_Parameter && "Not a parameter");
313 return (Parameter & 1);
316 /// \brief Retrieve the base specifier.
317 CXXBaseSpecifier *getBaseSpecifier() const {
318 assert(getKind() == EK_Base && "Not a base specifier");
319 return reinterpret_cast<CXXBaseSpecifier *>(Base & ~0x1);
322 /// \brief Return whether the base is an inherited virtual base.
323 bool isInheritedVirtualBase() const {
324 assert(getKind() == EK_Base && "Not a base specifier");
328 /// \brief Determine the location of the 'return' keyword when initializing
329 /// the result of a function call.
330 SourceLocation getReturnLoc() const {
331 assert(getKind() == EK_Result && "No 'return' location!");
332 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
335 /// \brief Determine the location of the 'throw' keyword when initializing
336 /// an exception object.
337 SourceLocation getThrowLoc() const {
338 assert(getKind() == EK_Exception && "No 'throw' location!");
339 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
342 /// \brief If this is already the initializer for an array or vector
343 /// element, sets the element index.
344 void setElementIndex(unsigned Index) {
345 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
346 getKind() == EK_ComplexElement);
350 /// \brief Retrieve the variable for a captured variable in a lambda.
351 VarDecl *getCapturedVar() const {
352 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
356 /// \brief Determine the location of the capture when initializing
357 /// field from a captured variable in a lambda.
358 SourceLocation getCaptureLoc() const {
359 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
360 return SourceLocation::getFromRawEncoding(Capture.Location);
364 /// \brief Describes the kind of initialization being performed, along with
365 /// location information for tokens related to the initialization (equal sign,
367 class InitializationKind {
369 /// \brief The kind of initialization being performed.
371 IK_Direct, ///< Direct initialization
372 IK_DirectList, ///< Direct list-initialization
373 IK_Copy, ///< Copy initialization
374 IK_Default, ///< Default initialization
375 IK_Value ///< Value initialization
379 /// \brief The context of the initialization.
381 IC_Normal, ///< Normal context
382 IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
383 IC_Implicit, ///< Implicit context (value initialization)
384 IC_StaticCast, ///< Static cast context
385 IC_CStyleCast, ///< C-style cast context
386 IC_FunctionalCast ///< Functional cast context
389 /// \brief The kind of initialization being performed.
392 /// \brief The context of the initialization.
393 InitContext Context : 8;
395 /// \brief The source locations involved in the initialization.
396 SourceLocation Locations[3];
398 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
399 SourceLocation Loc2, SourceLocation Loc3)
400 : Kind(Kind), Context(Context)
408 /// \brief Create a direct initialization.
409 static InitializationKind CreateDirect(SourceLocation InitLoc,
410 SourceLocation LParenLoc,
411 SourceLocation RParenLoc) {
412 return InitializationKind(IK_Direct, IC_Normal,
413 InitLoc, LParenLoc, RParenLoc);
416 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
417 return InitializationKind(IK_DirectList, IC_Normal,
418 InitLoc, InitLoc, InitLoc);
421 /// \brief Create a direct initialization due to a cast that isn't a C-style
422 /// or functional cast.
423 static InitializationKind CreateCast(SourceRange TypeRange) {
424 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
425 TypeRange.getBegin(), TypeRange.getEnd());
428 /// \brief Create a direct initialization for a C-style cast.
429 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
430 SourceRange TypeRange,
432 // C++ cast syntax doesn't permit init lists, but C compound literals are
434 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
435 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
439 /// \brief Create a direct initialization for a functional cast.
440 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
442 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
443 IC_FunctionalCast, TypeRange.getBegin(),
444 TypeRange.getBegin(), TypeRange.getEnd());
447 /// \brief Create a copy initialization.
448 static InitializationKind CreateCopy(SourceLocation InitLoc,
449 SourceLocation EqualLoc,
450 bool AllowExplicitConvs = false) {
451 return InitializationKind(IK_Copy,
452 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
453 InitLoc, EqualLoc, EqualLoc);
456 /// \brief Create a default initialization.
457 static InitializationKind CreateDefault(SourceLocation InitLoc) {
458 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
461 /// \brief Create a value initialization.
462 static InitializationKind CreateValue(SourceLocation InitLoc,
463 SourceLocation LParenLoc,
464 SourceLocation RParenLoc,
465 bool isImplicit = false) {
466 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
467 InitLoc, LParenLoc, RParenLoc);
470 /// \brief Determine the initialization kind.
471 InitKind getKind() const {
475 /// \brief Determine whether this initialization is an explicit cast.
476 bool isExplicitCast() const {
477 return Context >= IC_StaticCast;
480 /// \brief Determine whether this initialization is a C-style cast.
481 bool isCStyleOrFunctionalCast() const {
482 return Context >= IC_CStyleCast;
485 /// \brief Determine whether this is a C-style cast.
486 bool isCStyleCast() const {
487 return Context == IC_CStyleCast;
490 /// \brief Determine whether this is a functional-style cast.
491 bool isFunctionalCast() const {
492 return Context == IC_FunctionalCast;
495 /// \brief Determine whether this initialization is an implicit
496 /// value-initialization, e.g., as occurs during aggregate
498 bool isImplicitValueInit() const { return Context == IC_Implicit; }
500 /// \brief Retrieve the location at which initialization is occurring.
501 SourceLocation getLocation() const { return Locations[0]; }
503 /// \brief Retrieve the source range that covers the initialization.
504 SourceRange getRange() const {
505 return SourceRange(Locations[0], Locations[2]);
508 /// \brief Retrieve the location of the equal sign for copy initialization
510 SourceLocation getEqualLoc() const {
511 assert(Kind == IK_Copy && "Only copy initialization has an '='");
515 bool isCopyInit() const { return Kind == IK_Copy; }
517 /// \brief Retrieve whether this initialization allows the use of explicit
519 bool AllowExplicit() const { return !isCopyInit(); }
521 /// \brief Retrieve whether this initialization allows the use of explicit
522 /// conversion functions.
523 bool allowExplicitConversionFunctions() const {
524 return !isCopyInit() || Context == IC_ExplicitConvs;
527 /// \brief Retrieve the source range containing the locations of the open
528 /// and closing parentheses for value and direct initializations.
529 SourceRange getParenRange() const {
530 assert((Kind == IK_Direct || Kind == IK_Value) &&
531 "Only direct- and value-initialization have parentheses");
532 return SourceRange(Locations[1], Locations[2]);
536 /// \brief Describes the sequence of initializations required to initialize
537 /// a given object or reference with a set of arguments.
538 class InitializationSequence {
540 /// \brief Describes the kind of initialization sequence computed.
542 /// \brief A failed initialization sequence. The failure kind tells what
546 /// \brief A dependent initialization, which could not be
547 /// type-checked due to the presence of dependent types or
548 /// dependently-typed expressions.
551 /// \brief A normal sequence.
555 /// \brief Describes the kind of a particular step in an initialization
558 /// \brief Resolve the address of an overloaded function to a specific
559 /// function declaration.
560 SK_ResolveAddressOfOverloadedFunction,
561 /// \brief Perform a derived-to-base cast, producing an rvalue.
562 SK_CastDerivedToBaseRValue,
563 /// \brief Perform a derived-to-base cast, producing an xvalue.
564 SK_CastDerivedToBaseXValue,
565 /// \brief Perform a derived-to-base cast, producing an lvalue.
566 SK_CastDerivedToBaseLValue,
567 /// \brief Reference binding to an lvalue.
569 /// \brief Reference binding to a temporary.
570 SK_BindReferenceToTemporary,
571 /// \brief An optional copy of a temporary object to another
572 /// temporary object, which is permitted (but not required) by
573 /// C++98/03 but not C++0x.
574 SK_ExtraneousCopyToTemporary,
575 /// \brief Perform a user-defined conversion, either via a conversion
576 /// function or via a constructor.
578 /// \brief Perform a qualification conversion, producing an rvalue.
579 SK_QualificationConversionRValue,
580 /// \brief Perform a qualification conversion, producing an xvalue.
581 SK_QualificationConversionXValue,
582 /// \brief Perform a qualification conversion, producing an lvalue.
583 SK_QualificationConversionLValue,
584 /// \brief Perform an implicit conversion sequence.
585 SK_ConversionSequence,
586 /// \brief Perform list-initialization without a constructor
587 SK_ListInitialization,
588 /// \brief Perform list-initialization with a constructor.
589 SK_ListConstructorCall,
590 /// \brief Unwrap the single-element initializer list for a reference.
592 /// \brief Rewrap the single-element initializer list for a reference.
594 /// \brief Perform initialization via a constructor.
595 SK_ConstructorInitialization,
596 /// \brief Zero-initialize the object
597 SK_ZeroInitialization,
598 /// \brief C assignment
600 /// \brief Initialization by string
602 /// \brief An initialization that "converts" an Objective-C object
603 /// (not a point to an object) to another Objective-C object type.
604 SK_ObjCObjectConversion,
605 /// \brief Array initialization (from an array rvalue).
606 /// This is a GNU C extension.
608 /// \brief Array initialization from a parenthesized initializer list.
609 /// This is a GNU C++ extension.
610 SK_ParenthesizedArrayInit,
611 /// \brief Pass an object by indirect copy-and-restore.
612 SK_PassByIndirectCopyRestore,
613 /// \brief Pass an object by indirect restore.
614 SK_PassByIndirectRestore,
615 /// \brief Produce an Objective-C object pointer.
616 SK_ProduceObjCObject,
617 /// \brief Construct a std::initializer_list from an initializer list.
618 SK_StdInitializerList
621 /// \brief A single step in the initialization sequence.
624 /// \brief The kind of conversion or initialization step we are taking.
627 // \brief The type that results from this initialization.
631 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
632 /// SK_UserConversion, the function that the expression should be
633 /// resolved to or the conversion function to call, respectively.
634 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
635 /// the constructor to be called.
637 /// Always a FunctionDecl, plus a Boolean flag telling if it was
638 /// selected from an overloaded set having size greater than 1.
639 /// For conversion decls, the naming class is the source type.
640 /// For construct decls, the naming class is the target type.
642 bool HadMultipleCandidates;
643 FunctionDecl *Function;
644 DeclAccessPair FoundDecl;
647 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
649 ImplicitConversionSequence *ICS;
651 /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
653 InitListExpr *WrappingSyntacticList;
660 /// \brief The kind of initialization sequence computed.
661 enum SequenceKind SequenceKind;
663 /// \brief Steps taken by this initialization.
664 SmallVector<Step, 4> Steps;
667 /// \brief Describes why initialization failed.
669 /// \brief Too many initializers provided for a reference.
670 FK_TooManyInitsForReference,
671 /// \brief Array must be initialized with an initializer list.
672 FK_ArrayNeedsInitList,
673 /// \brief Array must be initialized with an initializer list or a
675 FK_ArrayNeedsInitListOrStringLiteral,
676 /// \brief Array type mismatch.
677 FK_ArrayTypeMismatch,
678 /// \brief Non-constant array initializer
679 FK_NonConstantArrayInit,
680 /// \brief Cannot resolve the address of an overloaded function.
681 FK_AddressOfOverloadFailed,
682 /// \brief Overloading due to reference initialization failed.
683 FK_ReferenceInitOverloadFailed,
684 /// \brief Non-const lvalue reference binding to a temporary.
685 FK_NonConstLValueReferenceBindingToTemporary,
686 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
688 FK_NonConstLValueReferenceBindingToUnrelated,
689 /// \brief Rvalue reference binding to an lvalue.
690 FK_RValueReferenceBindingToLValue,
691 /// \brief Reference binding drops qualifiers.
692 FK_ReferenceInitDropsQualifiers,
693 /// \brief Reference binding failed.
694 FK_ReferenceInitFailed,
695 /// \brief Implicit conversion failed.
697 /// \brief Implicit conversion failed.
698 FK_ConversionFromPropertyFailed,
699 /// \brief Too many initializers for scalar
700 FK_TooManyInitsForScalar,
701 /// \brief Reference initialization from an initializer list
702 FK_ReferenceBindingToInitList,
703 /// \brief Initialization of some unused destination type with an
704 /// initializer list.
705 FK_InitListBadDestinationType,
706 /// \brief Overloading for a user-defined conversion failed.
707 FK_UserConversionOverloadFailed,
708 /// \brief Overloading for initialization by constructor failed.
709 FK_ConstructorOverloadFailed,
710 /// \brief Overloading for list-initialization by constructor failed.
711 FK_ListConstructorOverloadFailed,
712 /// \brief Default-initialization of a 'const' object.
713 FK_DefaultInitOfConst,
714 /// \brief Initialization of an incomplete type.
716 /// \brief Variable-length array must not have an initializer.
717 FK_VariableLengthArrayHasInitializer,
718 /// \brief List initialization failed at some point.
719 FK_ListInitializationFailed,
720 /// \brief Initializer has a placeholder type which cannot be
721 /// resolved by initialization.
723 /// \brief Failed to initialize a std::initializer_list because copy
724 /// construction of some element failed.
725 FK_InitListElementCopyFailure,
726 /// \brief List-copy-initialization chose an explicit constructor.
727 FK_ExplicitConstructor
731 /// \brief The reason why initialization failed.
734 /// \brief The failed result of overload resolution.
735 OverloadingResult FailedOverloadResult;
737 /// \brief The candidate set created when initialization failed.
738 OverloadCandidateSet FailedCandidateSet;
740 /// \brief The incomplete type that caused a failure.
741 QualType FailedIncompleteType;
743 /// \brief Prints a follow-up note that highlights the location of
744 /// the initialized entity, if it's remote.
745 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
748 /// \brief Try to perform initialization of the given entity, creating a
749 /// record of the steps required to perform the initialization.
751 /// The generated initialization sequence will either contain enough
752 /// information to diagnose
754 /// \param S the semantic analysis object.
756 /// \param Entity the entity being initialized.
758 /// \param Kind the kind of initialization being performed.
760 /// \param Args the argument(s) provided for initialization.
762 /// \param NumArgs the number of arguments provided for initialization.
763 InitializationSequence(Sema &S,
764 const InitializedEntity &Entity,
765 const InitializationKind &Kind,
769 ~InitializationSequence();
771 /// \brief Perform the actual initialization of the given entity based on
772 /// the computed initialization sequence.
774 /// \param S the semantic analysis object.
776 /// \param Entity the entity being initialized.
778 /// \param Kind the kind of initialization being performed.
780 /// \param Args the argument(s) provided for initialization, ownership of
781 /// which is transferred into the routine.
783 /// \param ResultType if non-NULL, will be set to the type of the
784 /// initialized object, which is the type of the declaration in most
785 /// cases. However, when the initialized object is a variable of
786 /// incomplete array type and the initializer is an initializer
787 /// list, this type will be set to the completed array type.
789 /// \returns an expression that performs the actual object initialization, if
790 /// the initialization is well-formed. Otherwise, emits diagnostics
791 /// and returns an invalid expression.
792 ExprResult Perform(Sema &S,
793 const InitializedEntity &Entity,
794 const InitializationKind &Kind,
796 QualType *ResultType = 0);
798 /// \brief Diagnose an potentially-invalid initialization sequence.
800 /// \returns true if the initialization sequence was ill-formed,
802 bool Diagnose(Sema &S,
803 const InitializedEntity &Entity,
804 const InitializationKind &Kind,
805 Expr **Args, unsigned NumArgs);
807 /// \brief Determine the kind of initialization sequence computed.
808 enum SequenceKind getKind() const { return SequenceKind; }
810 /// \brief Set the kind of sequence computed.
811 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
813 /// \brief Determine whether the initialization sequence is valid.
814 operator bool() const { return !Failed(); }
816 /// \brief Determine whether the initialization sequence is invalid.
817 bool Failed() const { return SequenceKind == FailedSequence; }
819 typedef SmallVector<Step, 4>::const_iterator step_iterator;
820 step_iterator step_begin() const { return Steps.begin(); }
821 step_iterator step_end() const { return Steps.end(); }
823 /// \brief Determine whether this initialization is a direct reference
824 /// binding (C++ [dcl.init.ref]).
825 bool isDirectReferenceBinding() const;
827 /// \brief Determine whether this initialization failed due to an ambiguity.
828 bool isAmbiguous() const;
830 /// \brief Determine whether this initialization is direct call to a
832 bool isConstructorInitialization() const;
834 /// \brief Returns whether the last step in this initialization sequence is a
835 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
837 /// If this function returns true, *isInitializerConstant will be set to
838 /// describe whether *Initializer was a constant expression. If
839 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
840 /// evaluated value of *Initializer.
841 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
842 bool *isInitializerConstant,
843 APValue *ConstantValue) const;
845 /// \brief Add a new step in the initialization that resolves the address
846 /// of an overloaded function to a specific function declaration.
848 /// \param Function the function to which the overloaded function reference
850 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
851 DeclAccessPair Found,
852 bool HadMultipleCandidates);
854 /// \brief Add a new step in the initialization that performs a derived-to-
857 /// \param BaseType the base type to which we will be casting.
859 /// \param Category Indicates whether the result will be treated as an
860 /// rvalue, an xvalue, or an lvalue.
861 void AddDerivedToBaseCastStep(QualType BaseType,
862 ExprValueKind Category);
864 /// \brief Add a new step binding a reference to an object.
866 /// \param BindingTemporary True if we are binding a reference to a temporary
867 /// object (thereby extending its lifetime); false if we are binding to an
868 /// lvalue or an lvalue treated as an rvalue.
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 /// \param FromInitList The constructor call is syntactically an initializer
906 /// \param 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