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