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