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