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