• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides supporting data types for initialization of objects.
11 //
12 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
14 #define LLVM_CLANG_SEMA_INITIALIZATION_H
15 
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"
25 #include <cassert>
26 
27 namespace clang {
28 
29 class CXXBaseSpecifier;
30 class DeclaratorDecl;
31 class DeclaratorInfo;
32 class FieldDecl;
33 class FunctionDecl;
34 class ParmVarDecl;
35 class Sema;
36 class TypeLoc;
37 class VarDecl;
38 
39 /// \brief Describes an entity that is being initialized.
40 class InitializedEntity {
41 public:
42   /// \brief Specifies the kind of entity being initialized.
43   enum EntityKind {
44     /// \brief The entity being initialized is a variable.
45     EK_Variable,
46     /// \brief The entity being initialized is a function parameter.
47     EK_Parameter,
48     /// \brief The entity being initialized is the result of a function call.
49     EK_Result,
50     /// \brief The entity being initialized is an exception object that
51     /// is being thrown.
52     EK_Exception,
53     /// \brief The entity being initialized is a non-static data member
54     /// subobject.
55     EK_Member,
56     /// \brief The entity being initialized is an element of an array.
57     EK_ArrayElement,
58     /// \brief The entity being initialized is an object (or array of
59     /// objects) allocated via new.
60     EK_New,
61     /// \brief The entity being initialized is a temporary object.
62     EK_Temporary,
63     /// \brief The entity being initialized is a base member subobject.
64     EK_Base,
65     /// \brief The initialization is being done by a delegating constructor.
66     EK_Delegating,
67     /// \brief The entity being initialized is an element of a vector.
68     /// or vector.
69     EK_VectorElement,
70     /// \brief The entity being initialized is a field of block descriptor for
71     /// the copied-in c++ object.
72     EK_BlockElement,
73     /// \brief The entity being initialized is the real or imaginary part of a
74     /// complex number.
75     EK_ComplexElement,
76     /// \brief The entity being initialized is the field that captures a
77     /// variable in a lambda.
78     EK_LambdaCapture
79   };
80 
81 private:
82   /// \brief The kind of entity being initialized.
83   EntityKind Kind;
84 
85   /// \brief If non-NULL, the parent entity in which this
86   /// initialization occurs.
87   const InitializedEntity *Parent;
88 
89   /// \brief The type of the object or reference being initialized.
90   QualType Type;
91 
92   struct LN {
93     /// \brief When Kind == EK_Result, EK_Exception, EK_New, the
94     /// location of the 'return', 'throw', or 'new' keyword,
95     /// respectively. When Kind == EK_Temporary, the location where
96     /// the temporary is being created.
97     unsigned Location;
98 
99     /// \brief Whether the entity being initialized may end up using the
100     /// named return value optimization (NRVO).
101     bool NRVO;
102   };
103 
104   struct C {
105     /// \brief The variable being captured by an EK_LambdaCapture.
106     VarDecl *Var;
107 
108     /// \brief The source location at which the capture occurs.
109     unsigned Location;
110   };
111 
112   union {
113     /// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
114     /// FieldDecl, respectively.
115     DeclaratorDecl *VariableOrMember;
116 
117     /// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
118     /// low bit indicating whether the parameter is "consumed".
119     uintptr_t Parameter;
120 
121     /// \brief When Kind == EK_Temporary, the type source information for
122     /// the temporary.
123     TypeSourceInfo *TypeInfo;
124 
125     struct LN LocAndNRVO;
126 
127     /// \brief When Kind == EK_Base, the base specifier that provides the
128     /// base class. The lower bit specifies whether the base is an inherited
129     /// virtual base.
130     uintptr_t Base;
131 
132     /// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
133     /// EK_ComplexElement, the index of the array or vector element being
134     /// initialized.
135     unsigned Index;
136 
137     struct C Capture;
138   };
139 
InitializedEntity()140   InitializedEntity() { }
141 
142   /// \brief Create the initialization entity for a variable.
InitializedEntity(VarDecl * Var)143   InitializedEntity(VarDecl *Var)
144     : Kind(EK_Variable), Parent(0), Type(Var->getType()),
145       VariableOrMember(Var) { }
146 
147   /// \brief Create the initialization entity for the result of a
148   /// function, throwing an object, performing an explicit cast, or
149   /// initializing a parameter for which there is no declaration.
150   InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
151                     bool NRVO = false)
Kind(Kind)152     : Kind(Kind), Parent(0), Type(Type)
153   {
154     LocAndNRVO.Location = Loc.getRawEncoding();
155     LocAndNRVO.NRVO = NRVO;
156   }
157 
158   /// \brief Create the initialization entity for a member subobject.
InitializedEntity(FieldDecl * Member,const InitializedEntity * Parent)159   InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent)
160     : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
161       VariableOrMember(Member) { }
162 
163   /// \brief Create the initialization entity for an array element.
164   InitializedEntity(ASTContext &Context, unsigned Index,
165                     const InitializedEntity &Parent);
166 
167   /// \brief Create the initialization entity for a lambda capture.
InitializedEntity(VarDecl * Var,FieldDecl * Field,SourceLocation Loc)168   InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
169     : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType())
170   {
171     Capture.Var = Var;
172     Capture.Location = Loc.getRawEncoding();
173   }
174 
175 public:
176   /// \brief Create the initialization entity for a variable.
InitializeVariable(VarDecl * Var)177   static InitializedEntity InitializeVariable(VarDecl *Var) {
178     return InitializedEntity(Var);
179   }
180 
181   /// \brief Create the initialization entity for a parameter.
InitializeParameter(ASTContext & Context,ParmVarDecl * Parm)182   static InitializedEntity InitializeParameter(ASTContext &Context,
183                                                ParmVarDecl *Parm) {
184     return InitializeParameter(Context, Parm, Parm->getType());
185   }
186 
187   /// \brief Create the initialization entity for a parameter, but use
188   /// another type.
InitializeParameter(ASTContext & Context,ParmVarDecl * Parm,QualType Type)189   static InitializedEntity InitializeParameter(ASTContext &Context,
190                                                ParmVarDecl *Parm,
191                                                QualType Type) {
192     bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
193                      Parm->hasAttr<NSConsumedAttr>());
194 
195     InitializedEntity Entity;
196     Entity.Kind = EK_Parameter;
197     Entity.Type =
198       Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
199     Entity.Parent = 0;
200     Entity.Parameter
201       = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
202     return Entity;
203   }
204 
205   /// \brief Create the initialization entity for a parameter that is
206   /// only known by its type.
InitializeParameter(ASTContext & Context,QualType Type,bool Consumed)207   static InitializedEntity InitializeParameter(ASTContext &Context,
208                                                QualType Type,
209                                                bool Consumed) {
210     InitializedEntity Entity;
211     Entity.Kind = EK_Parameter;
212     Entity.Type = Context.getVariableArrayDecayedType(Type);
213     Entity.Parent = 0;
214     Entity.Parameter = (Consumed);
215     return Entity;
216   }
217 
218   /// \brief Create the initialization entity for the result of a function.
InitializeResult(SourceLocation ReturnLoc,QualType Type,bool NRVO)219   static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
220                                             QualType Type, bool NRVO) {
221     return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
222   }
223 
InitializeBlock(SourceLocation BlockVarLoc,QualType Type,bool NRVO)224   static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
225                                            QualType Type, bool NRVO) {
226     return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
227   }
228 
229   /// \brief Create the initialization entity for an exception object.
InitializeException(SourceLocation ThrowLoc,QualType Type,bool NRVO)230   static InitializedEntity InitializeException(SourceLocation ThrowLoc,
231                                                QualType Type, bool NRVO) {
232     return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
233   }
234 
235   /// \brief Create the initialization entity for an object allocated via new.
InitializeNew(SourceLocation NewLoc,QualType Type)236   static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
237     return InitializedEntity(EK_New, NewLoc, Type);
238   }
239 
240   /// \brief Create the initialization entity for a temporary.
InitializeTemporary(QualType Type)241   static InitializedEntity InitializeTemporary(QualType Type) {
242     InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
243     Result.TypeInfo = 0;
244     return Result;
245   }
246 
247   /// \brief Create the initialization entity for a temporary.
InitializeTemporary(TypeSourceInfo * TypeInfo)248   static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
249     InitializedEntity Result(EK_Temporary, SourceLocation(),
250                              TypeInfo->getType());
251     Result.TypeInfo = TypeInfo;
252     return Result;
253   }
254 
255   /// \brief Create the initialization entity for a base class subobject.
256   static InitializedEntity InitializeBase(ASTContext &Context,
257                                           CXXBaseSpecifier *Base,
258                                           bool IsInheritedVirtualBase);
259 
260   /// \brief Create the initialization entity for a delegated constructor.
InitializeDelegation(QualType Type)261   static InitializedEntity InitializeDelegation(QualType Type) {
262     return InitializedEntity(EK_Delegating, SourceLocation(), Type);
263   }
264 
265   /// \brief Create the initialization entity for a member subobject.
266   static InitializedEntity InitializeMember(FieldDecl *Member,
267                                           const InitializedEntity *Parent = 0) {
268     return InitializedEntity(Member, Parent);
269   }
270 
271   /// \brief Create the initialization entity for a member subobject.
272   static InitializedEntity InitializeMember(IndirectFieldDecl *Member,
273                                       const InitializedEntity *Parent = 0) {
274     return InitializedEntity(Member->getAnonField(), Parent);
275   }
276 
277   /// \brief Create the initialization entity for an array element.
InitializeElement(ASTContext & Context,unsigned Index,const InitializedEntity & Parent)278   static InitializedEntity InitializeElement(ASTContext &Context,
279                                              unsigned Index,
280                                              const InitializedEntity &Parent) {
281     return InitializedEntity(Context, Index, Parent);
282   }
283 
284   /// \brief Create the initialization entity for a lambda capture.
InitializeLambdaCapture(VarDecl * Var,FieldDecl * Field,SourceLocation Loc)285   static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
286                                                    FieldDecl *Field,
287                                                    SourceLocation Loc) {
288     return InitializedEntity(Var, Field, Loc);
289   }
290 
291   /// \brief Determine the kind of initialization.
getKind()292   EntityKind getKind() const { return Kind; }
293 
294   /// \brief Retrieve the parent of the entity being initialized, when
295   /// the initialization itself is occurring within the context of a
296   /// larger initialization.
getParent()297   const InitializedEntity *getParent() const { return Parent; }
298 
299   /// \brief Retrieve type being initialized.
getType()300   QualType getType() const { return Type; }
301 
302   /// \brief Retrieve complete type-source information for the object being
303   /// constructed, if known.
getTypeSourceInfo()304   TypeSourceInfo *getTypeSourceInfo() const {
305     if (Kind == EK_Temporary)
306       return TypeInfo;
307 
308     return 0;
309   }
310 
311   /// \brief Retrieve the name of the entity being initialized.
312   DeclarationName getName() const;
313 
314   /// \brief Retrieve the variable, parameter, or field being
315   /// initialized.
316   DeclaratorDecl *getDecl() const;
317 
318   /// \brief Determine whether this initialization allows the named return
319   /// value optimization, which also applies to thrown objects.
320   bool allowsNRVO() const;
321 
322   /// \brief Determine whether this initialization consumes the
323   /// parameter.
isParameterConsumed()324   bool isParameterConsumed() const {
325     assert(getKind() == EK_Parameter && "Not a parameter");
326     return (Parameter & 1);
327   }
328 
329   /// \brief Retrieve the base specifier.
getBaseSpecifier()330   CXXBaseSpecifier *getBaseSpecifier() const {
331     assert(getKind() == EK_Base && "Not a base specifier");
332     return reinterpret_cast<CXXBaseSpecifier *>(Base & ~0x1);
333   }
334 
335   /// \brief Return whether the base is an inherited virtual base.
isInheritedVirtualBase()336   bool isInheritedVirtualBase() const {
337     assert(getKind() == EK_Base && "Not a base specifier");
338     return Base & 0x1;
339   }
340 
341   /// \brief Determine the location of the 'return' keyword when initializing
342   /// the result of a function call.
getReturnLoc()343   SourceLocation getReturnLoc() const {
344     assert(getKind() == EK_Result && "No 'return' location!");
345     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
346   }
347 
348   /// \brief Determine the location of the 'throw' keyword when initializing
349   /// an exception object.
getThrowLoc()350   SourceLocation getThrowLoc() const {
351     assert(getKind() == EK_Exception && "No 'throw' location!");
352     return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
353   }
354 
355   /// \brief If this is already the initializer for an array or vector
356   /// element, sets the element index.
setElementIndex(unsigned Index)357   void setElementIndex(unsigned Index) {
358     assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
359            getKind() == EK_ComplexElement);
360     this->Index = Index;
361   }
362 
363   /// \brief Retrieve the variable for a captured variable in a lambda.
getCapturedVar()364   VarDecl *getCapturedVar() const {
365     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
366     return Capture.Var;
367   }
368 
369   /// \brief Determine the location of the capture when initializing
370   /// field from a captured variable in a lambda.
getCaptureLoc()371   SourceLocation getCaptureLoc() const {
372     assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
373     return SourceLocation::getFromRawEncoding(Capture.Location);
374   }
375 };
376 
377 /// \brief Describes the kind of initialization being performed, along with
378 /// location information for tokens related to the initialization (equal sign,
379 /// parentheses).
380 class InitializationKind {
381 public:
382   /// \brief The kind of initialization being performed.
383   enum InitKind {
384     IK_Direct,       ///< Direct initialization
385     IK_DirectList,   ///< Direct list-initialization
386     IK_Copy,         ///< Copy initialization
387     IK_Default,      ///< Default initialization
388     IK_Value         ///< Value initialization
389   };
390 
391 private:
392   /// \brief The context of the initialization.
393   enum InitContext {
394     IC_Normal,         ///< Normal context
395     IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion funcs
396     IC_Implicit,       ///< Implicit context (value initialization)
397     IC_StaticCast,     ///< Static cast context
398     IC_CStyleCast,     ///< C-style cast context
399     IC_FunctionalCast  ///< Functional cast context
400   };
401 
402   /// \brief The kind of initialization being performed.
403   InitKind Kind : 8;
404 
405   /// \brief The context of the initialization.
406   InitContext Context : 8;
407 
408   /// \brief The source locations involved in the initialization.
409   SourceLocation Locations[3];
410 
InitializationKind(InitKind Kind,InitContext Context,SourceLocation Loc1,SourceLocation Loc2,SourceLocation Loc3)411   InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
412                      SourceLocation Loc2, SourceLocation Loc3)
413     : Kind(Kind), Context(Context)
414   {
415     Locations[0] = Loc1;
416     Locations[1] = Loc2;
417     Locations[2] = Loc3;
418   }
419 
420 public:
421   /// \brief Create a direct initialization.
CreateDirect(SourceLocation InitLoc,SourceLocation LParenLoc,SourceLocation RParenLoc)422   static InitializationKind CreateDirect(SourceLocation InitLoc,
423                                          SourceLocation LParenLoc,
424                                          SourceLocation RParenLoc) {
425     return InitializationKind(IK_Direct, IC_Normal,
426                               InitLoc, LParenLoc, RParenLoc);
427   }
428 
CreateDirectList(SourceLocation InitLoc)429   static InitializationKind CreateDirectList(SourceLocation InitLoc) {
430     return InitializationKind(IK_DirectList, IC_Normal,
431                               InitLoc, InitLoc, InitLoc);
432   }
433 
434   /// \brief Create a direct initialization due to a cast that isn't a C-style
435   /// or functional cast.
CreateCast(SourceRange TypeRange)436   static InitializationKind CreateCast(SourceRange TypeRange) {
437     return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
438                               TypeRange.getBegin(), TypeRange.getEnd());
439   }
440 
441   /// \brief Create a direct initialization for a C-style cast.
CreateCStyleCast(SourceLocation StartLoc,SourceRange TypeRange,bool InitList)442   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
443                                              SourceRange TypeRange,
444                                              bool InitList) {
445     // C++ cast syntax doesn't permit init lists, but C compound literals are
446     // exactly that.
447     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
448                               IC_CStyleCast, StartLoc, TypeRange.getBegin(),
449                               TypeRange.getEnd());
450   }
451 
452   /// \brief Create a direct initialization for a functional cast.
CreateFunctionalCast(SourceRange TypeRange,bool InitList)453   static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
454                                                  bool InitList) {
455     return InitializationKind(InitList ? IK_DirectList : IK_Direct,
456                               IC_FunctionalCast, TypeRange.getBegin(),
457                               TypeRange.getBegin(), TypeRange.getEnd());
458   }
459 
460   /// \brief Create a copy initialization.
461   static InitializationKind CreateCopy(SourceLocation InitLoc,
462                                        SourceLocation EqualLoc,
463                                        bool AllowExplicitConvs = false) {
464     return InitializationKind(IK_Copy,
465                               AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
466                               InitLoc, EqualLoc, EqualLoc);
467   }
468 
469   /// \brief Create a default initialization.
CreateDefault(SourceLocation InitLoc)470   static InitializationKind CreateDefault(SourceLocation InitLoc) {
471     return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
472   }
473 
474   /// \brief Create a value initialization.
475   static InitializationKind CreateValue(SourceLocation InitLoc,
476                                         SourceLocation LParenLoc,
477                                         SourceLocation RParenLoc,
478                                         bool isImplicit = false) {
479     return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
480                               InitLoc, LParenLoc, RParenLoc);
481   }
482 
483   /// \brief Determine the initialization kind.
getKind()484   InitKind getKind() const {
485     return Kind;
486   }
487 
488   /// \brief Determine whether this initialization is an explicit cast.
isExplicitCast()489   bool isExplicitCast() const {
490     return Context >= IC_StaticCast;
491   }
492 
493   /// \brief Determine whether this initialization is a C-style cast.
isCStyleOrFunctionalCast()494   bool isCStyleOrFunctionalCast() const {
495     return Context >= IC_CStyleCast;
496   }
497 
498   /// \brief Determine whether this is a C-style cast.
isCStyleCast()499   bool isCStyleCast() const {
500     return Context == IC_CStyleCast;
501   }
502 
503   /// \brief Determine whether this is a functional-style cast.
isFunctionalCast()504   bool isFunctionalCast() const {
505     return Context == IC_FunctionalCast;
506   }
507 
508   /// \brief Determine whether this initialization is an implicit
509   /// value-initialization, e.g., as occurs during aggregate
510   /// initialization.
isImplicitValueInit()511   bool isImplicitValueInit() const { return Context == IC_Implicit; }
512 
513   /// \brief Retrieve the location at which initialization is occurring.
getLocation()514   SourceLocation getLocation() const { return Locations[0]; }
515 
516   /// \brief Retrieve the source range that covers the initialization.
getRange()517   SourceRange getRange() const {
518     return SourceRange(Locations[0], Locations[2]);
519   }
520 
521   /// \brief Retrieve the location of the equal sign for copy initialization
522   /// (if present).
getEqualLoc()523   SourceLocation getEqualLoc() const {
524     assert(Kind == IK_Copy && "Only copy initialization has an '='");
525     return Locations[1];
526   }
527 
isCopyInit()528   bool isCopyInit() const { return Kind == IK_Copy; }
529 
530   /// \brief Retrieve whether this initialization allows the use of explicit
531   ///        constructors.
AllowExplicit()532   bool AllowExplicit() const { return !isCopyInit(); }
533 
534   /// \brief Retrieve whether this initialization allows the use of explicit
535   /// conversion functions.
allowExplicitConversionFunctions()536   bool allowExplicitConversionFunctions() const {
537     return !isCopyInit() || Context == IC_ExplicitConvs;
538   }
539 
540   /// \brief Retrieve the source range containing the locations of the open
541   /// and closing parentheses for value and direct initializations.
getParenRange()542   SourceRange getParenRange() const {
543     assert((Kind == IK_Direct || Kind == IK_Value) &&
544            "Only direct- and value-initialization have parentheses");
545     return SourceRange(Locations[1], Locations[2]);
546   }
547 };
548 
549 /// \brief Describes the sequence of initializations required to initialize
550 /// a given object or reference with a set of arguments.
551 class InitializationSequence {
552 public:
553   /// \brief Describes the kind of initialization sequence computed.
554   enum SequenceKind {
555     /// \brief A failed initialization sequence. The failure kind tells what
556     /// happened.
557     FailedSequence = 0,
558 
559     /// \brief A dependent initialization, which could not be
560     /// type-checked due to the presence of dependent types or
561     /// dependently-typed expressions.
562     DependentSequence,
563 
564     /// \brief A normal sequence.
565     NormalSequence
566   };
567 
568   /// \brief Describes the kind of a particular step in an initialization
569   /// sequence.
570   enum StepKind {
571     /// \brief Resolve the address of an overloaded function to a specific
572     /// function declaration.
573     SK_ResolveAddressOfOverloadedFunction,
574     /// \brief Perform a derived-to-base cast, producing an rvalue.
575     SK_CastDerivedToBaseRValue,
576     /// \brief Perform a derived-to-base cast, producing an xvalue.
577     SK_CastDerivedToBaseXValue,
578     /// \brief Perform a derived-to-base cast, producing an lvalue.
579     SK_CastDerivedToBaseLValue,
580     /// \brief Reference binding to an lvalue.
581     SK_BindReference,
582     /// \brief Reference binding to a temporary.
583     SK_BindReferenceToTemporary,
584     /// \brief An optional copy of a temporary object to another
585     /// temporary object, which is permitted (but not required) by
586     /// C++98/03 but not C++0x.
587     SK_ExtraneousCopyToTemporary,
588     /// \brief Perform a user-defined conversion, either via a conversion
589     /// function or via a constructor.
590     SK_UserConversion,
591     /// \brief Perform a qualification conversion, producing an rvalue.
592     SK_QualificationConversionRValue,
593     /// \brief Perform a qualification conversion, producing an xvalue.
594     SK_QualificationConversionXValue,
595     /// \brief Perform a qualification conversion, producing an lvalue.
596     SK_QualificationConversionLValue,
597     /// \brief Perform an implicit conversion sequence.
598     SK_ConversionSequence,
599     /// \brief Perform list-initialization without a constructor
600     SK_ListInitialization,
601     /// \brief Perform list-initialization with a constructor.
602     SK_ListConstructorCall,
603     /// \brief Unwrap the single-element initializer list for a reference.
604     SK_UnwrapInitList,
605     /// \brief Rewrap the single-element initializer list for a reference.
606     SK_RewrapInitList,
607     /// \brief Perform initialization via a constructor.
608     SK_ConstructorInitialization,
609     /// \brief Zero-initialize the object
610     SK_ZeroInitialization,
611     /// \brief C assignment
612     SK_CAssignment,
613     /// \brief Initialization by string
614     SK_StringInit,
615     /// \brief An initialization that "converts" an Objective-C object
616     /// (not a point to an object) to another Objective-C object type.
617     SK_ObjCObjectConversion,
618     /// \brief Array initialization (from an array rvalue).
619     /// This is a GNU C extension.
620     SK_ArrayInit,
621     /// \brief Array initialization from a parenthesized initializer list.
622     /// This is a GNU C++ extension.
623     SK_ParenthesizedArrayInit,
624     /// \brief Pass an object by indirect copy-and-restore.
625     SK_PassByIndirectCopyRestore,
626     /// \brief Pass an object by indirect restore.
627     SK_PassByIndirectRestore,
628     /// \brief Produce an Objective-C object pointer.
629     SK_ProduceObjCObject,
630     /// \brief Construct a std::initializer_list from an initializer list.
631     SK_StdInitializerList,
632     /// \brief Initialize an OpenCL sampler from an integer.
633     SK_OCLSamplerInit,
634     /// \brief Passing zero to a function where OpenCL event_t is expected.
635     SK_OCLZeroEvent
636   };
637 
638   /// \brief A single step in the initialization sequence.
639   class Step {
640   public:
641     /// \brief The kind of conversion or initialization step we are taking.
642     StepKind Kind;
643 
644     // \brief The type that results from this initialization.
645     QualType Type;
646 
647     struct F {
648       bool HadMultipleCandidates;
649       FunctionDecl *Function;
650       DeclAccessPair FoundDecl;
651     };
652 
653     union {
654       /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
655       /// SK_UserConversion, the function that the expression should be
656       /// resolved to or the conversion function to call, respectively.
657       /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
658       /// the constructor to be called.
659       ///
660       /// Always a FunctionDecl, plus a Boolean flag telling if it was
661       /// selected from an overloaded set having size greater than 1.
662       /// For conversion decls, the naming class is the source type.
663       /// For construct decls, the naming class is the target type.
664       struct F Function;
665 
666       /// \brief When Kind = SK_ConversionSequence, the implicit conversion
667       /// sequence.
668       ImplicitConversionSequence *ICS;
669 
670       /// \brief When Kind = SK_RewrapInitList, the syntactic form of the
671       /// wrapping list.
672       InitListExpr *WrappingSyntacticList;
673     };
674 
675     void Destroy();
676   };
677 
678 private:
679   /// \brief The kind of initialization sequence computed.
680   enum SequenceKind SequenceKind;
681 
682   /// \brief Steps taken by this initialization.
683   SmallVector<Step, 4> Steps;
684 
685 public:
686   /// \brief Describes why initialization failed.
687   enum FailureKind {
688     /// \brief Too many initializers provided for a reference.
689     FK_TooManyInitsForReference,
690     /// \brief Array must be initialized with an initializer list.
691     FK_ArrayNeedsInitList,
692     /// \brief Array must be initialized with an initializer list or a
693     /// string literal.
694     FK_ArrayNeedsInitListOrStringLiteral,
695     /// \brief Array type mismatch.
696     FK_ArrayTypeMismatch,
697     /// \brief Non-constant array initializer
698     FK_NonConstantArrayInit,
699     /// \brief Cannot resolve the address of an overloaded function.
700     FK_AddressOfOverloadFailed,
701     /// \brief Overloading due to reference initialization failed.
702     FK_ReferenceInitOverloadFailed,
703     /// \brief Non-const lvalue reference binding to a temporary.
704     FK_NonConstLValueReferenceBindingToTemporary,
705     /// \brief Non-const lvalue reference binding to an lvalue of unrelated
706     /// type.
707     FK_NonConstLValueReferenceBindingToUnrelated,
708     /// \brief Rvalue reference binding to an lvalue.
709     FK_RValueReferenceBindingToLValue,
710     /// \brief Reference binding drops qualifiers.
711     FK_ReferenceInitDropsQualifiers,
712     /// \brief Reference binding failed.
713     FK_ReferenceInitFailed,
714     /// \brief Implicit conversion failed.
715     FK_ConversionFailed,
716     /// \brief Implicit conversion failed.
717     FK_ConversionFromPropertyFailed,
718     /// \brief Too many initializers for scalar
719     FK_TooManyInitsForScalar,
720     /// \brief Reference initialization from an initializer list
721     FK_ReferenceBindingToInitList,
722     /// \brief Initialization of some unused destination type with an
723     /// initializer list.
724     FK_InitListBadDestinationType,
725     /// \brief Overloading for a user-defined conversion failed.
726     FK_UserConversionOverloadFailed,
727     /// \brief Overloading for initialization by constructor failed.
728     FK_ConstructorOverloadFailed,
729     /// \brief Overloading for list-initialization by constructor failed.
730     FK_ListConstructorOverloadFailed,
731     /// \brief Default-initialization of a 'const' object.
732     FK_DefaultInitOfConst,
733     /// \brief Initialization of an incomplete type.
734     FK_Incomplete,
735     /// \brief Variable-length array must not have an initializer.
736     FK_VariableLengthArrayHasInitializer,
737     /// \brief List initialization failed at some point.
738     FK_ListInitializationFailed,
739     /// \brief Initializer has a placeholder type which cannot be
740     /// resolved by initialization.
741     FK_PlaceholderType,
742     /// \brief Failed to initialize a std::initializer_list because copy
743     /// construction of some element failed.
744     FK_InitListElementCopyFailure,
745     /// \brief List-copy-initialization chose an explicit constructor.
746     FK_ExplicitConstructor
747   };
748 
749 private:
750   /// \brief The reason why initialization failed.
751   FailureKind Failure;
752 
753   /// \brief The failed result of overload resolution.
754   OverloadingResult FailedOverloadResult;
755 
756   /// \brief The candidate set created when initialization failed.
757   OverloadCandidateSet FailedCandidateSet;
758 
759   /// \brief The incomplete type that caused a failure.
760   QualType FailedIncompleteType;
761 
762   /// \brief Prints a follow-up note that highlights the location of
763   /// the initialized entity, if it's remote.
764   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
765 
766 public:
767   /// \brief Try to perform initialization of the given entity, creating a
768   /// record of the steps required to perform the initialization.
769   ///
770   /// The generated initialization sequence will either contain enough
771   /// information to diagnose
772   ///
773   /// \param S the semantic analysis object.
774   ///
775   /// \param Entity the entity being initialized.
776   ///
777   /// \param Kind the kind of initialization being performed.
778   ///
779   /// \param Args the argument(s) provided for initialization.
780   ///
781   /// \param NumArgs the number of arguments provided for initialization.
782   InitializationSequence(Sema &S,
783                          const InitializedEntity &Entity,
784                          const InitializationKind &Kind,
785                          Expr **Args,
786                          unsigned NumArgs);
787 
788   ~InitializationSequence();
789 
790   /// \brief Perform the actual initialization of the given entity based on
791   /// the computed initialization sequence.
792   ///
793   /// \param S the semantic analysis object.
794   ///
795   /// \param Entity the entity being initialized.
796   ///
797   /// \param Kind the kind of initialization being performed.
798   ///
799   /// \param Args the argument(s) provided for initialization, ownership of
800   /// which is transferred into the routine.
801   ///
802   /// \param ResultType if non-NULL, will be set to the type of the
803   /// initialized object, which is the type of the declaration in most
804   /// cases. However, when the initialized object is a variable of
805   /// incomplete array type and the initializer is an initializer
806   /// list, this type will be set to the completed array type.
807   ///
808   /// \returns an expression that performs the actual object initialization, if
809   /// the initialization is well-formed. Otherwise, emits diagnostics
810   /// and returns an invalid expression.
811   ExprResult Perform(Sema &S,
812                      const InitializedEntity &Entity,
813                      const InitializationKind &Kind,
814                      MultiExprArg Args,
815                      QualType *ResultType = 0);
816 
817   /// \brief Diagnose an potentially-invalid initialization sequence.
818   ///
819   /// \returns true if the initialization sequence was ill-formed,
820   /// false otherwise.
821   bool Diagnose(Sema &S,
822                 const InitializedEntity &Entity,
823                 const InitializationKind &Kind,
824                 Expr **Args, unsigned NumArgs);
825 
826   /// \brief Determine the kind of initialization sequence computed.
getKind()827   enum SequenceKind getKind() const { return SequenceKind; }
828 
829   /// \brief Set the kind of sequence computed.
setSequenceKind(enum SequenceKind SK)830   void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
831 
832   /// \brief Determine whether the initialization sequence is valid.
833   operator bool() const { return !Failed(); }
834 
835   /// \brief Determine whether the initialization sequence is invalid.
Failed()836   bool Failed() const { return SequenceKind == FailedSequence; }
837 
838   typedef SmallVector<Step, 4>::const_iterator step_iterator;
step_begin()839   step_iterator step_begin() const { return Steps.begin(); }
step_end()840   step_iterator step_end()   const { return Steps.end(); }
841 
842   /// \brief Determine whether this initialization is a direct reference
843   /// binding (C++ [dcl.init.ref]).
844   bool isDirectReferenceBinding() const;
845 
846   /// \brief Determine whether this initialization failed due to an ambiguity.
847   bool isAmbiguous() const;
848 
849   /// \brief Determine whether this initialization is direct call to a
850   /// constructor.
851   bool isConstructorInitialization() const;
852 
853   /// \brief Returns whether the last step in this initialization sequence is a
854   /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
855   ///
856   /// If this function returns true, *isInitializerConstant will be set to
857   /// describe whether *Initializer was a constant expression.  If
858   /// *isInitializerConstant is set to true, *ConstantValue will be set to the
859   /// evaluated value of *Initializer.
860   bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
861                          bool *isInitializerConstant,
862                          APValue *ConstantValue) const;
863 
864   /// \brief Add a new step in the initialization that resolves the address
865   /// of an overloaded function to a specific function declaration.
866   ///
867   /// \param Function the function to which the overloaded function reference
868   /// resolves.
869   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
870                                         DeclAccessPair Found,
871                                         bool HadMultipleCandidates);
872 
873   /// \brief Add a new step in the initialization that performs a derived-to-
874   /// base cast.
875   ///
876   /// \param BaseType the base type to which we will be casting.
877   ///
878   /// \param Category Indicates whether the result will be treated as an
879   /// rvalue, an xvalue, or an lvalue.
880   void AddDerivedToBaseCastStep(QualType BaseType,
881                                 ExprValueKind Category);
882 
883   /// \brief Add a new step binding a reference to an object.
884   ///
885   /// \param BindingTemporary True if we are binding a reference to a temporary
886   /// object (thereby extending its lifetime); false if we are binding to an
887   /// lvalue or an lvalue treated as an rvalue.
888   void AddReferenceBindingStep(QualType T, bool BindingTemporary);
889 
890   /// \brief Add a new step that makes an extraneous copy of the input
891   /// to a temporary of the same class type.
892   ///
893   /// This extraneous copy only occurs during reference binding in
894   /// C++98/03, where we are permitted (but not required) to introduce
895   /// an extra copy. At a bare minimum, we must check that we could
896   /// call the copy constructor, and produce a diagnostic if the copy
897   /// constructor is inaccessible or no copy constructor matches.
898   //
899   /// \param T The type of the temporary being created.
900   void AddExtraneousCopyToTemporary(QualType T);
901 
902   /// \brief Add a new step invoking a conversion function, which is either
903   /// a constructor or a conversion function.
904   void AddUserConversionStep(FunctionDecl *Function,
905                              DeclAccessPair FoundDecl,
906                              QualType T,
907                              bool HadMultipleCandidates);
908 
909   /// \brief Add a new step that performs a qualification conversion to the
910   /// given type.
911   void AddQualificationConversionStep(QualType Ty,
912                                      ExprValueKind Category);
913 
914   /// \brief Add a new step that applies an implicit conversion sequence.
915   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
916                                  QualType T);
917 
918   /// \brief Add a list-initialization step.
919   void AddListInitializationStep(QualType T);
920 
921   /// \brief Add a constructor-initialization step.
922   ///
923   /// \param FromInitList The constructor call is syntactically an initializer
924   /// list.
925   /// \param AsInitList The constructor is called as an init list constructor.
926   void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
927                                         AccessSpecifier Access,
928                                         QualType T,
929                                         bool HadMultipleCandidates,
930                                         bool FromInitList, bool AsInitList);
931 
932   /// \brief Add a zero-initialization step.
933   void AddZeroInitializationStep(QualType T);
934 
935   /// \brief Add a C assignment step.
936   //
937   // FIXME: It isn't clear whether this should ever be needed;
938   // ideally, we would handle everything needed in C in the common
939   // path. However, that isn't the case yet.
940   void AddCAssignmentStep(QualType T);
941 
942   /// \brief Add a string init step.
943   void AddStringInitStep(QualType T);
944 
945   /// \brief Add an Objective-C object conversion step, which is
946   /// always a no-op.
947   void AddObjCObjectConversionStep(QualType T);
948 
949   /// \brief Add an array initialization step.
950   void AddArrayInitStep(QualType T);
951 
952   /// \brief Add a parenthesized array initialization step.
953   void AddParenthesizedArrayInitStep(QualType T);
954 
955   /// \brief Add a step to pass an object by indirect copy-restore.
956   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
957 
958   /// \brief Add a step to "produce" an Objective-C object (by
959   /// retaining it).
960   void AddProduceObjCObjectStep(QualType T);
961 
962   /// \brief Add a step to construct a std::initializer_list object from an
963   /// initializer list.
964   void AddStdInitializerListConstructionStep(QualType T);
965 
966   /// \brief Add a step to initialize an OpenCL sampler from an integer
967   /// constant.
968   void AddOCLSamplerInitStep(QualType T);
969 
970   /// \brief Add a step to initialize an OpenCL event_t from a NULL
971   /// constant.
972   void AddOCLZeroEventStep(QualType T);
973 
974   /// \brief Add steps to unwrap a initializer list for a reference around a
975   /// single element and rewrap it at the end.
976   void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
977 
978   /// \brief Note that this initialization sequence failed.
SetFailed(FailureKind Failure)979   void SetFailed(FailureKind Failure) {
980     SequenceKind = FailedSequence;
981     this->Failure = Failure;
982     assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
983            "Incomplete type failure requires a type!");
984   }
985 
986   /// \brief Note that this initialization sequence failed due to failed
987   /// overload resolution.
988   void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
989 
990   /// \brief Retrieve a reference to the candidate set when overload
991   /// resolution fails.
getFailedCandidateSet()992   OverloadCandidateSet &getFailedCandidateSet() {
993     return FailedCandidateSet;
994   }
995 
996   /// \brief Get the overloading result, for when the initialization
997   /// sequence failed due to a bad overload.
getFailedOverloadResult()998   OverloadingResult getFailedOverloadResult() const {
999     return FailedOverloadResult;
1000   }
1001 
1002   /// \brief Note that this initialization sequence failed due to an
1003   /// incomplete type.
setIncompleteTypeFailure(QualType IncompleteType)1004   void setIncompleteTypeFailure(QualType IncompleteType) {
1005     FailedIncompleteType = IncompleteType;
1006     SetFailed(FK_Incomplete);
1007   }
1008 
1009   /// \brief Determine why initialization failed.
getFailureKind()1010   FailureKind getFailureKind() const {
1011     assert(Failed() && "Not an initialization failure!");
1012     return Failure;
1013   }
1014 
1015   /// \brief Dump a representation of this initialization sequence to
1016   /// the given stream, for debugging purposes.
1017   void dump(raw_ostream &OS) const;
1018 
1019   /// \brief Dump a representation of this initialization sequence to
1020   /// standard error, for debugging purposes.
1021   void dump() const;
1022 };
1023 
1024 } // end namespace clang
1025 
1026 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H
1027