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