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