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