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