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