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