1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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 implements semantic analysis for initializers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/Initialization.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/Designator.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/SemaInternal.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <map>
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Sema Initialization Checking
33 //===----------------------------------------------------------------------===//
34 
35 static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36                           ASTContext &Context) {
37   if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38     return 0;
39 
40   // See if this is a string literal or @encode.
41   Init = Init->IgnoreParens();
42 
43   // Handle @encode, which is a narrow string.
44   if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45     return Init;
46 
47   // Otherwise we can only handle string literals.
48   StringLiteral *SL = dyn_cast<StringLiteral>(Init);
49   if (SL == 0) return 0;
50 
51   QualType ElemTy = Context.getCanonicalType(AT->getElementType());
52 
53   switch (SL->getKind()) {
54   case StringLiteral::Ascii:
55   case StringLiteral::UTF8:
56     // char array can be initialized with a narrow string.
57     // Only allow char x[] = "foo";  not char x[] = L"foo";
58     return ElemTy->isCharType() ? Init : 0;
59   case StringLiteral::UTF16:
60     return ElemTy->isChar16Type() ? Init : 0;
61   case StringLiteral::UTF32:
62     return ElemTy->isChar32Type() ? Init : 0;
63   case StringLiteral::Wide:
64     // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65     // correction from DR343): "An array with element type compatible with a
66     // qualified or unqualified version of wchar_t may be initialized by a wide
67     // string literal, optionally enclosed in braces."
68     if (Context.typesAreCompatible(Context.getWCharType(),
69                                    ElemTy.getUnqualifiedType()))
70       return Init;
71 
72     return 0;
73   }
74 
75   llvm_unreachable("missed a StringLiteral kind?");
76 }
77 
78 static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79   const ArrayType *arrayType = Context.getAsArrayType(declType);
80   if (!arrayType) return 0;
81 
82   return IsStringInit(init, arrayType, Context);
83 }
84 
85 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86                             Sema &S) {
87   // Get the length of the string as parsed.
88   uint64_t StrLength =
89     cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90 
91 
92   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
93     // C99 6.7.8p14. We have an array of character type with unknown size
94     // being initialized to a string literal.
95     llvm::APInt ConstVal(32, StrLength);
96     // Return a new array type (C99 6.7.8p22).
97     DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98                                            ConstVal,
99                                            ArrayType::Normal, 0);
100     return;
101   }
102 
103   const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
104 
105   // We have an array of character type with known size.  However,
106   // the size may be smaller or larger than the string we are initializing.
107   // FIXME: Avoid truncation for 64-bit length strings.
108   if (S.getLangOpts().CPlusPlus) {
109     if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110       // For Pascal strings it's OK to strip off the terminating null character,
111       // so the example below is valid:
112       //
113       // unsigned char a[2] = "\pa";
114       if (SL->isPascal())
115         StrLength--;
116     }
117 
118     // [dcl.init.string]p2
119     if (StrLength > CAT->getSize().getZExtValue())
120       S.Diag(Str->getLocStart(),
121              diag::err_initializer_string_for_char_array_too_long)
122         << Str->getSourceRange();
123   } else {
124     // C99 6.7.8p14.
125     if (StrLength-1 > CAT->getSize().getZExtValue())
126       S.Diag(Str->getLocStart(),
127              diag::warn_initializer_string_for_char_array_too_long)
128         << Str->getSourceRange();
129   }
130 
131   // Set the type to the actual size that we are initializing.  If we have
132   // something like:
133   //   char x[1] = "foo";
134   // then this will set the string literal's type to char[1].
135   Str->setType(DeclT);
136 }
137 
138 //===----------------------------------------------------------------------===//
139 // Semantic checking for initializer lists.
140 //===----------------------------------------------------------------------===//
141 
142 /// @brief Semantic checking for initializer lists.
143 ///
144 /// The InitListChecker class contains a set of routines that each
145 /// handle the initialization of a certain kind of entity, e.g.,
146 /// arrays, vectors, struct/union types, scalars, etc. The
147 /// InitListChecker itself performs a recursive walk of the subobject
148 /// structure of the type to be initialized, while stepping through
149 /// the initializer list one element at a time. The IList and Index
150 /// parameters to each of the Check* routines contain the active
151 /// (syntactic) initializer list and the index into that initializer
152 /// list that represents the current initializer. Each routine is
153 /// responsible for moving that Index forward as it consumes elements.
154 ///
155 /// Each Check* routine also has a StructuredList/StructuredIndex
156 /// arguments, which contains the current "structured" (semantic)
157 /// initializer list and the index into that initializer list where we
158 /// are copying initializers as we map them over to the semantic
159 /// list. Once we have completed our recursive walk of the subobject
160 /// structure, we will have constructed a full semantic initializer
161 /// list.
162 ///
163 /// C99 designators cause changes in the initializer list traversal,
164 /// because they make the initialization "jump" into a specific
165 /// subobject and then continue the initialization from that
166 /// point. CheckDesignatedInitializer() recursively steps into the
167 /// designated subobject and manages backing out the recursion to
168 /// initialize the subobjects after the one designated.
169 namespace {
170 class InitListChecker {
171   Sema &SemaRef;
172   bool hadError;
173   bool VerifyOnly; // no diagnostics, no structure building
174   bool AllowBraceElision;
175   llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
176   InitListExpr *FullyStructuredList;
177 
178   void CheckImplicitInitList(const InitializedEntity &Entity,
179                              InitListExpr *ParentIList, QualType T,
180                              unsigned &Index, InitListExpr *StructuredList,
181                              unsigned &StructuredIndex);
182   void CheckExplicitInitList(const InitializedEntity &Entity,
183                              InitListExpr *IList, QualType &T,
184                              unsigned &Index, InitListExpr *StructuredList,
185                              unsigned &StructuredIndex,
186                              bool TopLevelObject = false);
187   void CheckListElementTypes(const InitializedEntity &Entity,
188                              InitListExpr *IList, QualType &DeclType,
189                              bool SubobjectIsDesignatorContext,
190                              unsigned &Index,
191                              InitListExpr *StructuredList,
192                              unsigned &StructuredIndex,
193                              bool TopLevelObject = false);
194   void CheckSubElementType(const InitializedEntity &Entity,
195                            InitListExpr *IList, QualType ElemType,
196                            unsigned &Index,
197                            InitListExpr *StructuredList,
198                            unsigned &StructuredIndex);
199   void CheckComplexType(const InitializedEntity &Entity,
200                         InitListExpr *IList, QualType DeclType,
201                         unsigned &Index,
202                         InitListExpr *StructuredList,
203                         unsigned &StructuredIndex);
204   void CheckScalarType(const InitializedEntity &Entity,
205                        InitListExpr *IList, QualType DeclType,
206                        unsigned &Index,
207                        InitListExpr *StructuredList,
208                        unsigned &StructuredIndex);
209   void CheckReferenceType(const InitializedEntity &Entity,
210                           InitListExpr *IList, QualType DeclType,
211                           unsigned &Index,
212                           InitListExpr *StructuredList,
213                           unsigned &StructuredIndex);
214   void CheckVectorType(const InitializedEntity &Entity,
215                        InitListExpr *IList, QualType DeclType, unsigned &Index,
216                        InitListExpr *StructuredList,
217                        unsigned &StructuredIndex);
218   void CheckStructUnionTypes(const InitializedEntity &Entity,
219                              InitListExpr *IList, QualType DeclType,
220                              RecordDecl::field_iterator Field,
221                              bool SubobjectIsDesignatorContext, unsigned &Index,
222                              InitListExpr *StructuredList,
223                              unsigned &StructuredIndex,
224                              bool TopLevelObject = false);
225   void CheckArrayType(const InitializedEntity &Entity,
226                       InitListExpr *IList, QualType &DeclType,
227                       llvm::APSInt elementIndex,
228                       bool SubobjectIsDesignatorContext, unsigned &Index,
229                       InitListExpr *StructuredList,
230                       unsigned &StructuredIndex);
231   bool CheckDesignatedInitializer(const InitializedEntity &Entity,
232                                   InitListExpr *IList, DesignatedInitExpr *DIE,
233                                   unsigned DesigIdx,
234                                   QualType &CurrentObjectType,
235                                   RecordDecl::field_iterator *NextField,
236                                   llvm::APSInt *NextElementIndex,
237                                   unsigned &Index,
238                                   InitListExpr *StructuredList,
239                                   unsigned &StructuredIndex,
240                                   bool FinishSubobjectInit,
241                                   bool TopLevelObject);
242   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243                                            QualType CurrentObjectType,
244                                            InitListExpr *StructuredList,
245                                            unsigned StructuredIndex,
246                                            SourceRange InitRange);
247   void UpdateStructuredListElement(InitListExpr *StructuredList,
248                                    unsigned &StructuredIndex,
249                                    Expr *expr);
250   int numArrayElements(QualType DeclType);
251   int numStructUnionElements(QualType DeclType);
252 
253   void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254                                const InitializedEntity &ParentEntity,
255                                InitListExpr *ILE, bool &RequiresSecondPass);
256   void FillInValueInitializations(const InitializedEntity &Entity,
257                                   InitListExpr *ILE, bool &RequiresSecondPass);
258   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259                               Expr *InitExpr, FieldDecl *Field,
260                               bool TopLevelObject);
261   void CheckValueInitializable(const InitializedEntity &Entity);
262 
263 public:
264   InitListChecker(Sema &S, const InitializedEntity &Entity,
265                   InitListExpr *IL, QualType &T, bool VerifyOnly,
266                   bool AllowBraceElision);
267   bool HadError() { return hadError; }
268 
269   // @brief Retrieves the fully-structured initializer list used for
270   // semantic analysis and code generation.
271   InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272 };
273 } // end anonymous namespace
274 
275 void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276   assert(VerifyOnly &&
277          "CheckValueInitializable is only inteded for verification mode.");
278 
279   SourceLocation Loc;
280   InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281                                                             true);
282   InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283   if (InitSeq.Failed())
284     hadError = true;
285 }
286 
287 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288                                         const InitializedEntity &ParentEntity,
289                                               InitListExpr *ILE,
290                                               bool &RequiresSecondPass) {
291   SourceLocation Loc = ILE->getLocStart();
292   unsigned NumInits = ILE->getNumInits();
293   InitializedEntity MemberEntity
294     = InitializedEntity::InitializeMember(Field, &ParentEntity);
295   if (Init >= NumInits || !ILE->getInit(Init)) {
296     // If there's no explicit initializer but we have a default initializer, use
297     // that. This only happens in C++1y, since classes with default
298     // initializers are not aggregates in C++11.
299     if (Field->hasInClassInitializer()) {
300       Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
301                                              ILE->getRBraceLoc(), Field);
302       if (Init < NumInits)
303         ILE->setInit(Init, DIE);
304       else {
305         ILE->updateInit(SemaRef.Context, Init, DIE);
306         RequiresSecondPass = true;
307       }
308       return;
309     }
310 
311     // FIXME: We probably don't need to handle references
312     // specially here, since value-initialization of references is
313     // handled in InitializationSequence.
314     if (Field->getType()->isReferenceType()) {
315       // C++ [dcl.init.aggr]p9:
316       //   If an incomplete or empty initializer-list leaves a
317       //   member of reference type uninitialized, the program is
318       //   ill-formed.
319       SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
320         << Field->getType()
321         << ILE->getSyntacticForm()->getSourceRange();
322       SemaRef.Diag(Field->getLocation(),
323                    diag::note_uninit_reference_member);
324       hadError = true;
325       return;
326     }
327 
328     InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
329                                                               true);
330     InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
331     if (!InitSeq) {
332       InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
333       hadError = true;
334       return;
335     }
336 
337     ExprResult MemberInit
338       = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
339     if (MemberInit.isInvalid()) {
340       hadError = true;
341       return;
342     }
343 
344     if (hadError) {
345       // Do nothing
346     } else if (Init < NumInits) {
347       ILE->setInit(Init, MemberInit.takeAs<Expr>());
348     } else if (InitSeq.isConstructorInitialization()) {
349       // Value-initialization requires a constructor call, so
350       // extend the initializer list to include the constructor
351       // call and make a note that we'll need to take another pass
352       // through the initializer list.
353       ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
354       RequiresSecondPass = true;
355     }
356   } else if (InitListExpr *InnerILE
357                = dyn_cast<InitListExpr>(ILE->getInit(Init)))
358     FillInValueInitializations(MemberEntity, InnerILE,
359                                RequiresSecondPass);
360 }
361 
362 /// Recursively replaces NULL values within the given initializer list
363 /// with expressions that perform value-initialization of the
364 /// appropriate type.
365 void
366 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
367                                             InitListExpr *ILE,
368                                             bool &RequiresSecondPass) {
369   assert((ILE->getType() != SemaRef.Context.VoidTy) &&
370          "Should not have void type");
371   SourceLocation Loc = ILE->getLocStart();
372   if (ILE->getSyntacticForm())
373     Loc = ILE->getSyntacticForm()->getLocStart();
374 
375   if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
376     const RecordDecl *RDecl = RType->getDecl();
377     if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
378       FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
379                               Entity, ILE, RequiresSecondPass);
380     else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
381              cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
382       for (RecordDecl::field_iterator Field = RDecl->field_begin(),
383                                       FieldEnd = RDecl->field_end();
384            Field != FieldEnd; ++Field) {
385         if (Field->hasInClassInitializer()) {
386           FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
387           break;
388         }
389       }
390     } else {
391       unsigned Init = 0;
392       for (RecordDecl::field_iterator Field = RDecl->field_begin(),
393                                       FieldEnd = RDecl->field_end();
394            Field != FieldEnd; ++Field) {
395         if (Field->isUnnamedBitfield())
396           continue;
397 
398         if (hadError)
399           return;
400 
401         FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
402         if (hadError)
403           return;
404 
405         ++Init;
406 
407         // Only look at the first initialization of a union.
408         if (RDecl->isUnion())
409           break;
410       }
411     }
412 
413     return;
414   }
415 
416   QualType ElementType;
417 
418   InitializedEntity ElementEntity = Entity;
419   unsigned NumInits = ILE->getNumInits();
420   unsigned NumElements = NumInits;
421   if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
422     ElementType = AType->getElementType();
423     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
424       NumElements = CAType->getSize().getZExtValue();
425     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
426                                                          0, Entity);
427   } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
428     ElementType = VType->getElementType();
429     NumElements = VType->getNumElements();
430     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
431                                                          0, Entity);
432   } else
433     ElementType = ILE->getType();
434 
435 
436   for (unsigned Init = 0; Init != NumElements; ++Init) {
437     if (hadError)
438       return;
439 
440     if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
441         ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
442       ElementEntity.setElementIndex(Init);
443 
444     Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
445     if (!InitExpr && !ILE->hasArrayFiller()) {
446       InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
447                                                                 true);
448       InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
449       if (!InitSeq) {
450         InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
451         hadError = true;
452         return;
453       }
454 
455       ExprResult ElementInit
456         = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
457       if (ElementInit.isInvalid()) {
458         hadError = true;
459         return;
460       }
461 
462       if (hadError) {
463         // Do nothing
464       } else if (Init < NumInits) {
465         // For arrays, just set the expression used for value-initialization
466         // of the "holes" in the array.
467         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
468           ILE->setArrayFiller(ElementInit.takeAs<Expr>());
469         else
470           ILE->setInit(Init, ElementInit.takeAs<Expr>());
471       } else {
472         // For arrays, just set the expression used for value-initialization
473         // of the rest of elements and exit.
474         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
475           ILE->setArrayFiller(ElementInit.takeAs<Expr>());
476           return;
477         }
478 
479         if (InitSeq.isConstructorInitialization()) {
480           // Value-initialization requires a constructor call, so
481           // extend the initializer list to include the constructor
482           // call and make a note that we'll need to take another pass
483           // through the initializer list.
484           ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
485           RequiresSecondPass = true;
486         }
487       }
488     } else if (InitListExpr *InnerILE
489                  = dyn_cast_or_null<InitListExpr>(InitExpr))
490       FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
491   }
492 }
493 
494 
495 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
496                                  InitListExpr *IL, QualType &T,
497                                  bool VerifyOnly, bool AllowBraceElision)
498   : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
499   hadError = false;
500 
501   unsigned newIndex = 0;
502   unsigned newStructuredIndex = 0;
503   FullyStructuredList
504     = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
505   CheckExplicitInitList(Entity, IL, T, newIndex,
506                         FullyStructuredList, newStructuredIndex,
507                         /*TopLevelObject=*/true);
508 
509   if (!hadError && !VerifyOnly) {
510     bool RequiresSecondPass = false;
511     FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
512     if (RequiresSecondPass && !hadError)
513       FillInValueInitializations(Entity, FullyStructuredList,
514                                  RequiresSecondPass);
515   }
516 }
517 
518 int InitListChecker::numArrayElements(QualType DeclType) {
519   // FIXME: use a proper constant
520   int maxElements = 0x7FFFFFFF;
521   if (const ConstantArrayType *CAT =
522         SemaRef.Context.getAsConstantArrayType(DeclType)) {
523     maxElements = static_cast<int>(CAT->getSize().getZExtValue());
524   }
525   return maxElements;
526 }
527 
528 int InitListChecker::numStructUnionElements(QualType DeclType) {
529   RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
530   int InitializableMembers = 0;
531   for (RecordDecl::field_iterator
532          Field = structDecl->field_begin(),
533          FieldEnd = structDecl->field_end();
534        Field != FieldEnd; ++Field) {
535     if (!Field->isUnnamedBitfield())
536       ++InitializableMembers;
537   }
538   if (structDecl->isUnion())
539     return std::min(InitializableMembers, 1);
540   return InitializableMembers - structDecl->hasFlexibleArrayMember();
541 }
542 
543 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
544                                             InitListExpr *ParentIList,
545                                             QualType T, unsigned &Index,
546                                             InitListExpr *StructuredList,
547                                             unsigned &StructuredIndex) {
548   int maxElements = 0;
549 
550   if (T->isArrayType())
551     maxElements = numArrayElements(T);
552   else if (T->isRecordType())
553     maxElements = numStructUnionElements(T);
554   else if (T->isVectorType())
555     maxElements = T->getAs<VectorType>()->getNumElements();
556   else
557     llvm_unreachable("CheckImplicitInitList(): Illegal type");
558 
559   if (maxElements == 0) {
560     if (!VerifyOnly)
561       SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
562                    diag::err_implicit_empty_initializer);
563     ++Index;
564     hadError = true;
565     return;
566   }
567 
568   // Build a structured initializer list corresponding to this subobject.
569   InitListExpr *StructuredSubobjectInitList
570     = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
571                                  StructuredIndex,
572           SourceRange(ParentIList->getInit(Index)->getLocStart(),
573                       ParentIList->getSourceRange().getEnd()));
574   unsigned StructuredSubobjectInitIndex = 0;
575 
576   // Check the element types and build the structural subobject.
577   unsigned StartIndex = Index;
578   CheckListElementTypes(Entity, ParentIList, T,
579                         /*SubobjectIsDesignatorContext=*/false, Index,
580                         StructuredSubobjectInitList,
581                         StructuredSubobjectInitIndex);
582 
583   if (VerifyOnly) {
584     if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
585       hadError = true;
586   } else {
587     StructuredSubobjectInitList->setType(T);
588 
589     unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
590     // Update the structured sub-object initializer so that it's ending
591     // range corresponds with the end of the last initializer it used.
592     if (EndIndex < ParentIList->getNumInits()) {
593       SourceLocation EndLoc
594         = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
595       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
596     }
597 
598     // Complain about missing braces.
599     if (T->isArrayType() || T->isRecordType()) {
600       SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
601                     AllowBraceElision ? diag::warn_missing_braces :
602                                         diag::err_missing_braces)
603         << StructuredSubobjectInitList->getSourceRange()
604         << FixItHint::CreateInsertion(
605               StructuredSubobjectInitList->getLocStart(), "{")
606         << FixItHint::CreateInsertion(
607               SemaRef.PP.getLocForEndOfToken(
608                                       StructuredSubobjectInitList->getLocEnd()),
609               "}");
610       if (!AllowBraceElision)
611         hadError = true;
612     }
613   }
614 }
615 
616 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
617                                             InitListExpr *IList, QualType &T,
618                                             unsigned &Index,
619                                             InitListExpr *StructuredList,
620                                             unsigned &StructuredIndex,
621                                             bool TopLevelObject) {
622   assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
623   if (!VerifyOnly) {
624     SyntacticToSemantic[IList] = StructuredList;
625     StructuredList->setSyntacticForm(IList);
626   }
627   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
628                         Index, StructuredList, StructuredIndex, TopLevelObject);
629   if (!VerifyOnly) {
630     QualType ExprTy = T;
631     if (!ExprTy->isArrayType())
632       ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
633     IList->setType(ExprTy);
634     StructuredList->setType(ExprTy);
635   }
636   if (hadError)
637     return;
638 
639   if (Index < IList->getNumInits()) {
640     // We have leftover initializers
641     if (VerifyOnly) {
642       if (SemaRef.getLangOpts().CPlusPlus ||
643           (SemaRef.getLangOpts().OpenCL &&
644            IList->getType()->isVectorType())) {
645         hadError = true;
646       }
647       return;
648     }
649 
650     if (StructuredIndex == 1 &&
651         IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
652       unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
653       if (SemaRef.getLangOpts().CPlusPlus) {
654         DK = diag::err_excess_initializers_in_char_array_initializer;
655         hadError = true;
656       }
657       // Special-case
658       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
659         << IList->getInit(Index)->getSourceRange();
660     } else if (!T->isIncompleteType()) {
661       // Don't complain for incomplete types, since we'll get an error
662       // elsewhere
663       QualType CurrentObjectType = StructuredList->getType();
664       int initKind =
665         CurrentObjectType->isArrayType()? 0 :
666         CurrentObjectType->isVectorType()? 1 :
667         CurrentObjectType->isScalarType()? 2 :
668         CurrentObjectType->isUnionType()? 3 :
669         4;
670 
671       unsigned DK = diag::warn_excess_initializers;
672       if (SemaRef.getLangOpts().CPlusPlus) {
673         DK = diag::err_excess_initializers;
674         hadError = true;
675       }
676       if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
677         DK = diag::err_excess_initializers;
678         hadError = true;
679       }
680 
681       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
682         << initKind << IList->getInit(Index)->getSourceRange();
683     }
684   }
685 
686   if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
687       !TopLevelObject)
688     SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
689       << IList->getSourceRange()
690       << FixItHint::CreateRemoval(IList->getLocStart())
691       << FixItHint::CreateRemoval(IList->getLocEnd());
692 }
693 
694 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
695                                             InitListExpr *IList,
696                                             QualType &DeclType,
697                                             bool SubobjectIsDesignatorContext,
698                                             unsigned &Index,
699                                             InitListExpr *StructuredList,
700                                             unsigned &StructuredIndex,
701                                             bool TopLevelObject) {
702   if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
703     // Explicitly braced initializer for complex type can be real+imaginary
704     // parts.
705     CheckComplexType(Entity, IList, DeclType, Index,
706                      StructuredList, StructuredIndex);
707   } else if (DeclType->isScalarType()) {
708     CheckScalarType(Entity, IList, DeclType, Index,
709                     StructuredList, StructuredIndex);
710   } else if (DeclType->isVectorType()) {
711     CheckVectorType(Entity, IList, DeclType, Index,
712                     StructuredList, StructuredIndex);
713   } else if (DeclType->isRecordType()) {
714     assert(DeclType->isAggregateType() &&
715            "non-aggregate records should be handed in CheckSubElementType");
716     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
717     CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
718                           SubobjectIsDesignatorContext, Index,
719                           StructuredList, StructuredIndex,
720                           TopLevelObject);
721   } else if (DeclType->isArrayType()) {
722     llvm::APSInt Zero(
723                     SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
724                     false);
725     CheckArrayType(Entity, IList, DeclType, Zero,
726                    SubobjectIsDesignatorContext, Index,
727                    StructuredList, StructuredIndex);
728   } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
729     // This type is invalid, issue a diagnostic.
730     ++Index;
731     if (!VerifyOnly)
732       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
733         << DeclType;
734     hadError = true;
735   } else if (DeclType->isReferenceType()) {
736     CheckReferenceType(Entity, IList, DeclType, Index,
737                        StructuredList, StructuredIndex);
738   } else if (DeclType->isObjCObjectType()) {
739     if (!VerifyOnly)
740       SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
741         << DeclType;
742     hadError = true;
743   } else {
744     if (!VerifyOnly)
745       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
746         << DeclType;
747     hadError = true;
748   }
749 }
750 
751 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
752                                           InitListExpr *IList,
753                                           QualType ElemType,
754                                           unsigned &Index,
755                                           InitListExpr *StructuredList,
756                                           unsigned &StructuredIndex) {
757   Expr *expr = IList->getInit(Index);
758   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
759     if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
760       unsigned newIndex = 0;
761       unsigned newStructuredIndex = 0;
762       InitListExpr *newStructuredList
763         = getStructuredSubobjectInit(IList, Index, ElemType,
764                                      StructuredList, StructuredIndex,
765                                      SubInitList->getSourceRange());
766       CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
767                             newStructuredList, newStructuredIndex);
768       ++StructuredIndex;
769       ++Index;
770       return;
771     }
772     assert(SemaRef.getLangOpts().CPlusPlus &&
773            "non-aggregate records are only possible in C++");
774     // C++ initialization is handled later.
775   }
776 
777   if (ElemType->isScalarType()) {
778     return CheckScalarType(Entity, IList, ElemType, Index,
779                            StructuredList, StructuredIndex);
780   } else if (ElemType->isReferenceType()) {
781     return CheckReferenceType(Entity, IList, ElemType, Index,
782                               StructuredList, StructuredIndex);
783   }
784 
785   if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
786     // arrayType can be incomplete if we're initializing a flexible
787     // array member.  There's nothing we can do with the completed
788     // type here, though.
789 
790     if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
791       if (!VerifyOnly) {
792         CheckStringInit(Str, ElemType, arrayType, SemaRef);
793         UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
794       }
795       ++Index;
796       return;
797     }
798 
799     // Fall through for subaggregate initialization.
800 
801   } else if (SemaRef.getLangOpts().CPlusPlus) {
802     // C++ [dcl.init.aggr]p12:
803     //   All implicit type conversions (clause 4) are considered when
804     //   initializing the aggregate member with an initializer from
805     //   an initializer-list. If the initializer can initialize a
806     //   member, the member is initialized. [...]
807 
808     // FIXME: Better EqualLoc?
809     InitializationKind Kind =
810       InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
811     InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
812 
813     if (Seq) {
814       if (!VerifyOnly) {
815         ExprResult Result =
816           Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
817         if (Result.isInvalid())
818           hadError = true;
819 
820         UpdateStructuredListElement(StructuredList, StructuredIndex,
821                                     Result.takeAs<Expr>());
822       }
823       ++Index;
824       return;
825     }
826 
827     // Fall through for subaggregate initialization
828   } else {
829     // C99 6.7.8p13:
830     //
831     //   The initializer for a structure or union object that has
832     //   automatic storage duration shall be either an initializer
833     //   list as described below, or a single expression that has
834     //   compatible structure or union type. In the latter case, the
835     //   initial value of the object, including unnamed members, is
836     //   that of the expression.
837     ExprResult ExprRes = SemaRef.Owned(expr);
838     if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
839         SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
840                                                  !VerifyOnly)
841           == Sema::Compatible) {
842       if (ExprRes.isInvalid())
843         hadError = true;
844       else {
845         ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
846 	      if (ExprRes.isInvalid())
847 	        hadError = true;
848       }
849       UpdateStructuredListElement(StructuredList, StructuredIndex,
850                                   ExprRes.takeAs<Expr>());
851       ++Index;
852       return;
853     }
854     ExprRes.release();
855     // Fall through for subaggregate initialization
856   }
857 
858   // C++ [dcl.init.aggr]p12:
859   //
860   //   [...] Otherwise, if the member is itself a non-empty
861   //   subaggregate, brace elision is assumed and the initializer is
862   //   considered for the initialization of the first member of
863   //   the subaggregate.
864   if (!SemaRef.getLangOpts().OpenCL &&
865       (ElemType->isAggregateType() || ElemType->isVectorType())) {
866     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
867                           StructuredIndex);
868     ++StructuredIndex;
869   } else {
870     if (!VerifyOnly) {
871       // We cannot initialize this element, so let
872       // PerformCopyInitialization produce the appropriate diagnostic.
873       SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
874                                         SemaRef.Owned(expr),
875                                         /*TopLevelOfInitList=*/true);
876     }
877     hadError = true;
878     ++Index;
879     ++StructuredIndex;
880   }
881 }
882 
883 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
884                                        InitListExpr *IList, QualType DeclType,
885                                        unsigned &Index,
886                                        InitListExpr *StructuredList,
887                                        unsigned &StructuredIndex) {
888   assert(Index == 0 && "Index in explicit init list must be zero");
889 
890   // As an extension, clang supports complex initializers, which initialize
891   // a complex number component-wise.  When an explicit initializer list for
892   // a complex number contains two two initializers, this extension kicks in:
893   // it exepcts the initializer list to contain two elements convertible to
894   // the element type of the complex type. The first element initializes
895   // the real part, and the second element intitializes the imaginary part.
896 
897   if (IList->getNumInits() != 2)
898     return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
899                            StructuredIndex);
900 
901   // This is an extension in C.  (The builtin _Complex type does not exist
902   // in the C++ standard.)
903   if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
904     SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
905       << IList->getSourceRange();
906 
907   // Initialize the complex number.
908   QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
909   InitializedEntity ElementEntity =
910     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
911 
912   for (unsigned i = 0; i < 2; ++i) {
913     ElementEntity.setElementIndex(Index);
914     CheckSubElementType(ElementEntity, IList, elementType, Index,
915                         StructuredList, StructuredIndex);
916   }
917 }
918 
919 
920 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
921                                       InitListExpr *IList, QualType DeclType,
922                                       unsigned &Index,
923                                       InitListExpr *StructuredList,
924                                       unsigned &StructuredIndex) {
925   if (Index >= IList->getNumInits()) {
926     if (!VerifyOnly)
927       SemaRef.Diag(IList->getLocStart(),
928                    SemaRef.getLangOpts().CPlusPlus11 ?
929                      diag::warn_cxx98_compat_empty_scalar_initializer :
930                      diag::err_empty_scalar_initializer)
931         << IList->getSourceRange();
932     hadError = !SemaRef.getLangOpts().CPlusPlus11;
933     ++Index;
934     ++StructuredIndex;
935     return;
936   }
937 
938   Expr *expr = IList->getInit(Index);
939   if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
940     if (!VerifyOnly)
941       SemaRef.Diag(SubIList->getLocStart(),
942                    diag::warn_many_braces_around_scalar_init)
943         << SubIList->getSourceRange();
944 
945     CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
946                     StructuredIndex);
947     return;
948   } else if (isa<DesignatedInitExpr>(expr)) {
949     if (!VerifyOnly)
950       SemaRef.Diag(expr->getLocStart(),
951                    diag::err_designator_for_scalar_init)
952         << DeclType << expr->getSourceRange();
953     hadError = true;
954     ++Index;
955     ++StructuredIndex;
956     return;
957   }
958 
959   if (VerifyOnly) {
960     if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
961       hadError = true;
962     ++Index;
963     return;
964   }
965 
966   ExprResult Result =
967     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
968                                       SemaRef.Owned(expr),
969                                       /*TopLevelOfInitList=*/true);
970 
971   Expr *ResultExpr = 0;
972 
973   if (Result.isInvalid())
974     hadError = true; // types weren't compatible.
975   else {
976     ResultExpr = Result.takeAs<Expr>();
977 
978     if (ResultExpr != expr) {
979       // The type was promoted, update initializer list.
980       IList->setInit(Index, ResultExpr);
981     }
982   }
983   if (hadError)
984     ++StructuredIndex;
985   else
986     UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
987   ++Index;
988 }
989 
990 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
991                                          InitListExpr *IList, QualType DeclType,
992                                          unsigned &Index,
993                                          InitListExpr *StructuredList,
994                                          unsigned &StructuredIndex) {
995   if (Index >= IList->getNumInits()) {
996     // FIXME: It would be wonderful if we could point at the actual member. In
997     // general, it would be useful to pass location information down the stack,
998     // so that we know the location (or decl) of the "current object" being
999     // initialized.
1000     if (!VerifyOnly)
1001       SemaRef.Diag(IList->getLocStart(),
1002                     diag::err_init_reference_member_uninitialized)
1003         << DeclType
1004         << IList->getSourceRange();
1005     hadError = true;
1006     ++Index;
1007     ++StructuredIndex;
1008     return;
1009   }
1010 
1011   Expr *expr = IList->getInit(Index);
1012   if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1013     if (!VerifyOnly)
1014       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1015         << DeclType << IList->getSourceRange();
1016     hadError = true;
1017     ++Index;
1018     ++StructuredIndex;
1019     return;
1020   }
1021 
1022   if (VerifyOnly) {
1023     if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1024       hadError = true;
1025     ++Index;
1026     return;
1027   }
1028 
1029   ExprResult Result =
1030     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1031                                       SemaRef.Owned(expr),
1032                                       /*TopLevelOfInitList=*/true);
1033 
1034   if (Result.isInvalid())
1035     hadError = true;
1036 
1037   expr = Result.takeAs<Expr>();
1038   IList->setInit(Index, expr);
1039 
1040   if (hadError)
1041     ++StructuredIndex;
1042   else
1043     UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1044   ++Index;
1045 }
1046 
1047 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1048                                       InitListExpr *IList, QualType DeclType,
1049                                       unsigned &Index,
1050                                       InitListExpr *StructuredList,
1051                                       unsigned &StructuredIndex) {
1052   const VectorType *VT = DeclType->getAs<VectorType>();
1053   unsigned maxElements = VT->getNumElements();
1054   unsigned numEltsInit = 0;
1055   QualType elementType = VT->getElementType();
1056 
1057   if (Index >= IList->getNumInits()) {
1058     // Make sure the element type can be value-initialized.
1059     if (VerifyOnly)
1060       CheckValueInitializable(
1061           InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1062     return;
1063   }
1064 
1065   if (!SemaRef.getLangOpts().OpenCL) {
1066     // If the initializing element is a vector, try to copy-initialize
1067     // instead of breaking it apart (which is doomed to failure anyway).
1068     Expr *Init = IList->getInit(Index);
1069     if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1070       if (VerifyOnly) {
1071         if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1072           hadError = true;
1073         ++Index;
1074         return;
1075       }
1076 
1077       ExprResult Result =
1078         SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1079                                           SemaRef.Owned(Init),
1080                                           /*TopLevelOfInitList=*/true);
1081 
1082       Expr *ResultExpr = 0;
1083       if (Result.isInvalid())
1084         hadError = true; // types weren't compatible.
1085       else {
1086         ResultExpr = Result.takeAs<Expr>();
1087 
1088         if (ResultExpr != Init) {
1089           // The type was promoted, update initializer list.
1090           IList->setInit(Index, ResultExpr);
1091         }
1092       }
1093       if (hadError)
1094         ++StructuredIndex;
1095       else
1096         UpdateStructuredListElement(StructuredList, StructuredIndex,
1097                                     ResultExpr);
1098       ++Index;
1099       return;
1100     }
1101 
1102     InitializedEntity ElementEntity =
1103       InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1104 
1105     for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1106       // Don't attempt to go past the end of the init list
1107       if (Index >= IList->getNumInits()) {
1108         if (VerifyOnly)
1109           CheckValueInitializable(ElementEntity);
1110         break;
1111       }
1112 
1113       ElementEntity.setElementIndex(Index);
1114       CheckSubElementType(ElementEntity, IList, elementType, Index,
1115                           StructuredList, StructuredIndex);
1116     }
1117     return;
1118   }
1119 
1120   InitializedEntity ElementEntity =
1121     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1122 
1123   // OpenCL initializers allows vectors to be constructed from vectors.
1124   for (unsigned i = 0; i < maxElements; ++i) {
1125     // Don't attempt to go past the end of the init list
1126     if (Index >= IList->getNumInits())
1127       break;
1128 
1129     ElementEntity.setElementIndex(Index);
1130 
1131     QualType IType = IList->getInit(Index)->getType();
1132     if (!IType->isVectorType()) {
1133       CheckSubElementType(ElementEntity, IList, elementType, Index,
1134                           StructuredList, StructuredIndex);
1135       ++numEltsInit;
1136     } else {
1137       QualType VecType;
1138       const VectorType *IVT = IType->getAs<VectorType>();
1139       unsigned numIElts = IVT->getNumElements();
1140 
1141       if (IType->isExtVectorType())
1142         VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1143       else
1144         VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1145                                                 IVT->getVectorKind());
1146       CheckSubElementType(ElementEntity, IList, VecType, Index,
1147                           StructuredList, StructuredIndex);
1148       numEltsInit += numIElts;
1149     }
1150   }
1151 
1152   // OpenCL requires all elements to be initialized.
1153   if (numEltsInit != maxElements) {
1154     if (!VerifyOnly)
1155       SemaRef.Diag(IList->getLocStart(),
1156                    diag::err_vector_incorrect_num_initializers)
1157         << (numEltsInit < maxElements) << maxElements << numEltsInit;
1158     hadError = true;
1159   }
1160 }
1161 
1162 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1163                                      InitListExpr *IList, QualType &DeclType,
1164                                      llvm::APSInt elementIndex,
1165                                      bool SubobjectIsDesignatorContext,
1166                                      unsigned &Index,
1167                                      InitListExpr *StructuredList,
1168                                      unsigned &StructuredIndex) {
1169   const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1170 
1171   // Check for the special-case of initializing an array with a string.
1172   if (Index < IList->getNumInits()) {
1173     if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
1174                                  SemaRef.Context)) {
1175       // We place the string literal directly into the resulting
1176       // initializer list. This is the only place where the structure
1177       // of the structured initializer list doesn't match exactly,
1178       // because doing so would involve allocating one character
1179       // constant for each string.
1180       if (!VerifyOnly) {
1181         CheckStringInit(Str, DeclType, arrayType, SemaRef);
1182         UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1183         StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1184       }
1185       ++Index;
1186       return;
1187     }
1188   }
1189   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1190     // Check for VLAs; in standard C it would be possible to check this
1191     // earlier, but I don't know where clang accepts VLAs (gcc accepts
1192     // them in all sorts of strange places).
1193     if (!VerifyOnly)
1194       SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1195                     diag::err_variable_object_no_init)
1196         << VAT->getSizeExpr()->getSourceRange();
1197     hadError = true;
1198     ++Index;
1199     ++StructuredIndex;
1200     return;
1201   }
1202 
1203   // We might know the maximum number of elements in advance.
1204   llvm::APSInt maxElements(elementIndex.getBitWidth(),
1205                            elementIndex.isUnsigned());
1206   bool maxElementsKnown = false;
1207   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1208     maxElements = CAT->getSize();
1209     elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1210     elementIndex.setIsUnsigned(maxElements.isUnsigned());
1211     maxElementsKnown = true;
1212   }
1213 
1214   QualType elementType = arrayType->getElementType();
1215   while (Index < IList->getNumInits()) {
1216     Expr *Init = IList->getInit(Index);
1217     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1218       // If we're not the subobject that matches up with the '{' for
1219       // the designator, we shouldn't be handling the
1220       // designator. Return immediately.
1221       if (!SubobjectIsDesignatorContext)
1222         return;
1223 
1224       // Handle this designated initializer. elementIndex will be
1225       // updated to be the next array element we'll initialize.
1226       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1227                                      DeclType, 0, &elementIndex, Index,
1228                                      StructuredList, StructuredIndex, true,
1229                                      false)) {
1230         hadError = true;
1231         continue;
1232       }
1233 
1234       if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1235         maxElements = maxElements.extend(elementIndex.getBitWidth());
1236       else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1237         elementIndex = elementIndex.extend(maxElements.getBitWidth());
1238       elementIndex.setIsUnsigned(maxElements.isUnsigned());
1239 
1240       // If the array is of incomplete type, keep track of the number of
1241       // elements in the initializer.
1242       if (!maxElementsKnown && elementIndex > maxElements)
1243         maxElements = elementIndex;
1244 
1245       continue;
1246     }
1247 
1248     // If we know the maximum number of elements, and we've already
1249     // hit it, stop consuming elements in the initializer list.
1250     if (maxElementsKnown && elementIndex == maxElements)
1251       break;
1252 
1253     InitializedEntity ElementEntity =
1254       InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1255                                            Entity);
1256     // Check this element.
1257     CheckSubElementType(ElementEntity, IList, elementType, Index,
1258                         StructuredList, StructuredIndex);
1259     ++elementIndex;
1260 
1261     // If the array is of incomplete type, keep track of the number of
1262     // elements in the initializer.
1263     if (!maxElementsKnown && elementIndex > maxElements)
1264       maxElements = elementIndex;
1265   }
1266   if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1267     // If this is an incomplete array type, the actual type needs to
1268     // be calculated here.
1269     llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1270     if (maxElements == Zero) {
1271       // Sizing an array implicitly to zero is not allowed by ISO C,
1272       // but is supported by GNU.
1273       SemaRef.Diag(IList->getLocStart(),
1274                     diag::ext_typecheck_zero_array_size);
1275     }
1276 
1277     DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1278                                                      ArrayType::Normal, 0);
1279   }
1280   if (!hadError && VerifyOnly) {
1281     // Check if there are any members of the array that get value-initialized.
1282     // If so, check if doing that is possible.
1283     // FIXME: This needs to detect holes left by designated initializers too.
1284     if (maxElementsKnown && elementIndex < maxElements)
1285       CheckValueInitializable(InitializedEntity::InitializeElement(
1286                                                   SemaRef.Context, 0, Entity));
1287   }
1288 }
1289 
1290 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1291                                              Expr *InitExpr,
1292                                              FieldDecl *Field,
1293                                              bool TopLevelObject) {
1294   // Handle GNU flexible array initializers.
1295   unsigned FlexArrayDiag;
1296   if (isa<InitListExpr>(InitExpr) &&
1297       cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1298     // Empty flexible array init always allowed as an extension
1299     FlexArrayDiag = diag::ext_flexible_array_init;
1300   } else if (SemaRef.getLangOpts().CPlusPlus) {
1301     // Disallow flexible array init in C++; it is not required for gcc
1302     // compatibility, and it needs work to IRGen correctly in general.
1303     FlexArrayDiag = diag::err_flexible_array_init;
1304   } else if (!TopLevelObject) {
1305     // Disallow flexible array init on non-top-level object
1306     FlexArrayDiag = diag::err_flexible_array_init;
1307   } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1308     // Disallow flexible array init on anything which is not a variable.
1309     FlexArrayDiag = diag::err_flexible_array_init;
1310   } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1311     // Disallow flexible array init on local variables.
1312     FlexArrayDiag = diag::err_flexible_array_init;
1313   } else {
1314     // Allow other cases.
1315     FlexArrayDiag = diag::ext_flexible_array_init;
1316   }
1317 
1318   if (!VerifyOnly) {
1319     SemaRef.Diag(InitExpr->getLocStart(),
1320                  FlexArrayDiag)
1321       << InitExpr->getLocStart();
1322     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1323       << Field;
1324   }
1325 
1326   return FlexArrayDiag != diag::ext_flexible_array_init;
1327 }
1328 
1329 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1330                                             InitListExpr *IList,
1331                                             QualType DeclType,
1332                                             RecordDecl::field_iterator Field,
1333                                             bool SubobjectIsDesignatorContext,
1334                                             unsigned &Index,
1335                                             InitListExpr *StructuredList,
1336                                             unsigned &StructuredIndex,
1337                                             bool TopLevelObject) {
1338   RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1339 
1340   // If the record is invalid, some of it's members are invalid. To avoid
1341   // confusion, we forgo checking the intializer for the entire record.
1342   if (structDecl->isInvalidDecl()) {
1343     // Assume it was supposed to consume a single initializer.
1344     ++Index;
1345     hadError = true;
1346     return;
1347   }
1348 
1349   if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1350     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1351 
1352     // If there's a default initializer, use it.
1353     if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1354       if (VerifyOnly)
1355         return;
1356       for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1357            Field != FieldEnd; ++Field) {
1358         if (Field->hasInClassInitializer()) {
1359           StructuredList->setInitializedFieldInUnion(*Field);
1360           // FIXME: Actually build a CXXDefaultInitExpr?
1361           return;
1362         }
1363       }
1364     }
1365 
1366     // Value-initialize the first named member of the union.
1367     for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1368          Field != FieldEnd; ++Field) {
1369       if (Field->getDeclName()) {
1370         if (VerifyOnly)
1371           CheckValueInitializable(
1372               InitializedEntity::InitializeMember(*Field, &Entity));
1373         else
1374           StructuredList->setInitializedFieldInUnion(*Field);
1375         break;
1376       }
1377     }
1378     return;
1379   }
1380 
1381   // If structDecl is a forward declaration, this loop won't do
1382   // anything except look at designated initializers; That's okay,
1383   // because an error should get printed out elsewhere. It might be
1384   // worthwhile to skip over the rest of the initializer, though.
1385   RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1386   RecordDecl::field_iterator FieldEnd = RD->field_end();
1387   bool InitializedSomething = false;
1388   bool CheckForMissingFields = true;
1389   while (Index < IList->getNumInits()) {
1390     Expr *Init = IList->getInit(Index);
1391 
1392     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1393       // If we're not the subobject that matches up with the '{' for
1394       // the designator, we shouldn't be handling the
1395       // designator. Return immediately.
1396       if (!SubobjectIsDesignatorContext)
1397         return;
1398 
1399       // Handle this designated initializer. Field will be updated to
1400       // the next field that we'll be initializing.
1401       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1402                                      DeclType, &Field, 0, Index,
1403                                      StructuredList, StructuredIndex,
1404                                      true, TopLevelObject))
1405         hadError = true;
1406 
1407       InitializedSomething = true;
1408 
1409       // Disable check for missing fields when designators are used.
1410       // This matches gcc behaviour.
1411       CheckForMissingFields = false;
1412       continue;
1413     }
1414 
1415     if (Field == FieldEnd) {
1416       // We've run out of fields. We're done.
1417       break;
1418     }
1419 
1420     // We've already initialized a member of a union. We're done.
1421     if (InitializedSomething && DeclType->isUnionType())
1422       break;
1423 
1424     // If we've hit the flexible array member at the end, we're done.
1425     if (Field->getType()->isIncompleteArrayType())
1426       break;
1427 
1428     if (Field->isUnnamedBitfield()) {
1429       // Don't initialize unnamed bitfields, e.g. "int : 20;"
1430       ++Field;
1431       continue;
1432     }
1433 
1434     // Make sure we can use this declaration.
1435     bool InvalidUse;
1436     if (VerifyOnly)
1437       InvalidUse = !SemaRef.CanUseDecl(*Field);
1438     else
1439       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1440                                           IList->getInit(Index)->getLocStart());
1441     if (InvalidUse) {
1442       ++Index;
1443       ++Field;
1444       hadError = true;
1445       continue;
1446     }
1447 
1448     InitializedEntity MemberEntity =
1449       InitializedEntity::InitializeMember(*Field, &Entity);
1450     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1451                         StructuredList, StructuredIndex);
1452     InitializedSomething = true;
1453 
1454     if (DeclType->isUnionType() && !VerifyOnly) {
1455       // Initialize the first field within the union.
1456       StructuredList->setInitializedFieldInUnion(*Field);
1457     }
1458 
1459     ++Field;
1460   }
1461 
1462   // Emit warnings for missing struct field initializers.
1463   if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1464       Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1465       !DeclType->isUnionType()) {
1466     // It is possible we have one or more unnamed bitfields remaining.
1467     // Find first (if any) named field and emit warning.
1468     for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1469          it != end; ++it) {
1470       if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1471         SemaRef.Diag(IList->getSourceRange().getEnd(),
1472                      diag::warn_missing_field_initializers) << it->getName();
1473         break;
1474       }
1475     }
1476   }
1477 
1478   // Check that any remaining fields can be value-initialized.
1479   if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1480       !Field->getType()->isIncompleteArrayType()) {
1481     // FIXME: Should check for holes left by designated initializers too.
1482     for (; Field != FieldEnd && !hadError; ++Field) {
1483       if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1484         CheckValueInitializable(
1485             InitializedEntity::InitializeMember(*Field, &Entity));
1486     }
1487   }
1488 
1489   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1490       Index >= IList->getNumInits())
1491     return;
1492 
1493   if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1494                              TopLevelObject)) {
1495     hadError = true;
1496     ++Index;
1497     return;
1498   }
1499 
1500   InitializedEntity MemberEntity =
1501     InitializedEntity::InitializeMember(*Field, &Entity);
1502 
1503   if (isa<InitListExpr>(IList->getInit(Index)))
1504     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1505                         StructuredList, StructuredIndex);
1506   else
1507     CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1508                           StructuredList, StructuredIndex);
1509 }
1510 
1511 /// \brief Expand a field designator that refers to a member of an
1512 /// anonymous struct or union into a series of field designators that
1513 /// refers to the field within the appropriate subobject.
1514 ///
1515 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1516                                            DesignatedInitExpr *DIE,
1517                                            unsigned DesigIdx,
1518                                            IndirectFieldDecl *IndirectField) {
1519   typedef DesignatedInitExpr::Designator Designator;
1520 
1521   // Build the replacement designators.
1522   SmallVector<Designator, 4> Replacements;
1523   for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1524        PE = IndirectField->chain_end(); PI != PE; ++PI) {
1525     if (PI + 1 == PE)
1526       Replacements.push_back(Designator((IdentifierInfo *)0,
1527                                     DIE->getDesignator(DesigIdx)->getDotLoc(),
1528                                 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1529     else
1530       Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1531                                         SourceLocation()));
1532     assert(isa<FieldDecl>(*PI));
1533     Replacements.back().setField(cast<FieldDecl>(*PI));
1534   }
1535 
1536   // Expand the current designator into the set of replacement
1537   // designators, so we have a full subobject path down to where the
1538   // member of the anonymous struct/union is actually stored.
1539   DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1540                         &Replacements[0] + Replacements.size());
1541 }
1542 
1543 /// \brief Given an implicit anonymous field, search the IndirectField that
1544 ///  corresponds to FieldName.
1545 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1546                                                  IdentifierInfo *FieldName) {
1547   if (!FieldName)
1548     return 0;
1549 
1550   assert(AnonField->isAnonymousStructOrUnion());
1551   Decl *NextDecl = AnonField->getNextDeclInContext();
1552   while (IndirectFieldDecl *IF =
1553           dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1554     if (FieldName == IF->getAnonField()->getIdentifier())
1555       return IF;
1556     NextDecl = NextDecl->getNextDeclInContext();
1557   }
1558   return 0;
1559 }
1560 
1561 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1562                                                    DesignatedInitExpr *DIE) {
1563   unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1564   SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1565   for (unsigned I = 0; I < NumIndexExprs; ++I)
1566     IndexExprs[I] = DIE->getSubExpr(I + 1);
1567   return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1568                                     DIE->size(), IndexExprs,
1569                                     DIE->getEqualOrColonLoc(),
1570                                     DIE->usesGNUSyntax(), DIE->getInit());
1571 }
1572 
1573 namespace {
1574 
1575 // Callback to only accept typo corrections that are for field members of
1576 // the given struct or union.
1577 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1578  public:
1579   explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1580       : Record(RD) {}
1581 
1582   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1583     FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1584     return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1585   }
1586 
1587  private:
1588   RecordDecl *Record;
1589 };
1590 
1591 }
1592 
1593 /// @brief Check the well-formedness of a C99 designated initializer.
1594 ///
1595 /// Determines whether the designated initializer @p DIE, which
1596 /// resides at the given @p Index within the initializer list @p
1597 /// IList, is well-formed for a current object of type @p DeclType
1598 /// (C99 6.7.8). The actual subobject that this designator refers to
1599 /// within the current subobject is returned in either
1600 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1601 ///
1602 /// @param IList  The initializer list in which this designated
1603 /// initializer occurs.
1604 ///
1605 /// @param DIE The designated initializer expression.
1606 ///
1607 /// @param DesigIdx  The index of the current designator.
1608 ///
1609 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1610 /// into which the designation in @p DIE should refer.
1611 ///
1612 /// @param NextField  If non-NULL and the first designator in @p DIE is
1613 /// a field, this will be set to the field declaration corresponding
1614 /// to the field named by the designator.
1615 ///
1616 /// @param NextElementIndex  If non-NULL and the first designator in @p
1617 /// DIE is an array designator or GNU array-range designator, this
1618 /// will be set to the last index initialized by this designator.
1619 ///
1620 /// @param Index  Index into @p IList where the designated initializer
1621 /// @p DIE occurs.
1622 ///
1623 /// @param StructuredList  The initializer list expression that
1624 /// describes all of the subobject initializers in the order they'll
1625 /// actually be initialized.
1626 ///
1627 /// @returns true if there was an error, false otherwise.
1628 bool
1629 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1630                                             InitListExpr *IList,
1631                                             DesignatedInitExpr *DIE,
1632                                             unsigned DesigIdx,
1633                                             QualType &CurrentObjectType,
1634                                           RecordDecl::field_iterator *NextField,
1635                                             llvm::APSInt *NextElementIndex,
1636                                             unsigned &Index,
1637                                             InitListExpr *StructuredList,
1638                                             unsigned &StructuredIndex,
1639                                             bool FinishSubobjectInit,
1640                                             bool TopLevelObject) {
1641   if (DesigIdx == DIE->size()) {
1642     // Check the actual initialization for the designated object type.
1643     bool prevHadError = hadError;
1644 
1645     // Temporarily remove the designator expression from the
1646     // initializer list that the child calls see, so that we don't try
1647     // to re-process the designator.
1648     unsigned OldIndex = Index;
1649     IList->setInit(OldIndex, DIE->getInit());
1650 
1651     CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1652                         StructuredList, StructuredIndex);
1653 
1654     // Restore the designated initializer expression in the syntactic
1655     // form of the initializer list.
1656     if (IList->getInit(OldIndex) != DIE->getInit())
1657       DIE->setInit(IList->getInit(OldIndex));
1658     IList->setInit(OldIndex, DIE);
1659 
1660     return hadError && !prevHadError;
1661   }
1662 
1663   DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1664   bool IsFirstDesignator = (DesigIdx == 0);
1665   if (!VerifyOnly) {
1666     assert((IsFirstDesignator || StructuredList) &&
1667            "Need a non-designated initializer list to start from");
1668 
1669     // Determine the structural initializer list that corresponds to the
1670     // current subobject.
1671     StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1672       : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1673                                    StructuredList, StructuredIndex,
1674                                    SourceRange(D->getLocStart(),
1675                                                DIE->getLocEnd()));
1676     assert(StructuredList && "Expected a structured initializer list");
1677   }
1678 
1679   if (D->isFieldDesignator()) {
1680     // C99 6.7.8p7:
1681     //
1682     //   If a designator has the form
1683     //
1684     //      . identifier
1685     //
1686     //   then the current object (defined below) shall have
1687     //   structure or union type and the identifier shall be the
1688     //   name of a member of that type.
1689     const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1690     if (!RT) {
1691       SourceLocation Loc = D->getDotLoc();
1692       if (Loc.isInvalid())
1693         Loc = D->getFieldLoc();
1694       if (!VerifyOnly)
1695         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1696           << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1697       ++Index;
1698       return true;
1699     }
1700 
1701     // Note: we perform a linear search of the fields here, despite
1702     // the fact that we have a faster lookup method, because we always
1703     // need to compute the field's index.
1704     FieldDecl *KnownField = D->getField();
1705     IdentifierInfo *FieldName = D->getFieldName();
1706     unsigned FieldIndex = 0;
1707     RecordDecl::field_iterator
1708       Field = RT->getDecl()->field_begin(),
1709       FieldEnd = RT->getDecl()->field_end();
1710     for (; Field != FieldEnd; ++Field) {
1711       if (Field->isUnnamedBitfield())
1712         continue;
1713 
1714       // If we find a field representing an anonymous field, look in the
1715       // IndirectFieldDecl that follow for the designated initializer.
1716       if (!KnownField && Field->isAnonymousStructOrUnion()) {
1717         if (IndirectFieldDecl *IF =
1718             FindIndirectFieldDesignator(*Field, FieldName)) {
1719           // In verify mode, don't modify the original.
1720           if (VerifyOnly)
1721             DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1722           ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1723           D = DIE->getDesignator(DesigIdx);
1724           break;
1725         }
1726       }
1727       if (KnownField && KnownField == *Field)
1728         break;
1729       if (FieldName && FieldName == Field->getIdentifier())
1730         break;
1731 
1732       ++FieldIndex;
1733     }
1734 
1735     if (Field == FieldEnd) {
1736       if (VerifyOnly) {
1737         ++Index;
1738         return true; // No typo correction when just trying this out.
1739       }
1740 
1741       // There was no normal field in the struct with the designated
1742       // name. Perform another lookup for this name, which may find
1743       // something that we can't designate (e.g., a member function),
1744       // may find nothing, or may find a member of an anonymous
1745       // struct/union.
1746       DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1747       FieldDecl *ReplacementField = 0;
1748       if (Lookup.empty()) {
1749         // Name lookup didn't find anything. Determine whether this
1750         // was a typo for another field name.
1751         FieldInitializerValidatorCCC Validator(RT->getDecl());
1752         TypoCorrection Corrected = SemaRef.CorrectTypo(
1753             DeclarationNameInfo(FieldName, D->getFieldLoc()),
1754             Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
1755             RT->getDecl());
1756         if (Corrected) {
1757           std::string CorrectedStr(
1758               Corrected.getAsString(SemaRef.getLangOpts()));
1759           std::string CorrectedQuotedStr(
1760               Corrected.getQuoted(SemaRef.getLangOpts()));
1761           ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1762           SemaRef.Diag(D->getFieldLoc(),
1763                        diag::err_field_designator_unknown_suggest)
1764             << FieldName << CurrentObjectType << CorrectedQuotedStr
1765             << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
1766           SemaRef.Diag(ReplacementField->getLocation(),
1767                        diag::note_previous_decl) << CorrectedQuotedStr;
1768           hadError = true;
1769         } else {
1770           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1771             << FieldName << CurrentObjectType;
1772           ++Index;
1773           return true;
1774         }
1775       }
1776 
1777       if (!ReplacementField) {
1778         // Name lookup found something, but it wasn't a field.
1779         SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1780           << FieldName;
1781         SemaRef.Diag(Lookup.front()->getLocation(),
1782                       diag::note_field_designator_found);
1783         ++Index;
1784         return true;
1785       }
1786 
1787       if (!KnownField) {
1788         // The replacement field comes from typo correction; find it
1789         // in the list of fields.
1790         FieldIndex = 0;
1791         Field = RT->getDecl()->field_begin();
1792         for (; Field != FieldEnd; ++Field) {
1793           if (Field->isUnnamedBitfield())
1794             continue;
1795 
1796           if (ReplacementField == *Field ||
1797               Field->getIdentifier() == ReplacementField->getIdentifier())
1798             break;
1799 
1800           ++FieldIndex;
1801         }
1802       }
1803     }
1804 
1805     // All of the fields of a union are located at the same place in
1806     // the initializer list.
1807     if (RT->getDecl()->isUnion()) {
1808       FieldIndex = 0;
1809       if (!VerifyOnly)
1810         StructuredList->setInitializedFieldInUnion(*Field);
1811     }
1812 
1813     // Make sure we can use this declaration.
1814     bool InvalidUse;
1815     if (VerifyOnly)
1816       InvalidUse = !SemaRef.CanUseDecl(*Field);
1817     else
1818       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1819     if (InvalidUse) {
1820       ++Index;
1821       return true;
1822     }
1823 
1824     if (!VerifyOnly) {
1825       // Update the designator with the field declaration.
1826       D->setField(*Field);
1827 
1828       // Make sure that our non-designated initializer list has space
1829       // for a subobject corresponding to this field.
1830       if (FieldIndex >= StructuredList->getNumInits())
1831         StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1832     }
1833 
1834     // This designator names a flexible array member.
1835     if (Field->getType()->isIncompleteArrayType()) {
1836       bool Invalid = false;
1837       if ((DesigIdx + 1) != DIE->size()) {
1838         // We can't designate an object within the flexible array
1839         // member (because GCC doesn't allow it).
1840         if (!VerifyOnly) {
1841           DesignatedInitExpr::Designator *NextD
1842             = DIE->getDesignator(DesigIdx + 1);
1843           SemaRef.Diag(NextD->getLocStart(),
1844                         diag::err_designator_into_flexible_array_member)
1845             << SourceRange(NextD->getLocStart(),
1846                            DIE->getLocEnd());
1847           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1848             << *Field;
1849         }
1850         Invalid = true;
1851       }
1852 
1853       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1854           !isa<StringLiteral>(DIE->getInit())) {
1855         // The initializer is not an initializer list.
1856         if (!VerifyOnly) {
1857           SemaRef.Diag(DIE->getInit()->getLocStart(),
1858                         diag::err_flexible_array_init_needs_braces)
1859             << DIE->getInit()->getSourceRange();
1860           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1861             << *Field;
1862         }
1863         Invalid = true;
1864       }
1865 
1866       // Check GNU flexible array initializer.
1867       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1868                                              TopLevelObject))
1869         Invalid = true;
1870 
1871       if (Invalid) {
1872         ++Index;
1873         return true;
1874       }
1875 
1876       // Initialize the array.
1877       bool prevHadError = hadError;
1878       unsigned newStructuredIndex = FieldIndex;
1879       unsigned OldIndex = Index;
1880       IList->setInit(Index, DIE->getInit());
1881 
1882       InitializedEntity MemberEntity =
1883         InitializedEntity::InitializeMember(*Field, &Entity);
1884       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1885                           StructuredList, newStructuredIndex);
1886 
1887       IList->setInit(OldIndex, DIE);
1888       if (hadError && !prevHadError) {
1889         ++Field;
1890         ++FieldIndex;
1891         if (NextField)
1892           *NextField = Field;
1893         StructuredIndex = FieldIndex;
1894         return true;
1895       }
1896     } else {
1897       // Recurse to check later designated subobjects.
1898       QualType FieldType = Field->getType();
1899       unsigned newStructuredIndex = FieldIndex;
1900 
1901       InitializedEntity MemberEntity =
1902         InitializedEntity::InitializeMember(*Field, &Entity);
1903       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1904                                      FieldType, 0, 0, Index,
1905                                      StructuredList, newStructuredIndex,
1906                                      true, false))
1907         return true;
1908     }
1909 
1910     // Find the position of the next field to be initialized in this
1911     // subobject.
1912     ++Field;
1913     ++FieldIndex;
1914 
1915     // If this the first designator, our caller will continue checking
1916     // the rest of this struct/class/union subobject.
1917     if (IsFirstDesignator) {
1918       if (NextField)
1919         *NextField = Field;
1920       StructuredIndex = FieldIndex;
1921       return false;
1922     }
1923 
1924     if (!FinishSubobjectInit)
1925       return false;
1926 
1927     // We've already initialized something in the union; we're done.
1928     if (RT->getDecl()->isUnion())
1929       return hadError;
1930 
1931     // Check the remaining fields within this class/struct/union subobject.
1932     bool prevHadError = hadError;
1933 
1934     CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1935                           StructuredList, FieldIndex);
1936     return hadError && !prevHadError;
1937   }
1938 
1939   // C99 6.7.8p6:
1940   //
1941   //   If a designator has the form
1942   //
1943   //      [ constant-expression ]
1944   //
1945   //   then the current object (defined below) shall have array
1946   //   type and the expression shall be an integer constant
1947   //   expression. If the array is of unknown size, any
1948   //   nonnegative value is valid.
1949   //
1950   // Additionally, cope with the GNU extension that permits
1951   // designators of the form
1952   //
1953   //      [ constant-expression ... constant-expression ]
1954   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1955   if (!AT) {
1956     if (!VerifyOnly)
1957       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1958         << CurrentObjectType;
1959     ++Index;
1960     return true;
1961   }
1962 
1963   Expr *IndexExpr = 0;
1964   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1965   if (D->isArrayDesignator()) {
1966     IndexExpr = DIE->getArrayIndex(*D);
1967     DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
1968     DesignatedEndIndex = DesignatedStartIndex;
1969   } else {
1970     assert(D->isArrayRangeDesignator() && "Need array-range designator");
1971 
1972     DesignatedStartIndex =
1973       DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
1974     DesignatedEndIndex =
1975       DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
1976     IndexExpr = DIE->getArrayRangeEnd(*D);
1977 
1978     // Codegen can't handle evaluating array range designators that have side
1979     // effects, because we replicate the AST value for each initialized element.
1980     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1981     // elements with something that has a side effect, so codegen can emit an
1982     // "error unsupported" error instead of miscompiling the app.
1983     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1984         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
1985       FullyStructuredList->sawArrayRangeDesignator();
1986   }
1987 
1988   if (isa<ConstantArrayType>(AT)) {
1989     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1990     DesignatedStartIndex
1991       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1992     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1993     DesignatedEndIndex
1994       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1995     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1996     if (DesignatedEndIndex >= MaxElements) {
1997       if (!VerifyOnly)
1998         SemaRef.Diag(IndexExpr->getLocStart(),
1999                       diag::err_array_designator_too_large)
2000           << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2001           << IndexExpr->getSourceRange();
2002       ++Index;
2003       return true;
2004     }
2005   } else {
2006     // Make sure the bit-widths and signedness match.
2007     if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2008       DesignatedEndIndex
2009         = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2010     else if (DesignatedStartIndex.getBitWidth() <
2011              DesignatedEndIndex.getBitWidth())
2012       DesignatedStartIndex
2013         = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2014     DesignatedStartIndex.setIsUnsigned(true);
2015     DesignatedEndIndex.setIsUnsigned(true);
2016   }
2017 
2018   // Make sure that our non-designated initializer list has space
2019   // for a subobject corresponding to this array element.
2020   if (!VerifyOnly &&
2021       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2022     StructuredList->resizeInits(SemaRef.Context,
2023                                 DesignatedEndIndex.getZExtValue() + 1);
2024 
2025   // Repeatedly perform subobject initializations in the range
2026   // [DesignatedStartIndex, DesignatedEndIndex].
2027 
2028   // Move to the next designator
2029   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2030   unsigned OldIndex = Index;
2031 
2032   InitializedEntity ElementEntity =
2033     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2034 
2035   while (DesignatedStartIndex <= DesignatedEndIndex) {
2036     // Recurse to check later designated subobjects.
2037     QualType ElementType = AT->getElementType();
2038     Index = OldIndex;
2039 
2040     ElementEntity.setElementIndex(ElementIndex);
2041     if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2042                                    ElementType, 0, 0, Index,
2043                                    StructuredList, ElementIndex,
2044                                    (DesignatedStartIndex == DesignatedEndIndex),
2045                                    false))
2046       return true;
2047 
2048     // Move to the next index in the array that we'll be initializing.
2049     ++DesignatedStartIndex;
2050     ElementIndex = DesignatedStartIndex.getZExtValue();
2051   }
2052 
2053   // If this the first designator, our caller will continue checking
2054   // the rest of this array subobject.
2055   if (IsFirstDesignator) {
2056     if (NextElementIndex)
2057       *NextElementIndex = DesignatedStartIndex;
2058     StructuredIndex = ElementIndex;
2059     return false;
2060   }
2061 
2062   if (!FinishSubobjectInit)
2063     return false;
2064 
2065   // Check the remaining elements within this array subobject.
2066   bool prevHadError = hadError;
2067   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2068                  /*SubobjectIsDesignatorContext=*/false, Index,
2069                  StructuredList, ElementIndex);
2070   return hadError && !prevHadError;
2071 }
2072 
2073 // Get the structured initializer list for a subobject of type
2074 // @p CurrentObjectType.
2075 InitListExpr *
2076 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2077                                             QualType CurrentObjectType,
2078                                             InitListExpr *StructuredList,
2079                                             unsigned StructuredIndex,
2080                                             SourceRange InitRange) {
2081   if (VerifyOnly)
2082     return 0; // No structured list in verification-only mode.
2083   Expr *ExistingInit = 0;
2084   if (!StructuredList)
2085     ExistingInit = SyntacticToSemantic.lookup(IList);
2086   else if (StructuredIndex < StructuredList->getNumInits())
2087     ExistingInit = StructuredList->getInit(StructuredIndex);
2088 
2089   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2090     return Result;
2091 
2092   if (ExistingInit) {
2093     // We are creating an initializer list that initializes the
2094     // subobjects of the current object, but there was already an
2095     // initialization that completely initialized the current
2096     // subobject, e.g., by a compound literal:
2097     //
2098     // struct X { int a, b; };
2099     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2100     //
2101     // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2102     // designated initializer re-initializes the whole
2103     // subobject [0], overwriting previous initializers.
2104     SemaRef.Diag(InitRange.getBegin(),
2105                  diag::warn_subobject_initializer_overrides)
2106       << InitRange;
2107     SemaRef.Diag(ExistingInit->getLocStart(),
2108                   diag::note_previous_initializer)
2109       << /*FIXME:has side effects=*/0
2110       << ExistingInit->getSourceRange();
2111   }
2112 
2113   InitListExpr *Result
2114     = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2115                                          InitRange.getBegin(), MultiExprArg(),
2116                                          InitRange.getEnd());
2117 
2118   QualType ResultType = CurrentObjectType;
2119   if (!ResultType->isArrayType())
2120     ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2121   Result->setType(ResultType);
2122 
2123   // Pre-allocate storage for the structured initializer list.
2124   unsigned NumElements = 0;
2125   unsigned NumInits = 0;
2126   bool GotNumInits = false;
2127   if (!StructuredList) {
2128     NumInits = IList->getNumInits();
2129     GotNumInits = true;
2130   } else if (Index < IList->getNumInits()) {
2131     if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2132       NumInits = SubList->getNumInits();
2133       GotNumInits = true;
2134     }
2135   }
2136 
2137   if (const ArrayType *AType
2138       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2139     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2140       NumElements = CAType->getSize().getZExtValue();
2141       // Simple heuristic so that we don't allocate a very large
2142       // initializer with many empty entries at the end.
2143       if (GotNumInits && NumElements > NumInits)
2144         NumElements = 0;
2145     }
2146   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2147     NumElements = VType->getNumElements();
2148   else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2149     RecordDecl *RDecl = RType->getDecl();
2150     if (RDecl->isUnion())
2151       NumElements = 1;
2152     else
2153       NumElements = std::distance(RDecl->field_begin(),
2154                                   RDecl->field_end());
2155   }
2156 
2157   Result->reserveInits(SemaRef.Context, NumElements);
2158 
2159   // Link this new initializer list into the structured initializer
2160   // lists.
2161   if (StructuredList)
2162     StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2163   else {
2164     Result->setSyntacticForm(IList);
2165     SyntacticToSemantic[IList] = Result;
2166   }
2167 
2168   return Result;
2169 }
2170 
2171 /// Update the initializer at index @p StructuredIndex within the
2172 /// structured initializer list to the value @p expr.
2173 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2174                                                   unsigned &StructuredIndex,
2175                                                   Expr *expr) {
2176   // No structured initializer list to update
2177   if (!StructuredList)
2178     return;
2179 
2180   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2181                                                   StructuredIndex, expr)) {
2182     // This initializer overwrites a previous initializer. Warn.
2183     SemaRef.Diag(expr->getLocStart(),
2184                   diag::warn_initializer_overrides)
2185       << expr->getSourceRange();
2186     SemaRef.Diag(PrevInit->getLocStart(),
2187                   diag::note_previous_initializer)
2188       << /*FIXME:has side effects=*/0
2189       << PrevInit->getSourceRange();
2190   }
2191 
2192   ++StructuredIndex;
2193 }
2194 
2195 /// Check that the given Index expression is a valid array designator
2196 /// value. This is essentially just a wrapper around
2197 /// VerifyIntegerConstantExpression that also checks for negative values
2198 /// and produces a reasonable diagnostic if there is a
2199 /// failure. Returns the index expression, possibly with an implicit cast
2200 /// added, on success.  If everything went okay, Value will receive the
2201 /// value of the constant expression.
2202 static ExprResult
2203 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2204   SourceLocation Loc = Index->getLocStart();
2205 
2206   // Make sure this is an integer constant expression.
2207   ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2208   if (Result.isInvalid())
2209     return Result;
2210 
2211   if (Value.isSigned() && Value.isNegative())
2212     return S.Diag(Loc, diag::err_array_designator_negative)
2213       << Value.toString(10) << Index->getSourceRange();
2214 
2215   Value.setIsUnsigned(true);
2216   return Result;
2217 }
2218 
2219 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2220                                             SourceLocation Loc,
2221                                             bool GNUSyntax,
2222                                             ExprResult Init) {
2223   typedef DesignatedInitExpr::Designator ASTDesignator;
2224 
2225   bool Invalid = false;
2226   SmallVector<ASTDesignator, 32> Designators;
2227   SmallVector<Expr *, 32> InitExpressions;
2228 
2229   // Build designators and check array designator expressions.
2230   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2231     const Designator &D = Desig.getDesignator(Idx);
2232     switch (D.getKind()) {
2233     case Designator::FieldDesignator:
2234       Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2235                                           D.getFieldLoc()));
2236       break;
2237 
2238     case Designator::ArrayDesignator: {
2239       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2240       llvm::APSInt IndexValue;
2241       if (!Index->isTypeDependent() && !Index->isValueDependent())
2242         Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2243       if (!Index)
2244         Invalid = true;
2245       else {
2246         Designators.push_back(ASTDesignator(InitExpressions.size(),
2247                                             D.getLBracketLoc(),
2248                                             D.getRBracketLoc()));
2249         InitExpressions.push_back(Index);
2250       }
2251       break;
2252     }
2253 
2254     case Designator::ArrayRangeDesignator: {
2255       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2256       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2257       llvm::APSInt StartValue;
2258       llvm::APSInt EndValue;
2259       bool StartDependent = StartIndex->isTypeDependent() ||
2260                             StartIndex->isValueDependent();
2261       bool EndDependent = EndIndex->isTypeDependent() ||
2262                           EndIndex->isValueDependent();
2263       if (!StartDependent)
2264         StartIndex =
2265             CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2266       if (!EndDependent)
2267         EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2268 
2269       if (!StartIndex || !EndIndex)
2270         Invalid = true;
2271       else {
2272         // Make sure we're comparing values with the same bit width.
2273         if (StartDependent || EndDependent) {
2274           // Nothing to compute.
2275         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2276           EndValue = EndValue.extend(StartValue.getBitWidth());
2277         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2278           StartValue = StartValue.extend(EndValue.getBitWidth());
2279 
2280         if (!StartDependent && !EndDependent && EndValue < StartValue) {
2281           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2282             << StartValue.toString(10) << EndValue.toString(10)
2283             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2284           Invalid = true;
2285         } else {
2286           Designators.push_back(ASTDesignator(InitExpressions.size(),
2287                                               D.getLBracketLoc(),
2288                                               D.getEllipsisLoc(),
2289                                               D.getRBracketLoc()));
2290           InitExpressions.push_back(StartIndex);
2291           InitExpressions.push_back(EndIndex);
2292         }
2293       }
2294       break;
2295     }
2296     }
2297   }
2298 
2299   if (Invalid || Init.isInvalid())
2300     return ExprError();
2301 
2302   // Clear out the expressions within the designation.
2303   Desig.ClearExprs(*this);
2304 
2305   DesignatedInitExpr *DIE
2306     = DesignatedInitExpr::Create(Context,
2307                                  Designators.data(), Designators.size(),
2308                                  InitExpressions, Loc, GNUSyntax,
2309                                  Init.takeAs<Expr>());
2310 
2311   if (!getLangOpts().C99)
2312     Diag(DIE->getLocStart(), diag::ext_designated_init)
2313       << DIE->getSourceRange();
2314 
2315   return Owned(DIE);
2316 }
2317 
2318 //===----------------------------------------------------------------------===//
2319 // Initialization entity
2320 //===----------------------------------------------------------------------===//
2321 
2322 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2323                                      const InitializedEntity &Parent)
2324   : Parent(&Parent), Index(Index)
2325 {
2326   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2327     Kind = EK_ArrayElement;
2328     Type = AT->getElementType();
2329   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2330     Kind = EK_VectorElement;
2331     Type = VT->getElementType();
2332   } else {
2333     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2334     assert(CT && "Unexpected type");
2335     Kind = EK_ComplexElement;
2336     Type = CT->getElementType();
2337   }
2338 }
2339 
2340 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
2341                                                     CXXBaseSpecifier *Base,
2342                                                     bool IsInheritedVirtualBase)
2343 {
2344   InitializedEntity Result;
2345   Result.Kind = EK_Base;
2346   Result.Base = reinterpret_cast<uintptr_t>(Base);
2347   if (IsInheritedVirtualBase)
2348     Result.Base |= 0x01;
2349 
2350   Result.Type = Base->getType();
2351   return Result;
2352 }
2353 
2354 DeclarationName InitializedEntity::getName() const {
2355   switch (getKind()) {
2356   case EK_Parameter: {
2357     ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2358     return (D ? D->getDeclName() : DeclarationName());
2359   }
2360 
2361   case EK_Variable:
2362   case EK_Member:
2363     return VariableOrMember->getDeclName();
2364 
2365   case EK_LambdaCapture:
2366     return Capture.Var->getDeclName();
2367 
2368   case EK_Result:
2369   case EK_Exception:
2370   case EK_New:
2371   case EK_Temporary:
2372   case EK_Base:
2373   case EK_Delegating:
2374   case EK_ArrayElement:
2375   case EK_VectorElement:
2376   case EK_ComplexElement:
2377   case EK_BlockElement:
2378     return DeclarationName();
2379   }
2380 
2381   llvm_unreachable("Invalid EntityKind!");
2382 }
2383 
2384 DeclaratorDecl *InitializedEntity::getDecl() const {
2385   switch (getKind()) {
2386   case EK_Variable:
2387   case EK_Member:
2388     return VariableOrMember;
2389 
2390   case EK_Parameter:
2391     return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2392 
2393   case EK_Result:
2394   case EK_Exception:
2395   case EK_New:
2396   case EK_Temporary:
2397   case EK_Base:
2398   case EK_Delegating:
2399   case EK_ArrayElement:
2400   case EK_VectorElement:
2401   case EK_ComplexElement:
2402   case EK_BlockElement:
2403   case EK_LambdaCapture:
2404     return 0;
2405   }
2406 
2407   llvm_unreachable("Invalid EntityKind!");
2408 }
2409 
2410 bool InitializedEntity::allowsNRVO() const {
2411   switch (getKind()) {
2412   case EK_Result:
2413   case EK_Exception:
2414     return LocAndNRVO.NRVO;
2415 
2416   case EK_Variable:
2417   case EK_Parameter:
2418   case EK_Member:
2419   case EK_New:
2420   case EK_Temporary:
2421   case EK_Base:
2422   case EK_Delegating:
2423   case EK_ArrayElement:
2424   case EK_VectorElement:
2425   case EK_ComplexElement:
2426   case EK_BlockElement:
2427   case EK_LambdaCapture:
2428     break;
2429   }
2430 
2431   return false;
2432 }
2433 
2434 //===----------------------------------------------------------------------===//
2435 // Initialization sequence
2436 //===----------------------------------------------------------------------===//
2437 
2438 void InitializationSequence::Step::Destroy() {
2439   switch (Kind) {
2440   case SK_ResolveAddressOfOverloadedFunction:
2441   case SK_CastDerivedToBaseRValue:
2442   case SK_CastDerivedToBaseXValue:
2443   case SK_CastDerivedToBaseLValue:
2444   case SK_BindReference:
2445   case SK_BindReferenceToTemporary:
2446   case SK_ExtraneousCopyToTemporary:
2447   case SK_UserConversion:
2448   case SK_QualificationConversionRValue:
2449   case SK_QualificationConversionXValue:
2450   case SK_QualificationConversionLValue:
2451   case SK_LValueToRValue:
2452   case SK_ListInitialization:
2453   case SK_ListConstructorCall:
2454   case SK_UnwrapInitList:
2455   case SK_RewrapInitList:
2456   case SK_ConstructorInitialization:
2457   case SK_ZeroInitialization:
2458   case SK_CAssignment:
2459   case SK_StringInit:
2460   case SK_ObjCObjectConversion:
2461   case SK_ArrayInit:
2462   case SK_ParenthesizedArrayInit:
2463   case SK_PassByIndirectCopyRestore:
2464   case SK_PassByIndirectRestore:
2465   case SK_ProduceObjCObject:
2466   case SK_StdInitializerList:
2467   case SK_OCLSamplerInit:
2468   case SK_OCLZeroEvent:
2469     break;
2470 
2471   case SK_ConversionSequence:
2472     delete ICS;
2473   }
2474 }
2475 
2476 bool InitializationSequence::isDirectReferenceBinding() const {
2477   return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2478 }
2479 
2480 bool InitializationSequence::isAmbiguous() const {
2481   if (!Failed())
2482     return false;
2483 
2484   switch (getFailureKind()) {
2485   case FK_TooManyInitsForReference:
2486   case FK_ArrayNeedsInitList:
2487   case FK_ArrayNeedsInitListOrStringLiteral:
2488   case FK_AddressOfOverloadFailed: // FIXME: Could do better
2489   case FK_NonConstLValueReferenceBindingToTemporary:
2490   case FK_NonConstLValueReferenceBindingToUnrelated:
2491   case FK_RValueReferenceBindingToLValue:
2492   case FK_ReferenceInitDropsQualifiers:
2493   case FK_ReferenceInitFailed:
2494   case FK_ConversionFailed:
2495   case FK_ConversionFromPropertyFailed:
2496   case FK_TooManyInitsForScalar:
2497   case FK_ReferenceBindingToInitList:
2498   case FK_InitListBadDestinationType:
2499   case FK_DefaultInitOfConst:
2500   case FK_Incomplete:
2501   case FK_ArrayTypeMismatch:
2502   case FK_NonConstantArrayInit:
2503   case FK_ListInitializationFailed:
2504   case FK_VariableLengthArrayHasInitializer:
2505   case FK_PlaceholderType:
2506   case FK_InitListElementCopyFailure:
2507   case FK_ExplicitConstructor:
2508     return false;
2509 
2510   case FK_ReferenceInitOverloadFailed:
2511   case FK_UserConversionOverloadFailed:
2512   case FK_ConstructorOverloadFailed:
2513   case FK_ListConstructorOverloadFailed:
2514     return FailedOverloadResult == OR_Ambiguous;
2515   }
2516 
2517   llvm_unreachable("Invalid EntityKind!");
2518 }
2519 
2520 bool InitializationSequence::isConstructorInitialization() const {
2521   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2522 }
2523 
2524 void
2525 InitializationSequence
2526 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2527                                    DeclAccessPair Found,
2528                                    bool HadMultipleCandidates) {
2529   Step S;
2530   S.Kind = SK_ResolveAddressOfOverloadedFunction;
2531   S.Type = Function->getType();
2532   S.Function.HadMultipleCandidates = HadMultipleCandidates;
2533   S.Function.Function = Function;
2534   S.Function.FoundDecl = Found;
2535   Steps.push_back(S);
2536 }
2537 
2538 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2539                                                       ExprValueKind VK) {
2540   Step S;
2541   switch (VK) {
2542   case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2543   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2544   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2545   }
2546   S.Type = BaseType;
2547   Steps.push_back(S);
2548 }
2549 
2550 void InitializationSequence::AddReferenceBindingStep(QualType T,
2551                                                      bool BindingTemporary) {
2552   Step S;
2553   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2554   S.Type = T;
2555   Steps.push_back(S);
2556 }
2557 
2558 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2559   Step S;
2560   S.Kind = SK_ExtraneousCopyToTemporary;
2561   S.Type = T;
2562   Steps.push_back(S);
2563 }
2564 
2565 void
2566 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2567                                               DeclAccessPair FoundDecl,
2568                                               QualType T,
2569                                               bool HadMultipleCandidates) {
2570   Step S;
2571   S.Kind = SK_UserConversion;
2572   S.Type = T;
2573   S.Function.HadMultipleCandidates = HadMultipleCandidates;
2574   S.Function.Function = Function;
2575   S.Function.FoundDecl = FoundDecl;
2576   Steps.push_back(S);
2577 }
2578 
2579 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2580                                                             ExprValueKind VK) {
2581   Step S;
2582   S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2583   switch (VK) {
2584   case VK_RValue:
2585     S.Kind = SK_QualificationConversionRValue;
2586     break;
2587   case VK_XValue:
2588     S.Kind = SK_QualificationConversionXValue;
2589     break;
2590   case VK_LValue:
2591     S.Kind = SK_QualificationConversionLValue;
2592     break;
2593   }
2594   S.Type = Ty;
2595   Steps.push_back(S);
2596 }
2597 
2598 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2599   assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2600 
2601   Step S;
2602   S.Kind = SK_LValueToRValue;
2603   S.Type = Ty;
2604   Steps.push_back(S);
2605 }
2606 
2607 void InitializationSequence::AddConversionSequenceStep(
2608                                        const ImplicitConversionSequence &ICS,
2609                                                        QualType T) {
2610   Step S;
2611   S.Kind = SK_ConversionSequence;
2612   S.Type = T;
2613   S.ICS = new ImplicitConversionSequence(ICS);
2614   Steps.push_back(S);
2615 }
2616 
2617 void InitializationSequence::AddListInitializationStep(QualType T) {
2618   Step S;
2619   S.Kind = SK_ListInitialization;
2620   S.Type = T;
2621   Steps.push_back(S);
2622 }
2623 
2624 void
2625 InitializationSequence
2626 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2627                                    AccessSpecifier Access,
2628                                    QualType T,
2629                                    bool HadMultipleCandidates,
2630                                    bool FromInitList, bool AsInitList) {
2631   Step S;
2632   S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2633                                        : SK_ConstructorInitialization;
2634   S.Type = T;
2635   S.Function.HadMultipleCandidates = HadMultipleCandidates;
2636   S.Function.Function = Constructor;
2637   S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2638   Steps.push_back(S);
2639 }
2640 
2641 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2642   Step S;
2643   S.Kind = SK_ZeroInitialization;
2644   S.Type = T;
2645   Steps.push_back(S);
2646 }
2647 
2648 void InitializationSequence::AddCAssignmentStep(QualType T) {
2649   Step S;
2650   S.Kind = SK_CAssignment;
2651   S.Type = T;
2652   Steps.push_back(S);
2653 }
2654 
2655 void InitializationSequence::AddStringInitStep(QualType T) {
2656   Step S;
2657   S.Kind = SK_StringInit;
2658   S.Type = T;
2659   Steps.push_back(S);
2660 }
2661 
2662 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2663   Step S;
2664   S.Kind = SK_ObjCObjectConversion;
2665   S.Type = T;
2666   Steps.push_back(S);
2667 }
2668 
2669 void InitializationSequence::AddArrayInitStep(QualType T) {
2670   Step S;
2671   S.Kind = SK_ArrayInit;
2672   S.Type = T;
2673   Steps.push_back(S);
2674 }
2675 
2676 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2677   Step S;
2678   S.Kind = SK_ParenthesizedArrayInit;
2679   S.Type = T;
2680   Steps.push_back(S);
2681 }
2682 
2683 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2684                                                               bool shouldCopy) {
2685   Step s;
2686   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2687                        : SK_PassByIndirectRestore);
2688   s.Type = type;
2689   Steps.push_back(s);
2690 }
2691 
2692 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2693   Step S;
2694   S.Kind = SK_ProduceObjCObject;
2695   S.Type = T;
2696   Steps.push_back(S);
2697 }
2698 
2699 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2700   Step S;
2701   S.Kind = SK_StdInitializerList;
2702   S.Type = T;
2703   Steps.push_back(S);
2704 }
2705 
2706 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2707   Step S;
2708   S.Kind = SK_OCLSamplerInit;
2709   S.Type = T;
2710   Steps.push_back(S);
2711 }
2712 
2713 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2714   Step S;
2715   S.Kind = SK_OCLZeroEvent;
2716   S.Type = T;
2717   Steps.push_back(S);
2718 }
2719 
2720 void InitializationSequence::RewrapReferenceInitList(QualType T,
2721                                                      InitListExpr *Syntactic) {
2722   assert(Syntactic->getNumInits() == 1 &&
2723          "Can only rewrap trivial init lists.");
2724   Step S;
2725   S.Kind = SK_UnwrapInitList;
2726   S.Type = Syntactic->getInit(0)->getType();
2727   Steps.insert(Steps.begin(), S);
2728 
2729   S.Kind = SK_RewrapInitList;
2730   S.Type = T;
2731   S.WrappingSyntacticList = Syntactic;
2732   Steps.push_back(S);
2733 }
2734 
2735 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2736                                                 OverloadingResult Result) {
2737   setSequenceKind(FailedSequence);
2738   this->Failure = Failure;
2739   this->FailedOverloadResult = Result;
2740 }
2741 
2742 //===----------------------------------------------------------------------===//
2743 // Attempt initialization
2744 //===----------------------------------------------------------------------===//
2745 
2746 static void MaybeProduceObjCObject(Sema &S,
2747                                    InitializationSequence &Sequence,
2748                                    const InitializedEntity &Entity) {
2749   if (!S.getLangOpts().ObjCAutoRefCount) return;
2750 
2751   /// When initializing a parameter, produce the value if it's marked
2752   /// __attribute__((ns_consumed)).
2753   if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2754     if (!Entity.isParameterConsumed())
2755       return;
2756 
2757     assert(Entity.getType()->isObjCRetainableType() &&
2758            "consuming an object of unretainable type?");
2759     Sequence.AddProduceObjCObjectStep(Entity.getType());
2760 
2761   /// When initializing a return value, if the return type is a
2762   /// retainable type, then returns need to immediately retain the
2763   /// object.  If an autorelease is required, it will be done at the
2764   /// last instant.
2765   } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2766     if (!Entity.getType()->isObjCRetainableType())
2767       return;
2768 
2769     Sequence.AddProduceObjCObjectStep(Entity.getType());
2770   }
2771 }
2772 
2773 /// \brief When initializing from init list via constructor, handle
2774 /// initialization of an object of type std::initializer_list<T>.
2775 ///
2776 /// \return true if we have handled initialization of an object of type
2777 /// std::initializer_list<T>, false otherwise.
2778 static bool TryInitializerListConstruction(Sema &S,
2779                                            InitListExpr *List,
2780                                            QualType DestType,
2781                                            InitializationSequence &Sequence) {
2782   QualType E;
2783   if (!S.isStdInitializerList(DestType, &E))
2784     return false;
2785 
2786   // Check that each individual element can be copy-constructed. But since we
2787   // have no place to store further information, we'll recalculate everything
2788   // later.
2789   InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2790       S.Context.getConstantArrayType(E,
2791           llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2792                       List->getNumInits()),
2793           ArrayType::Normal, 0));
2794   InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2795       0, HiddenArray);
2796   for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2797     Element.setElementIndex(i);
2798     if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2799       Sequence.SetFailed(
2800           InitializationSequence::FK_InitListElementCopyFailure);
2801       return true;
2802     }
2803   }
2804   Sequence.AddStdInitializerListConstructionStep(DestType);
2805   return true;
2806 }
2807 
2808 static OverloadingResult
2809 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2810                            Expr **Args, unsigned NumArgs,
2811                            OverloadCandidateSet &CandidateSet,
2812                            ArrayRef<NamedDecl *> Ctors,
2813                            OverloadCandidateSet::iterator &Best,
2814                            bool CopyInitializing, bool AllowExplicit,
2815                            bool OnlyListConstructors, bool InitListSyntax) {
2816   CandidateSet.clear();
2817 
2818   for (ArrayRef<NamedDecl *>::iterator
2819          Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
2820     NamedDecl *D = *Con;
2821     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2822     bool SuppressUserConversions = false;
2823 
2824     // Find the constructor (which may be a template).
2825     CXXConstructorDecl *Constructor = 0;
2826     FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2827     if (ConstructorTmpl)
2828       Constructor = cast<CXXConstructorDecl>(
2829                                            ConstructorTmpl->getTemplatedDecl());
2830     else {
2831       Constructor = cast<CXXConstructorDecl>(D);
2832 
2833       // If we're performing copy initialization using a copy constructor, we
2834       // suppress user-defined conversions on the arguments. We do the same for
2835       // move constructors.
2836       if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2837           Constructor->isCopyOrMoveConstructor())
2838         SuppressUserConversions = true;
2839     }
2840 
2841     if (!Constructor->isInvalidDecl() &&
2842         (AllowExplicit || !Constructor->isExplicit()) &&
2843         (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
2844       if (ConstructorTmpl)
2845         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2846                                        /*ExplicitArgs*/ 0,
2847                                        llvm::makeArrayRef(Args, NumArgs),
2848                                        CandidateSet, SuppressUserConversions);
2849       else {
2850         // C++ [over.match.copy]p1:
2851         //   - When initializing a temporary to be bound to the first parameter
2852         //     of a constructor that takes a reference to possibly cv-qualified
2853         //     T as its first argument, called with a single argument in the
2854         //     context of direct-initialization, explicit conversion functions
2855         //     are also considered.
2856         bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2857                                  NumArgs == 1 &&
2858                                  Constructor->isCopyOrMoveConstructor();
2859         S.AddOverloadCandidate(Constructor, FoundDecl,
2860                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
2861                                SuppressUserConversions,
2862                                /*PartialOverloading=*/false,
2863                                /*AllowExplicit=*/AllowExplicitConv);
2864       }
2865     }
2866   }
2867 
2868   // Perform overload resolution and return the result.
2869   return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2870 }
2871 
2872 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2873 /// enumerates the constructors of the initialized entity and performs overload
2874 /// resolution to select the best.
2875 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
2876 /// class type.
2877 static void TryConstructorInitialization(Sema &S,
2878                                          const InitializedEntity &Entity,
2879                                          const InitializationKind &Kind,
2880                                          Expr **Args, unsigned NumArgs,
2881                                          QualType DestType,
2882                                          InitializationSequence &Sequence,
2883                                          bool InitListSyntax = false) {
2884   assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2885          "InitListSyntax must come with a single initializer list argument.");
2886 
2887   // The type we're constructing needs to be complete.
2888   if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2889     Sequence.setIncompleteTypeFailure(DestType);
2890     return;
2891   }
2892 
2893   const RecordType *DestRecordType = DestType->getAs<RecordType>();
2894   assert(DestRecordType && "Constructor initialization requires record type");
2895   CXXRecordDecl *DestRecordDecl
2896     = cast<CXXRecordDecl>(DestRecordType->getDecl());
2897 
2898   // Build the candidate set directly in the initialization sequence
2899   // structure, so that it will persist if we fail.
2900   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2901 
2902   // Determine whether we are allowed to call explicit constructors or
2903   // explicit conversion operators.
2904   bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
2905   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
2906 
2907   //   - Otherwise, if T is a class type, constructors are considered. The
2908   //     applicable constructors are enumerated, and the best one is chosen
2909   //     through overload resolution.
2910   DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
2911   // The container holding the constructors can under certain conditions
2912   // be changed while iterating (e.g. because of deserialization).
2913   // To be safe we copy the lookup results to a new container.
2914   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
2915 
2916   OverloadingResult Result = OR_No_Viable_Function;
2917   OverloadCandidateSet::iterator Best;
2918   bool AsInitializerList = false;
2919 
2920   // C++11 [over.match.list]p1:
2921   //   When objects of non-aggregate type T are list-initialized, overload
2922   //   resolution selects the constructor in two phases:
2923   //   - Initially, the candidate functions are the initializer-list
2924   //     constructors of the class T and the argument list consists of the
2925   //     initializer list as a single argument.
2926   if (InitListSyntax) {
2927     InitListExpr *ILE = cast<InitListExpr>(Args[0]);
2928     AsInitializerList = true;
2929 
2930     // If the initializer list has no elements and T has a default constructor,
2931     // the first phase is omitted.
2932     if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
2933       Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2934                                           CandidateSet, Ctors, Best,
2935                                           CopyInitialization, AllowExplicit,
2936                                           /*OnlyListConstructor=*/true,
2937                                           InitListSyntax);
2938 
2939     // Time to unwrap the init list.
2940     Args = ILE->getInits();
2941     NumArgs = ILE->getNumInits();
2942   }
2943 
2944   // C++11 [over.match.list]p1:
2945   //   - If no viable initializer-list constructor is found, overload resolution
2946   //     is performed again, where the candidate functions are all the
2947   //     constructors of the class T and the argument list consists of the
2948   //     elements of the initializer list.
2949   if (Result == OR_No_Viable_Function) {
2950     AsInitializerList = false;
2951     Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
2952                                         CandidateSet, Ctors, Best,
2953                                         CopyInitialization, AllowExplicit,
2954                                         /*OnlyListConstructors=*/false,
2955                                         InitListSyntax);
2956   }
2957   if (Result) {
2958     Sequence.SetOverloadFailure(InitListSyntax ?
2959                       InitializationSequence::FK_ListConstructorOverloadFailed :
2960                       InitializationSequence::FK_ConstructorOverloadFailed,
2961                                 Result);
2962     return;
2963   }
2964 
2965   // C++11 [dcl.init]p6:
2966   //   If a program calls for the default initialization of an object
2967   //   of a const-qualified type T, T shall be a class type with a
2968   //   user-provided default constructor.
2969   if (Kind.getKind() == InitializationKind::IK_Default &&
2970       Entity.getType().isConstQualified() &&
2971       !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
2972     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2973     return;
2974   }
2975 
2976   // C++11 [over.match.list]p1:
2977   //   In copy-list-initialization, if an explicit constructor is chosen, the
2978   //   initializer is ill-formed.
2979   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2980   if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2981     Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2982     return;
2983   }
2984 
2985   // Add the constructor initialization step. Any cv-qualification conversion is
2986   // subsumed by the initialization.
2987   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2988   Sequence.AddConstructorInitializationStep(CtorDecl,
2989                                             Best->FoundDecl.getAccess(),
2990                                             DestType, HadMultipleCandidates,
2991                                             InitListSyntax, AsInitializerList);
2992 }
2993 
2994 static bool
2995 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2996                                              Expr *Initializer,
2997                                              QualType &SourceType,
2998                                              QualType &UnqualifiedSourceType,
2999                                              QualType UnqualifiedTargetType,
3000                                              InitializationSequence &Sequence) {
3001   if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3002         S.Context.OverloadTy) {
3003     DeclAccessPair Found;
3004     bool HadMultipleCandidates = false;
3005     if (FunctionDecl *Fn
3006         = S.ResolveAddressOfOverloadedFunction(Initializer,
3007                                                UnqualifiedTargetType,
3008                                                false, Found,
3009                                                &HadMultipleCandidates)) {
3010       Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3011                                                 HadMultipleCandidates);
3012       SourceType = Fn->getType();
3013       UnqualifiedSourceType = SourceType.getUnqualifiedType();
3014     } else if (!UnqualifiedTargetType->isRecordType()) {
3015       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3016       return true;
3017     }
3018   }
3019   return false;
3020 }
3021 
3022 static void TryReferenceInitializationCore(Sema &S,
3023                                            const InitializedEntity &Entity,
3024                                            const InitializationKind &Kind,
3025                                            Expr *Initializer,
3026                                            QualType cv1T1, QualType T1,
3027                                            Qualifiers T1Quals,
3028                                            QualType cv2T2, QualType T2,
3029                                            Qualifiers T2Quals,
3030                                            InitializationSequence &Sequence);
3031 
3032 static void TryValueInitialization(Sema &S,
3033                                    const InitializedEntity &Entity,
3034                                    const InitializationKind &Kind,
3035                                    InitializationSequence &Sequence,
3036                                    InitListExpr *InitList = 0);
3037 
3038 static void TryListInitialization(Sema &S,
3039                                   const InitializedEntity &Entity,
3040                                   const InitializationKind &Kind,
3041                                   InitListExpr *InitList,
3042                                   InitializationSequence &Sequence);
3043 
3044 /// \brief Attempt list initialization of a reference.
3045 static void TryReferenceListInitialization(Sema &S,
3046                                            const InitializedEntity &Entity,
3047                                            const InitializationKind &Kind,
3048                                            InitListExpr *InitList,
3049                                            InitializationSequence &Sequence)
3050 {
3051   // First, catch C++03 where this isn't possible.
3052   if (!S.getLangOpts().CPlusPlus11) {
3053     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3054     return;
3055   }
3056 
3057   QualType DestType = Entity.getType();
3058   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3059   Qualifiers T1Quals;
3060   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3061 
3062   // Reference initialization via an initializer list works thus:
3063   // If the initializer list consists of a single element that is
3064   // reference-related to the referenced type, bind directly to that element
3065   // (possibly creating temporaries).
3066   // Otherwise, initialize a temporary with the initializer list and
3067   // bind to that.
3068   if (InitList->getNumInits() == 1) {
3069     Expr *Initializer = InitList->getInit(0);
3070     QualType cv2T2 = Initializer->getType();
3071     Qualifiers T2Quals;
3072     QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3073 
3074     // If this fails, creating a temporary wouldn't work either.
3075     if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3076                                                      T1, Sequence))
3077       return;
3078 
3079     SourceLocation DeclLoc = Initializer->getLocStart();
3080     bool dummy1, dummy2, dummy3;
3081     Sema::ReferenceCompareResult RefRelationship
3082       = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3083                                        dummy2, dummy3);
3084     if (RefRelationship >= Sema::Ref_Related) {
3085       // Try to bind the reference here.
3086       TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3087                                      T1Quals, cv2T2, T2, T2Quals, Sequence);
3088       if (Sequence)
3089         Sequence.RewrapReferenceInitList(cv1T1, InitList);
3090       return;
3091     }
3092 
3093     // Update the initializer if we've resolved an overloaded function.
3094     if (Sequence.step_begin() != Sequence.step_end())
3095       Sequence.RewrapReferenceInitList(cv1T1, InitList);
3096   }
3097 
3098   // Not reference-related. Create a temporary and bind to that.
3099   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3100 
3101   TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3102   if (Sequence) {
3103     if (DestType->isRValueReferenceType() ||
3104         (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3105       Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3106     else
3107       Sequence.SetFailed(
3108           InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3109   }
3110 }
3111 
3112 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3113 static void TryListInitialization(Sema &S,
3114                                   const InitializedEntity &Entity,
3115                                   const InitializationKind &Kind,
3116                                   InitListExpr *InitList,
3117                                   InitializationSequence &Sequence) {
3118   QualType DestType = Entity.getType();
3119 
3120   // C++ doesn't allow scalar initialization with more than one argument.
3121   // But C99 complex numbers are scalars and it makes sense there.
3122   if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3123       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3124     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3125     return;
3126   }
3127   if (DestType->isReferenceType()) {
3128     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3129     return;
3130   }
3131   if (DestType->isRecordType()) {
3132     if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3133       Sequence.setIncompleteTypeFailure(DestType);
3134       return;
3135     }
3136 
3137     // C++11 [dcl.init.list]p3:
3138     //   - If T is an aggregate, aggregate initialization is performed.
3139     if (!DestType->isAggregateType()) {
3140       if (S.getLangOpts().CPlusPlus11) {
3141         //   - Otherwise, if the initializer list has no elements and T is a
3142         //     class type with a default constructor, the object is
3143         //     value-initialized.
3144         if (InitList->getNumInits() == 0) {
3145           CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3146           if (RD->hasDefaultConstructor()) {
3147             TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3148             return;
3149           }
3150         }
3151 
3152         //   - Otherwise, if T is a specialization of std::initializer_list<E>,
3153         //     an initializer_list object constructed [...]
3154         if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3155           return;
3156 
3157         //   - Otherwise, if T is a class type, constructors are considered.
3158         Expr *Arg = InitList;
3159         TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3160                                      Sequence, /*InitListSyntax*/true);
3161       } else
3162         Sequence.SetFailed(
3163             InitializationSequence::FK_InitListBadDestinationType);
3164       return;
3165     }
3166   }
3167 
3168   InitListChecker CheckInitList(S, Entity, InitList,
3169           DestType, /*VerifyOnly=*/true,
3170           Kind.getKind() != InitializationKind::IK_DirectList ||
3171             !S.getLangOpts().CPlusPlus11);
3172   if (CheckInitList.HadError()) {
3173     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3174     return;
3175   }
3176 
3177   // Add the list initialization step with the built init list.
3178   Sequence.AddListInitializationStep(DestType);
3179 }
3180 
3181 /// \brief Try a reference initialization that involves calling a conversion
3182 /// function.
3183 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3184                                              const InitializedEntity &Entity,
3185                                              const InitializationKind &Kind,
3186                                              Expr *Initializer,
3187                                              bool AllowRValues,
3188                                              InitializationSequence &Sequence) {
3189   QualType DestType = Entity.getType();
3190   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3191   QualType T1 = cv1T1.getUnqualifiedType();
3192   QualType cv2T2 = Initializer->getType();
3193   QualType T2 = cv2T2.getUnqualifiedType();
3194 
3195   bool DerivedToBase;
3196   bool ObjCConversion;
3197   bool ObjCLifetimeConversion;
3198   assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3199                                          T1, T2, DerivedToBase,
3200                                          ObjCConversion,
3201                                          ObjCLifetimeConversion) &&
3202          "Must have incompatible references when binding via conversion");
3203   (void)DerivedToBase;
3204   (void)ObjCConversion;
3205   (void)ObjCLifetimeConversion;
3206 
3207   // Build the candidate set directly in the initialization sequence
3208   // structure, so that it will persist if we fail.
3209   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3210   CandidateSet.clear();
3211 
3212   // Determine whether we are allowed to call explicit constructors or
3213   // explicit conversion operators.
3214   bool AllowExplicit = Kind.AllowExplicit();
3215   bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3216 
3217   const RecordType *T1RecordType = 0;
3218   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3219       !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3220     // The type we're converting to is a class type. Enumerate its constructors
3221     // to see if there is a suitable conversion.
3222     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3223 
3224     DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
3225     // The container holding the constructors can under certain conditions
3226     // be changed while iterating (e.g. because of deserialization).
3227     // To be safe we copy the lookup results to a new container.
3228     SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3229     for (SmallVector<NamedDecl*, 16>::iterator
3230            CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3231       NamedDecl *D = *CI;
3232       DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3233 
3234       // Find the constructor (which may be a template).
3235       CXXConstructorDecl *Constructor = 0;
3236       FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3237       if (ConstructorTmpl)
3238         Constructor = cast<CXXConstructorDecl>(
3239                                          ConstructorTmpl->getTemplatedDecl());
3240       else
3241         Constructor = cast<CXXConstructorDecl>(D);
3242 
3243       if (!Constructor->isInvalidDecl() &&
3244           Constructor->isConvertingConstructor(AllowExplicit)) {
3245         if (ConstructorTmpl)
3246           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3247                                          /*ExplicitArgs*/ 0,
3248                                          Initializer, CandidateSet,
3249                                          /*SuppressUserConversions=*/true);
3250         else
3251           S.AddOverloadCandidate(Constructor, FoundDecl,
3252                                  Initializer, CandidateSet,
3253                                  /*SuppressUserConversions=*/true);
3254       }
3255     }
3256   }
3257   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3258     return OR_No_Viable_Function;
3259 
3260   const RecordType *T2RecordType = 0;
3261   if ((T2RecordType = T2->getAs<RecordType>()) &&
3262       !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3263     // The type we're converting from is a class type, enumerate its conversion
3264     // functions.
3265     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3266 
3267     std::pair<CXXRecordDecl::conversion_iterator,
3268               CXXRecordDecl::conversion_iterator>
3269       Conversions = T2RecordDecl->getVisibleConversionFunctions();
3270     for (CXXRecordDecl::conversion_iterator
3271            I = Conversions.first, E = Conversions.second; I != E; ++I) {
3272       NamedDecl *D = *I;
3273       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3274       if (isa<UsingShadowDecl>(D))
3275         D = cast<UsingShadowDecl>(D)->getTargetDecl();
3276 
3277       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3278       CXXConversionDecl *Conv;
3279       if (ConvTemplate)
3280         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3281       else
3282         Conv = cast<CXXConversionDecl>(D);
3283 
3284       // If the conversion function doesn't return a reference type,
3285       // it can't be considered for this conversion unless we're allowed to
3286       // consider rvalues.
3287       // FIXME: Do we need to make sure that we only consider conversion
3288       // candidates with reference-compatible results? That might be needed to
3289       // break recursion.
3290       if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3291           (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3292         if (ConvTemplate)
3293           S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3294                                            ActingDC, Initializer,
3295                                            DestType, CandidateSet);
3296         else
3297           S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3298                                    Initializer, DestType, CandidateSet);
3299       }
3300     }
3301   }
3302   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3303     return OR_No_Viable_Function;
3304 
3305   SourceLocation DeclLoc = Initializer->getLocStart();
3306 
3307   // Perform overload resolution. If it fails, return the failed result.
3308   OverloadCandidateSet::iterator Best;
3309   if (OverloadingResult Result
3310         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3311     return Result;
3312 
3313   FunctionDecl *Function = Best->Function;
3314   // This is the overload that will be used for this initialization step if we
3315   // use this initialization. Mark it as referenced.
3316   Function->setReferenced();
3317 
3318   // Compute the returned type of the conversion.
3319   if (isa<CXXConversionDecl>(Function))
3320     T2 = Function->getResultType();
3321   else
3322     T2 = cv1T1;
3323 
3324   // Add the user-defined conversion step.
3325   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3326   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3327                                  T2.getNonLValueExprType(S.Context),
3328                                  HadMultipleCandidates);
3329 
3330   // Determine whether we need to perform derived-to-base or
3331   // cv-qualification adjustments.
3332   ExprValueKind VK = VK_RValue;
3333   if (T2->isLValueReferenceType())
3334     VK = VK_LValue;
3335   else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3336     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3337 
3338   bool NewDerivedToBase = false;
3339   bool NewObjCConversion = false;
3340   bool NewObjCLifetimeConversion = false;
3341   Sema::ReferenceCompareResult NewRefRelationship
3342     = S.CompareReferenceRelationship(DeclLoc, T1,
3343                                      T2.getNonLValueExprType(S.Context),
3344                                      NewDerivedToBase, NewObjCConversion,
3345                                      NewObjCLifetimeConversion);
3346   if (NewRefRelationship == Sema::Ref_Incompatible) {
3347     // If the type we've converted to is not reference-related to the
3348     // type we're looking for, then there is another conversion step
3349     // we need to perform to produce a temporary of the right type
3350     // that we'll be binding to.
3351     ImplicitConversionSequence ICS;
3352     ICS.setStandard();
3353     ICS.Standard = Best->FinalConversion;
3354     T2 = ICS.Standard.getToType(2);
3355     Sequence.AddConversionSequenceStep(ICS, T2);
3356   } else if (NewDerivedToBase)
3357     Sequence.AddDerivedToBaseCastStep(
3358                                 S.Context.getQualifiedType(T1,
3359                                   T2.getNonReferenceType().getQualifiers()),
3360                                       VK);
3361   else if (NewObjCConversion)
3362     Sequence.AddObjCObjectConversionStep(
3363                                 S.Context.getQualifiedType(T1,
3364                                   T2.getNonReferenceType().getQualifiers()));
3365 
3366   if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3367     Sequence.AddQualificationConversionStep(cv1T1, VK);
3368 
3369   Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3370   return OR_Success;
3371 }
3372 
3373 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3374                                            const InitializedEntity &Entity,
3375                                            Expr *CurInitExpr);
3376 
3377 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3378 static void TryReferenceInitialization(Sema &S,
3379                                        const InitializedEntity &Entity,
3380                                        const InitializationKind &Kind,
3381                                        Expr *Initializer,
3382                                        InitializationSequence &Sequence) {
3383   QualType DestType = Entity.getType();
3384   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3385   Qualifiers T1Quals;
3386   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3387   QualType cv2T2 = Initializer->getType();
3388   Qualifiers T2Quals;
3389   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3390 
3391   // If the initializer is the address of an overloaded function, try
3392   // to resolve the overloaded function. If all goes well, T2 is the
3393   // type of the resulting function.
3394   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3395                                                    T1, Sequence))
3396     return;
3397 
3398   // Delegate everything else to a subfunction.
3399   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3400                                  T1Quals, cv2T2, T2, T2Quals, Sequence);
3401 }
3402 
3403 /// Converts the target of reference initialization so that it has the
3404 /// appropriate qualifiers and value kind.
3405 ///
3406 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3407 /// \code
3408 ///   int x;
3409 ///   const int &r = x;
3410 /// \endcode
3411 ///
3412 /// In this case the reference is binding to a bitfield lvalue, which isn't
3413 /// valid. Perform a load to create a lifetime-extended temporary instead.
3414 /// \code
3415 ///   const int &r = someStruct.bitfield;
3416 /// \endcode
3417 static ExprValueKind
3418 convertQualifiersAndValueKindIfNecessary(Sema &S,
3419                                          InitializationSequence &Sequence,
3420                                          Expr *Initializer,
3421                                          QualType cv1T1,
3422                                          Qualifiers T1Quals,
3423                                          Qualifiers T2Quals,
3424                                          bool IsLValueRef) {
3425   bool IsNonAddressableType = Initializer->getBitField() ||
3426                               Initializer->refersToVectorElement();
3427 
3428   if (IsNonAddressableType) {
3429     // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3430     // lvalue reference to a non-volatile const type, or the reference shall be
3431     // an rvalue reference.
3432     //
3433     // If not, we can't make a temporary and bind to that. Give up and allow the
3434     // error to be diagnosed later.
3435     if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3436       assert(Initializer->isGLValue());
3437       return Initializer->getValueKind();
3438     }
3439 
3440     // Force a load so we can materialize a temporary.
3441     Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3442     return VK_RValue;
3443   }
3444 
3445   if (T1Quals != T2Quals) {
3446     Sequence.AddQualificationConversionStep(cv1T1,
3447                                             Initializer->getValueKind());
3448   }
3449 
3450   return Initializer->getValueKind();
3451 }
3452 
3453 
3454 /// \brief Reference initialization without resolving overloaded functions.
3455 static void TryReferenceInitializationCore(Sema &S,
3456                                            const InitializedEntity &Entity,
3457                                            const InitializationKind &Kind,
3458                                            Expr *Initializer,
3459                                            QualType cv1T1, QualType T1,
3460                                            Qualifiers T1Quals,
3461                                            QualType cv2T2, QualType T2,
3462                                            Qualifiers T2Quals,
3463                                            InitializationSequence &Sequence) {
3464   QualType DestType = Entity.getType();
3465   SourceLocation DeclLoc = Initializer->getLocStart();
3466   // Compute some basic properties of the types and the initializer.
3467   bool isLValueRef = DestType->isLValueReferenceType();
3468   bool isRValueRef = !isLValueRef;
3469   bool DerivedToBase = false;
3470   bool ObjCConversion = false;
3471   bool ObjCLifetimeConversion = false;
3472   Expr::Classification InitCategory = Initializer->Classify(S.Context);
3473   Sema::ReferenceCompareResult RefRelationship
3474     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3475                                      ObjCConversion, ObjCLifetimeConversion);
3476 
3477   // C++0x [dcl.init.ref]p5:
3478   //   A reference to type "cv1 T1" is initialized by an expression of type
3479   //   "cv2 T2" as follows:
3480   //
3481   //     - If the reference is an lvalue reference and the initializer
3482   //       expression
3483   // Note the analogous bullet points for rvlaue refs to functions. Because
3484   // there are no function rvalues in C++, rvalue refs to functions are treated
3485   // like lvalue refs.
3486   OverloadingResult ConvOvlResult = OR_Success;
3487   bool T1Function = T1->isFunctionType();
3488   if (isLValueRef || T1Function) {
3489     if (InitCategory.isLValue() &&
3490         (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3491          (Kind.isCStyleOrFunctionalCast() &&
3492           RefRelationship == Sema::Ref_Related))) {
3493       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3494       //     reference-compatible with "cv2 T2," or
3495       //
3496       // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3497       // bit-field when we're determining whether the reference initialization
3498       // can occur. However, we do pay attention to whether it is a bit-field
3499       // to decide whether we're actually binding to a temporary created from
3500       // the bit-field.
3501       if (DerivedToBase)
3502         Sequence.AddDerivedToBaseCastStep(
3503                          S.Context.getQualifiedType(T1, T2Quals),
3504                          VK_LValue);
3505       else if (ObjCConversion)
3506         Sequence.AddObjCObjectConversionStep(
3507                                      S.Context.getQualifiedType(T1, T2Quals));
3508 
3509       ExprValueKind ValueKind =
3510         convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3511                                                  cv1T1, T1Quals, T2Quals,
3512                                                  isLValueRef);
3513       Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3514       return;
3515     }
3516 
3517     //     - has a class type (i.e., T2 is a class type), where T1 is not
3518     //       reference-related to T2, and can be implicitly converted to an
3519     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3520     //       with "cv3 T3" (this conversion is selected by enumerating the
3521     //       applicable conversion functions (13.3.1.6) and choosing the best
3522     //       one through overload resolution (13.3)),
3523     // If we have an rvalue ref to function type here, the rhs must be
3524     // an rvalue.
3525     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3526         (isLValueRef || InitCategory.isRValue())) {
3527       ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
3528                                                        Initializer,
3529                                                    /*AllowRValues=*/isRValueRef,
3530                                                        Sequence);
3531       if (ConvOvlResult == OR_Success)
3532         return;
3533       if (ConvOvlResult != OR_No_Viable_Function) {
3534         Sequence.SetOverloadFailure(
3535                       InitializationSequence::FK_ReferenceInitOverloadFailed,
3536                                     ConvOvlResult);
3537       }
3538     }
3539   }
3540 
3541   //     - Otherwise, the reference shall be an lvalue reference to a
3542   //       non-volatile const type (i.e., cv1 shall be const), or the reference
3543   //       shall be an rvalue reference.
3544   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3545     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3546       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3547     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3548       Sequence.SetOverloadFailure(
3549                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3550                                   ConvOvlResult);
3551     else
3552       Sequence.SetFailed(InitCategory.isLValue()
3553         ? (RefRelationship == Sema::Ref_Related
3554              ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3555              : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3556         : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3557 
3558     return;
3559   }
3560 
3561   //    - If the initializer expression
3562   //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3563   //        "cv1 T1" is reference-compatible with "cv2 T2"
3564   // Note: functions are handled below.
3565   if (!T1Function &&
3566       (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3567        (Kind.isCStyleOrFunctionalCast() &&
3568         RefRelationship == Sema::Ref_Related)) &&
3569       (InitCategory.isXValue() ||
3570        (InitCategory.isPRValue() && T2->isRecordType()) ||
3571        (InitCategory.isPRValue() && T2->isArrayType()))) {
3572     ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3573     if (InitCategory.isPRValue() && T2->isRecordType()) {
3574       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3575       // compiler the freedom to perform a copy here or bind to the
3576       // object, while C++0x requires that we bind directly to the
3577       // object. Hence, we always bind to the object without making an
3578       // extra copy. However, in C++03 requires that we check for the
3579       // presence of a suitable copy constructor:
3580       //
3581       //   The constructor that would be used to make the copy shall
3582       //   be callable whether or not the copy is actually done.
3583       if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3584         Sequence.AddExtraneousCopyToTemporary(cv2T2);
3585       else if (S.getLangOpts().CPlusPlus11)
3586         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3587     }
3588 
3589     if (DerivedToBase)
3590       Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3591                                         ValueKind);
3592     else if (ObjCConversion)
3593       Sequence.AddObjCObjectConversionStep(
3594                                        S.Context.getQualifiedType(T1, T2Quals));
3595 
3596     ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3597                                                          Initializer, cv1T1,
3598                                                          T1Quals, T2Quals,
3599                                                          isLValueRef);
3600 
3601     Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3602     return;
3603   }
3604 
3605   //       - has a class type (i.e., T2 is a class type), where T1 is not
3606   //         reference-related to T2, and can be implicitly converted to an
3607   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3608   //         where "cv1 T1" is reference-compatible with "cv3 T3",
3609   if (T2->isRecordType()) {
3610     if (RefRelationship == Sema::Ref_Incompatible) {
3611       ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3612                                                        Kind, Initializer,
3613                                                        /*AllowRValues=*/true,
3614                                                        Sequence);
3615       if (ConvOvlResult)
3616         Sequence.SetOverloadFailure(
3617                       InitializationSequence::FK_ReferenceInitOverloadFailed,
3618                                     ConvOvlResult);
3619 
3620       return;
3621     }
3622 
3623     if ((RefRelationship == Sema::Ref_Compatible ||
3624          RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3625         isRValueRef && InitCategory.isLValue()) {
3626       Sequence.SetFailed(
3627         InitializationSequence::FK_RValueReferenceBindingToLValue);
3628       return;
3629     }
3630 
3631     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3632     return;
3633   }
3634 
3635   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3636   //        from the initializer expression using the rules for a non-reference
3637   //        copy initialization (8.5). The reference is then bound to the
3638   //        temporary. [...]
3639 
3640   // Determine whether we are allowed to call explicit constructors or
3641   // explicit conversion operators.
3642   bool AllowExplicit = Kind.AllowExplicit();
3643 
3644   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3645 
3646   ImplicitConversionSequence ICS
3647     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3648                               /*SuppressUserConversions*/ false,
3649                               AllowExplicit,
3650                               /*FIXME:InOverloadResolution=*/false,
3651                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3652                               /*AllowObjCWritebackConversion=*/false);
3653 
3654   if (ICS.isBad()) {
3655     // FIXME: Use the conversion function set stored in ICS to turn
3656     // this into an overloading ambiguity diagnostic. However, we need
3657     // to keep that set as an OverloadCandidateSet rather than as some
3658     // other kind of set.
3659     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3660       Sequence.SetOverloadFailure(
3661                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3662                                   ConvOvlResult);
3663     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3664       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3665     else
3666       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3667     return;
3668   } else {
3669     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3670   }
3671 
3672   //        [...] If T1 is reference-related to T2, cv1 must be the
3673   //        same cv-qualification as, or greater cv-qualification
3674   //        than, cv2; otherwise, the program is ill-formed.
3675   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3676   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3677   if (RefRelationship == Sema::Ref_Related &&
3678       (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3679     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3680     return;
3681   }
3682 
3683   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3684   //   reference, the initializer expression shall not be an lvalue.
3685   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3686       InitCategory.isLValue()) {
3687     Sequence.SetFailed(
3688                     InitializationSequence::FK_RValueReferenceBindingToLValue);
3689     return;
3690   }
3691 
3692   Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3693   return;
3694 }
3695 
3696 /// \brief Attempt character array initialization from a string literal
3697 /// (C++ [dcl.init.string], C99 6.7.8).
3698 static void TryStringLiteralInitialization(Sema &S,
3699                                            const InitializedEntity &Entity,
3700                                            const InitializationKind &Kind,
3701                                            Expr *Initializer,
3702                                        InitializationSequence &Sequence) {
3703   Sequence.AddStringInitStep(Entity.getType());
3704 }
3705 
3706 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3707 static void TryValueInitialization(Sema &S,
3708                                    const InitializedEntity &Entity,
3709                                    const InitializationKind &Kind,
3710                                    InitializationSequence &Sequence,
3711                                    InitListExpr *InitList) {
3712   assert((!InitList || InitList->getNumInits() == 0) &&
3713          "Shouldn't use value-init for non-empty init lists");
3714 
3715   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3716   //
3717   //   To value-initialize an object of type T means:
3718   QualType T = Entity.getType();
3719 
3720   //     -- if T is an array type, then each element is value-initialized;
3721   T = S.Context.getBaseElementType(T);
3722 
3723   if (const RecordType *RT = T->getAs<RecordType>()) {
3724     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3725       bool NeedZeroInitialization = true;
3726       if (!S.getLangOpts().CPlusPlus11) {
3727         // C++98:
3728         // -- if T is a class type (clause 9) with a user-declared constructor
3729         //    (12.1), then the default constructor for T is called (and the
3730         //    initialization is ill-formed if T has no accessible default
3731         //    constructor);
3732         if (ClassDecl->hasUserDeclaredConstructor())
3733           NeedZeroInitialization = false;
3734       } else {
3735         // C++11:
3736         // -- if T is a class type (clause 9) with either no default constructor
3737         //    (12.1 [class.ctor]) or a default constructor that is user-provided
3738         //    or deleted, then the object is default-initialized;
3739         CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3740         if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3741           NeedZeroInitialization = false;
3742       }
3743 
3744       // -- if T is a (possibly cv-qualified) non-union class type without a
3745       //    user-provided or deleted default constructor, then the object is
3746       //    zero-initialized and, if T has a non-trivial default constructor,
3747       //    default-initialized;
3748       // The 'non-union' here was removed by DR1502. The 'non-trivial default
3749       // constructor' part was removed by DR1507.
3750       if (NeedZeroInitialization)
3751         Sequence.AddZeroInitializationStep(Entity.getType());
3752 
3753       // C++03:
3754       // -- if T is a non-union class type without a user-declared constructor,
3755       //    then every non-static data member and base class component of T is
3756       //    value-initialized;
3757       // [...] A program that calls for [...] value-initialization of an
3758       // entity of reference type is ill-formed.
3759       //
3760       // C++11 doesn't need this handling, because value-initialization does not
3761       // occur recursively there, and the implicit default constructor is
3762       // defined as deleted in the problematic cases.
3763       if (!S.getLangOpts().CPlusPlus11 &&
3764           ClassDecl->hasUninitializedReferenceMember()) {
3765         Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3766         return;
3767       }
3768 
3769       // If this is list-value-initialization, pass the empty init list on when
3770       // building the constructor call. This affects the semantics of a few
3771       // things (such as whether an explicit default constructor can be called).
3772       Expr *InitListAsExpr = InitList;
3773       Expr **Args = InitList ? &InitListAsExpr : 0;
3774       unsigned NumArgs = InitList ? 1 : 0;
3775       bool InitListSyntax = InitList;
3776 
3777       return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3778                                           Sequence, InitListSyntax);
3779     }
3780   }
3781 
3782   Sequence.AddZeroInitializationStep(Entity.getType());
3783 }
3784 
3785 /// \brief Attempt default initialization (C++ [dcl.init]p6).
3786 static void TryDefaultInitialization(Sema &S,
3787                                      const InitializedEntity &Entity,
3788                                      const InitializationKind &Kind,
3789                                      InitializationSequence &Sequence) {
3790   assert(Kind.getKind() == InitializationKind::IK_Default);
3791 
3792   // C++ [dcl.init]p6:
3793   //   To default-initialize an object of type T means:
3794   //     - if T is an array type, each element is default-initialized;
3795   QualType DestType = S.Context.getBaseElementType(Entity.getType());
3796 
3797   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
3798   //       constructor for T is called (and the initialization is ill-formed if
3799   //       T has no accessible default constructor);
3800   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
3801     TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3802     return;
3803   }
3804 
3805   //     - otherwise, no initialization is performed.
3806 
3807   //   If a program calls for the default initialization of an object of
3808   //   a const-qualified type T, T shall be a class type with a user-provided
3809   //   default constructor.
3810   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
3811     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3812     return;
3813   }
3814 
3815   // If the destination type has a lifetime property, zero-initialize it.
3816   if (DestType.getQualifiers().hasObjCLifetime()) {
3817     Sequence.AddZeroInitializationStep(Entity.getType());
3818     return;
3819   }
3820 }
3821 
3822 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3823 /// which enumerates all conversion functions and performs overload resolution
3824 /// to select the best.
3825 static void TryUserDefinedConversion(Sema &S,
3826                                      const InitializedEntity &Entity,
3827                                      const InitializationKind &Kind,
3828                                      Expr *Initializer,
3829                                      InitializationSequence &Sequence) {
3830   QualType DestType = Entity.getType();
3831   assert(!DestType->isReferenceType() && "References are handled elsewhere");
3832   QualType SourceType = Initializer->getType();
3833   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3834          "Must have a class type to perform a user-defined conversion");
3835 
3836   // Build the candidate set directly in the initialization sequence
3837   // structure, so that it will persist if we fail.
3838   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3839   CandidateSet.clear();
3840 
3841   // Determine whether we are allowed to call explicit constructors or
3842   // explicit conversion operators.
3843   bool AllowExplicit = Kind.AllowExplicit();
3844 
3845   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3846     // The type we're converting to is a class type. Enumerate its constructors
3847     // to see if there is a suitable conversion.
3848     CXXRecordDecl *DestRecordDecl
3849       = cast<CXXRecordDecl>(DestRecordType->getDecl());
3850 
3851     // Try to complete the type we're converting to.
3852     if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3853       DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
3854       // The container holding the constructors can under certain conditions
3855       // be changed while iterating. To be safe we copy the lookup results
3856       // to a new container.
3857       SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
3858       for (SmallVector<NamedDecl*, 8>::iterator
3859              Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
3860            Con != ConEnd; ++Con) {
3861         NamedDecl *D = *Con;
3862         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3863 
3864         // Find the constructor (which may be a template).
3865         CXXConstructorDecl *Constructor = 0;
3866         FunctionTemplateDecl *ConstructorTmpl
3867           = dyn_cast<FunctionTemplateDecl>(D);
3868         if (ConstructorTmpl)
3869           Constructor = cast<CXXConstructorDecl>(
3870                                            ConstructorTmpl->getTemplatedDecl());
3871         else
3872           Constructor = cast<CXXConstructorDecl>(D);
3873 
3874         if (!Constructor->isInvalidDecl() &&
3875             Constructor->isConvertingConstructor(AllowExplicit)) {
3876           if (ConstructorTmpl)
3877             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3878                                            /*ExplicitArgs*/ 0,
3879                                            Initializer, CandidateSet,
3880                                            /*SuppressUserConversions=*/true);
3881           else
3882             S.AddOverloadCandidate(Constructor, FoundDecl,
3883                                    Initializer, CandidateSet,
3884                                    /*SuppressUserConversions=*/true);
3885         }
3886       }
3887     }
3888   }
3889 
3890   SourceLocation DeclLoc = Initializer->getLocStart();
3891 
3892   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3893     // The type we're converting from is a class type, enumerate its conversion
3894     // functions.
3895 
3896     // We can only enumerate the conversion functions for a complete type; if
3897     // the type isn't complete, simply skip this step.
3898     if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3899       CXXRecordDecl *SourceRecordDecl
3900         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
3901 
3902       std::pair<CXXRecordDecl::conversion_iterator,
3903                 CXXRecordDecl::conversion_iterator>
3904         Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3905       for (CXXRecordDecl::conversion_iterator
3906              I = Conversions.first, E = Conversions.second; I != E; ++I) {
3907         NamedDecl *D = *I;
3908         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3909         if (isa<UsingShadowDecl>(D))
3910           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3911 
3912         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3913         CXXConversionDecl *Conv;
3914         if (ConvTemplate)
3915           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3916         else
3917           Conv = cast<CXXConversionDecl>(D);
3918 
3919         if (AllowExplicit || !Conv->isExplicit()) {
3920           if (ConvTemplate)
3921             S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3922                                              ActingDC, Initializer, DestType,
3923                                              CandidateSet);
3924           else
3925             S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3926                                      Initializer, DestType, CandidateSet);
3927         }
3928       }
3929     }
3930   }
3931 
3932   // Perform overload resolution. If it fails, return the failed result.
3933   OverloadCandidateSet::iterator Best;
3934   if (OverloadingResult Result
3935         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3936     Sequence.SetOverloadFailure(
3937                         InitializationSequence::FK_UserConversionOverloadFailed,
3938                                 Result);
3939     return;
3940   }
3941 
3942   FunctionDecl *Function = Best->Function;
3943   Function->setReferenced();
3944   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3945 
3946   if (isa<CXXConstructorDecl>(Function)) {
3947     // Add the user-defined conversion step. Any cv-qualification conversion is
3948     // subsumed by the initialization. Per DR5, the created temporary is of the
3949     // cv-unqualified type of the destination.
3950     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3951                                    DestType.getUnqualifiedType(),
3952                                    HadMultipleCandidates);
3953     return;
3954   }
3955 
3956   // Add the user-defined conversion step that calls the conversion function.
3957   QualType ConvType = Function->getCallResultType();
3958   if (ConvType->getAs<RecordType>()) {
3959     // If we're converting to a class type, there may be an copy of
3960     // the resulting temporary object (possible to create an object of
3961     // a base class type). That copy is not a separate conversion, so
3962     // we just make a note of the actual destination type (possibly a
3963     // base class of the type returned by the conversion function) and
3964     // let the user-defined conversion step handle the conversion.
3965     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3966                                    HadMultipleCandidates);
3967     return;
3968   }
3969 
3970   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3971                                  HadMultipleCandidates);
3972 
3973   // If the conversion following the call to the conversion function
3974   // is interesting, add it as a separate step.
3975   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3976       Best->FinalConversion.Third) {
3977     ImplicitConversionSequence ICS;
3978     ICS.setStandard();
3979     ICS.Standard = Best->FinalConversion;
3980     Sequence.AddConversionSequenceStep(ICS, DestType);
3981   }
3982 }
3983 
3984 /// The non-zero enum values here are indexes into diagnostic alternatives.
3985 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3986 
3987 /// Determines whether this expression is an acceptable ICR source.
3988 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3989                                          bool isAddressOf, bool &isWeakAccess) {
3990   // Skip parens.
3991   e = e->IgnoreParens();
3992 
3993   // Skip address-of nodes.
3994   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3995     if (op->getOpcode() == UO_AddrOf)
3996       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
3997                                 isWeakAccess);
3998 
3999   // Skip certain casts.
4000   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4001     switch (ce->getCastKind()) {
4002     case CK_Dependent:
4003     case CK_BitCast:
4004     case CK_LValueBitCast:
4005     case CK_NoOp:
4006       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4007 
4008     case CK_ArrayToPointerDecay:
4009       return IIK_nonscalar;
4010 
4011     case CK_NullToPointer:
4012       return IIK_okay;
4013 
4014     default:
4015       break;
4016     }
4017 
4018   // If we have a declaration reference, it had better be a local variable.
4019   } else if (isa<DeclRefExpr>(e)) {
4020     // set isWeakAccess to true, to mean that there will be an implicit
4021     // load which requires a cleanup.
4022     if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4023       isWeakAccess = true;
4024 
4025     if (!isAddressOf) return IIK_nonlocal;
4026 
4027     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4028     if (!var) return IIK_nonlocal;
4029 
4030     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4031 
4032   // If we have a conditional operator, check both sides.
4033   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4034     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4035                                                 isWeakAccess))
4036       return iik;
4037 
4038     return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4039 
4040   // These are never scalar.
4041   } else if (isa<ArraySubscriptExpr>(e)) {
4042     return IIK_nonscalar;
4043 
4044   // Otherwise, it needs to be a null pointer constant.
4045   } else {
4046     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4047             ? IIK_okay : IIK_nonlocal);
4048   }
4049 
4050   return IIK_nonlocal;
4051 }
4052 
4053 /// Check whether the given expression is a valid operand for an
4054 /// indirect copy/restore.
4055 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4056   assert(src->isRValue());
4057   bool isWeakAccess = false;
4058   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4059   // If isWeakAccess to true, there will be an implicit
4060   // load which requires a cleanup.
4061   if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4062     S.ExprNeedsCleanups = true;
4063 
4064   if (iik == IIK_okay) return;
4065 
4066   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4067     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
4068     << src->getSourceRange();
4069 }
4070 
4071 /// \brief Determine whether we have compatible array types for the
4072 /// purposes of GNU by-copy array initialization.
4073 static bool hasCompatibleArrayTypes(ASTContext &Context,
4074                                     const ArrayType *Dest,
4075                                     const ArrayType *Source) {
4076   // If the source and destination array types are equivalent, we're
4077   // done.
4078   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4079     return true;
4080 
4081   // Make sure that the element types are the same.
4082   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4083     return false;
4084 
4085   // The only mismatch we allow is when the destination is an
4086   // incomplete array type and the source is a constant array type.
4087   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4088 }
4089 
4090 static bool tryObjCWritebackConversion(Sema &S,
4091                                        InitializationSequence &Sequence,
4092                                        const InitializedEntity &Entity,
4093                                        Expr *Initializer) {
4094   bool ArrayDecay = false;
4095   QualType ArgType = Initializer->getType();
4096   QualType ArgPointee;
4097   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4098     ArrayDecay = true;
4099     ArgPointee = ArgArrayType->getElementType();
4100     ArgType = S.Context.getPointerType(ArgPointee);
4101   }
4102 
4103   // Handle write-back conversion.
4104   QualType ConvertedArgType;
4105   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4106                                    ConvertedArgType))
4107     return false;
4108 
4109   // We should copy unless we're passing to an argument explicitly
4110   // marked 'out'.
4111   bool ShouldCopy = true;
4112   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4113     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4114 
4115   // Do we need an lvalue conversion?
4116   if (ArrayDecay || Initializer->isGLValue()) {
4117     ImplicitConversionSequence ICS;
4118     ICS.setStandard();
4119     ICS.Standard.setAsIdentityConversion();
4120 
4121     QualType ResultType;
4122     if (ArrayDecay) {
4123       ICS.Standard.First = ICK_Array_To_Pointer;
4124       ResultType = S.Context.getPointerType(ArgPointee);
4125     } else {
4126       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4127       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4128     }
4129 
4130     Sequence.AddConversionSequenceStep(ICS, ResultType);
4131   }
4132 
4133   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4134   return true;
4135 }
4136 
4137 static bool TryOCLSamplerInitialization(Sema &S,
4138                                         InitializationSequence &Sequence,
4139                                         QualType DestType,
4140                                         Expr *Initializer) {
4141   if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4142     !Initializer->isIntegerConstantExpr(S.getASTContext()))
4143     return false;
4144 
4145   Sequence.AddOCLSamplerInitStep(DestType);
4146   return true;
4147 }
4148 
4149 //
4150 // OpenCL 1.2 spec, s6.12.10
4151 //
4152 // The event argument can also be used to associate the
4153 // async_work_group_copy with a previous async copy allowing
4154 // an event to be shared by multiple async copies; otherwise
4155 // event should be zero.
4156 //
4157 static bool TryOCLZeroEventInitialization(Sema &S,
4158                                           InitializationSequence &Sequence,
4159                                           QualType DestType,
4160                                           Expr *Initializer) {
4161   if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4162       !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4163       (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4164     return false;
4165 
4166   Sequence.AddOCLZeroEventStep(DestType);
4167   return true;
4168 }
4169 
4170 InitializationSequence::InitializationSequence(Sema &S,
4171                                                const InitializedEntity &Entity,
4172                                                const InitializationKind &Kind,
4173                                                Expr **Args,
4174                                                unsigned NumArgs)
4175     : FailedCandidateSet(Kind.getLocation()) {
4176   ASTContext &Context = S.Context;
4177 
4178   // Eliminate non-overload placeholder types in the arguments.  We
4179   // need to do this before checking whether types are dependent
4180   // because lowering a pseudo-object expression might well give us
4181   // something of dependent type.
4182   for (unsigned I = 0; I != NumArgs; ++I)
4183     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4184       // FIXME: should we be doing this here?
4185       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4186       if (result.isInvalid()) {
4187         SetFailed(FK_PlaceholderType);
4188         return;
4189       }
4190       Args[I] = result.take();
4191     }
4192 
4193   // C++0x [dcl.init]p16:
4194   //   The semantics of initializers are as follows. The destination type is
4195   //   the type of the object or reference being initialized and the source
4196   //   type is the type of the initializer expression. The source type is not
4197   //   defined when the initializer is a braced-init-list or when it is a
4198   //   parenthesized list of expressions.
4199   QualType DestType = Entity.getType();
4200 
4201   if (DestType->isDependentType() ||
4202       Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
4203     SequenceKind = DependentSequence;
4204     return;
4205   }
4206 
4207   // Almost everything is a normal sequence.
4208   setSequenceKind(NormalSequence);
4209 
4210   QualType SourceType;
4211   Expr *Initializer = 0;
4212   if (NumArgs == 1) {
4213     Initializer = Args[0];
4214     if (!isa<InitListExpr>(Initializer))
4215       SourceType = Initializer->getType();
4216   }
4217 
4218   //     - If the initializer is a (non-parenthesized) braced-init-list, the
4219   //       object is list-initialized (8.5.4).
4220   if (Kind.getKind() != InitializationKind::IK_Direct) {
4221     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4222       TryListInitialization(S, Entity, Kind, InitList, *this);
4223       return;
4224     }
4225   }
4226 
4227   //     - If the destination type is a reference type, see 8.5.3.
4228   if (DestType->isReferenceType()) {
4229     // C++0x [dcl.init.ref]p1:
4230     //   A variable declared to be a T& or T&&, that is, "reference to type T"
4231     //   (8.3.2), shall be initialized by an object, or function, of type T or
4232     //   by an object that can be converted into a T.
4233     // (Therefore, multiple arguments are not permitted.)
4234     if (NumArgs != 1)
4235       SetFailed(FK_TooManyInitsForReference);
4236     else
4237       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4238     return;
4239   }
4240 
4241   //     - If the initializer is (), the object is value-initialized.
4242   if (Kind.getKind() == InitializationKind::IK_Value ||
4243       (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
4244     TryValueInitialization(S, Entity, Kind, *this);
4245     return;
4246   }
4247 
4248   // Handle default initialization.
4249   if (Kind.getKind() == InitializationKind::IK_Default) {
4250     TryDefaultInitialization(S, Entity, Kind, *this);
4251     return;
4252   }
4253 
4254   //     - If the destination type is an array of characters, an array of
4255   //       char16_t, an array of char32_t, or an array of wchar_t, and the
4256   //       initializer is a string literal, see 8.5.2.
4257   //     - Otherwise, if the destination type is an array, the program is
4258   //       ill-formed.
4259   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4260     if (Initializer && isa<VariableArrayType>(DestAT)) {
4261       SetFailed(FK_VariableLengthArrayHasInitializer);
4262       return;
4263     }
4264 
4265     if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
4266       TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4267       return;
4268     }
4269 
4270     // Note: as an GNU C extension, we allow initialization of an
4271     // array from a compound literal that creates an array of the same
4272     // type, so long as the initializer has no side effects.
4273     if (!S.getLangOpts().CPlusPlus && Initializer &&
4274         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4275         Initializer->getType()->isArrayType()) {
4276       const ArrayType *SourceAT
4277         = Context.getAsArrayType(Initializer->getType());
4278       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4279         SetFailed(FK_ArrayTypeMismatch);
4280       else if (Initializer->HasSideEffects(S.Context))
4281         SetFailed(FK_NonConstantArrayInit);
4282       else {
4283         AddArrayInitStep(DestType);
4284       }
4285     }
4286     // Note: as a GNU C++ extension, we allow list-initialization of a
4287     // class member of array type from a parenthesized initializer list.
4288     else if (S.getLangOpts().CPlusPlus &&
4289              Entity.getKind() == InitializedEntity::EK_Member &&
4290              Initializer && isa<InitListExpr>(Initializer)) {
4291       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4292                             *this);
4293       AddParenthesizedArrayInitStep(DestType);
4294     } else if (DestAT->getElementType()->isAnyCharacterType())
4295       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4296     else
4297       SetFailed(FK_ArrayNeedsInitList);
4298 
4299     return;
4300   }
4301 
4302   // Determine whether we should consider writeback conversions for
4303   // Objective-C ARC.
4304   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4305     Entity.getKind() == InitializedEntity::EK_Parameter;
4306 
4307   // We're at the end of the line for C: it's either a write-back conversion
4308   // or it's a C assignment. There's no need to check anything else.
4309   if (!S.getLangOpts().CPlusPlus) {
4310     // If allowed, check whether this is an Objective-C writeback conversion.
4311     if (allowObjCWritebackConversion &&
4312         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4313       return;
4314     }
4315 
4316     if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4317       return;
4318 
4319     if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4320       return;
4321 
4322     // Handle initialization in C
4323     AddCAssignmentStep(DestType);
4324     MaybeProduceObjCObject(S, *this, Entity);
4325     return;
4326   }
4327 
4328   assert(S.getLangOpts().CPlusPlus);
4329 
4330   //     - If the destination type is a (possibly cv-qualified) class type:
4331   if (DestType->isRecordType()) {
4332     //     - If the initialization is direct-initialization, or if it is
4333     //       copy-initialization where the cv-unqualified version of the
4334     //       source type is the same class as, or a derived class of, the
4335     //       class of the destination, constructors are considered. [...]
4336     if (Kind.getKind() == InitializationKind::IK_Direct ||
4337         (Kind.getKind() == InitializationKind::IK_Copy &&
4338          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4339           S.IsDerivedFrom(SourceType, DestType))))
4340       TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
4341                                    Entity.getType(), *this);
4342     //     - Otherwise (i.e., for the remaining copy-initialization cases),
4343     //       user-defined conversion sequences that can convert from the source
4344     //       type to the destination type or (when a conversion function is
4345     //       used) to a derived class thereof are enumerated as described in
4346     //       13.3.1.4, and the best one is chosen through overload resolution
4347     //       (13.3).
4348     else
4349       TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4350     return;
4351   }
4352 
4353   if (NumArgs > 1) {
4354     SetFailed(FK_TooManyInitsForScalar);
4355     return;
4356   }
4357   assert(NumArgs == 1 && "Zero-argument case handled above");
4358 
4359   //    - Otherwise, if the source type is a (possibly cv-qualified) class
4360   //      type, conversion functions are considered.
4361   if (!SourceType.isNull() && SourceType->isRecordType()) {
4362     TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4363     MaybeProduceObjCObject(S, *this, Entity);
4364     return;
4365   }
4366 
4367   //    - Otherwise, the initial value of the object being initialized is the
4368   //      (possibly converted) value of the initializer expression. Standard
4369   //      conversions (Clause 4) will be used, if necessary, to convert the
4370   //      initializer expression to the cv-unqualified version of the
4371   //      destination type; no user-defined conversions are considered.
4372 
4373   ImplicitConversionSequence ICS
4374     = S.TryImplicitConversion(Initializer, Entity.getType(),
4375                               /*SuppressUserConversions*/true,
4376                               /*AllowExplicitConversions*/ false,
4377                               /*InOverloadResolution*/ false,
4378                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4379                               allowObjCWritebackConversion);
4380 
4381   if (ICS.isStandard() &&
4382       ICS.Standard.Second == ICK_Writeback_Conversion) {
4383     // Objective-C ARC writeback conversion.
4384 
4385     // We should copy unless we're passing to an argument explicitly
4386     // marked 'out'.
4387     bool ShouldCopy = true;
4388     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4389       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4390 
4391     // If there was an lvalue adjustment, add it as a separate conversion.
4392     if (ICS.Standard.First == ICK_Array_To_Pointer ||
4393         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4394       ImplicitConversionSequence LvalueICS;
4395       LvalueICS.setStandard();
4396       LvalueICS.Standard.setAsIdentityConversion();
4397       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4398       LvalueICS.Standard.First = ICS.Standard.First;
4399       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4400     }
4401 
4402     AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4403   } else if (ICS.isBad()) {
4404     DeclAccessPair dap;
4405     if (Initializer->getType() == Context.OverloadTy &&
4406           !S.ResolveAddressOfOverloadedFunction(Initializer
4407                       , DestType, false, dap))
4408       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4409     else
4410       SetFailed(InitializationSequence::FK_ConversionFailed);
4411   } else {
4412     AddConversionSequenceStep(ICS, Entity.getType());
4413 
4414     MaybeProduceObjCObject(S, *this, Entity);
4415   }
4416 }
4417 
4418 InitializationSequence::~InitializationSequence() {
4419   for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4420                                           StepEnd = Steps.end();
4421        Step != StepEnd; ++Step)
4422     Step->Destroy();
4423 }
4424 
4425 //===----------------------------------------------------------------------===//
4426 // Perform initialization
4427 //===----------------------------------------------------------------------===//
4428 static Sema::AssignmentAction
4429 getAssignmentAction(const InitializedEntity &Entity) {
4430   switch(Entity.getKind()) {
4431   case InitializedEntity::EK_Variable:
4432   case InitializedEntity::EK_New:
4433   case InitializedEntity::EK_Exception:
4434   case InitializedEntity::EK_Base:
4435   case InitializedEntity::EK_Delegating:
4436     return Sema::AA_Initializing;
4437 
4438   case InitializedEntity::EK_Parameter:
4439     if (Entity.getDecl() &&
4440         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4441       return Sema::AA_Sending;
4442 
4443     return Sema::AA_Passing;
4444 
4445   case InitializedEntity::EK_Result:
4446     return Sema::AA_Returning;
4447 
4448   case InitializedEntity::EK_Temporary:
4449     // FIXME: Can we tell apart casting vs. converting?
4450     return Sema::AA_Casting;
4451 
4452   case InitializedEntity::EK_Member:
4453   case InitializedEntity::EK_ArrayElement:
4454   case InitializedEntity::EK_VectorElement:
4455   case InitializedEntity::EK_ComplexElement:
4456   case InitializedEntity::EK_BlockElement:
4457   case InitializedEntity::EK_LambdaCapture:
4458     return Sema::AA_Initializing;
4459   }
4460 
4461   llvm_unreachable("Invalid EntityKind!");
4462 }
4463 
4464 /// \brief Whether we should bind a created object as a temporary when
4465 /// initializing the given entity.
4466 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4467   switch (Entity.getKind()) {
4468   case InitializedEntity::EK_ArrayElement:
4469   case InitializedEntity::EK_Member:
4470   case InitializedEntity::EK_Result:
4471   case InitializedEntity::EK_New:
4472   case InitializedEntity::EK_Variable:
4473   case InitializedEntity::EK_Base:
4474   case InitializedEntity::EK_Delegating:
4475   case InitializedEntity::EK_VectorElement:
4476   case InitializedEntity::EK_ComplexElement:
4477   case InitializedEntity::EK_Exception:
4478   case InitializedEntity::EK_BlockElement:
4479   case InitializedEntity::EK_LambdaCapture:
4480     return false;
4481 
4482   case InitializedEntity::EK_Parameter:
4483   case InitializedEntity::EK_Temporary:
4484     return true;
4485   }
4486 
4487   llvm_unreachable("missed an InitializedEntity kind?");
4488 }
4489 
4490 /// \brief Whether the given entity, when initialized with an object
4491 /// created for that initialization, requires destruction.
4492 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4493   switch (Entity.getKind()) {
4494     case InitializedEntity::EK_Result:
4495     case InitializedEntity::EK_New:
4496     case InitializedEntity::EK_Base:
4497     case InitializedEntity::EK_Delegating:
4498     case InitializedEntity::EK_VectorElement:
4499     case InitializedEntity::EK_ComplexElement:
4500     case InitializedEntity::EK_BlockElement:
4501     case InitializedEntity::EK_LambdaCapture:
4502       return false;
4503 
4504     case InitializedEntity::EK_Member:
4505     case InitializedEntity::EK_Variable:
4506     case InitializedEntity::EK_Parameter:
4507     case InitializedEntity::EK_Temporary:
4508     case InitializedEntity::EK_ArrayElement:
4509     case InitializedEntity::EK_Exception:
4510       return true;
4511   }
4512 
4513   llvm_unreachable("missed an InitializedEntity kind?");
4514 }
4515 
4516 /// \brief Look for copy and move constructors and constructor templates, for
4517 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4518 static void LookupCopyAndMoveConstructors(Sema &S,
4519                                           OverloadCandidateSet &CandidateSet,
4520                                           CXXRecordDecl *Class,
4521                                           Expr *CurInitExpr) {
4522   DeclContext::lookup_result R = S.LookupConstructors(Class);
4523   // The container holding the constructors can under certain conditions
4524   // be changed while iterating (e.g. because of deserialization).
4525   // To be safe we copy the lookup results to a new container.
4526   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4527   for (SmallVector<NamedDecl*, 16>::iterator
4528          CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4529     NamedDecl *D = *CI;
4530     CXXConstructorDecl *Constructor = 0;
4531 
4532     if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4533       // Handle copy/moveconstructors, only.
4534       if (!Constructor || Constructor->isInvalidDecl() ||
4535           !Constructor->isCopyOrMoveConstructor() ||
4536           !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4537         continue;
4538 
4539       DeclAccessPair FoundDecl
4540         = DeclAccessPair::make(Constructor, Constructor->getAccess());
4541       S.AddOverloadCandidate(Constructor, FoundDecl,
4542                              CurInitExpr, CandidateSet);
4543       continue;
4544     }
4545 
4546     // Handle constructor templates.
4547     FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4548     if (ConstructorTmpl->isInvalidDecl())
4549       continue;
4550 
4551     Constructor = cast<CXXConstructorDecl>(
4552                                          ConstructorTmpl->getTemplatedDecl());
4553     if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4554       continue;
4555 
4556     // FIXME: Do we need to limit this to copy-constructor-like
4557     // candidates?
4558     DeclAccessPair FoundDecl
4559       = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4560     S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4561                                    CurInitExpr, CandidateSet, true);
4562   }
4563 }
4564 
4565 /// \brief Get the location at which initialization diagnostics should appear.
4566 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4567                                            Expr *Initializer) {
4568   switch (Entity.getKind()) {
4569   case InitializedEntity::EK_Result:
4570     return Entity.getReturnLoc();
4571 
4572   case InitializedEntity::EK_Exception:
4573     return Entity.getThrowLoc();
4574 
4575   case InitializedEntity::EK_Variable:
4576     return Entity.getDecl()->getLocation();
4577 
4578   case InitializedEntity::EK_LambdaCapture:
4579     return Entity.getCaptureLoc();
4580 
4581   case InitializedEntity::EK_ArrayElement:
4582   case InitializedEntity::EK_Member:
4583   case InitializedEntity::EK_Parameter:
4584   case InitializedEntity::EK_Temporary:
4585   case InitializedEntity::EK_New:
4586   case InitializedEntity::EK_Base:
4587   case InitializedEntity::EK_Delegating:
4588   case InitializedEntity::EK_VectorElement:
4589   case InitializedEntity::EK_ComplexElement:
4590   case InitializedEntity::EK_BlockElement:
4591     return Initializer->getLocStart();
4592   }
4593   llvm_unreachable("missed an InitializedEntity kind?");
4594 }
4595 
4596 /// \brief Make a (potentially elidable) temporary copy of the object
4597 /// provided by the given initializer by calling the appropriate copy
4598 /// constructor.
4599 ///
4600 /// \param S The Sema object used for type-checking.
4601 ///
4602 /// \param T The type of the temporary object, which must either be
4603 /// the type of the initializer expression or a superclass thereof.
4604 ///
4605 /// \param Entity The entity being initialized.
4606 ///
4607 /// \param CurInit The initializer expression.
4608 ///
4609 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4610 /// is permitted in C++03 (but not C++0x) when binding a reference to
4611 /// an rvalue.
4612 ///
4613 /// \returns An expression that copies the initializer expression into
4614 /// a temporary object, or an error expression if a copy could not be
4615 /// created.
4616 static ExprResult CopyObject(Sema &S,
4617                              QualType T,
4618                              const InitializedEntity &Entity,
4619                              ExprResult CurInit,
4620                              bool IsExtraneousCopy) {
4621   // Determine which class type we're copying to.
4622   Expr *CurInitExpr = (Expr *)CurInit.get();
4623   CXXRecordDecl *Class = 0;
4624   if (const RecordType *Record = T->getAs<RecordType>())
4625     Class = cast<CXXRecordDecl>(Record->getDecl());
4626   if (!Class)
4627     return CurInit;
4628 
4629   // C++0x [class.copy]p32:
4630   //   When certain criteria are met, an implementation is allowed to
4631   //   omit the copy/move construction of a class object, even if the
4632   //   copy/move constructor and/or destructor for the object have
4633   //   side effects. [...]
4634   //     - when a temporary class object that has not been bound to a
4635   //       reference (12.2) would be copied/moved to a class object
4636   //       with the same cv-unqualified type, the copy/move operation
4637   //       can be omitted by constructing the temporary object
4638   //       directly into the target of the omitted copy/move
4639   //
4640   // Note that the other three bullets are handled elsewhere. Copy
4641   // elision for return statements and throw expressions are handled as part
4642   // of constructor initialization, while copy elision for exception handlers
4643   // is handled by the run-time.
4644   bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4645   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4646 
4647   // Make sure that the type we are copying is complete.
4648   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4649     return CurInit;
4650 
4651   // Perform overload resolution using the class's copy/move constructors.
4652   // Only consider constructors and constructor templates. Per
4653   // C++0x [dcl.init]p16, second bullet to class types, this initialization
4654   // is direct-initialization.
4655   OverloadCandidateSet CandidateSet(Loc);
4656   LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4657 
4658   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4659 
4660   OverloadCandidateSet::iterator Best;
4661   switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4662   case OR_Success:
4663     break;
4664 
4665   case OR_No_Viable_Function:
4666     S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4667            ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4668            : diag::err_temp_copy_no_viable)
4669       << (int)Entity.getKind() << CurInitExpr->getType()
4670       << CurInitExpr->getSourceRange();
4671     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4672     if (!IsExtraneousCopy || S.isSFINAEContext())
4673       return ExprError();
4674     return CurInit;
4675 
4676   case OR_Ambiguous:
4677     S.Diag(Loc, diag::err_temp_copy_ambiguous)
4678       << (int)Entity.getKind() << CurInitExpr->getType()
4679       << CurInitExpr->getSourceRange();
4680     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4681     return ExprError();
4682 
4683   case OR_Deleted:
4684     S.Diag(Loc, diag::err_temp_copy_deleted)
4685       << (int)Entity.getKind() << CurInitExpr->getType()
4686       << CurInitExpr->getSourceRange();
4687     S.NoteDeletedFunction(Best->Function);
4688     return ExprError();
4689   }
4690 
4691   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4692   SmallVector<Expr*, 8> ConstructorArgs;
4693   CurInit.release(); // Ownership transferred into MultiExprArg, below.
4694 
4695   S.CheckConstructorAccess(Loc, Constructor, Entity,
4696                            Best->FoundDecl.getAccess(), IsExtraneousCopy);
4697 
4698   if (IsExtraneousCopy) {
4699     // If this is a totally extraneous copy for C++03 reference
4700     // binding purposes, just return the original initialization
4701     // expression. We don't generate an (elided) copy operation here
4702     // because doing so would require us to pass down a flag to avoid
4703     // infinite recursion, where each step adds another extraneous,
4704     // elidable copy.
4705 
4706     // Instantiate the default arguments of any extra parameters in
4707     // the selected copy constructor, as if we were going to create a
4708     // proper call to the copy constructor.
4709     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4710       ParmVarDecl *Parm = Constructor->getParamDecl(I);
4711       if (S.RequireCompleteType(Loc, Parm->getType(),
4712                                 diag::err_call_incomplete_argument))
4713         break;
4714 
4715       // Build the default argument expression; we don't actually care
4716       // if this succeeds or not, because this routine will complain
4717       // if there was a problem.
4718       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4719     }
4720 
4721     return S.Owned(CurInitExpr);
4722   }
4723 
4724   // Determine the arguments required to actually perform the
4725   // constructor call (we might have derived-to-base conversions, or
4726   // the copy constructor may have default arguments).
4727   if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
4728                                 Loc, ConstructorArgs))
4729     return ExprError();
4730 
4731   // Actually perform the constructor call.
4732   CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4733                                     ConstructorArgs,
4734                                     HadMultipleCandidates,
4735                                     /*ListInit*/ false,
4736                                     /*ZeroInit*/ false,
4737                                     CXXConstructExpr::CK_Complete,
4738                                     SourceRange());
4739 
4740   // If we're supposed to bind temporaries, do so.
4741   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4742     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4743   return CurInit;
4744 }
4745 
4746 /// \brief Check whether elidable copy construction for binding a reference to
4747 /// a temporary would have succeeded if we were building in C++98 mode, for
4748 /// -Wc++98-compat.
4749 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4750                                            const InitializedEntity &Entity,
4751                                            Expr *CurInitExpr) {
4752   assert(S.getLangOpts().CPlusPlus11);
4753 
4754   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4755   if (!Record)
4756     return;
4757 
4758   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4759   if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4760         == DiagnosticsEngine::Ignored)
4761     return;
4762 
4763   // Find constructors which would have been considered.
4764   OverloadCandidateSet CandidateSet(Loc);
4765   LookupCopyAndMoveConstructors(
4766       S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4767 
4768   // Perform overload resolution.
4769   OverloadCandidateSet::iterator Best;
4770   OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4771 
4772   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4773     << OR << (int)Entity.getKind() << CurInitExpr->getType()
4774     << CurInitExpr->getSourceRange();
4775 
4776   switch (OR) {
4777   case OR_Success:
4778     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4779                              Entity, Best->FoundDecl.getAccess(), Diag);
4780     // FIXME: Check default arguments as far as that's possible.
4781     break;
4782 
4783   case OR_No_Viable_Function:
4784     S.Diag(Loc, Diag);
4785     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4786     break;
4787 
4788   case OR_Ambiguous:
4789     S.Diag(Loc, Diag);
4790     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4791     break;
4792 
4793   case OR_Deleted:
4794     S.Diag(Loc, Diag);
4795     S.NoteDeletedFunction(Best->Function);
4796     break;
4797   }
4798 }
4799 
4800 void InitializationSequence::PrintInitLocationNote(Sema &S,
4801                                               const InitializedEntity &Entity) {
4802   if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4803     if (Entity.getDecl()->getLocation().isInvalid())
4804       return;
4805 
4806     if (Entity.getDecl()->getDeclName())
4807       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4808         << Entity.getDecl()->getDeclName();
4809     else
4810       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4811   }
4812 }
4813 
4814 static bool isReferenceBinding(const InitializationSequence::Step &s) {
4815   return s.Kind == InitializationSequence::SK_BindReference ||
4816          s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4817 }
4818 
4819 static ExprResult
4820 PerformConstructorInitialization(Sema &S,
4821                                  const InitializedEntity &Entity,
4822                                  const InitializationKind &Kind,
4823                                  MultiExprArg Args,
4824                                  const InitializationSequence::Step& Step,
4825                                  bool &ConstructorInitRequiresZeroInit,
4826                                  bool IsListInitialization) {
4827   unsigned NumArgs = Args.size();
4828   CXXConstructorDecl *Constructor
4829     = cast<CXXConstructorDecl>(Step.Function.Function);
4830   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4831 
4832   // Build a call to the selected constructor.
4833   SmallVector<Expr*, 8> ConstructorArgs;
4834   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4835                          ? Kind.getEqualLoc()
4836                          : Kind.getLocation();
4837 
4838   if (Kind.getKind() == InitializationKind::IK_Default) {
4839     // Force even a trivial, implicit default constructor to be
4840     // semantically checked. We do this explicitly because we don't build
4841     // the definition for completely trivial constructors.
4842     assert(Constructor->getParent() && "No parent class for constructor.");
4843     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4844         Constructor->isTrivial() && !Constructor->isUsed(false))
4845       S.DefineImplicitDefaultConstructor(Loc, Constructor);
4846   }
4847 
4848   ExprResult CurInit = S.Owned((Expr *)0);
4849 
4850   // C++ [over.match.copy]p1:
4851   //   - When initializing a temporary to be bound to the first parameter
4852   //     of a constructor that takes a reference to possibly cv-qualified
4853   //     T as its first argument, called with a single argument in the
4854   //     context of direct-initialization, explicit conversion functions
4855   //     are also considered.
4856   bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4857                            Args.size() == 1 &&
4858                            Constructor->isCopyOrMoveConstructor();
4859 
4860   // Determine the arguments required to actually perform the constructor
4861   // call.
4862   if (S.CompleteConstructorCall(Constructor, Args,
4863                                 Loc, ConstructorArgs,
4864                                 AllowExplicitConv,
4865                                 IsListInitialization))
4866     return ExprError();
4867 
4868 
4869   if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4870       (Kind.getKind() == InitializationKind::IK_DirectList ||
4871        (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4872         (Kind.getKind() == InitializationKind::IK_Direct ||
4873          Kind.getKind() == InitializationKind::IK_Value)))) {
4874     // An explicitly-constructed temporary, e.g., X(1, 2).
4875     S.MarkFunctionReferenced(Loc, Constructor);
4876     S.DiagnoseUseOfDecl(Constructor, Loc);
4877 
4878     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4879     if (!TSInfo)
4880       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4881     SourceRange ParenRange;
4882     if (Kind.getKind() != InitializationKind::IK_DirectList)
4883       ParenRange = Kind.getParenRange();
4884 
4885     CurInit = S.Owned(
4886       new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
4887                                              TSInfo, ConstructorArgs,
4888                                              ParenRange, IsListInitialization,
4889                                              HadMultipleCandidates,
4890                                              ConstructorInitRequiresZeroInit));
4891   } else {
4892     CXXConstructExpr::ConstructionKind ConstructKind =
4893       CXXConstructExpr::CK_Complete;
4894 
4895     if (Entity.getKind() == InitializedEntity::EK_Base) {
4896       ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4897         CXXConstructExpr::CK_VirtualBase :
4898         CXXConstructExpr::CK_NonVirtualBase;
4899     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4900       ConstructKind = CXXConstructExpr::CK_Delegating;
4901     }
4902 
4903     // Only get the parenthesis range if it is a direct construction.
4904     SourceRange parenRange =
4905         Kind.getKind() == InitializationKind::IK_Direct ?
4906         Kind.getParenRange() : SourceRange();
4907 
4908     // If the entity allows NRVO, mark the construction as elidable
4909     // unconditionally.
4910     if (Entity.allowsNRVO())
4911       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4912                                         Constructor, /*Elidable=*/true,
4913                                         ConstructorArgs,
4914                                         HadMultipleCandidates,
4915                                         IsListInitialization,
4916                                         ConstructorInitRequiresZeroInit,
4917                                         ConstructKind,
4918                                         parenRange);
4919     else
4920       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4921                                         Constructor,
4922                                         ConstructorArgs,
4923                                         HadMultipleCandidates,
4924                                         IsListInitialization,
4925                                         ConstructorInitRequiresZeroInit,
4926                                         ConstructKind,
4927                                         parenRange);
4928   }
4929   if (CurInit.isInvalid())
4930     return ExprError();
4931 
4932   // Only check access if all of that succeeded.
4933   S.CheckConstructorAccess(Loc, Constructor, Entity,
4934                            Step.Function.FoundDecl.getAccess());
4935   S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4936 
4937   if (shouldBindAsTemporary(Entity))
4938     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4939 
4940   return CurInit;
4941 }
4942 
4943 /// Determine whether the specified InitializedEntity definitely has a lifetime
4944 /// longer than the current full-expression. Conservatively returns false if
4945 /// it's unclear.
4946 static bool
4947 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4948   const InitializedEntity *Top = &Entity;
4949   while (Top->getParent())
4950     Top = Top->getParent();
4951 
4952   switch (Top->getKind()) {
4953   case InitializedEntity::EK_Variable:
4954   case InitializedEntity::EK_Result:
4955   case InitializedEntity::EK_Exception:
4956   case InitializedEntity::EK_Member:
4957   case InitializedEntity::EK_New:
4958   case InitializedEntity::EK_Base:
4959   case InitializedEntity::EK_Delegating:
4960     return true;
4961 
4962   case InitializedEntity::EK_ArrayElement:
4963   case InitializedEntity::EK_VectorElement:
4964   case InitializedEntity::EK_BlockElement:
4965   case InitializedEntity::EK_ComplexElement:
4966     // Could not determine what the full initialization is. Assume it might not
4967     // outlive the full-expression.
4968     return false;
4969 
4970   case InitializedEntity::EK_Parameter:
4971   case InitializedEntity::EK_Temporary:
4972   case InitializedEntity::EK_LambdaCapture:
4973     // The entity being initialized might not outlive the full-expression.
4974     return false;
4975   }
4976 
4977   llvm_unreachable("unknown entity kind");
4978 }
4979 
4980 ExprResult
4981 InitializationSequence::Perform(Sema &S,
4982                                 const InitializedEntity &Entity,
4983                                 const InitializationKind &Kind,
4984                                 MultiExprArg Args,
4985                                 QualType *ResultType) {
4986   if (Failed()) {
4987     unsigned NumArgs = Args.size();
4988     Diagnose(S, Entity, Kind, Args.data(), NumArgs);
4989     return ExprError();
4990   }
4991 
4992   if (getKind() == DependentSequence) {
4993     // If the declaration is a non-dependent, incomplete array type
4994     // that has an initializer, then its type will be completed once
4995     // the initializer is instantiated.
4996     if (ResultType && !Entity.getType()->isDependentType() &&
4997         Args.size() == 1) {
4998       QualType DeclType = Entity.getType();
4999       if (const IncompleteArrayType *ArrayT
5000                            = S.Context.getAsIncompleteArrayType(DeclType)) {
5001         // FIXME: We don't currently have the ability to accurately
5002         // compute the length of an initializer list without
5003         // performing full type-checking of the initializer list
5004         // (since we have to determine where braces are implicitly
5005         // introduced and such).  So, we fall back to making the array
5006         // type a dependently-sized array type with no specified
5007         // bound.
5008         if (isa<InitListExpr>((Expr *)Args[0])) {
5009           SourceRange Brackets;
5010 
5011           // Scavange the location of the brackets from the entity, if we can.
5012           if (DeclaratorDecl *DD = Entity.getDecl()) {
5013             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5014               TypeLoc TL = TInfo->getTypeLoc();
5015               if (IncompleteArrayTypeLoc ArrayLoc =
5016                       TL.getAs<IncompleteArrayTypeLoc>())
5017                 Brackets = ArrayLoc.getBracketsRange();
5018             }
5019           }
5020 
5021           *ResultType
5022             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5023                                                    /*NumElts=*/0,
5024                                                    ArrayT->getSizeModifier(),
5025                                        ArrayT->getIndexTypeCVRQualifiers(),
5026                                                    Brackets);
5027         }
5028 
5029       }
5030     }
5031     if (Kind.getKind() == InitializationKind::IK_Direct &&
5032         !Kind.isExplicitCast()) {
5033       // Rebuild the ParenListExpr.
5034       SourceRange ParenRange = Kind.getParenRange();
5035       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5036                                   Args);
5037     }
5038     assert(Kind.getKind() == InitializationKind::IK_Copy ||
5039            Kind.isExplicitCast() ||
5040            Kind.getKind() == InitializationKind::IK_DirectList);
5041     return ExprResult(Args[0]);
5042   }
5043 
5044   // No steps means no initialization.
5045   if (Steps.empty())
5046     return S.Owned((Expr *)0);
5047 
5048   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5049       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5050       Entity.getKind() != InitializedEntity::EK_Parameter) {
5051     // Produce a C++98 compatibility warning if we are initializing a reference
5052     // from an initializer list. For parameters, we produce a better warning
5053     // elsewhere.
5054     Expr *Init = Args[0];
5055     S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5056       << Init->getSourceRange();
5057   }
5058 
5059   // Diagnose cases where we initialize a pointer to an array temporary, and the
5060   // pointer obviously outlives the temporary.
5061   if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5062       Entity.getType()->isPointerType() &&
5063       InitializedEntityOutlivesFullExpression(Entity)) {
5064     Expr *Init = Args[0];
5065     Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5066     if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5067       S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5068         << Init->getSourceRange();
5069   }
5070 
5071   QualType DestType = Entity.getType().getNonReferenceType();
5072   // FIXME: Ugly hack around the fact that Entity.getType() is not
5073   // the same as Entity.getDecl()->getType() in cases involving type merging,
5074   //  and we want latter when it makes sense.
5075   if (ResultType)
5076     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5077                                      Entity.getType();
5078 
5079   ExprResult CurInit = S.Owned((Expr *)0);
5080 
5081   // For initialization steps that start with a single initializer,
5082   // grab the only argument out the Args and place it into the "current"
5083   // initializer.
5084   switch (Steps.front().Kind) {
5085   case SK_ResolveAddressOfOverloadedFunction:
5086   case SK_CastDerivedToBaseRValue:
5087   case SK_CastDerivedToBaseXValue:
5088   case SK_CastDerivedToBaseLValue:
5089   case SK_BindReference:
5090   case SK_BindReferenceToTemporary:
5091   case SK_ExtraneousCopyToTemporary:
5092   case SK_UserConversion:
5093   case SK_QualificationConversionLValue:
5094   case SK_QualificationConversionXValue:
5095   case SK_QualificationConversionRValue:
5096   case SK_LValueToRValue:
5097   case SK_ConversionSequence:
5098   case SK_ListInitialization:
5099   case SK_UnwrapInitList:
5100   case SK_RewrapInitList:
5101   case SK_CAssignment:
5102   case SK_StringInit:
5103   case SK_ObjCObjectConversion:
5104   case SK_ArrayInit:
5105   case SK_ParenthesizedArrayInit:
5106   case SK_PassByIndirectCopyRestore:
5107   case SK_PassByIndirectRestore:
5108   case SK_ProduceObjCObject:
5109   case SK_StdInitializerList:
5110   case SK_OCLSamplerInit:
5111   case SK_OCLZeroEvent: {
5112     assert(Args.size() == 1);
5113     CurInit = Args[0];
5114     if (!CurInit.get()) return ExprError();
5115     break;
5116   }
5117 
5118   case SK_ConstructorInitialization:
5119   case SK_ListConstructorCall:
5120   case SK_ZeroInitialization:
5121     break;
5122   }
5123 
5124   // Walk through the computed steps for the initialization sequence,
5125   // performing the specified conversions along the way.
5126   bool ConstructorInitRequiresZeroInit = false;
5127   for (step_iterator Step = step_begin(), StepEnd = step_end();
5128        Step != StepEnd; ++Step) {
5129     if (CurInit.isInvalid())
5130       return ExprError();
5131 
5132     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5133 
5134     switch (Step->Kind) {
5135     case SK_ResolveAddressOfOverloadedFunction:
5136       // Overload resolution determined which function invoke; update the
5137       // initializer to reflect that choice.
5138       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5139       S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
5140       CurInit = S.FixOverloadedFunctionReference(CurInit,
5141                                                  Step->Function.FoundDecl,
5142                                                  Step->Function.Function);
5143       break;
5144 
5145     case SK_CastDerivedToBaseRValue:
5146     case SK_CastDerivedToBaseXValue:
5147     case SK_CastDerivedToBaseLValue: {
5148       // We have a derived-to-base cast that produces either an rvalue or an
5149       // lvalue. Perform that cast.
5150 
5151       CXXCastPath BasePath;
5152 
5153       // Casts to inaccessible base classes are allowed with C-style casts.
5154       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5155       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5156                                          CurInit.get()->getLocStart(),
5157                                          CurInit.get()->getSourceRange(),
5158                                          &BasePath, IgnoreBaseAccess))
5159         return ExprError();
5160 
5161       if (S.BasePathInvolvesVirtualBase(BasePath)) {
5162         QualType T = SourceType;
5163         if (const PointerType *Pointer = T->getAs<PointerType>())
5164           T = Pointer->getPointeeType();
5165         if (const RecordType *RecordTy = T->getAs<RecordType>())
5166           S.MarkVTableUsed(CurInit.get()->getLocStart(),
5167                            cast<CXXRecordDecl>(RecordTy->getDecl()));
5168       }
5169 
5170       ExprValueKind VK =
5171           Step->Kind == SK_CastDerivedToBaseLValue ?
5172               VK_LValue :
5173               (Step->Kind == SK_CastDerivedToBaseXValue ?
5174                    VK_XValue :
5175                    VK_RValue);
5176       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5177                                                  Step->Type,
5178                                                  CK_DerivedToBase,
5179                                                  CurInit.get(),
5180                                                  &BasePath, VK));
5181       break;
5182     }
5183 
5184     case SK_BindReference:
5185       if (FieldDecl *BitField = CurInit.get()->getBitField()) {
5186         // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5187         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5188           << Entity.getType().isVolatileQualified()
5189           << BitField->getDeclName()
5190           << CurInit.get()->getSourceRange();
5191         S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5192         return ExprError();
5193       }
5194 
5195       if (CurInit.get()->refersToVectorElement()) {
5196         // References cannot bind to vector elements.
5197         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5198           << Entity.getType().isVolatileQualified()
5199           << CurInit.get()->getSourceRange();
5200         PrintInitLocationNote(S, Entity);
5201         return ExprError();
5202       }
5203 
5204       // Reference binding does not have any corresponding ASTs.
5205 
5206       // Check exception specifications
5207       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5208         return ExprError();
5209 
5210       break;
5211 
5212     case SK_BindReferenceToTemporary:
5213       // Make sure the "temporary" is actually an rvalue.
5214       assert(CurInit.get()->isRValue() && "not a temporary");
5215 
5216       // Check exception specifications
5217       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5218         return ExprError();
5219 
5220       // Materialize the temporary into memory.
5221       CurInit = new (S.Context) MaterializeTemporaryExpr(
5222                                          Entity.getType().getNonReferenceType(),
5223                                                          CurInit.get(),
5224                                      Entity.getType()->isLValueReferenceType());
5225 
5226       // If we're binding to an Objective-C object that has lifetime, we
5227       // need cleanups.
5228       if (S.getLangOpts().ObjCAutoRefCount &&
5229           CurInit.get()->getType()->isObjCLifetimeType())
5230         S.ExprNeedsCleanups = true;
5231 
5232       break;
5233 
5234     case SK_ExtraneousCopyToTemporary:
5235       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5236                            /*IsExtraneousCopy=*/true);
5237       break;
5238 
5239     case SK_UserConversion: {
5240       // We have a user-defined conversion that invokes either a constructor
5241       // or a conversion function.
5242       CastKind CastKind;
5243       bool IsCopy = false;
5244       FunctionDecl *Fn = Step->Function.Function;
5245       DeclAccessPair FoundFn = Step->Function.FoundDecl;
5246       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5247       bool CreatedObject = false;
5248       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5249         // Build a call to the selected constructor.
5250         SmallVector<Expr*, 8> ConstructorArgs;
5251         SourceLocation Loc = CurInit.get()->getLocStart();
5252         CurInit.release(); // Ownership transferred into MultiExprArg, below.
5253 
5254         // Determine the arguments required to actually perform the constructor
5255         // call.
5256         Expr *Arg = CurInit.get();
5257         if (S.CompleteConstructorCall(Constructor,
5258                                       MultiExprArg(&Arg, 1),
5259                                       Loc, ConstructorArgs))
5260           return ExprError();
5261 
5262         // Build an expression that constructs a temporary.
5263         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5264                                           ConstructorArgs,
5265                                           HadMultipleCandidates,
5266                                           /*ListInit*/ false,
5267                                           /*ZeroInit*/ false,
5268                                           CXXConstructExpr::CK_Complete,
5269                                           SourceRange());
5270         if (CurInit.isInvalid())
5271           return ExprError();
5272 
5273         S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5274                                  FoundFn.getAccess());
5275         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
5276 
5277         CastKind = CK_ConstructorConversion;
5278         QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5279         if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5280             S.IsDerivedFrom(SourceType, Class))
5281           IsCopy = true;
5282 
5283         CreatedObject = true;
5284       } else {
5285         // Build a call to the conversion function.
5286         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5287         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5288                                     FoundFn);
5289         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
5290 
5291         // FIXME: Should we move this initialization into a separate
5292         // derived-to-base conversion? I believe the answer is "no", because
5293         // we don't want to turn off access control here for c-style casts.
5294         ExprResult CurInitExprRes =
5295           S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5296                                                 FoundFn, Conversion);
5297         if(CurInitExprRes.isInvalid())
5298           return ExprError();
5299         CurInit = CurInitExprRes;
5300 
5301         // Build the actual call to the conversion function.
5302         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5303                                            HadMultipleCandidates);
5304         if (CurInit.isInvalid() || !CurInit.get())
5305           return ExprError();
5306 
5307         CastKind = CK_UserDefinedConversion;
5308 
5309         CreatedObject = Conversion->getResultType()->isRecordType();
5310       }
5311 
5312       bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5313       bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5314 
5315       if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5316         QualType T = CurInit.get()->getType();
5317         if (const RecordType *Record = T->getAs<RecordType>()) {
5318           CXXDestructorDecl *Destructor
5319             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5320           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5321                                   S.PDiag(diag::err_access_dtor_temp) << T);
5322           S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5323           S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
5324         }
5325       }
5326 
5327       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5328                                                  CurInit.get()->getType(),
5329                                                  CastKind, CurInit.get(), 0,
5330                                                 CurInit.get()->getValueKind()));
5331       if (MaybeBindToTemp)
5332         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5333       if (RequiresCopy)
5334         CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5335                              CurInit, /*IsExtraneousCopy=*/false);
5336       break;
5337     }
5338 
5339     case SK_QualificationConversionLValue:
5340     case SK_QualificationConversionXValue:
5341     case SK_QualificationConversionRValue: {
5342       // Perform a qualification conversion; these can never go wrong.
5343       ExprValueKind VK =
5344           Step->Kind == SK_QualificationConversionLValue ?
5345               VK_LValue :
5346               (Step->Kind == SK_QualificationConversionXValue ?
5347                    VK_XValue :
5348                    VK_RValue);
5349       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5350       break;
5351     }
5352 
5353     case SK_LValueToRValue: {
5354       assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5355       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5356                                                  CK_LValueToRValue,
5357                                                  CurInit.take(),
5358                                                  /*BasePath=*/0,
5359                                                  VK_RValue));
5360       break;
5361     }
5362 
5363     case SK_ConversionSequence: {
5364       Sema::CheckedConversionKind CCK
5365         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5366         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5367         : Kind.isExplicitCast()? Sema::CCK_OtherCast
5368         : Sema::CCK_ImplicitConversion;
5369       ExprResult CurInitExprRes =
5370         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5371                                     getAssignmentAction(Entity), CCK);
5372       if (CurInitExprRes.isInvalid())
5373         return ExprError();
5374       CurInit = CurInitExprRes;
5375       break;
5376     }
5377 
5378     case SK_ListInitialization: {
5379       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5380       // Hack: We must pass *ResultType if available in order to set the type
5381       // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5382       // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5383       // temporary, not a reference, so we should pass Ty.
5384       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5385       // Since this step is never used for a reference directly, we explicitly
5386       // unwrap references here and rewrap them afterwards.
5387       // We also need to create a InitializeTemporary entity for this.
5388       QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5389       bool IsTemporary = Entity.getType()->isReferenceType();
5390       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5391       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5392       InitListChecker PerformInitList(S, InitEntity,
5393           InitList, Ty, /*VerifyOnly=*/false,
5394           Kind.getKind() != InitializationKind::IK_DirectList ||
5395             !S.getLangOpts().CPlusPlus11);
5396       if (PerformInitList.HadError())
5397         return ExprError();
5398 
5399       if (ResultType) {
5400         if ((*ResultType)->isRValueReferenceType())
5401           Ty = S.Context.getRValueReferenceType(Ty);
5402         else if ((*ResultType)->isLValueReferenceType())
5403           Ty = S.Context.getLValueReferenceType(Ty,
5404             (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5405         *ResultType = Ty;
5406       }
5407 
5408       InitListExpr *StructuredInitList =
5409           PerformInitList.getFullyStructuredList();
5410       CurInit.release();
5411       CurInit = shouldBindAsTemporary(InitEntity)
5412           ? S.MaybeBindToTemporary(StructuredInitList)
5413           : S.Owned(StructuredInitList);
5414       break;
5415     }
5416 
5417     case SK_ListConstructorCall: {
5418       // When an initializer list is passed for a parameter of type "reference
5419       // to object", we don't get an EK_Temporary entity, but instead an
5420       // EK_Parameter entity with reference type.
5421       // FIXME: This is a hack. What we really should do is create a user
5422       // conversion step for this case, but this makes it considerably more
5423       // complicated. For now, this will do.
5424       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5425                                         Entity.getType().getNonReferenceType());
5426       bool UseTemporary = Entity.getType()->isReferenceType();
5427       assert(Args.size() == 1 && "expected a single argument for list init");
5428       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5429       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5430         << InitList->getSourceRange();
5431       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5432       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5433                                                                    Entity,
5434                                                  Kind, Arg, *Step,
5435                                                ConstructorInitRequiresZeroInit,
5436                                                /*IsListInitialization*/ true);
5437       break;
5438     }
5439 
5440     case SK_UnwrapInitList:
5441       CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5442       break;
5443 
5444     case SK_RewrapInitList: {
5445       Expr *E = CurInit.take();
5446       InitListExpr *Syntactic = Step->WrappingSyntacticList;
5447       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5448           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
5449       ILE->setSyntacticForm(Syntactic);
5450       ILE->setType(E->getType());
5451       ILE->setValueKind(E->getValueKind());
5452       CurInit = S.Owned(ILE);
5453       break;
5454     }
5455 
5456     case SK_ConstructorInitialization: {
5457       // When an initializer list is passed for a parameter of type "reference
5458       // to object", we don't get an EK_Temporary entity, but instead an
5459       // EK_Parameter entity with reference type.
5460       // FIXME: This is a hack. What we really should do is create a user
5461       // conversion step for this case, but this makes it considerably more
5462       // complicated. For now, this will do.
5463       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5464                                         Entity.getType().getNonReferenceType());
5465       bool UseTemporary = Entity.getType()->isReferenceType();
5466       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5467                                                                  : Entity,
5468                                                  Kind, Args, *Step,
5469                                                ConstructorInitRequiresZeroInit,
5470                                                /*IsListInitialization*/ false);
5471       break;
5472     }
5473 
5474     case SK_ZeroInitialization: {
5475       step_iterator NextStep = Step;
5476       ++NextStep;
5477       if (NextStep != StepEnd &&
5478           (NextStep->Kind == SK_ConstructorInitialization ||
5479            NextStep->Kind == SK_ListConstructorCall)) {
5480         // The need for zero-initialization is recorded directly into
5481         // the call to the object's constructor within the next step.
5482         ConstructorInitRequiresZeroInit = true;
5483       } else if (Kind.getKind() == InitializationKind::IK_Value &&
5484                  S.getLangOpts().CPlusPlus &&
5485                  !Kind.isImplicitValueInit()) {
5486         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5487         if (!TSInfo)
5488           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
5489                                                     Kind.getRange().getBegin());
5490 
5491         CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5492                               TSInfo->getType().getNonLValueExprType(S.Context),
5493                                                                  TSInfo,
5494                                                     Kind.getRange().getEnd()));
5495       } else {
5496         CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
5497       }
5498       break;
5499     }
5500 
5501     case SK_CAssignment: {
5502       QualType SourceType = CurInit.get()->getType();
5503       ExprResult Result = CurInit;
5504       Sema::AssignConvertType ConvTy =
5505         S.CheckSingleAssignmentConstraints(Step->Type, Result);
5506       if (Result.isInvalid())
5507         return ExprError();
5508       CurInit = Result;
5509 
5510       // If this is a call, allow conversion to a transparent union.
5511       ExprResult CurInitExprRes = CurInit;
5512       if (ConvTy != Sema::Compatible &&
5513           Entity.getKind() == InitializedEntity::EK_Parameter &&
5514           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
5515             == Sema::Compatible)
5516         ConvTy = Sema::Compatible;
5517       if (CurInitExprRes.isInvalid())
5518         return ExprError();
5519       CurInit = CurInitExprRes;
5520 
5521       bool Complained;
5522       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5523                                      Step->Type, SourceType,
5524                                      CurInit.get(),
5525                                      getAssignmentAction(Entity),
5526                                      &Complained)) {
5527         PrintInitLocationNote(S, Entity);
5528         return ExprError();
5529       } else if (Complained)
5530         PrintInitLocationNote(S, Entity);
5531       break;
5532     }
5533 
5534     case SK_StringInit: {
5535       QualType Ty = Step->Type;
5536       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
5537                       S.Context.getAsArrayType(Ty), S);
5538       break;
5539     }
5540 
5541     case SK_ObjCObjectConversion:
5542       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5543                           CK_ObjCObjectLValueCast,
5544                           CurInit.get()->getValueKind());
5545       break;
5546 
5547     case SK_ArrayInit:
5548       // Okay: we checked everything before creating this step. Note that
5549       // this is a GNU extension.
5550       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
5551         << Step->Type << CurInit.get()->getType()
5552         << CurInit.get()->getSourceRange();
5553 
5554       // If the destination type is an incomplete array type, update the
5555       // type accordingly.
5556       if (ResultType) {
5557         if (const IncompleteArrayType *IncompleteDest
5558                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
5559           if (const ConstantArrayType *ConstantSource
5560                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
5561             *ResultType = S.Context.getConstantArrayType(
5562                                              IncompleteDest->getElementType(),
5563                                              ConstantSource->getSize(),
5564                                              ArrayType::Normal, 0);
5565           }
5566         }
5567       }
5568       break;
5569 
5570     case SK_ParenthesizedArrayInit:
5571       // Okay: we checked everything before creating this step. Note that
5572       // this is a GNU extension.
5573       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5574         << CurInit.get()->getSourceRange();
5575       break;
5576 
5577     case SK_PassByIndirectCopyRestore:
5578     case SK_PassByIndirectRestore:
5579       checkIndirectCopyRestoreSource(S, CurInit.get());
5580       CurInit = S.Owned(new (S.Context)
5581                         ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5582                                 Step->Kind == SK_PassByIndirectCopyRestore));
5583       break;
5584 
5585     case SK_ProduceObjCObject:
5586       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5587                                                  CK_ARCProduceObject,
5588                                                  CurInit.take(), 0, VK_RValue));
5589       break;
5590 
5591     case SK_StdInitializerList: {
5592       QualType Dest = Step->Type;
5593       QualType E;
5594       bool Success = S.isStdInitializerList(Dest.getNonReferenceType(), &E);
5595       (void)Success;
5596       assert(Success && "Destination type changed?");
5597 
5598       // If the element type has a destructor, check it.
5599       if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5600         if (!RD->hasIrrelevantDestructor()) {
5601           if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5602             S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5603             S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5604                                     S.PDiag(diag::err_access_dtor_temp) << E);
5605             S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5606           }
5607         }
5608       }
5609 
5610       InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5611       S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5612         << ILE->getSourceRange();
5613       unsigned NumInits = ILE->getNumInits();
5614       SmallVector<Expr*, 16> Converted(NumInits);
5615       InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5616           S.Context.getConstantArrayType(E,
5617               llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5618                           NumInits),
5619               ArrayType::Normal, 0));
5620       InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5621           0, HiddenArray);
5622       for (unsigned i = 0; i < NumInits; ++i) {
5623         Element.setElementIndex(i);
5624         ExprResult Init = S.Owned(ILE->getInit(i));
5625         ExprResult Res = S.PerformCopyInitialization(
5626                              Element, Init.get()->getExprLoc(), Init,
5627                              /*TopLevelOfInitList=*/ true);
5628         assert(!Res.isInvalid() && "Result changed since try phase.");
5629         Converted[i] = Res.take();
5630       }
5631       InitListExpr *Semantic = new (S.Context)
5632           InitListExpr(S.Context, ILE->getLBraceLoc(),
5633                        Converted, ILE->getRBraceLoc());
5634       Semantic->setSyntacticForm(ILE);
5635       Semantic->setType(Dest);
5636       Semantic->setInitializesStdInitializerList();
5637       CurInit = S.Owned(Semantic);
5638       break;
5639     }
5640     case SK_OCLSamplerInit: {
5641       assert(Step->Type->isSamplerT() &&
5642              "Sampler initialization on non sampler type.");
5643 
5644       QualType SourceType = CurInit.get()->getType();
5645       InitializedEntity::EntityKind EntityKind = Entity.getKind();
5646 
5647       if (EntityKind == InitializedEntity::EK_Parameter) {
5648         if (!SourceType->isSamplerT())
5649           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
5650             << SourceType;
5651       } else if (EntityKind != InitializedEntity::EK_Variable) {
5652         llvm_unreachable("Invalid EntityKind!");
5653       }
5654 
5655       break;
5656     }
5657     case SK_OCLZeroEvent: {
5658       assert(Step->Type->isEventT() &&
5659              "Event initialization on non event type.");
5660 
5661       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
5662                                     CK_ZeroToOCLEvent,
5663                                     CurInit.get()->getValueKind());
5664       break;
5665     }
5666     }
5667   }
5668 
5669   // Diagnose non-fatal problems with the completed initialization.
5670   if (Entity.getKind() == InitializedEntity::EK_Member &&
5671       cast<FieldDecl>(Entity.getDecl())->isBitField())
5672     S.CheckBitFieldInitialization(Kind.getLocation(),
5673                                   cast<FieldDecl>(Entity.getDecl()),
5674                                   CurInit.get());
5675 
5676   return CurInit;
5677 }
5678 
5679 /// Somewhere within T there is an uninitialized reference subobject.
5680 /// Dig it out and diagnose it.
5681 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
5682                                            QualType T) {
5683   if (T->isReferenceType()) {
5684     S.Diag(Loc, diag::err_reference_without_init)
5685       << T.getNonReferenceType();
5686     return true;
5687   }
5688 
5689   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5690   if (!RD || !RD->hasUninitializedReferenceMember())
5691     return false;
5692 
5693   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5694                                      FE = RD->field_end(); FI != FE; ++FI) {
5695     if (FI->isUnnamedBitfield())
5696       continue;
5697 
5698     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
5699       S.Diag(Loc, diag::note_value_initialization_here) << RD;
5700       return true;
5701     }
5702   }
5703 
5704   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5705                                           BE = RD->bases_end();
5706        BI != BE; ++BI) {
5707     if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
5708       S.Diag(Loc, diag::note_value_initialization_here) << RD;
5709       return true;
5710     }
5711   }
5712 
5713   return false;
5714 }
5715 
5716 
5717 //===----------------------------------------------------------------------===//
5718 // Diagnose initialization failures
5719 //===----------------------------------------------------------------------===//
5720 
5721 /// Emit notes associated with an initialization that failed due to a
5722 /// "simple" conversion failure.
5723 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
5724                                    Expr *op) {
5725   QualType destType = entity.getType();
5726   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
5727       op->getType()->isObjCObjectPointerType()) {
5728 
5729     // Emit a possible note about the conversion failing because the
5730     // operand is a message send with a related result type.
5731     S.EmitRelatedResultTypeNote(op);
5732 
5733     // Emit a possible note about a return failing because we're
5734     // expecting a related result type.
5735     if (entity.getKind() == InitializedEntity::EK_Result)
5736       S.EmitRelatedResultTypeNoteForReturn(destType);
5737   }
5738 }
5739 
5740 bool InitializationSequence::Diagnose(Sema &S,
5741                                       const InitializedEntity &Entity,
5742                                       const InitializationKind &Kind,
5743                                       Expr **Args, unsigned NumArgs) {
5744   if (!Failed())
5745     return false;
5746 
5747   QualType DestType = Entity.getType();
5748   switch (Failure) {
5749   case FK_TooManyInitsForReference:
5750     // FIXME: Customize for the initialized entity?
5751     if (NumArgs == 0) {
5752       // Dig out the reference subobject which is uninitialized and diagnose it.
5753       // If this is value-initialization, this could be nested some way within
5754       // the target type.
5755       assert(Kind.getKind() == InitializationKind::IK_Value ||
5756              DestType->isReferenceType());
5757       bool Diagnosed =
5758         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
5759       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
5760       (void)Diagnosed;
5761     } else  // FIXME: diagnostic below could be better!
5762       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5763         << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
5764     break;
5765 
5766   case FK_ArrayNeedsInitList:
5767   case FK_ArrayNeedsInitListOrStringLiteral:
5768     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5769       << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5770     break;
5771 
5772   case FK_ArrayTypeMismatch:
5773   case FK_NonConstantArrayInit:
5774     S.Diag(Kind.getLocation(),
5775            (Failure == FK_ArrayTypeMismatch
5776               ? diag::err_array_init_different_type
5777               : diag::err_array_init_non_constant_array))
5778       << DestType.getNonReferenceType()
5779       << Args[0]->getType()
5780       << Args[0]->getSourceRange();
5781     break;
5782 
5783   case FK_VariableLengthArrayHasInitializer:
5784     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5785       << Args[0]->getSourceRange();
5786     break;
5787 
5788   case FK_AddressOfOverloadFailed: {
5789     DeclAccessPair Found;
5790     S.ResolveAddressOfOverloadedFunction(Args[0],
5791                                          DestType.getNonReferenceType(),
5792                                          true,
5793                                          Found);
5794     break;
5795   }
5796 
5797   case FK_ReferenceInitOverloadFailed:
5798   case FK_UserConversionOverloadFailed:
5799     switch (FailedOverloadResult) {
5800     case OR_Ambiguous:
5801       if (Failure == FK_UserConversionOverloadFailed)
5802         S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5803           << Args[0]->getType() << DestType
5804           << Args[0]->getSourceRange();
5805       else
5806         S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5807           << DestType << Args[0]->getType()
5808           << Args[0]->getSourceRange();
5809 
5810       FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5811                                         llvm::makeArrayRef(Args, NumArgs));
5812       break;
5813 
5814     case OR_No_Viable_Function:
5815       S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5816         << Args[0]->getType() << DestType.getNonReferenceType()
5817         << Args[0]->getSourceRange();
5818       FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5819                                         llvm::makeArrayRef(Args, NumArgs));
5820       break;
5821 
5822     case OR_Deleted: {
5823       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5824         << Args[0]->getType() << DestType.getNonReferenceType()
5825         << Args[0]->getSourceRange();
5826       OverloadCandidateSet::iterator Best;
5827       OverloadingResult Ovl
5828         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5829                                                 true);
5830       if (Ovl == OR_Deleted) {
5831         S.NoteDeletedFunction(Best->Function);
5832       } else {
5833         llvm_unreachable("Inconsistent overload resolution?");
5834       }
5835       break;
5836     }
5837 
5838     case OR_Success:
5839       llvm_unreachable("Conversion did not fail!");
5840     }
5841     break;
5842 
5843   case FK_NonConstLValueReferenceBindingToTemporary:
5844     if (isa<InitListExpr>(Args[0])) {
5845       S.Diag(Kind.getLocation(),
5846              diag::err_lvalue_reference_bind_to_initlist)
5847       << DestType.getNonReferenceType().isVolatileQualified()
5848       << DestType.getNonReferenceType()
5849       << Args[0]->getSourceRange();
5850       break;
5851     }
5852     // Intentional fallthrough
5853 
5854   case FK_NonConstLValueReferenceBindingToUnrelated:
5855     S.Diag(Kind.getLocation(),
5856            Failure == FK_NonConstLValueReferenceBindingToTemporary
5857              ? diag::err_lvalue_reference_bind_to_temporary
5858              : diag::err_lvalue_reference_bind_to_unrelated)
5859       << DestType.getNonReferenceType().isVolatileQualified()
5860       << DestType.getNonReferenceType()
5861       << Args[0]->getType()
5862       << Args[0]->getSourceRange();
5863     break;
5864 
5865   case FK_RValueReferenceBindingToLValue:
5866     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
5867       << DestType.getNonReferenceType() << Args[0]->getType()
5868       << Args[0]->getSourceRange();
5869     break;
5870 
5871   case FK_ReferenceInitDropsQualifiers:
5872     S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5873       << DestType.getNonReferenceType()
5874       << Args[0]->getType()
5875       << Args[0]->getSourceRange();
5876     break;
5877 
5878   case FK_ReferenceInitFailed:
5879     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5880       << DestType.getNonReferenceType()
5881       << Args[0]->isLValue()
5882       << Args[0]->getType()
5883       << Args[0]->getSourceRange();
5884     emitBadConversionNotes(S, Entity, Args[0]);
5885     break;
5886 
5887   case FK_ConversionFailed: {
5888     QualType FromType = Args[0]->getType();
5889     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
5890       << (int)Entity.getKind()
5891       << DestType
5892       << Args[0]->isLValue()
5893       << FromType
5894       << Args[0]->getSourceRange();
5895     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5896     S.Diag(Kind.getLocation(), PDiag);
5897     emitBadConversionNotes(S, Entity, Args[0]);
5898     break;
5899   }
5900 
5901   case FK_ConversionFromPropertyFailed:
5902     // No-op. This error has already been reported.
5903     break;
5904 
5905   case FK_TooManyInitsForScalar: {
5906     SourceRange R;
5907 
5908     if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
5909       R = SourceRange(InitList->getInit(0)->getLocEnd(),
5910                       InitList->getLocEnd());
5911     else
5912       R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
5913 
5914     R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5915     if (Kind.isCStyleOrFunctionalCast())
5916       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5917         << R;
5918     else
5919       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5920         << /*scalar=*/2 << R;
5921     break;
5922   }
5923 
5924   case FK_ReferenceBindingToInitList:
5925     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5926       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5927     break;
5928 
5929   case FK_InitListBadDestinationType:
5930     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5931       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5932     break;
5933 
5934   case FK_ListConstructorOverloadFailed:
5935   case FK_ConstructorOverloadFailed: {
5936     SourceRange ArgsRange;
5937     if (NumArgs)
5938       ArgsRange = SourceRange(Args[0]->getLocStart(),
5939                               Args[NumArgs - 1]->getLocEnd());
5940 
5941     if (Failure == FK_ListConstructorOverloadFailed) {
5942       assert(NumArgs == 1 && "List construction from other than 1 argument.");
5943       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5944       Args = InitList->getInits();
5945       NumArgs = InitList->getNumInits();
5946     }
5947 
5948     // FIXME: Using "DestType" for the entity we're printing is probably
5949     // bad.
5950     switch (FailedOverloadResult) {
5951       case OR_Ambiguous:
5952         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5953           << DestType << ArgsRange;
5954         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5955                                           llvm::makeArrayRef(Args, NumArgs));
5956         break;
5957 
5958       case OR_No_Viable_Function:
5959         if (Kind.getKind() == InitializationKind::IK_Default &&
5960             (Entity.getKind() == InitializedEntity::EK_Base ||
5961              Entity.getKind() == InitializedEntity::EK_Member) &&
5962             isa<CXXConstructorDecl>(S.CurContext)) {
5963           // This is implicit default initialization of a member or
5964           // base within a constructor. If no viable function was
5965           // found, notify the user that she needs to explicitly
5966           // initialize this base/member.
5967           CXXConstructorDecl *Constructor
5968             = cast<CXXConstructorDecl>(S.CurContext);
5969           if (Entity.getKind() == InitializedEntity::EK_Base) {
5970             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5971               << (Constructor->getInheritedConstructor() ? 2 :
5972                   Constructor->isImplicit() ? 1 : 0)
5973               << S.Context.getTypeDeclType(Constructor->getParent())
5974               << /*base=*/0
5975               << Entity.getType();
5976 
5977             RecordDecl *BaseDecl
5978               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5979                                                                   ->getDecl();
5980             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5981               << S.Context.getTagDeclType(BaseDecl);
5982           } else {
5983             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5984               << (Constructor->getInheritedConstructor() ? 2 :
5985                   Constructor->isImplicit() ? 1 : 0)
5986               << S.Context.getTypeDeclType(Constructor->getParent())
5987               << /*member=*/1
5988               << Entity.getName();
5989             S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5990 
5991             if (const RecordType *Record
5992                                  = Entity.getType()->getAs<RecordType>())
5993               S.Diag(Record->getDecl()->getLocation(),
5994                      diag::note_previous_decl)
5995                 << S.Context.getTagDeclType(Record->getDecl());
5996           }
5997           break;
5998         }
5999 
6000         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6001           << DestType << ArgsRange;
6002         FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
6003                                           llvm::makeArrayRef(Args, NumArgs));
6004         break;
6005 
6006       case OR_Deleted: {
6007         OverloadCandidateSet::iterator Best;
6008         OverloadingResult Ovl
6009           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6010         if (Ovl != OR_Deleted) {
6011           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6012             << true << DestType << ArgsRange;
6013           llvm_unreachable("Inconsistent overload resolution?");
6014           break;
6015         }
6016 
6017         // If this is a defaulted or implicitly-declared function, then
6018         // it was implicitly deleted. Make it clear that the deletion was
6019         // implicit.
6020         if (S.isImplicitlyDeleted(Best->Function))
6021           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6022             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6023             << DestType << ArgsRange;
6024         else
6025           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6026             << true << DestType << ArgsRange;
6027 
6028         S.NoteDeletedFunction(Best->Function);
6029         break;
6030       }
6031 
6032       case OR_Success:
6033         llvm_unreachable("Conversion did not fail!");
6034     }
6035   }
6036   break;
6037 
6038   case FK_DefaultInitOfConst:
6039     if (Entity.getKind() == InitializedEntity::EK_Member &&
6040         isa<CXXConstructorDecl>(S.CurContext)) {
6041       // This is implicit default-initialization of a const member in
6042       // a constructor. Complain that it needs to be explicitly
6043       // initialized.
6044       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6045       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6046         << (Constructor->getInheritedConstructor() ? 2 :
6047             Constructor->isImplicit() ? 1 : 0)
6048         << S.Context.getTypeDeclType(Constructor->getParent())
6049         << /*const=*/1
6050         << Entity.getName();
6051       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6052         << Entity.getName();
6053     } else {
6054       S.Diag(Kind.getLocation(), diag::err_default_init_const)
6055         << DestType << (bool)DestType->getAs<RecordType>();
6056     }
6057     break;
6058 
6059   case FK_Incomplete:
6060     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6061                           diag::err_init_incomplete_type);
6062     break;
6063 
6064   case FK_ListInitializationFailed: {
6065     // Run the init list checker again to emit diagnostics.
6066     InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6067     QualType DestType = Entity.getType();
6068     InitListChecker DiagnoseInitList(S, Entity, InitList,
6069             DestType, /*VerifyOnly=*/false,
6070             Kind.getKind() != InitializationKind::IK_DirectList ||
6071               !S.getLangOpts().CPlusPlus11);
6072     assert(DiagnoseInitList.HadError() &&
6073            "Inconsistent init list check result.");
6074     break;
6075   }
6076 
6077   case FK_PlaceholderType: {
6078     // FIXME: Already diagnosed!
6079     break;
6080   }
6081 
6082   case FK_InitListElementCopyFailure: {
6083     // Try to perform all copies again.
6084     InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6085     unsigned NumInits = InitList->getNumInits();
6086     QualType DestType = Entity.getType();
6087     QualType E;
6088     bool Success = S.isStdInitializerList(DestType.getNonReferenceType(), &E);
6089     (void)Success;
6090     assert(Success && "Where did the std::initializer_list go?");
6091     InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
6092         S.Context.getConstantArrayType(E,
6093             llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6094                         NumInits),
6095             ArrayType::Normal, 0));
6096     InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
6097         0, HiddenArray);
6098     // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
6099     // where the init list type is wrong, e.g.
6100     //   std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
6101     // FIXME: Emit a note if we hit the limit?
6102     int ErrorCount = 0;
6103     for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
6104       Element.setElementIndex(i);
6105       ExprResult Init = S.Owned(InitList->getInit(i));
6106       if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
6107            .isInvalid())
6108         ++ErrorCount;
6109     }
6110     break;
6111   }
6112 
6113   case FK_ExplicitConstructor: {
6114     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6115       << Args[0]->getSourceRange();
6116     OverloadCandidateSet::iterator Best;
6117     OverloadingResult Ovl
6118       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6119     (void)Ovl;
6120     assert(Ovl == OR_Success && "Inconsistent overload resolution");
6121     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6122     S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6123     break;
6124   }
6125   }
6126 
6127   PrintInitLocationNote(S, Entity);
6128   return true;
6129 }
6130 
6131 void InitializationSequence::dump(raw_ostream &OS) const {
6132   switch (SequenceKind) {
6133   case FailedSequence: {
6134     OS << "Failed sequence: ";
6135     switch (Failure) {
6136     case FK_TooManyInitsForReference:
6137       OS << "too many initializers for reference";
6138       break;
6139 
6140     case FK_ArrayNeedsInitList:
6141       OS << "array requires initializer list";
6142       break;
6143 
6144     case FK_ArrayNeedsInitListOrStringLiteral:
6145       OS << "array requires initializer list or string literal";
6146       break;
6147 
6148     case FK_ArrayTypeMismatch:
6149       OS << "array type mismatch";
6150       break;
6151 
6152     case FK_NonConstantArrayInit:
6153       OS << "non-constant array initializer";
6154       break;
6155 
6156     case FK_AddressOfOverloadFailed:
6157       OS << "address of overloaded function failed";
6158       break;
6159 
6160     case FK_ReferenceInitOverloadFailed:
6161       OS << "overload resolution for reference initialization failed";
6162       break;
6163 
6164     case FK_NonConstLValueReferenceBindingToTemporary:
6165       OS << "non-const lvalue reference bound to temporary";
6166       break;
6167 
6168     case FK_NonConstLValueReferenceBindingToUnrelated:
6169       OS << "non-const lvalue reference bound to unrelated type";
6170       break;
6171 
6172     case FK_RValueReferenceBindingToLValue:
6173       OS << "rvalue reference bound to an lvalue";
6174       break;
6175 
6176     case FK_ReferenceInitDropsQualifiers:
6177       OS << "reference initialization drops qualifiers";
6178       break;
6179 
6180     case FK_ReferenceInitFailed:
6181       OS << "reference initialization failed";
6182       break;
6183 
6184     case FK_ConversionFailed:
6185       OS << "conversion failed";
6186       break;
6187 
6188     case FK_ConversionFromPropertyFailed:
6189       OS << "conversion from property failed";
6190       break;
6191 
6192     case FK_TooManyInitsForScalar:
6193       OS << "too many initializers for scalar";
6194       break;
6195 
6196     case FK_ReferenceBindingToInitList:
6197       OS << "referencing binding to initializer list";
6198       break;
6199 
6200     case FK_InitListBadDestinationType:
6201       OS << "initializer list for non-aggregate, non-scalar type";
6202       break;
6203 
6204     case FK_UserConversionOverloadFailed:
6205       OS << "overloading failed for user-defined conversion";
6206       break;
6207 
6208     case FK_ConstructorOverloadFailed:
6209       OS << "constructor overloading failed";
6210       break;
6211 
6212     case FK_DefaultInitOfConst:
6213       OS << "default initialization of a const variable";
6214       break;
6215 
6216     case FK_Incomplete:
6217       OS << "initialization of incomplete type";
6218       break;
6219 
6220     case FK_ListInitializationFailed:
6221       OS << "list initialization checker failure";
6222       break;
6223 
6224     case FK_VariableLengthArrayHasInitializer:
6225       OS << "variable length array has an initializer";
6226       break;
6227 
6228     case FK_PlaceholderType:
6229       OS << "initializer expression isn't contextually valid";
6230       break;
6231 
6232     case FK_ListConstructorOverloadFailed:
6233       OS << "list constructor overloading failed";
6234       break;
6235 
6236     case FK_InitListElementCopyFailure:
6237       OS << "copy construction of initializer list element failed";
6238       break;
6239 
6240     case FK_ExplicitConstructor:
6241       OS << "list copy initialization chose explicit constructor";
6242       break;
6243     }
6244     OS << '\n';
6245     return;
6246   }
6247 
6248   case DependentSequence:
6249     OS << "Dependent sequence\n";
6250     return;
6251 
6252   case NormalSequence:
6253     OS << "Normal sequence: ";
6254     break;
6255   }
6256 
6257   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6258     if (S != step_begin()) {
6259       OS << " -> ";
6260     }
6261 
6262     switch (S->Kind) {
6263     case SK_ResolveAddressOfOverloadedFunction:
6264       OS << "resolve address of overloaded function";
6265       break;
6266 
6267     case SK_CastDerivedToBaseRValue:
6268       OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6269       break;
6270 
6271     case SK_CastDerivedToBaseXValue:
6272       OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6273       break;
6274 
6275     case SK_CastDerivedToBaseLValue:
6276       OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6277       break;
6278 
6279     case SK_BindReference:
6280       OS << "bind reference to lvalue";
6281       break;
6282 
6283     case SK_BindReferenceToTemporary:
6284       OS << "bind reference to a temporary";
6285       break;
6286 
6287     case SK_ExtraneousCopyToTemporary:
6288       OS << "extraneous C++03 copy to temporary";
6289       break;
6290 
6291     case SK_UserConversion:
6292       OS << "user-defined conversion via " << *S->Function.Function;
6293       break;
6294 
6295     case SK_QualificationConversionRValue:
6296       OS << "qualification conversion (rvalue)";
6297       break;
6298 
6299     case SK_QualificationConversionXValue:
6300       OS << "qualification conversion (xvalue)";
6301       break;
6302 
6303     case SK_QualificationConversionLValue:
6304       OS << "qualification conversion (lvalue)";
6305       break;
6306 
6307     case SK_LValueToRValue:
6308       OS << "load (lvalue to rvalue)";
6309       break;
6310 
6311     case SK_ConversionSequence:
6312       OS << "implicit conversion sequence (";
6313       S->ICS->DebugPrint(); // FIXME: use OS
6314       OS << ")";
6315       break;
6316 
6317     case SK_ListInitialization:
6318       OS << "list aggregate initialization";
6319       break;
6320 
6321     case SK_ListConstructorCall:
6322       OS << "list initialization via constructor";
6323       break;
6324 
6325     case SK_UnwrapInitList:
6326       OS << "unwrap reference initializer list";
6327       break;
6328 
6329     case SK_RewrapInitList:
6330       OS << "rewrap reference initializer list";
6331       break;
6332 
6333     case SK_ConstructorInitialization:
6334       OS << "constructor initialization";
6335       break;
6336 
6337     case SK_ZeroInitialization:
6338       OS << "zero initialization";
6339       break;
6340 
6341     case SK_CAssignment:
6342       OS << "C assignment";
6343       break;
6344 
6345     case SK_StringInit:
6346       OS << "string initialization";
6347       break;
6348 
6349     case SK_ObjCObjectConversion:
6350       OS << "Objective-C object conversion";
6351       break;
6352 
6353     case SK_ArrayInit:
6354       OS << "array initialization";
6355       break;
6356 
6357     case SK_ParenthesizedArrayInit:
6358       OS << "parenthesized array initialization";
6359       break;
6360 
6361     case SK_PassByIndirectCopyRestore:
6362       OS << "pass by indirect copy and restore";
6363       break;
6364 
6365     case SK_PassByIndirectRestore:
6366       OS << "pass by indirect restore";
6367       break;
6368 
6369     case SK_ProduceObjCObject:
6370       OS << "Objective-C object retension";
6371       break;
6372 
6373     case SK_StdInitializerList:
6374       OS << "std::initializer_list from initializer list";
6375       break;
6376 
6377     case SK_OCLSamplerInit:
6378       OS << "OpenCL sampler_t from integer constant";
6379       break;
6380 
6381     case SK_OCLZeroEvent:
6382       OS << "OpenCL event_t from zero";
6383       break;
6384     }
6385 
6386     OS << " [" << S->Type.getAsString() << ']';
6387   }
6388 
6389   OS << '\n';
6390 }
6391 
6392 void InitializationSequence::dump() const {
6393   dump(llvm::errs());
6394 }
6395 
6396 static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6397                                         QualType EntityType,
6398                                         const Expr *PreInit,
6399                                         const Expr *PostInit) {
6400   if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6401     return;
6402 
6403   // A narrowing conversion can only appear as the final implicit conversion in
6404   // an initialization sequence.
6405   const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6406   if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6407     return;
6408 
6409   const ImplicitConversionSequence &ICS = *LastStep.ICS;
6410   const StandardConversionSequence *SCS = 0;
6411   switch (ICS.getKind()) {
6412   case ImplicitConversionSequence::StandardConversion:
6413     SCS = &ICS.Standard;
6414     break;
6415   case ImplicitConversionSequence::UserDefinedConversion:
6416     SCS = &ICS.UserDefined.After;
6417     break;
6418   case ImplicitConversionSequence::AmbiguousConversion:
6419   case ImplicitConversionSequence::EllipsisConversion:
6420   case ImplicitConversionSequence::BadConversion:
6421     return;
6422   }
6423 
6424   // Determine the type prior to the narrowing conversion. If a conversion
6425   // operator was used, this may be different from both the type of the entity
6426   // and of the pre-initialization expression.
6427   QualType PreNarrowingType = PreInit->getType();
6428   if (Seq.step_begin() + 1 != Seq.step_end())
6429     PreNarrowingType = Seq.step_end()[-2].Type;
6430 
6431   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6432   APValue ConstantValue;
6433   QualType ConstantType;
6434   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6435                                 ConstantType)) {
6436   case NK_Not_Narrowing:
6437     // No narrowing occurred.
6438     return;
6439 
6440   case NK_Type_Narrowing:
6441     // This was a floating-to-integer conversion, which is always considered a
6442     // narrowing conversion even if the value is a constant and can be
6443     // represented exactly as an integer.
6444     S.Diag(PostInit->getLocStart(),
6445            S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6446              diag::warn_init_list_type_narrowing
6447            : S.isSFINAEContext()?
6448              diag::err_init_list_type_narrowing_sfinae
6449            : diag::err_init_list_type_narrowing)
6450       << PostInit->getSourceRange()
6451       << PreNarrowingType.getLocalUnqualifiedType()
6452       << EntityType.getLocalUnqualifiedType();
6453     break;
6454 
6455   case NK_Constant_Narrowing:
6456     // A constant value was narrowed.
6457     S.Diag(PostInit->getLocStart(),
6458            S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6459              diag::warn_init_list_constant_narrowing
6460            : S.isSFINAEContext()?
6461              diag::err_init_list_constant_narrowing_sfinae
6462            : diag::err_init_list_constant_narrowing)
6463       << PostInit->getSourceRange()
6464       << ConstantValue.getAsString(S.getASTContext(), ConstantType)
6465       << EntityType.getLocalUnqualifiedType();
6466     break;
6467 
6468   case NK_Variable_Narrowing:
6469     // A variable's value may have been narrowed.
6470     S.Diag(PostInit->getLocStart(),
6471            S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6472              diag::warn_init_list_variable_narrowing
6473            : S.isSFINAEContext()?
6474              diag::err_init_list_variable_narrowing_sfinae
6475            : diag::err_init_list_variable_narrowing)
6476       << PostInit->getSourceRange()
6477       << PreNarrowingType.getLocalUnqualifiedType()
6478       << EntityType.getLocalUnqualifiedType();
6479     break;
6480   }
6481 
6482   SmallString<128> StaticCast;
6483   llvm::raw_svector_ostream OS(StaticCast);
6484   OS << "static_cast<";
6485   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6486     // It's important to use the typedef's name if there is one so that the
6487     // fixit doesn't break code using types like int64_t.
6488     //
6489     // FIXME: This will break if the typedef requires qualification.  But
6490     // getQualifiedNameAsString() includes non-machine-parsable components.
6491     OS << *TT->getDecl();
6492   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6493     OS << BT->getName(S.getLangOpts());
6494   else {
6495     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
6496     // with a broken cast.
6497     return;
6498   }
6499   OS << ">(";
6500   S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6501     << PostInit->getSourceRange()
6502     << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
6503     << FixItHint::CreateInsertion(
6504       S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
6505 }
6506 
6507 //===----------------------------------------------------------------------===//
6508 // Initialization helper functions
6509 //===----------------------------------------------------------------------===//
6510 bool
6511 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6512                                    ExprResult Init) {
6513   if (Init.isInvalid())
6514     return false;
6515 
6516   Expr *InitE = Init.get();
6517   assert(InitE && "No initialization expression");
6518 
6519   InitializationKind Kind
6520     = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
6521   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6522   return !Seq.Failed();
6523 }
6524 
6525 ExprResult
6526 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6527                                 SourceLocation EqualLoc,
6528                                 ExprResult Init,
6529                                 bool TopLevelOfInitList,
6530                                 bool AllowExplicit) {
6531   if (Init.isInvalid())
6532     return ExprError();
6533 
6534   Expr *InitE = Init.get();
6535   assert(InitE && "No initialization expression?");
6536 
6537   if (EqualLoc.isInvalid())
6538     EqualLoc = InitE->getLocStart();
6539 
6540   InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6541                                                            EqualLoc,
6542                                                            AllowExplicit);
6543   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6544   Init.release();
6545 
6546   ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6547 
6548   if (!Result.isInvalid() && TopLevelOfInitList)
6549     DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6550                                 InitE, Result.get());
6551 
6552   return Result;
6553 }
6554