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