1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for initializers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/ExprOpenMP.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Sema/Designator.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/SemaInternal.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Sema Initialization Checking
34 //===----------------------------------------------------------------------===//
35 
36 /// Check whether T is compatible with a wide character type (wchar_t,
37 /// char16_t or char32_t).
38 static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
39   if (Context.typesAreCompatible(Context.getWideCharType(), T))
40     return true;
41   if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
42     return Context.typesAreCompatible(Context.Char16Ty, T) ||
43            Context.typesAreCompatible(Context.Char32Ty, T);
44   }
45   return false;
46 }
47 
48 enum StringInitFailureKind {
49   SIF_None,
50   SIF_NarrowStringIntoWideChar,
51   SIF_WideStringIntoChar,
52   SIF_IncompatWideStringIntoWideChar,
53   SIF_UTF8StringIntoPlainChar,
54   SIF_PlainStringIntoUTF8Char,
55   SIF_Other
56 };
57 
58 /// Check whether the array of type AT can be initialized by the Init
59 /// expression by means of string initialization. Returns SIF_None if so,
60 /// otherwise returns a StringInitFailureKind that describes why the
61 /// initialization would not work.
62 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
63                                           ASTContext &Context) {
64   if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
65     return SIF_Other;
66 
67   // See if this is a string literal or @encode.
68   Init = Init->IgnoreParens();
69 
70   // Handle @encode, which is a narrow string.
71   if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
72     return SIF_None;
73 
74   // Otherwise we can only handle string literals.
75   StringLiteral *SL = dyn_cast<StringLiteral>(Init);
76   if (!SL)
77     return SIF_Other;
78 
79   const QualType ElemTy =
80       Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
81 
82   switch (SL->getKind()) {
83   case StringLiteral::UTF8:
84     // char8_t array can be initialized with a UTF-8 string.
85     if (ElemTy->isChar8Type())
86       return SIF_None;
87     LLVM_FALLTHROUGH;
88   case StringLiteral::Ascii:
89     // char array can be initialized with a narrow string.
90     // Only allow char x[] = "foo";  not char x[] = L"foo";
91     if (ElemTy->isCharType())
92       return (SL->getKind() == StringLiteral::UTF8 &&
93               Context.getLangOpts().Char8)
94                  ? SIF_UTF8StringIntoPlainChar
95                  : SIF_None;
96     if (ElemTy->isChar8Type())
97       return SIF_PlainStringIntoUTF8Char;
98     if (IsWideCharCompatible(ElemTy, Context))
99       return SIF_NarrowStringIntoWideChar;
100     return SIF_Other;
101   // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
102   // "An array with element type compatible with a qualified or unqualified
103   // version of wchar_t, char16_t, or char32_t may be initialized by a wide
104   // string literal with the corresponding encoding prefix (L, u, or U,
105   // respectively), optionally enclosed in braces.
106   case StringLiteral::UTF16:
107     if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
108       return SIF_None;
109     if (ElemTy->isCharType() || ElemTy->isChar8Type())
110       return SIF_WideStringIntoChar;
111     if (IsWideCharCompatible(ElemTy, Context))
112       return SIF_IncompatWideStringIntoWideChar;
113     return SIF_Other;
114   case StringLiteral::UTF32:
115     if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
116       return SIF_None;
117     if (ElemTy->isCharType() || ElemTy->isChar8Type())
118       return SIF_WideStringIntoChar;
119     if (IsWideCharCompatible(ElemTy, Context))
120       return SIF_IncompatWideStringIntoWideChar;
121     return SIF_Other;
122   case StringLiteral::Wide:
123     if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
124       return SIF_None;
125     if (ElemTy->isCharType() || ElemTy->isChar8Type())
126       return SIF_WideStringIntoChar;
127     if (IsWideCharCompatible(ElemTy, Context))
128       return SIF_IncompatWideStringIntoWideChar;
129     return SIF_Other;
130   }
131 
132   llvm_unreachable("missed a StringLiteral kind?");
133 }
134 
135 static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
136                                           ASTContext &Context) {
137   const ArrayType *arrayType = Context.getAsArrayType(declType);
138   if (!arrayType)
139     return SIF_Other;
140   return IsStringInit(init, arrayType, Context);
141 }
142 
143 /// Update the type of a string literal, including any surrounding parentheses,
144 /// to match the type of the object which it is initializing.
145 static void updateStringLiteralType(Expr *E, QualType Ty) {
146   while (true) {
147     E->setType(Ty);
148     E->setValueKind(VK_RValue);
149     if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
150       break;
151     } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
152       E = PE->getSubExpr();
153     } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
154       assert(UO->getOpcode() == UO_Extension);
155       E = UO->getSubExpr();
156     } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
157       E = GSE->getResultExpr();
158     } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
159       E = CE->getChosenSubExpr();
160     } else {
161       llvm_unreachable("unexpected expr in string literal init");
162     }
163   }
164 }
165 
166 /// Fix a compound literal initializing an array so it's correctly marked
167 /// as an rvalue.
168 static void updateGNUCompoundLiteralRValue(Expr *E) {
169   while (true) {
170     E->setValueKind(VK_RValue);
171     if (isa<CompoundLiteralExpr>(E)) {
172       break;
173     } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
174       E = PE->getSubExpr();
175     } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
176       assert(UO->getOpcode() == UO_Extension);
177       E = UO->getSubExpr();
178     } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
179       E = GSE->getResultExpr();
180     } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
181       E = CE->getChosenSubExpr();
182     } else {
183       llvm_unreachable("unexpected expr in array compound literal init");
184     }
185   }
186 }
187 
188 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
189                             Sema &S) {
190   // Get the length of the string as parsed.
191   auto *ConstantArrayTy =
192       cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
193   uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
194 
195   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
196     // C99 6.7.8p14. We have an array of character type with unknown size
197     // being initialized to a string literal.
198     llvm::APInt ConstVal(32, StrLength);
199     // Return a new array type (C99 6.7.8p22).
200     DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
201                                            ConstVal,
202                                            ArrayType::Normal, 0);
203     updateStringLiteralType(Str, DeclT);
204     return;
205   }
206 
207   const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
208 
209   // We have an array of character type with known size.  However,
210   // the size may be smaller or larger than the string we are initializing.
211   // FIXME: Avoid truncation for 64-bit length strings.
212   if (S.getLangOpts().CPlusPlus) {
213     if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
214       // For Pascal strings it's OK to strip off the terminating null character,
215       // so the example below is valid:
216       //
217       // unsigned char a[2] = "\pa";
218       if (SL->isPascal())
219         StrLength--;
220     }
221 
222     // [dcl.init.string]p2
223     if (StrLength > CAT->getSize().getZExtValue())
224       S.Diag(Str->getBeginLoc(),
225              diag::err_initializer_string_for_char_array_too_long)
226           << Str->getSourceRange();
227   } else {
228     // C99 6.7.8p14.
229     if (StrLength-1 > CAT->getSize().getZExtValue())
230       S.Diag(Str->getBeginLoc(),
231              diag::ext_initializer_string_for_char_array_too_long)
232           << Str->getSourceRange();
233   }
234 
235   // Set the type to the actual size that we are initializing.  If we have
236   // something like:
237   //   char x[1] = "foo";
238   // then this will set the string literal's type to char[1].
239   updateStringLiteralType(Str, DeclT);
240 }
241 
242 //===----------------------------------------------------------------------===//
243 // Semantic checking for initializer lists.
244 //===----------------------------------------------------------------------===//
245 
246 namespace {
247 
248 /// Semantic checking for initializer lists.
249 ///
250 /// The InitListChecker class contains a set of routines that each
251 /// handle the initialization of a certain kind of entity, e.g.,
252 /// arrays, vectors, struct/union types, scalars, etc. The
253 /// InitListChecker itself performs a recursive walk of the subobject
254 /// structure of the type to be initialized, while stepping through
255 /// the initializer list one element at a time. The IList and Index
256 /// parameters to each of the Check* routines contain the active
257 /// (syntactic) initializer list and the index into that initializer
258 /// list that represents the current initializer. Each routine is
259 /// responsible for moving that Index forward as it consumes elements.
260 ///
261 /// Each Check* routine also has a StructuredList/StructuredIndex
262 /// arguments, which contains the current "structured" (semantic)
263 /// initializer list and the index into that initializer list where we
264 /// are copying initializers as we map them over to the semantic
265 /// list. Once we have completed our recursive walk of the subobject
266 /// structure, we will have constructed a full semantic initializer
267 /// list.
268 ///
269 /// C99 designators cause changes in the initializer list traversal,
270 /// because they make the initialization "jump" into a specific
271 /// subobject and then continue the initialization from that
272 /// point. CheckDesignatedInitializer() recursively steps into the
273 /// designated subobject and manages backing out the recursion to
274 /// initialize the subobjects after the one designated.
275 class InitListChecker {
276   Sema &SemaRef;
277   bool hadError;
278   bool VerifyOnly; // no diagnostics, no structure building
279   bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
280   llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
281   InitListExpr *FullyStructuredList;
282 
283   void CheckImplicitInitList(const InitializedEntity &Entity,
284                              InitListExpr *ParentIList, QualType T,
285                              unsigned &Index, InitListExpr *StructuredList,
286                              unsigned &StructuredIndex);
287   void CheckExplicitInitList(const InitializedEntity &Entity,
288                              InitListExpr *IList, QualType &T,
289                              InitListExpr *StructuredList,
290                              bool TopLevelObject = false);
291   void CheckListElementTypes(const InitializedEntity &Entity,
292                              InitListExpr *IList, QualType &DeclType,
293                              bool SubobjectIsDesignatorContext,
294                              unsigned &Index,
295                              InitListExpr *StructuredList,
296                              unsigned &StructuredIndex,
297                              bool TopLevelObject = false);
298   void CheckSubElementType(const InitializedEntity &Entity,
299                            InitListExpr *IList, QualType ElemType,
300                            unsigned &Index,
301                            InitListExpr *StructuredList,
302                            unsigned &StructuredIndex);
303   void CheckComplexType(const InitializedEntity &Entity,
304                         InitListExpr *IList, QualType DeclType,
305                         unsigned &Index,
306                         InitListExpr *StructuredList,
307                         unsigned &StructuredIndex);
308   void CheckScalarType(const InitializedEntity &Entity,
309                        InitListExpr *IList, QualType DeclType,
310                        unsigned &Index,
311                        InitListExpr *StructuredList,
312                        unsigned &StructuredIndex);
313   void CheckReferenceType(const InitializedEntity &Entity,
314                           InitListExpr *IList, QualType DeclType,
315                           unsigned &Index,
316                           InitListExpr *StructuredList,
317                           unsigned &StructuredIndex);
318   void CheckVectorType(const InitializedEntity &Entity,
319                        InitListExpr *IList, QualType DeclType, unsigned &Index,
320                        InitListExpr *StructuredList,
321                        unsigned &StructuredIndex);
322   void CheckStructUnionTypes(const InitializedEntity &Entity,
323                              InitListExpr *IList, QualType DeclType,
324                              CXXRecordDecl::base_class_range Bases,
325                              RecordDecl::field_iterator Field,
326                              bool SubobjectIsDesignatorContext, unsigned &Index,
327                              InitListExpr *StructuredList,
328                              unsigned &StructuredIndex,
329                              bool TopLevelObject = false);
330   void CheckArrayType(const InitializedEntity &Entity,
331                       InitListExpr *IList, QualType &DeclType,
332                       llvm::APSInt elementIndex,
333                       bool SubobjectIsDesignatorContext, unsigned &Index,
334                       InitListExpr *StructuredList,
335                       unsigned &StructuredIndex);
336   bool CheckDesignatedInitializer(const InitializedEntity &Entity,
337                                   InitListExpr *IList, DesignatedInitExpr *DIE,
338                                   unsigned DesigIdx,
339                                   QualType &CurrentObjectType,
340                                   RecordDecl::field_iterator *NextField,
341                                   llvm::APSInt *NextElementIndex,
342                                   unsigned &Index,
343                                   InitListExpr *StructuredList,
344                                   unsigned &StructuredIndex,
345                                   bool FinishSubobjectInit,
346                                   bool TopLevelObject);
347   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
348                                            QualType CurrentObjectType,
349                                            InitListExpr *StructuredList,
350                                            unsigned StructuredIndex,
351                                            SourceRange InitRange,
352                                            bool IsFullyOverwritten = false);
353   void UpdateStructuredListElement(InitListExpr *StructuredList,
354                                    unsigned &StructuredIndex,
355                                    Expr *expr);
356   int numArrayElements(QualType DeclType);
357   int numStructUnionElements(QualType DeclType);
358 
359   static ExprResult PerformEmptyInit(Sema &SemaRef,
360                                      SourceLocation Loc,
361                                      const InitializedEntity &Entity,
362                                      bool VerifyOnly,
363                                      bool TreatUnavailableAsInvalid);
364 
365   // Explanation on the "FillWithNoInit" mode:
366   //
367   // Assume we have the following definitions (Case#1):
368   // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
369   // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
370   //
371   // l.lp.x[1][0..1] should not be filled with implicit initializers because the
372   // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
373   //
374   // But if we have (Case#2):
375   // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
376   //
377   // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
378   // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
379   //
380   // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
381   // in the InitListExpr, the "holes" in Case#1 are filled not with empty
382   // initializers but with special "NoInitExpr" place holders, which tells the
383   // CodeGen not to generate any initializers for these parts.
384   void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
385                               const InitializedEntity &ParentEntity,
386                               InitListExpr *ILE, bool &RequiresSecondPass,
387                               bool FillWithNoInit);
388   void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
389                                const InitializedEntity &ParentEntity,
390                                InitListExpr *ILE, bool &RequiresSecondPass,
391                                bool FillWithNoInit = false);
392   void FillInEmptyInitializations(const InitializedEntity &Entity,
393                                   InitListExpr *ILE, bool &RequiresSecondPass,
394                                   InitListExpr *OuterILE, unsigned OuterIndex,
395                                   bool FillWithNoInit = false);
396   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
397                               Expr *InitExpr, FieldDecl *Field,
398                               bool TopLevelObject);
399   void CheckEmptyInitializable(const InitializedEntity &Entity,
400                                SourceLocation Loc);
401 
402 public:
403   InitListChecker(Sema &S, const InitializedEntity &Entity,
404                   InitListExpr *IL, QualType &T, bool VerifyOnly,
405                   bool TreatUnavailableAsInvalid);
406   bool HadError() { return hadError; }
407 
408   // Retrieves the fully-structured initializer list used for
409   // semantic analysis and code generation.
410   InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
411 };
412 
413 } // end anonymous namespace
414 
415 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
416                                              SourceLocation Loc,
417                                              const InitializedEntity &Entity,
418                                              bool VerifyOnly,
419                                              bool TreatUnavailableAsInvalid) {
420   InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
421                                                             true);
422   MultiExprArg SubInit;
423   Expr *InitExpr;
424   InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
425 
426   // C++ [dcl.init.aggr]p7:
427   //   If there are fewer initializer-clauses in the list than there are
428   //   members in the aggregate, then each member not explicitly initialized
429   //   ...
430   bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
431       Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
432   if (EmptyInitList) {
433     // C++1y / DR1070:
434     //   shall be initialized [...] from an empty initializer list.
435     //
436     // We apply the resolution of this DR to C++11 but not C++98, since C++98
437     // does not have useful semantics for initialization from an init list.
438     // We treat this as copy-initialization, because aggregate initialization
439     // always performs copy-initialization on its elements.
440     //
441     // Only do this if we're initializing a class type, to avoid filling in
442     // the initializer list where possible.
443     InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
444                    InitListExpr(SemaRef.Context, Loc, None, Loc);
445     InitExpr->setType(SemaRef.Context.VoidTy);
446     SubInit = InitExpr;
447     Kind = InitializationKind::CreateCopy(Loc, Loc);
448   } else {
449     // C++03:
450     //   shall be value-initialized.
451   }
452 
453   InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
454   // libstdc++4.6 marks the vector default constructor as explicit in
455   // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
456   // stlport does so too. Look for std::__debug for libstdc++, and for
457   // std:: for stlport.  This is effectively a compiler-side implementation of
458   // LWG2193.
459   if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
460           InitializationSequence::FK_ExplicitConstructor) {
461     OverloadCandidateSet::iterator Best;
462     OverloadingResult O =
463         InitSeq.getFailedCandidateSet()
464             .BestViableFunction(SemaRef, Kind.getLocation(), Best);
465     (void)O;
466     assert(O == OR_Success && "Inconsistent overload resolution");
467     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
468     CXXRecordDecl *R = CtorDecl->getParent();
469 
470     if (CtorDecl->getMinRequiredArguments() == 0 &&
471         CtorDecl->isExplicit() && R->getDeclName() &&
472         SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
473       bool IsInStd = false;
474       for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
475            ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
476         if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
477           IsInStd = true;
478       }
479 
480       if (IsInStd && llvm::StringSwitch<bool>(R->getName())
481               .Cases("basic_string", "deque", "forward_list", true)
482               .Cases("list", "map", "multimap", "multiset", true)
483               .Cases("priority_queue", "queue", "set", "stack", true)
484               .Cases("unordered_map", "unordered_set", "vector", true)
485               .Default(false)) {
486         InitSeq.InitializeFrom(
487             SemaRef, Entity,
488             InitializationKind::CreateValue(Loc, Loc, Loc, true),
489             MultiExprArg(), /*TopLevelOfInitList=*/false,
490             TreatUnavailableAsInvalid);
491         // Emit a warning for this.  System header warnings aren't shown
492         // by default, but people working on system headers should see it.
493         if (!VerifyOnly) {
494           SemaRef.Diag(CtorDecl->getLocation(),
495                        diag::warn_invalid_initializer_from_system_header);
496           if (Entity.getKind() == InitializedEntity::EK_Member)
497             SemaRef.Diag(Entity.getDecl()->getLocation(),
498                          diag::note_used_in_initialization_here);
499           else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
500             SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
501         }
502       }
503     }
504   }
505   if (!InitSeq) {
506     if (!VerifyOnly) {
507       InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
508       if (Entity.getKind() == InitializedEntity::EK_Member)
509         SemaRef.Diag(Entity.getDecl()->getLocation(),
510                      diag::note_in_omitted_aggregate_initializer)
511           << /*field*/1 << Entity.getDecl();
512       else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
513         bool IsTrailingArrayNewMember =
514             Entity.getParent() &&
515             Entity.getParent()->isVariableLengthArrayNew();
516         SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
517           << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
518           << Entity.getElementIndex();
519       }
520     }
521     return ExprError();
522   }
523 
524   return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
525                     : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
526 }
527 
528 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
529                                               SourceLocation Loc) {
530   assert(VerifyOnly &&
531          "CheckEmptyInitializable is only inteded for verification mode.");
532   if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
533                        TreatUnavailableAsInvalid).isInvalid())
534     hadError = true;
535 }
536 
537 void InitListChecker::FillInEmptyInitForBase(
538     unsigned Init, const CXXBaseSpecifier &Base,
539     const InitializedEntity &ParentEntity, InitListExpr *ILE,
540     bool &RequiresSecondPass, bool FillWithNoInit) {
541   assert(Init < ILE->getNumInits() && "should have been expanded");
542 
543   InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
544       SemaRef.Context, &Base, false, &ParentEntity);
545 
546   if (!ILE->getInit(Init)) {
547     ExprResult BaseInit =
548         FillWithNoInit
549             ? new (SemaRef.Context) NoInitExpr(Base.getType())
550             : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
551                                /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
552     if (BaseInit.isInvalid()) {
553       hadError = true;
554       return;
555     }
556 
557     ILE->setInit(Init, BaseInit.getAs<Expr>());
558   } else if (InitListExpr *InnerILE =
559                  dyn_cast<InitListExpr>(ILE->getInit(Init))) {
560     FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
561                                ILE, Init, FillWithNoInit);
562   } else if (DesignatedInitUpdateExpr *InnerDIUE =
563                dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
564     FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
565                                RequiresSecondPass, ILE, Init,
566                                /*FillWithNoInit =*/true);
567   }
568 }
569 
570 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
571                                         const InitializedEntity &ParentEntity,
572                                               InitListExpr *ILE,
573                                               bool &RequiresSecondPass,
574                                               bool FillWithNoInit) {
575   SourceLocation Loc = ILE->getEndLoc();
576   unsigned NumInits = ILE->getNumInits();
577   InitializedEntity MemberEntity
578     = InitializedEntity::InitializeMember(Field, &ParentEntity);
579 
580   if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
581     if (!RType->getDecl()->isUnion())
582       assert(Init < NumInits && "This ILE should have been expanded");
583 
584   if (Init >= NumInits || !ILE->getInit(Init)) {
585     if (FillWithNoInit) {
586       Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
587       if (Init < NumInits)
588         ILE->setInit(Init, Filler);
589       else
590         ILE->updateInit(SemaRef.Context, Init, Filler);
591       return;
592     }
593     // C++1y [dcl.init.aggr]p7:
594     //   If there are fewer initializer-clauses in the list than there are
595     //   members in the aggregate, then each member not explicitly initialized
596     //   shall be initialized from its brace-or-equal-initializer [...]
597     if (Field->hasInClassInitializer()) {
598       ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
599       if (DIE.isInvalid()) {
600         hadError = true;
601         return;
602       }
603       SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
604       if (Init < NumInits)
605         ILE->setInit(Init, DIE.get());
606       else {
607         ILE->updateInit(SemaRef.Context, Init, DIE.get());
608         RequiresSecondPass = true;
609       }
610       return;
611     }
612 
613     if (Field->getType()->isReferenceType()) {
614       // C++ [dcl.init.aggr]p9:
615       //   If an incomplete or empty initializer-list leaves a
616       //   member of reference type uninitialized, the program is
617       //   ill-formed.
618       SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
619         << Field->getType()
620         << ILE->getSyntacticForm()->getSourceRange();
621       SemaRef.Diag(Field->getLocation(),
622                    diag::note_uninit_reference_member);
623       hadError = true;
624       return;
625     }
626 
627     ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
628                                              /*VerifyOnly*/false,
629                                              TreatUnavailableAsInvalid);
630     if (MemberInit.isInvalid()) {
631       hadError = true;
632       return;
633     }
634 
635     if (hadError) {
636       // Do nothing
637     } else if (Init < NumInits) {
638       ILE->setInit(Init, MemberInit.getAs<Expr>());
639     } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
640       // Empty initialization requires a constructor call, so
641       // extend the initializer list to include the constructor
642       // call and make a note that we'll need to take another pass
643       // through the initializer list.
644       ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
645       RequiresSecondPass = true;
646     }
647   } else if (InitListExpr *InnerILE
648                = dyn_cast<InitListExpr>(ILE->getInit(Init)))
649     FillInEmptyInitializations(MemberEntity, InnerILE,
650                                RequiresSecondPass, ILE, Init, FillWithNoInit);
651   else if (DesignatedInitUpdateExpr *InnerDIUE
652                = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
653     FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
654                                RequiresSecondPass, ILE, Init,
655                                /*FillWithNoInit =*/true);
656 }
657 
658 /// Recursively replaces NULL values within the given initializer list
659 /// with expressions that perform value-initialization of the
660 /// appropriate type, and finish off the InitListExpr formation.
661 void
662 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
663                                             InitListExpr *ILE,
664                                             bool &RequiresSecondPass,
665                                             InitListExpr *OuterILE,
666                                             unsigned OuterIndex,
667                                             bool FillWithNoInit) {
668   assert((ILE->getType() != SemaRef.Context.VoidTy) &&
669          "Should not have void type");
670 
671   // If this is a nested initializer list, we might have changed its contents
672   // (and therefore some of its properties, such as instantiation-dependence)
673   // while filling it in. Inform the outer initializer list so that its state
674   // can be updated to match.
675   // FIXME: We should fully build the inner initializers before constructing
676   // the outer InitListExpr instead of mutating AST nodes after they have
677   // been used as subexpressions of other nodes.
678   struct UpdateOuterILEWithUpdatedInit {
679     InitListExpr *Outer;
680     unsigned OuterIndex;
681     ~UpdateOuterILEWithUpdatedInit() {
682       if (Outer)
683         Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
684     }
685   } UpdateOuterRAII = {OuterILE, OuterIndex};
686 
687   // A transparent ILE is not performing aggregate initialization and should
688   // not be filled in.
689   if (ILE->isTransparent())
690     return;
691 
692   if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
693     const RecordDecl *RDecl = RType->getDecl();
694     if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
695       FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
696                               Entity, ILE, RequiresSecondPass, FillWithNoInit);
697     else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
698              cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
699       for (auto *Field : RDecl->fields()) {
700         if (Field->hasInClassInitializer()) {
701           FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
702                                   FillWithNoInit);
703           break;
704         }
705       }
706     } else {
707       // The fields beyond ILE->getNumInits() are default initialized, so in
708       // order to leave them uninitialized, the ILE is expanded and the extra
709       // fields are then filled with NoInitExpr.
710       unsigned NumElems = numStructUnionElements(ILE->getType());
711       if (RDecl->hasFlexibleArrayMember())
712         ++NumElems;
713       if (ILE->getNumInits() < NumElems)
714         ILE->resizeInits(SemaRef.Context, NumElems);
715 
716       unsigned Init = 0;
717 
718       if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
719         for (auto &Base : CXXRD->bases()) {
720           if (hadError)
721             return;
722 
723           FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
724                                  FillWithNoInit);
725           ++Init;
726         }
727       }
728 
729       for (auto *Field : RDecl->fields()) {
730         if (Field->isUnnamedBitfield())
731           continue;
732 
733         if (hadError)
734           return;
735 
736         FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
737                                 FillWithNoInit);
738         if (hadError)
739           return;
740 
741         ++Init;
742 
743         // Only look at the first initialization of a union.
744         if (RDecl->isUnion())
745           break;
746       }
747     }
748 
749     return;
750   }
751 
752   QualType ElementType;
753 
754   InitializedEntity ElementEntity = Entity;
755   unsigned NumInits = ILE->getNumInits();
756   unsigned NumElements = NumInits;
757   if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
758     ElementType = AType->getElementType();
759     if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
760       NumElements = CAType->getSize().getZExtValue();
761     // For an array new with an unknown bound, ask for one additional element
762     // in order to populate the array filler.
763     if (Entity.isVariableLengthArrayNew())
764       ++NumElements;
765     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
766                                                          0, Entity);
767   } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
768     ElementType = VType->getElementType();
769     NumElements = VType->getNumElements();
770     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
771                                                          0, Entity);
772   } else
773     ElementType = ILE->getType();
774 
775   for (unsigned Init = 0; Init != NumElements; ++Init) {
776     if (hadError)
777       return;
778 
779     if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
780         ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
781       ElementEntity.setElementIndex(Init);
782 
783     if (Init >= NumInits && ILE->hasArrayFiller())
784       return;
785 
786     Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
787     if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
788       ILE->setInit(Init, ILE->getArrayFiller());
789     else if (!InitExpr && !ILE->hasArrayFiller()) {
790       Expr *Filler = nullptr;
791 
792       if (FillWithNoInit)
793         Filler = new (SemaRef.Context) NoInitExpr(ElementType);
794       else {
795         ExprResult ElementInit =
796             PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
797                              /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
798         if (ElementInit.isInvalid()) {
799           hadError = true;
800           return;
801         }
802 
803         Filler = ElementInit.getAs<Expr>();
804       }
805 
806       if (hadError) {
807         // Do nothing
808       } else if (Init < NumInits) {
809         // For arrays, just set the expression used for value-initialization
810         // of the "holes" in the array.
811         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
812           ILE->setArrayFiller(Filler);
813         else
814           ILE->setInit(Init, Filler);
815       } else {
816         // For arrays, just set the expression used for value-initialization
817         // of the rest of elements and exit.
818         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
819           ILE->setArrayFiller(Filler);
820           return;
821         }
822 
823         if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
824           // Empty initialization requires a constructor call, so
825           // extend the initializer list to include the constructor
826           // call and make a note that we'll need to take another pass
827           // through the initializer list.
828           ILE->updateInit(SemaRef.Context, Init, Filler);
829           RequiresSecondPass = true;
830         }
831       }
832     } else if (InitListExpr *InnerILE
833                  = dyn_cast_or_null<InitListExpr>(InitExpr))
834       FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
835                                  ILE, Init, FillWithNoInit);
836     else if (DesignatedInitUpdateExpr *InnerDIUE
837                  = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
838       FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
839                                  RequiresSecondPass, ILE, Init,
840                                  /*FillWithNoInit =*/true);
841   }
842 }
843 
844 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
845                                  InitListExpr *IL, QualType &T,
846                                  bool VerifyOnly,
847                                  bool TreatUnavailableAsInvalid)
848   : SemaRef(S), VerifyOnly(VerifyOnly),
849     TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
850   // FIXME: Check that IL isn't already the semantic form of some other
851   // InitListExpr. If it is, we'd create a broken AST.
852 
853   hadError = false;
854 
855   FullyStructuredList =
856       getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
857   CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
858                         /*TopLevelObject=*/true);
859 
860   if (!hadError && !VerifyOnly) {
861     bool RequiresSecondPass = false;
862     FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
863                                /*OuterILE=*/nullptr, /*OuterIndex=*/0);
864     if (RequiresSecondPass && !hadError)
865       FillInEmptyInitializations(Entity, FullyStructuredList,
866                                  RequiresSecondPass, nullptr, 0);
867   }
868 }
869 
870 int InitListChecker::numArrayElements(QualType DeclType) {
871   // FIXME: use a proper constant
872   int maxElements = 0x7FFFFFFF;
873   if (const ConstantArrayType *CAT =
874         SemaRef.Context.getAsConstantArrayType(DeclType)) {
875     maxElements = static_cast<int>(CAT->getSize().getZExtValue());
876   }
877   return maxElements;
878 }
879 
880 int InitListChecker::numStructUnionElements(QualType DeclType) {
881   RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
882   int InitializableMembers = 0;
883   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
884     InitializableMembers += CXXRD->getNumBases();
885   for (const auto *Field : structDecl->fields())
886     if (!Field->isUnnamedBitfield())
887       ++InitializableMembers;
888 
889   if (structDecl->isUnion())
890     return std::min(InitializableMembers, 1);
891   return InitializableMembers - structDecl->hasFlexibleArrayMember();
892 }
893 
894 /// Determine whether Entity is an entity for which it is idiomatic to elide
895 /// the braces in aggregate initialization.
896 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
897   // Recursive initialization of the one and only field within an aggregate
898   // class is considered idiomatic. This case arises in particular for
899   // initialization of std::array, where the C++ standard suggests the idiom of
900   //
901   //   std::array<T, N> arr = {1, 2, 3};
902   //
903   // (where std::array is an aggregate struct containing a single array field.
904 
905   // FIXME: Should aggregate initialization of a struct with a single
906   // base class and no members also suppress the warning?
907   if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
908     return false;
909 
910   auto *ParentRD =
911       Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
912   if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
913     if (CXXRD->getNumBases())
914       return false;
915 
916   auto FieldIt = ParentRD->field_begin();
917   assert(FieldIt != ParentRD->field_end() &&
918          "no fields but have initializer for member?");
919   return ++FieldIt == ParentRD->field_end();
920 }
921 
922 /// Check whether the range of the initializer \p ParentIList from element
923 /// \p Index onwards can be used to initialize an object of type \p T. Update
924 /// \p Index to indicate how many elements of the list were consumed.
925 ///
926 /// This also fills in \p StructuredList, from element \p StructuredIndex
927 /// onwards, with the fully-braced, desugared form of the initialization.
928 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
929                                             InitListExpr *ParentIList,
930                                             QualType T, unsigned &Index,
931                                             InitListExpr *StructuredList,
932                                             unsigned &StructuredIndex) {
933   int maxElements = 0;
934 
935   if (T->isArrayType())
936     maxElements = numArrayElements(T);
937   else if (T->isRecordType())
938     maxElements = numStructUnionElements(T);
939   else if (T->isVectorType())
940     maxElements = T->getAs<VectorType>()->getNumElements();
941   else
942     llvm_unreachable("CheckImplicitInitList(): Illegal type");
943 
944   if (maxElements == 0) {
945     if (!VerifyOnly)
946       SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
947                    diag::err_implicit_empty_initializer);
948     ++Index;
949     hadError = true;
950     return;
951   }
952 
953   // Build a structured initializer list corresponding to this subobject.
954   InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
955       ParentIList, Index, T, StructuredList, StructuredIndex,
956       SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
957                   ParentIList->getSourceRange().getEnd()));
958   unsigned StructuredSubobjectInitIndex = 0;
959 
960   // Check the element types and build the structural subobject.
961   unsigned StartIndex = Index;
962   CheckListElementTypes(Entity, ParentIList, T,
963                         /*SubobjectIsDesignatorContext=*/false, Index,
964                         StructuredSubobjectInitList,
965                         StructuredSubobjectInitIndex);
966 
967   if (!VerifyOnly) {
968     StructuredSubobjectInitList->setType(T);
969 
970     unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
971     // Update the structured sub-object initializer so that it's ending
972     // range corresponds with the end of the last initializer it used.
973     if (EndIndex < ParentIList->getNumInits() &&
974         ParentIList->getInit(EndIndex)) {
975       SourceLocation EndLoc
976         = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
977       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
978     }
979 
980     // Complain about missing braces.
981     if ((T->isArrayType() || T->isRecordType()) &&
982         !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
983         !isIdiomaticBraceElisionEntity(Entity)) {
984       SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
985                    diag::warn_missing_braces)
986           << StructuredSubobjectInitList->getSourceRange()
987           << FixItHint::CreateInsertion(
988                  StructuredSubobjectInitList->getBeginLoc(), "{")
989           << FixItHint::CreateInsertion(
990                  SemaRef.getLocForEndOfToken(
991                      StructuredSubobjectInitList->getEndLoc()),
992                  "}");
993     }
994 
995     // Warn if this type won't be an aggregate in future versions of C++.
996     auto *CXXRD = T->getAsCXXRecordDecl();
997     if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
998       SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
999                    diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1000           << StructuredSubobjectInitList->getSourceRange() << T;
1001     }
1002   }
1003 }
1004 
1005 /// Warn that \p Entity was of scalar type and was initialized by a
1006 /// single-element braced initializer list.
1007 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1008                                  SourceRange Braces) {
1009   // Don't warn during template instantiation. If the initialization was
1010   // non-dependent, we warned during the initial parse; otherwise, the
1011   // type might not be scalar in some uses of the template.
1012   if (S.inTemplateInstantiation())
1013     return;
1014 
1015   unsigned DiagID = 0;
1016 
1017   switch (Entity.getKind()) {
1018   case InitializedEntity::EK_VectorElement:
1019   case InitializedEntity::EK_ComplexElement:
1020   case InitializedEntity::EK_ArrayElement:
1021   case InitializedEntity::EK_Parameter:
1022   case InitializedEntity::EK_Parameter_CF_Audited:
1023   case InitializedEntity::EK_Result:
1024     // Extra braces here are suspicious.
1025     DiagID = diag::warn_braces_around_scalar_init;
1026     break;
1027 
1028   case InitializedEntity::EK_Member:
1029     // Warn on aggregate initialization but not on ctor init list or
1030     // default member initializer.
1031     if (Entity.getParent())
1032       DiagID = diag::warn_braces_around_scalar_init;
1033     break;
1034 
1035   case InitializedEntity::EK_Variable:
1036   case InitializedEntity::EK_LambdaCapture:
1037     // No warning, might be direct-list-initialization.
1038     // FIXME: Should we warn for copy-list-initialization in these cases?
1039     break;
1040 
1041   case InitializedEntity::EK_New:
1042   case InitializedEntity::EK_Temporary:
1043   case InitializedEntity::EK_CompoundLiteralInit:
1044     // No warning, braces are part of the syntax of the underlying construct.
1045     break;
1046 
1047   case InitializedEntity::EK_RelatedResult:
1048     // No warning, we already warned when initializing the result.
1049     break;
1050 
1051   case InitializedEntity::EK_Exception:
1052   case InitializedEntity::EK_Base:
1053   case InitializedEntity::EK_Delegating:
1054   case InitializedEntity::EK_BlockElement:
1055   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1056   case InitializedEntity::EK_Binding:
1057   case InitializedEntity::EK_StmtExprResult:
1058     llvm_unreachable("unexpected braced scalar init");
1059   }
1060 
1061   if (DiagID) {
1062     S.Diag(Braces.getBegin(), DiagID)
1063       << Braces
1064       << FixItHint::CreateRemoval(Braces.getBegin())
1065       << FixItHint::CreateRemoval(Braces.getEnd());
1066   }
1067 }
1068 
1069 /// Check whether the initializer \p IList (that was written with explicit
1070 /// braces) can be used to initialize an object of type \p T.
1071 ///
1072 /// This also fills in \p StructuredList with the fully-braced, desugared
1073 /// form of the initialization.
1074 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1075                                             InitListExpr *IList, QualType &T,
1076                                             InitListExpr *StructuredList,
1077                                             bool TopLevelObject) {
1078   if (!VerifyOnly) {
1079     SyntacticToSemantic[IList] = StructuredList;
1080     StructuredList->setSyntacticForm(IList);
1081   }
1082 
1083   unsigned Index = 0, StructuredIndex = 0;
1084   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1085                         Index, StructuredList, StructuredIndex, TopLevelObject);
1086   if (!VerifyOnly) {
1087     QualType ExprTy = T;
1088     if (!ExprTy->isArrayType())
1089       ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1090     IList->setType(ExprTy);
1091     StructuredList->setType(ExprTy);
1092   }
1093   if (hadError)
1094     return;
1095 
1096   if (Index < IList->getNumInits()) {
1097     // We have leftover initializers
1098     if (VerifyOnly) {
1099       if (SemaRef.getLangOpts().CPlusPlus ||
1100           (SemaRef.getLangOpts().OpenCL &&
1101            IList->getType()->isVectorType())) {
1102         hadError = true;
1103       }
1104       return;
1105     }
1106 
1107     if (StructuredIndex == 1 &&
1108         IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1109             SIF_None) {
1110       unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1111       if (SemaRef.getLangOpts().CPlusPlus) {
1112         DK = diag::err_excess_initializers_in_char_array_initializer;
1113         hadError = true;
1114       }
1115       // Special-case
1116       SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1117           << IList->getInit(Index)->getSourceRange();
1118     } else if (!T->isIncompleteType()) {
1119       // Don't complain for incomplete types, since we'll get an error
1120       // elsewhere
1121       QualType CurrentObjectType = StructuredList->getType();
1122       int initKind =
1123         CurrentObjectType->isArrayType()? 0 :
1124         CurrentObjectType->isVectorType()? 1 :
1125         CurrentObjectType->isScalarType()? 2 :
1126         CurrentObjectType->isUnionType()? 3 :
1127         4;
1128 
1129       unsigned DK = diag::ext_excess_initializers;
1130       if (SemaRef.getLangOpts().CPlusPlus) {
1131         DK = diag::err_excess_initializers;
1132         hadError = true;
1133       }
1134       if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1135         DK = diag::err_excess_initializers;
1136         hadError = true;
1137       }
1138 
1139       SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1140           << initKind << IList->getInit(Index)->getSourceRange();
1141     }
1142   }
1143 
1144   if (!VerifyOnly) {
1145     if (T->isScalarType() && IList->getNumInits() == 1 &&
1146         !isa<InitListExpr>(IList->getInit(0)))
1147       warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1148 
1149     // Warn if this is a class type that won't be an aggregate in future
1150     // versions of C++.
1151     auto *CXXRD = T->getAsCXXRecordDecl();
1152     if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1153       // Don't warn if there's an equivalent default constructor that would be
1154       // used instead.
1155       bool HasEquivCtor = false;
1156       if (IList->getNumInits() == 0) {
1157         auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1158         HasEquivCtor = CD && !CD->isDeleted();
1159       }
1160 
1161       if (!HasEquivCtor) {
1162         SemaRef.Diag(IList->getBeginLoc(),
1163                      diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1164             << IList->getSourceRange() << T;
1165       }
1166     }
1167   }
1168 }
1169 
1170 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1171                                             InitListExpr *IList,
1172                                             QualType &DeclType,
1173                                             bool SubobjectIsDesignatorContext,
1174                                             unsigned &Index,
1175                                             InitListExpr *StructuredList,
1176                                             unsigned &StructuredIndex,
1177                                             bool TopLevelObject) {
1178   if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1179     // Explicitly braced initializer for complex type can be real+imaginary
1180     // parts.
1181     CheckComplexType(Entity, IList, DeclType, Index,
1182                      StructuredList, StructuredIndex);
1183   } else if (DeclType->isScalarType()) {
1184     CheckScalarType(Entity, IList, DeclType, Index,
1185                     StructuredList, StructuredIndex);
1186   } else if (DeclType->isVectorType()) {
1187     CheckVectorType(Entity, IList, DeclType, Index,
1188                     StructuredList, StructuredIndex);
1189   } else if (DeclType->isRecordType()) {
1190     assert(DeclType->isAggregateType() &&
1191            "non-aggregate records should be handed in CheckSubElementType");
1192     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1193     auto Bases =
1194         CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1195                                         CXXRecordDecl::base_class_iterator());
1196     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1197       Bases = CXXRD->bases();
1198     CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1199                           SubobjectIsDesignatorContext, Index, StructuredList,
1200                           StructuredIndex, TopLevelObject);
1201   } else if (DeclType->isArrayType()) {
1202     llvm::APSInt Zero(
1203                     SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1204                     false);
1205     CheckArrayType(Entity, IList, DeclType, Zero,
1206                    SubobjectIsDesignatorContext, Index,
1207                    StructuredList, StructuredIndex);
1208   } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1209     // This type is invalid, issue a diagnostic.
1210     ++Index;
1211     if (!VerifyOnly)
1212       SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1213           << DeclType;
1214     hadError = true;
1215   } else if (DeclType->isReferenceType()) {
1216     CheckReferenceType(Entity, IList, DeclType, Index,
1217                        StructuredList, StructuredIndex);
1218   } else if (DeclType->isObjCObjectType()) {
1219     if (!VerifyOnly)
1220       SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1221     hadError = true;
1222   } else if (DeclType->isOCLIntelSubgroupAVCType()) {
1223     // Checks for scalar type are sufficient for these types too.
1224     CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1225                     StructuredIndex);
1226   } else {
1227     if (!VerifyOnly)
1228       SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1229           << DeclType;
1230     hadError = true;
1231   }
1232 }
1233 
1234 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1235                                           InitListExpr *IList,
1236                                           QualType ElemType,
1237                                           unsigned &Index,
1238                                           InitListExpr *StructuredList,
1239                                           unsigned &StructuredIndex) {
1240   Expr *expr = IList->getInit(Index);
1241 
1242   if (ElemType->isReferenceType())
1243     return CheckReferenceType(Entity, IList, ElemType, Index,
1244                               StructuredList, StructuredIndex);
1245 
1246   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1247     if (SubInitList->getNumInits() == 1 &&
1248         IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1249         SIF_None) {
1250       expr = SubInitList->getInit(0);
1251     } else if (!SemaRef.getLangOpts().CPlusPlus) {
1252       InitListExpr *InnerStructuredList
1253         = getStructuredSubobjectInit(IList, Index, ElemType,
1254                                      StructuredList, StructuredIndex,
1255                                      SubInitList->getSourceRange(), true);
1256       CheckExplicitInitList(Entity, SubInitList, ElemType,
1257                             InnerStructuredList);
1258 
1259       if (!hadError && !VerifyOnly) {
1260         bool RequiresSecondPass = false;
1261         FillInEmptyInitializations(Entity, InnerStructuredList,
1262                                    RequiresSecondPass, StructuredList,
1263                                    StructuredIndex);
1264         if (RequiresSecondPass && !hadError)
1265           FillInEmptyInitializations(Entity, InnerStructuredList,
1266                                      RequiresSecondPass, StructuredList,
1267                                      StructuredIndex);
1268       }
1269       ++StructuredIndex;
1270       ++Index;
1271       return;
1272     }
1273     // C++ initialization is handled later.
1274   } else if (isa<ImplicitValueInitExpr>(expr)) {
1275     // This happens during template instantiation when we see an InitListExpr
1276     // that we've already checked once.
1277     assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1278            "found implicit initialization for the wrong type");
1279     if (!VerifyOnly)
1280       UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1281     ++Index;
1282     return;
1283   }
1284 
1285   if (SemaRef.getLangOpts().CPlusPlus) {
1286     // C++ [dcl.init.aggr]p2:
1287     //   Each member is copy-initialized from the corresponding
1288     //   initializer-clause.
1289 
1290     // FIXME: Better EqualLoc?
1291     InitializationKind Kind =
1292         InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1293 
1294     // Vector elements can be initialized from other vectors in which case
1295     // we need initialization entity with a type of a vector (and not a vector
1296     // element!) initializing multiple vector elements.
1297     auto TmpEntity =
1298         (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1299             ? InitializedEntity::InitializeTemporary(ElemType)
1300             : Entity;
1301 
1302     InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1303                                /*TopLevelOfInitList*/ true);
1304 
1305     // C++14 [dcl.init.aggr]p13:
1306     //   If the assignment-expression can initialize a member, the member is
1307     //   initialized. Otherwise [...] brace elision is assumed
1308     //
1309     // Brace elision is never performed if the element is not an
1310     // assignment-expression.
1311     if (Seq || isa<InitListExpr>(expr)) {
1312       if (!VerifyOnly) {
1313         ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1314         if (Result.isInvalid())
1315           hadError = true;
1316 
1317         UpdateStructuredListElement(StructuredList, StructuredIndex,
1318                                     Result.getAs<Expr>());
1319       } else if (!Seq)
1320         hadError = true;
1321       ++Index;
1322       return;
1323     }
1324 
1325     // Fall through for subaggregate initialization
1326   } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1327     // FIXME: Need to handle atomic aggregate types with implicit init lists.
1328     return CheckScalarType(Entity, IList, ElemType, Index,
1329                            StructuredList, StructuredIndex);
1330   } else if (const ArrayType *arrayType =
1331                  SemaRef.Context.getAsArrayType(ElemType)) {
1332     // arrayType can be incomplete if we're initializing a flexible
1333     // array member.  There's nothing we can do with the completed
1334     // type here, though.
1335 
1336     if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1337       if (!VerifyOnly) {
1338         CheckStringInit(expr, ElemType, arrayType, SemaRef);
1339         UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1340       }
1341       ++Index;
1342       return;
1343     }
1344 
1345     // Fall through for subaggregate initialization.
1346 
1347   } else {
1348     assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1349             ElemType->isOpenCLSpecificType()) && "Unexpected type");
1350 
1351     // C99 6.7.8p13:
1352     //
1353     //   The initializer for a structure or union object that has
1354     //   automatic storage duration shall be either an initializer
1355     //   list as described below, or a single expression that has
1356     //   compatible structure or union type. In the latter case, the
1357     //   initial value of the object, including unnamed members, is
1358     //   that of the expression.
1359     ExprResult ExprRes = expr;
1360     if (SemaRef.CheckSingleAssignmentConstraints(
1361             ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1362       if (ExprRes.isInvalid())
1363         hadError = true;
1364       else {
1365         ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1366           if (ExprRes.isInvalid())
1367             hadError = true;
1368       }
1369       UpdateStructuredListElement(StructuredList, StructuredIndex,
1370                                   ExprRes.getAs<Expr>());
1371       ++Index;
1372       return;
1373     }
1374     ExprRes.get();
1375     // Fall through for subaggregate initialization
1376   }
1377 
1378   // C++ [dcl.init.aggr]p12:
1379   //
1380   //   [...] Otherwise, if the member is itself a non-empty
1381   //   subaggregate, brace elision is assumed and the initializer is
1382   //   considered for the initialization of the first member of
1383   //   the subaggregate.
1384   // OpenCL vector initializer is handled elsewhere.
1385   if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1386       ElemType->isAggregateType()) {
1387     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1388                           StructuredIndex);
1389     ++StructuredIndex;
1390   } else {
1391     if (!VerifyOnly) {
1392       // We cannot initialize this element, so let
1393       // PerformCopyInitialization produce the appropriate diagnostic.
1394       SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1395                                         /*TopLevelOfInitList=*/true);
1396     }
1397     hadError = true;
1398     ++Index;
1399     ++StructuredIndex;
1400   }
1401 }
1402 
1403 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1404                                        InitListExpr *IList, QualType DeclType,
1405                                        unsigned &Index,
1406                                        InitListExpr *StructuredList,
1407                                        unsigned &StructuredIndex) {
1408   assert(Index == 0 && "Index in explicit init list must be zero");
1409 
1410   // As an extension, clang supports complex initializers, which initialize
1411   // a complex number component-wise.  When an explicit initializer list for
1412   // a complex number contains two two initializers, this extension kicks in:
1413   // it exepcts the initializer list to contain two elements convertible to
1414   // the element type of the complex type. The first element initializes
1415   // the real part, and the second element intitializes the imaginary part.
1416 
1417   if (IList->getNumInits() != 2)
1418     return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1419                            StructuredIndex);
1420 
1421   // This is an extension in C.  (The builtin _Complex type does not exist
1422   // in the C++ standard.)
1423   if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1424     SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1425         << IList->getSourceRange();
1426 
1427   // Initialize the complex number.
1428   QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1429   InitializedEntity ElementEntity =
1430     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1431 
1432   for (unsigned i = 0; i < 2; ++i) {
1433     ElementEntity.setElementIndex(Index);
1434     CheckSubElementType(ElementEntity, IList, elementType, Index,
1435                         StructuredList, StructuredIndex);
1436   }
1437 }
1438 
1439 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1440                                       InitListExpr *IList, QualType DeclType,
1441                                       unsigned &Index,
1442                                       InitListExpr *StructuredList,
1443                                       unsigned &StructuredIndex) {
1444   if (Index >= IList->getNumInits()) {
1445     if (!VerifyOnly)
1446       SemaRef.Diag(IList->getBeginLoc(),
1447                    SemaRef.getLangOpts().CPlusPlus11
1448                        ? diag::warn_cxx98_compat_empty_scalar_initializer
1449                        : diag::err_empty_scalar_initializer)
1450           << IList->getSourceRange();
1451     hadError = !SemaRef.getLangOpts().CPlusPlus11;
1452     ++Index;
1453     ++StructuredIndex;
1454     return;
1455   }
1456 
1457   Expr *expr = IList->getInit(Index);
1458   if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1459     // FIXME: This is invalid, and accepting it causes overload resolution
1460     // to pick the wrong overload in some corner cases.
1461     if (!VerifyOnly)
1462       SemaRef.Diag(SubIList->getBeginLoc(),
1463                    diag::ext_many_braces_around_scalar_init)
1464           << SubIList->getSourceRange();
1465 
1466     CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1467                     StructuredIndex);
1468     return;
1469   } else if (isa<DesignatedInitExpr>(expr)) {
1470     if (!VerifyOnly)
1471       SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1472           << DeclType << expr->getSourceRange();
1473     hadError = true;
1474     ++Index;
1475     ++StructuredIndex;
1476     return;
1477   }
1478 
1479   if (VerifyOnly) {
1480     if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1481       hadError = true;
1482     ++Index;
1483     return;
1484   }
1485 
1486   ExprResult Result =
1487       SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1488                                         /*TopLevelOfInitList=*/true);
1489 
1490   Expr *ResultExpr = nullptr;
1491 
1492   if (Result.isInvalid())
1493     hadError = true; // types weren't compatible.
1494   else {
1495     ResultExpr = Result.getAs<Expr>();
1496 
1497     if (ResultExpr != expr) {
1498       // The type was promoted, update initializer list.
1499       IList->setInit(Index, ResultExpr);
1500     }
1501   }
1502   if (hadError)
1503     ++StructuredIndex;
1504   else
1505     UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1506   ++Index;
1507 }
1508 
1509 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1510                                          InitListExpr *IList, QualType DeclType,
1511                                          unsigned &Index,
1512                                          InitListExpr *StructuredList,
1513                                          unsigned &StructuredIndex) {
1514   if (Index >= IList->getNumInits()) {
1515     // FIXME: It would be wonderful if we could point at the actual member. In
1516     // general, it would be useful to pass location information down the stack,
1517     // so that we know the location (or decl) of the "current object" being
1518     // initialized.
1519     if (!VerifyOnly)
1520       SemaRef.Diag(IList->getBeginLoc(),
1521                    diag::err_init_reference_member_uninitialized)
1522           << DeclType << IList->getSourceRange();
1523     hadError = true;
1524     ++Index;
1525     ++StructuredIndex;
1526     return;
1527   }
1528 
1529   Expr *expr = IList->getInit(Index);
1530   if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1531     if (!VerifyOnly)
1532       SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1533           << DeclType << IList->getSourceRange();
1534     hadError = true;
1535     ++Index;
1536     ++StructuredIndex;
1537     return;
1538   }
1539 
1540   if (VerifyOnly) {
1541     if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1542       hadError = true;
1543     ++Index;
1544     return;
1545   }
1546 
1547   ExprResult Result =
1548       SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1549                                         /*TopLevelOfInitList=*/true);
1550 
1551   if (Result.isInvalid())
1552     hadError = true;
1553 
1554   expr = Result.getAs<Expr>();
1555   IList->setInit(Index, expr);
1556 
1557   if (hadError)
1558     ++StructuredIndex;
1559   else
1560     UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1561   ++Index;
1562 }
1563 
1564 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1565                                       InitListExpr *IList, QualType DeclType,
1566                                       unsigned &Index,
1567                                       InitListExpr *StructuredList,
1568                                       unsigned &StructuredIndex) {
1569   const VectorType *VT = DeclType->getAs<VectorType>();
1570   unsigned maxElements = VT->getNumElements();
1571   unsigned numEltsInit = 0;
1572   QualType elementType = VT->getElementType();
1573 
1574   if (Index >= IList->getNumInits()) {
1575     // Make sure the element type can be value-initialized.
1576     if (VerifyOnly)
1577       CheckEmptyInitializable(
1578           InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1579           IList->getEndLoc());
1580     return;
1581   }
1582 
1583   if (!SemaRef.getLangOpts().OpenCL) {
1584     // If the initializing element is a vector, try to copy-initialize
1585     // instead of breaking it apart (which is doomed to failure anyway).
1586     Expr *Init = IList->getInit(Index);
1587     if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1588       if (VerifyOnly) {
1589         if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1590           hadError = true;
1591         ++Index;
1592         return;
1593       }
1594 
1595       ExprResult Result =
1596           SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1597                                             /*TopLevelOfInitList=*/true);
1598 
1599       Expr *ResultExpr = nullptr;
1600       if (Result.isInvalid())
1601         hadError = true; // types weren't compatible.
1602       else {
1603         ResultExpr = Result.getAs<Expr>();
1604 
1605         if (ResultExpr != Init) {
1606           // The type was promoted, update initializer list.
1607           IList->setInit(Index, ResultExpr);
1608         }
1609       }
1610       if (hadError)
1611         ++StructuredIndex;
1612       else
1613         UpdateStructuredListElement(StructuredList, StructuredIndex,
1614                                     ResultExpr);
1615       ++Index;
1616       return;
1617     }
1618 
1619     InitializedEntity ElementEntity =
1620       InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1621 
1622     for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1623       // Don't attempt to go past the end of the init list
1624       if (Index >= IList->getNumInits()) {
1625         if (VerifyOnly)
1626           CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1627         break;
1628       }
1629 
1630       ElementEntity.setElementIndex(Index);
1631       CheckSubElementType(ElementEntity, IList, elementType, Index,
1632                           StructuredList, StructuredIndex);
1633     }
1634 
1635     if (VerifyOnly)
1636       return;
1637 
1638     bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1639     const VectorType *T = Entity.getType()->getAs<VectorType>();
1640     if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1641                         T->getVectorKind() == VectorType::NeonPolyVector)) {
1642       // The ability to use vector initializer lists is a GNU vector extension
1643       // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1644       // endian machines it works fine, however on big endian machines it
1645       // exhibits surprising behaviour:
1646       //
1647       //   uint32x2_t x = {42, 64};
1648       //   return vget_lane_u32(x, 0); // Will return 64.
1649       //
1650       // Because of this, explicitly call out that it is non-portable.
1651       //
1652       SemaRef.Diag(IList->getBeginLoc(),
1653                    diag::warn_neon_vector_initializer_non_portable);
1654 
1655       const char *typeCode;
1656       unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1657 
1658       if (elementType->isFloatingType())
1659         typeCode = "f";
1660       else if (elementType->isSignedIntegerType())
1661         typeCode = "s";
1662       else if (elementType->isUnsignedIntegerType())
1663         typeCode = "u";
1664       else
1665         llvm_unreachable("Invalid element type!");
1666 
1667       SemaRef.Diag(IList->getBeginLoc(),
1668                    SemaRef.Context.getTypeSize(VT) > 64
1669                        ? diag::note_neon_vector_initializer_non_portable_q
1670                        : diag::note_neon_vector_initializer_non_portable)
1671           << typeCode << typeSize;
1672     }
1673 
1674     return;
1675   }
1676 
1677   InitializedEntity ElementEntity =
1678     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1679 
1680   // OpenCL initializers allows vectors to be constructed from vectors.
1681   for (unsigned i = 0; i < maxElements; ++i) {
1682     // Don't attempt to go past the end of the init list
1683     if (Index >= IList->getNumInits())
1684       break;
1685 
1686     ElementEntity.setElementIndex(Index);
1687 
1688     QualType IType = IList->getInit(Index)->getType();
1689     if (!IType->isVectorType()) {
1690       CheckSubElementType(ElementEntity, IList, elementType, Index,
1691                           StructuredList, StructuredIndex);
1692       ++numEltsInit;
1693     } else {
1694       QualType VecType;
1695       const VectorType *IVT = IType->getAs<VectorType>();
1696       unsigned numIElts = IVT->getNumElements();
1697 
1698       if (IType->isExtVectorType())
1699         VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1700       else
1701         VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1702                                                 IVT->getVectorKind());
1703       CheckSubElementType(ElementEntity, IList, VecType, Index,
1704                           StructuredList, StructuredIndex);
1705       numEltsInit += numIElts;
1706     }
1707   }
1708 
1709   // OpenCL requires all elements to be initialized.
1710   if (numEltsInit != maxElements) {
1711     if (!VerifyOnly)
1712       SemaRef.Diag(IList->getBeginLoc(),
1713                    diag::err_vector_incorrect_num_initializers)
1714           << (numEltsInit < maxElements) << maxElements << numEltsInit;
1715     hadError = true;
1716   }
1717 }
1718 
1719 /// Check if the type of a class element has an accessible destructor, and marks
1720 /// it referenced. Returns true if we shouldn't form a reference to the
1721 /// destructor.
1722 ///
1723 /// Aggregate initialization requires a class element's destructor be
1724 /// accessible per 11.6.1 [dcl.init.aggr]:
1725 ///
1726 /// The destructor for each element of class type is potentially invoked
1727 /// (15.4 [class.dtor]) from the context where the aggregate initialization
1728 /// occurs.
1729 static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1730                                      Sema &SemaRef) {
1731   auto *CXXRD = ElementType->getAsCXXRecordDecl();
1732   if (!CXXRD)
1733     return false;
1734 
1735   CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1736   SemaRef.CheckDestructorAccess(Loc, Destructor,
1737                                 SemaRef.PDiag(diag::err_access_dtor_temp)
1738                                 << ElementType);
1739   SemaRef.MarkFunctionReferenced(Loc, Destructor);
1740   return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1741 }
1742 
1743 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1744                                      InitListExpr *IList, QualType &DeclType,
1745                                      llvm::APSInt elementIndex,
1746                                      bool SubobjectIsDesignatorContext,
1747                                      unsigned &Index,
1748                                      InitListExpr *StructuredList,
1749                                      unsigned &StructuredIndex) {
1750   const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1751 
1752   if (!VerifyOnly) {
1753     if (checkDestructorReference(arrayType->getElementType(),
1754                                  IList->getEndLoc(), SemaRef)) {
1755       hadError = true;
1756       return;
1757     }
1758   }
1759 
1760   // Check for the special-case of initializing an array with a string.
1761   if (Index < IList->getNumInits()) {
1762     if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1763         SIF_None) {
1764       // We place the string literal directly into the resulting
1765       // initializer list. This is the only place where the structure
1766       // of the structured initializer list doesn't match exactly,
1767       // because doing so would involve allocating one character
1768       // constant for each string.
1769       if (!VerifyOnly) {
1770         CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1771         UpdateStructuredListElement(StructuredList, StructuredIndex,
1772                                     IList->getInit(Index));
1773         StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1774       }
1775       ++Index;
1776       return;
1777     }
1778   }
1779   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1780     // Check for VLAs; in standard C it would be possible to check this
1781     // earlier, but I don't know where clang accepts VLAs (gcc accepts
1782     // them in all sorts of strange places).
1783     if (!VerifyOnly)
1784       SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1785                    diag::err_variable_object_no_init)
1786           << VAT->getSizeExpr()->getSourceRange();
1787     hadError = true;
1788     ++Index;
1789     ++StructuredIndex;
1790     return;
1791   }
1792 
1793   // We might know the maximum number of elements in advance.
1794   llvm::APSInt maxElements(elementIndex.getBitWidth(),
1795                            elementIndex.isUnsigned());
1796   bool maxElementsKnown = false;
1797   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1798     maxElements = CAT->getSize();
1799     elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1800     elementIndex.setIsUnsigned(maxElements.isUnsigned());
1801     maxElementsKnown = true;
1802   }
1803 
1804   QualType elementType = arrayType->getElementType();
1805   while (Index < IList->getNumInits()) {
1806     Expr *Init = IList->getInit(Index);
1807     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1808       // If we're not the subobject that matches up with the '{' for
1809       // the designator, we shouldn't be handling the
1810       // designator. Return immediately.
1811       if (!SubobjectIsDesignatorContext)
1812         return;
1813 
1814       // Handle this designated initializer. elementIndex will be
1815       // updated to be the next array element we'll initialize.
1816       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1817                                      DeclType, nullptr, &elementIndex, Index,
1818                                      StructuredList, StructuredIndex, true,
1819                                      false)) {
1820         hadError = true;
1821         continue;
1822       }
1823 
1824       if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1825         maxElements = maxElements.extend(elementIndex.getBitWidth());
1826       else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1827         elementIndex = elementIndex.extend(maxElements.getBitWidth());
1828       elementIndex.setIsUnsigned(maxElements.isUnsigned());
1829 
1830       // If the array is of incomplete type, keep track of the number of
1831       // elements in the initializer.
1832       if (!maxElementsKnown && elementIndex > maxElements)
1833         maxElements = elementIndex;
1834 
1835       continue;
1836     }
1837 
1838     // If we know the maximum number of elements, and we've already
1839     // hit it, stop consuming elements in the initializer list.
1840     if (maxElementsKnown && elementIndex == maxElements)
1841       break;
1842 
1843     InitializedEntity ElementEntity =
1844       InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1845                                            Entity);
1846     // Check this element.
1847     CheckSubElementType(ElementEntity, IList, elementType, Index,
1848                         StructuredList, StructuredIndex);
1849     ++elementIndex;
1850 
1851     // If the array is of incomplete type, keep track of the number of
1852     // elements in the initializer.
1853     if (!maxElementsKnown && elementIndex > maxElements)
1854       maxElements = elementIndex;
1855   }
1856   if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1857     // If this is an incomplete array type, the actual type needs to
1858     // be calculated here.
1859     llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1860     if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1861       // Sizing an array implicitly to zero is not allowed by ISO C,
1862       // but is supported by GNU.
1863       SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
1864     }
1865 
1866     DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1867                                                      ArrayType::Normal, 0);
1868   }
1869   if (!hadError && VerifyOnly) {
1870     // If there are any members of the array that get value-initialized, check
1871     // that is possible. That happens if we know the bound and don't have
1872     // enough elements, or if we're performing an array new with an unknown
1873     // bound.
1874     // FIXME: This needs to detect holes left by designated initializers too.
1875     if ((maxElementsKnown && elementIndex < maxElements) ||
1876         Entity.isVariableLengthArrayNew())
1877       CheckEmptyInitializable(
1878           InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1879           IList->getEndLoc());
1880   }
1881 }
1882 
1883 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1884                                              Expr *InitExpr,
1885                                              FieldDecl *Field,
1886                                              bool TopLevelObject) {
1887   // Handle GNU flexible array initializers.
1888   unsigned FlexArrayDiag;
1889   if (isa<InitListExpr>(InitExpr) &&
1890       cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1891     // Empty flexible array init always allowed as an extension
1892     FlexArrayDiag = diag::ext_flexible_array_init;
1893   } else if (SemaRef.getLangOpts().CPlusPlus) {
1894     // Disallow flexible array init in C++; it is not required for gcc
1895     // compatibility, and it needs work to IRGen correctly in general.
1896     FlexArrayDiag = diag::err_flexible_array_init;
1897   } else if (!TopLevelObject) {
1898     // Disallow flexible array init on non-top-level object
1899     FlexArrayDiag = diag::err_flexible_array_init;
1900   } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1901     // Disallow flexible array init on anything which is not a variable.
1902     FlexArrayDiag = diag::err_flexible_array_init;
1903   } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1904     // Disallow flexible array init on local variables.
1905     FlexArrayDiag = diag::err_flexible_array_init;
1906   } else {
1907     // Allow other cases.
1908     FlexArrayDiag = diag::ext_flexible_array_init;
1909   }
1910 
1911   if (!VerifyOnly) {
1912     SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1913         << InitExpr->getBeginLoc();
1914     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1915       << Field;
1916   }
1917 
1918   return FlexArrayDiag != diag::ext_flexible_array_init;
1919 }
1920 
1921 void InitListChecker::CheckStructUnionTypes(
1922     const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1923     CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1924     bool SubobjectIsDesignatorContext, unsigned &Index,
1925     InitListExpr *StructuredList, unsigned &StructuredIndex,
1926     bool TopLevelObject) {
1927   RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1928 
1929   // If the record is invalid, some of it's members are invalid. To avoid
1930   // confusion, we forgo checking the intializer for the entire record.
1931   if (structDecl->isInvalidDecl()) {
1932     // Assume it was supposed to consume a single initializer.
1933     ++Index;
1934     hadError = true;
1935     return;
1936   }
1937 
1938   if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1939     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1940 
1941     if (!VerifyOnly)
1942       for (FieldDecl *FD : RD->fields()) {
1943         QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
1944         if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
1945           hadError = true;
1946           return;
1947         }
1948       }
1949 
1950     // If there's a default initializer, use it.
1951     if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1952       if (VerifyOnly)
1953         return;
1954       for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1955            Field != FieldEnd; ++Field) {
1956         if (Field->hasInClassInitializer()) {
1957           StructuredList->setInitializedFieldInUnion(*Field);
1958           // FIXME: Actually build a CXXDefaultInitExpr?
1959           return;
1960         }
1961       }
1962     }
1963 
1964     // Value-initialize the first member of the union that isn't an unnamed
1965     // bitfield.
1966     for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1967          Field != FieldEnd; ++Field) {
1968       if (!Field->isUnnamedBitfield()) {
1969         if (VerifyOnly)
1970           CheckEmptyInitializable(
1971               InitializedEntity::InitializeMember(*Field, &Entity),
1972               IList->getEndLoc());
1973         else
1974           StructuredList->setInitializedFieldInUnion(*Field);
1975         break;
1976       }
1977     }
1978     return;
1979   }
1980 
1981   bool InitializedSomething = false;
1982 
1983   // If we have any base classes, they are initialized prior to the fields.
1984   for (auto &Base : Bases) {
1985     Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1986 
1987     // Designated inits always initialize fields, so if we see one, all
1988     // remaining base classes have no explicit initializer.
1989     if (Init && isa<DesignatedInitExpr>(Init))
1990       Init = nullptr;
1991 
1992     SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
1993     InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1994         SemaRef.Context, &Base, false, &Entity);
1995     if (Init) {
1996       CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1997                           StructuredList, StructuredIndex);
1998       InitializedSomething = true;
1999     } else if (VerifyOnly) {
2000       CheckEmptyInitializable(BaseEntity, InitLoc);
2001     }
2002 
2003     if (!VerifyOnly)
2004       if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2005         hadError = true;
2006         return;
2007       }
2008   }
2009 
2010   // If structDecl is a forward declaration, this loop won't do
2011   // anything except look at designated initializers; That's okay,
2012   // because an error should get printed out elsewhere. It might be
2013   // worthwhile to skip over the rest of the initializer, though.
2014   RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
2015   RecordDecl::field_iterator FieldEnd = RD->field_end();
2016   bool CheckForMissingFields =
2017     !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2018   bool HasDesignatedInit = false;
2019 
2020   while (Index < IList->getNumInits()) {
2021     Expr *Init = IList->getInit(Index);
2022     SourceLocation InitLoc = Init->getBeginLoc();
2023 
2024     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2025       // If we're not the subobject that matches up with the '{' for
2026       // the designator, we shouldn't be handling the
2027       // designator. Return immediately.
2028       if (!SubobjectIsDesignatorContext)
2029         return;
2030 
2031       HasDesignatedInit = true;
2032 
2033       // Handle this designated initializer. Field will be updated to
2034       // the next field that we'll be initializing.
2035       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2036                                      DeclType, &Field, nullptr, Index,
2037                                      StructuredList, StructuredIndex,
2038                                      true, TopLevelObject))
2039         hadError = true;
2040       else if (!VerifyOnly) {
2041         // Find the field named by the designated initializer.
2042         RecordDecl::field_iterator F = RD->field_begin();
2043         while (std::next(F) != Field)
2044           ++F;
2045         QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2046         if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2047           hadError = true;
2048           return;
2049         }
2050       }
2051 
2052       InitializedSomething = true;
2053 
2054       // Disable check for missing fields when designators are used.
2055       // This matches gcc behaviour.
2056       CheckForMissingFields = false;
2057       continue;
2058     }
2059 
2060     if (Field == FieldEnd) {
2061       // We've run out of fields. We're done.
2062       break;
2063     }
2064 
2065     // We've already initialized a member of a union. We're done.
2066     if (InitializedSomething && DeclType->isUnionType())
2067       break;
2068 
2069     // If we've hit the flexible array member at the end, we're done.
2070     if (Field->getType()->isIncompleteArrayType())
2071       break;
2072 
2073     if (Field->isUnnamedBitfield()) {
2074       // Don't initialize unnamed bitfields, e.g. "int : 20;"
2075       ++Field;
2076       continue;
2077     }
2078 
2079     // Make sure we can use this declaration.
2080     bool InvalidUse;
2081     if (VerifyOnly)
2082       InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2083     else
2084       InvalidUse = SemaRef.DiagnoseUseOfDecl(
2085           *Field, IList->getInit(Index)->getBeginLoc());
2086     if (InvalidUse) {
2087       ++Index;
2088       ++Field;
2089       hadError = true;
2090       continue;
2091     }
2092 
2093     if (!VerifyOnly) {
2094       QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2095       if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2096         hadError = true;
2097         return;
2098       }
2099     }
2100 
2101     InitializedEntity MemberEntity =
2102       InitializedEntity::InitializeMember(*Field, &Entity);
2103     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2104                         StructuredList, StructuredIndex);
2105     InitializedSomething = true;
2106 
2107     if (DeclType->isUnionType() && !VerifyOnly) {
2108       // Initialize the first field within the union.
2109       StructuredList->setInitializedFieldInUnion(*Field);
2110     }
2111 
2112     ++Field;
2113   }
2114 
2115   // Emit warnings for missing struct field initializers.
2116   if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2117       Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2118       !DeclType->isUnionType()) {
2119     // It is possible we have one or more unnamed bitfields remaining.
2120     // Find first (if any) named field and emit warning.
2121     for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2122          it != end; ++it) {
2123       if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2124         SemaRef.Diag(IList->getSourceRange().getEnd(),
2125                      diag::warn_missing_field_initializers) << *it;
2126         break;
2127       }
2128     }
2129   }
2130 
2131   // Check that any remaining fields can be value-initialized.
2132   if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2133       !Field->getType()->isIncompleteArrayType()) {
2134     // FIXME: Should check for holes left by designated initializers too.
2135     for (; Field != FieldEnd && !hadError; ++Field) {
2136       if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2137         CheckEmptyInitializable(
2138             InitializedEntity::InitializeMember(*Field, &Entity),
2139             IList->getEndLoc());
2140     }
2141   }
2142 
2143   // Check that the types of the remaining fields have accessible destructors.
2144   if (!VerifyOnly) {
2145     // If the initializer expression has a designated initializer, check the
2146     // elements for which a designated initializer is not provided too.
2147     RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2148                                                      : Field;
2149     for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2150       QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2151       if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2152         hadError = true;
2153         return;
2154       }
2155     }
2156   }
2157 
2158   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2159       Index >= IList->getNumInits())
2160     return;
2161 
2162   if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2163                              TopLevelObject)) {
2164     hadError = true;
2165     ++Index;
2166     return;
2167   }
2168 
2169   InitializedEntity MemberEntity =
2170     InitializedEntity::InitializeMember(*Field, &Entity);
2171 
2172   if (isa<InitListExpr>(IList->getInit(Index)))
2173     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2174                         StructuredList, StructuredIndex);
2175   else
2176     CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2177                           StructuredList, StructuredIndex);
2178 }
2179 
2180 /// Expand a field designator that refers to a member of an
2181 /// anonymous struct or union into a series of field designators that
2182 /// refers to the field within the appropriate subobject.
2183 ///
2184 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2185                                            DesignatedInitExpr *DIE,
2186                                            unsigned DesigIdx,
2187                                            IndirectFieldDecl *IndirectField) {
2188   typedef DesignatedInitExpr::Designator Designator;
2189 
2190   // Build the replacement designators.
2191   SmallVector<Designator, 4> Replacements;
2192   for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2193        PE = IndirectField->chain_end(); PI != PE; ++PI) {
2194     if (PI + 1 == PE)
2195       Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2196                                     DIE->getDesignator(DesigIdx)->getDotLoc(),
2197                                 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2198     else
2199       Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2200                                         SourceLocation(), SourceLocation()));
2201     assert(isa<FieldDecl>(*PI));
2202     Replacements.back().setField(cast<FieldDecl>(*PI));
2203   }
2204 
2205   // Expand the current designator into the set of replacement
2206   // designators, so we have a full subobject path down to where the
2207   // member of the anonymous struct/union is actually stored.
2208   DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2209                         &Replacements[0] + Replacements.size());
2210 }
2211 
2212 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2213                                                    DesignatedInitExpr *DIE) {
2214   unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2215   SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2216   for (unsigned I = 0; I < NumIndexExprs; ++I)
2217     IndexExprs[I] = DIE->getSubExpr(I + 1);
2218   return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2219                                     IndexExprs,
2220                                     DIE->getEqualOrColonLoc(),
2221                                     DIE->usesGNUSyntax(), DIE->getInit());
2222 }
2223 
2224 namespace {
2225 
2226 // Callback to only accept typo corrections that are for field members of
2227 // the given struct or union.
2228 class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2229  public:
2230   explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2231       : Record(RD) {}
2232 
2233   bool ValidateCandidate(const TypoCorrection &candidate) override {
2234     FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2235     return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2236   }
2237 
2238   std::unique_ptr<CorrectionCandidateCallback> clone() override {
2239     return std::make_unique<FieldInitializerValidatorCCC>(*this);
2240   }
2241 
2242  private:
2243   RecordDecl *Record;
2244 };
2245 
2246 } // end anonymous namespace
2247 
2248 /// Check the well-formedness of a C99 designated initializer.
2249 ///
2250 /// Determines whether the designated initializer @p DIE, which
2251 /// resides at the given @p Index within the initializer list @p
2252 /// IList, is well-formed for a current object of type @p DeclType
2253 /// (C99 6.7.8). The actual subobject that this designator refers to
2254 /// within the current subobject is returned in either
2255 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2256 ///
2257 /// @param IList  The initializer list in which this designated
2258 /// initializer occurs.
2259 ///
2260 /// @param DIE The designated initializer expression.
2261 ///
2262 /// @param DesigIdx  The index of the current designator.
2263 ///
2264 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2265 /// into which the designation in @p DIE should refer.
2266 ///
2267 /// @param NextField  If non-NULL and the first designator in @p DIE is
2268 /// a field, this will be set to the field declaration corresponding
2269 /// to the field named by the designator.
2270 ///
2271 /// @param NextElementIndex  If non-NULL and the first designator in @p
2272 /// DIE is an array designator or GNU array-range designator, this
2273 /// will be set to the last index initialized by this designator.
2274 ///
2275 /// @param Index  Index into @p IList where the designated initializer
2276 /// @p DIE occurs.
2277 ///
2278 /// @param StructuredList  The initializer list expression that
2279 /// describes all of the subobject initializers in the order they'll
2280 /// actually be initialized.
2281 ///
2282 /// @returns true if there was an error, false otherwise.
2283 bool
2284 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2285                                             InitListExpr *IList,
2286                                             DesignatedInitExpr *DIE,
2287                                             unsigned DesigIdx,
2288                                             QualType &CurrentObjectType,
2289                                           RecordDecl::field_iterator *NextField,
2290                                             llvm::APSInt *NextElementIndex,
2291                                             unsigned &Index,
2292                                             InitListExpr *StructuredList,
2293                                             unsigned &StructuredIndex,
2294                                             bool FinishSubobjectInit,
2295                                             bool TopLevelObject) {
2296   if (DesigIdx == DIE->size()) {
2297     // Check the actual initialization for the designated object type.
2298     bool prevHadError = hadError;
2299 
2300     // Temporarily remove the designator expression from the
2301     // initializer list that the child calls see, so that we don't try
2302     // to re-process the designator.
2303     unsigned OldIndex = Index;
2304     IList->setInit(OldIndex, DIE->getInit());
2305 
2306     CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2307                         StructuredList, StructuredIndex);
2308 
2309     // Restore the designated initializer expression in the syntactic
2310     // form of the initializer list.
2311     if (IList->getInit(OldIndex) != DIE->getInit())
2312       DIE->setInit(IList->getInit(OldIndex));
2313     IList->setInit(OldIndex, DIE);
2314 
2315     return hadError && !prevHadError;
2316   }
2317 
2318   DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2319   bool IsFirstDesignator = (DesigIdx == 0);
2320   if (!VerifyOnly) {
2321     assert((IsFirstDesignator || StructuredList) &&
2322            "Need a non-designated initializer list to start from");
2323 
2324     // Determine the structural initializer list that corresponds to the
2325     // current subobject.
2326     if (IsFirstDesignator)
2327       StructuredList = SyntacticToSemantic.lookup(IList);
2328     else {
2329       Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2330           StructuredList->getInit(StructuredIndex) : nullptr;
2331       if (!ExistingInit && StructuredList->hasArrayFiller())
2332         ExistingInit = StructuredList->getArrayFiller();
2333 
2334       if (!ExistingInit)
2335         StructuredList = getStructuredSubobjectInit(
2336             IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2337             SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2338       else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2339         StructuredList = Result;
2340       else {
2341         if (DesignatedInitUpdateExpr *E =
2342                 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2343           StructuredList = E->getUpdater();
2344         else {
2345           DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2346               DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2347                                        ExistingInit, DIE->getEndLoc());
2348           StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2349           StructuredList = DIUE->getUpdater();
2350         }
2351 
2352         // We need to check on source range validity because the previous
2353         // initializer does not have to be an explicit initializer. e.g.,
2354         //
2355         // struct P { int a, b; };
2356         // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2357         //
2358         // There is an overwrite taking place because the first braced initializer
2359         // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2360         if (ExistingInit->getSourceRange().isValid()) {
2361           // We are creating an initializer list that initializes the
2362           // subobjects of the current object, but there was already an
2363           // initialization that completely initialized the current
2364           // subobject, e.g., by a compound literal:
2365           //
2366           // struct X { int a, b; };
2367           // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2368           //
2369           // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2370           // designated initializer re-initializes the whole
2371           // subobject [0], overwriting previous initializers.
2372           SemaRef.Diag(D->getBeginLoc(),
2373                        diag::warn_subobject_initializer_overrides)
2374               << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
2375 
2376           SemaRef.Diag(ExistingInit->getBeginLoc(),
2377                        diag::note_previous_initializer)
2378               << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2379         }
2380       }
2381     }
2382     assert(StructuredList && "Expected a structured initializer list");
2383   }
2384 
2385   if (D->isFieldDesignator()) {
2386     // C99 6.7.8p7:
2387     //
2388     //   If a designator has the form
2389     //
2390     //      . identifier
2391     //
2392     //   then the current object (defined below) shall have
2393     //   structure or union type and the identifier shall be the
2394     //   name of a member of that type.
2395     const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2396     if (!RT) {
2397       SourceLocation Loc = D->getDotLoc();
2398       if (Loc.isInvalid())
2399         Loc = D->getFieldLoc();
2400       if (!VerifyOnly)
2401         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2402           << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2403       ++Index;
2404       return true;
2405     }
2406 
2407     FieldDecl *KnownField = D->getField();
2408     if (!KnownField) {
2409       IdentifierInfo *FieldName = D->getFieldName();
2410       DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2411       for (NamedDecl *ND : Lookup) {
2412         if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2413           KnownField = FD;
2414           break;
2415         }
2416         if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2417           // In verify mode, don't modify the original.
2418           if (VerifyOnly)
2419             DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2420           ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2421           D = DIE->getDesignator(DesigIdx);
2422           KnownField = cast<FieldDecl>(*IFD->chain_begin());
2423           break;
2424         }
2425       }
2426       if (!KnownField) {
2427         if (VerifyOnly) {
2428           ++Index;
2429           return true;  // No typo correction when just trying this out.
2430         }
2431 
2432         // Name lookup found something, but it wasn't a field.
2433         if (!Lookup.empty()) {
2434           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2435             << FieldName;
2436           SemaRef.Diag(Lookup.front()->getLocation(),
2437                        diag::note_field_designator_found);
2438           ++Index;
2439           return true;
2440         }
2441 
2442         // Name lookup didn't find anything.
2443         // Determine whether this was a typo for another field name.
2444         FieldInitializerValidatorCCC CCC(RT->getDecl());
2445         if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2446                 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2447                 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2448                 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2449           SemaRef.diagnoseTypo(
2450               Corrected,
2451               SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2452                 << FieldName << CurrentObjectType);
2453           KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2454           hadError = true;
2455         } else {
2456           // Typo correction didn't find anything.
2457           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2458             << FieldName << CurrentObjectType;
2459           ++Index;
2460           return true;
2461         }
2462       }
2463     }
2464 
2465     unsigned FieldIndex = 0;
2466 
2467     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2468       FieldIndex = CXXRD->getNumBases();
2469 
2470     for (auto *FI : RT->getDecl()->fields()) {
2471       if (FI->isUnnamedBitfield())
2472         continue;
2473       if (declaresSameEntity(KnownField, FI)) {
2474         KnownField = FI;
2475         break;
2476       }
2477       ++FieldIndex;
2478     }
2479 
2480     RecordDecl::field_iterator Field =
2481         RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2482 
2483     // All of the fields of a union are located at the same place in
2484     // the initializer list.
2485     if (RT->getDecl()->isUnion()) {
2486       FieldIndex = 0;
2487       if (!VerifyOnly) {
2488         FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2489         if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2490           assert(StructuredList->getNumInits() == 1
2491                  && "A union should never have more than one initializer!");
2492 
2493           Expr *ExistingInit = StructuredList->getInit(0);
2494           if (ExistingInit) {
2495             // We're about to throw away an initializer, emit warning.
2496             SemaRef.Diag(D->getFieldLoc(),
2497                          diag::warn_initializer_overrides)
2498               << D->getSourceRange();
2499             SemaRef.Diag(ExistingInit->getBeginLoc(),
2500                          diag::note_previous_initializer)
2501                 << /*FIXME:has side effects=*/0
2502                 << ExistingInit->getSourceRange();
2503           }
2504 
2505           // remove existing initializer
2506           StructuredList->resizeInits(SemaRef.Context, 0);
2507           StructuredList->setInitializedFieldInUnion(nullptr);
2508         }
2509 
2510         StructuredList->setInitializedFieldInUnion(*Field);
2511       }
2512     }
2513 
2514     // Make sure we can use this declaration.
2515     bool InvalidUse;
2516     if (VerifyOnly)
2517       InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2518     else
2519       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2520     if (InvalidUse) {
2521       ++Index;
2522       return true;
2523     }
2524 
2525     if (!VerifyOnly) {
2526       // Update the designator with the field declaration.
2527       D->setField(*Field);
2528 
2529       // Make sure that our non-designated initializer list has space
2530       // for a subobject corresponding to this field.
2531       if (FieldIndex >= StructuredList->getNumInits())
2532         StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2533     }
2534 
2535     // This designator names a flexible array member.
2536     if (Field->getType()->isIncompleteArrayType()) {
2537       bool Invalid = false;
2538       if ((DesigIdx + 1) != DIE->size()) {
2539         // We can't designate an object within the flexible array
2540         // member (because GCC doesn't allow it).
2541         if (!VerifyOnly) {
2542           DesignatedInitExpr::Designator *NextD
2543             = DIE->getDesignator(DesigIdx + 1);
2544           SemaRef.Diag(NextD->getBeginLoc(),
2545                        diag::err_designator_into_flexible_array_member)
2546               << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2547           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2548             << *Field;
2549         }
2550         Invalid = true;
2551       }
2552 
2553       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2554           !isa<StringLiteral>(DIE->getInit())) {
2555         // The initializer is not an initializer list.
2556         if (!VerifyOnly) {
2557           SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2558                        diag::err_flexible_array_init_needs_braces)
2559               << DIE->getInit()->getSourceRange();
2560           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2561             << *Field;
2562         }
2563         Invalid = true;
2564       }
2565 
2566       // Check GNU flexible array initializer.
2567       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2568                                              TopLevelObject))
2569         Invalid = true;
2570 
2571       if (Invalid) {
2572         ++Index;
2573         return true;
2574       }
2575 
2576       // Initialize the array.
2577       bool prevHadError = hadError;
2578       unsigned newStructuredIndex = FieldIndex;
2579       unsigned OldIndex = Index;
2580       IList->setInit(Index, DIE->getInit());
2581 
2582       InitializedEntity MemberEntity =
2583         InitializedEntity::InitializeMember(*Field, &Entity);
2584       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2585                           StructuredList, newStructuredIndex);
2586 
2587       IList->setInit(OldIndex, DIE);
2588       if (hadError && !prevHadError) {
2589         ++Field;
2590         ++FieldIndex;
2591         if (NextField)
2592           *NextField = Field;
2593         StructuredIndex = FieldIndex;
2594         return true;
2595       }
2596     } else {
2597       // Recurse to check later designated subobjects.
2598       QualType FieldType = Field->getType();
2599       unsigned newStructuredIndex = FieldIndex;
2600 
2601       InitializedEntity MemberEntity =
2602         InitializedEntity::InitializeMember(*Field, &Entity);
2603       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2604                                      FieldType, nullptr, nullptr, Index,
2605                                      StructuredList, newStructuredIndex,
2606                                      FinishSubobjectInit, false))
2607         return true;
2608     }
2609 
2610     // Find the position of the next field to be initialized in this
2611     // subobject.
2612     ++Field;
2613     ++FieldIndex;
2614 
2615     // If this the first designator, our caller will continue checking
2616     // the rest of this struct/class/union subobject.
2617     if (IsFirstDesignator) {
2618       if (NextField)
2619         *NextField = Field;
2620       StructuredIndex = FieldIndex;
2621       return false;
2622     }
2623 
2624     if (!FinishSubobjectInit)
2625       return false;
2626 
2627     // We've already initialized something in the union; we're done.
2628     if (RT->getDecl()->isUnion())
2629       return hadError;
2630 
2631     // Check the remaining fields within this class/struct/union subobject.
2632     bool prevHadError = hadError;
2633 
2634     auto NoBases =
2635         CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2636                                         CXXRecordDecl::base_class_iterator());
2637     CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2638                           false, Index, StructuredList, FieldIndex);
2639     return hadError && !prevHadError;
2640   }
2641 
2642   // C99 6.7.8p6:
2643   //
2644   //   If a designator has the form
2645   //
2646   //      [ constant-expression ]
2647   //
2648   //   then the current object (defined below) shall have array
2649   //   type and the expression shall be an integer constant
2650   //   expression. If the array is of unknown size, any
2651   //   nonnegative value is valid.
2652   //
2653   // Additionally, cope with the GNU extension that permits
2654   // designators of the form
2655   //
2656   //      [ constant-expression ... constant-expression ]
2657   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2658   if (!AT) {
2659     if (!VerifyOnly)
2660       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2661         << CurrentObjectType;
2662     ++Index;
2663     return true;
2664   }
2665 
2666   Expr *IndexExpr = nullptr;
2667   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2668   if (D->isArrayDesignator()) {
2669     IndexExpr = DIE->getArrayIndex(*D);
2670     DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2671     DesignatedEndIndex = DesignatedStartIndex;
2672   } else {
2673     assert(D->isArrayRangeDesignator() && "Need array-range designator");
2674 
2675     DesignatedStartIndex =
2676       DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2677     DesignatedEndIndex =
2678       DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2679     IndexExpr = DIE->getArrayRangeEnd(*D);
2680 
2681     // Codegen can't handle evaluating array range designators that have side
2682     // effects, because we replicate the AST value for each initialized element.
2683     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2684     // elements with something that has a side effect, so codegen can emit an
2685     // "error unsupported" error instead of miscompiling the app.
2686     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2687         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2688       FullyStructuredList->sawArrayRangeDesignator();
2689   }
2690 
2691   if (isa<ConstantArrayType>(AT)) {
2692     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2693     DesignatedStartIndex
2694       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2695     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2696     DesignatedEndIndex
2697       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2698     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2699     if (DesignatedEndIndex >= MaxElements) {
2700       if (!VerifyOnly)
2701         SemaRef.Diag(IndexExpr->getBeginLoc(),
2702                      diag::err_array_designator_too_large)
2703             << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2704             << IndexExpr->getSourceRange();
2705       ++Index;
2706       return true;
2707     }
2708   } else {
2709     unsigned DesignatedIndexBitWidth =
2710       ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2711     DesignatedStartIndex =
2712       DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2713     DesignatedEndIndex =
2714       DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2715     DesignatedStartIndex.setIsUnsigned(true);
2716     DesignatedEndIndex.setIsUnsigned(true);
2717   }
2718 
2719   if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2720     // We're modifying a string literal init; we have to decompose the string
2721     // so we can modify the individual characters.
2722     ASTContext &Context = SemaRef.Context;
2723     Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2724 
2725     // Compute the character type
2726     QualType CharTy = AT->getElementType();
2727 
2728     // Compute the type of the integer literals.
2729     QualType PromotedCharTy = CharTy;
2730     if (CharTy->isPromotableIntegerType())
2731       PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2732     unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2733 
2734     if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2735       // Get the length of the string.
2736       uint64_t StrLen = SL->getLength();
2737       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2738         StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2739       StructuredList->resizeInits(Context, StrLen);
2740 
2741       // Build a literal for each character in the string, and put them into
2742       // the init list.
2743       for (unsigned i = 0, e = StrLen; i != e; ++i) {
2744         llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2745         Expr *Init = new (Context) IntegerLiteral(
2746             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2747         if (CharTy != PromotedCharTy)
2748           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2749                                           Init, nullptr, VK_RValue);
2750         StructuredList->updateInit(Context, i, Init);
2751       }
2752     } else {
2753       ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2754       std::string Str;
2755       Context.getObjCEncodingForType(E->getEncodedType(), Str);
2756 
2757       // Get the length of the string.
2758       uint64_t StrLen = Str.size();
2759       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2760         StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2761       StructuredList->resizeInits(Context, StrLen);
2762 
2763       // Build a literal for each character in the string, and put them into
2764       // the init list.
2765       for (unsigned i = 0, e = StrLen; i != e; ++i) {
2766         llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2767         Expr *Init = new (Context) IntegerLiteral(
2768             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2769         if (CharTy != PromotedCharTy)
2770           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2771                                           Init, nullptr, VK_RValue);
2772         StructuredList->updateInit(Context, i, Init);
2773       }
2774     }
2775   }
2776 
2777   // Make sure that our non-designated initializer list has space
2778   // for a subobject corresponding to this array element.
2779   if (!VerifyOnly &&
2780       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2781     StructuredList->resizeInits(SemaRef.Context,
2782                                 DesignatedEndIndex.getZExtValue() + 1);
2783 
2784   // Repeatedly perform subobject initializations in the range
2785   // [DesignatedStartIndex, DesignatedEndIndex].
2786 
2787   // Move to the next designator
2788   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2789   unsigned OldIndex = Index;
2790 
2791   InitializedEntity ElementEntity =
2792     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2793 
2794   while (DesignatedStartIndex <= DesignatedEndIndex) {
2795     // Recurse to check later designated subobjects.
2796     QualType ElementType = AT->getElementType();
2797     Index = OldIndex;
2798 
2799     ElementEntity.setElementIndex(ElementIndex);
2800     if (CheckDesignatedInitializer(
2801             ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2802             nullptr, Index, StructuredList, ElementIndex,
2803             FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2804             false))
2805       return true;
2806 
2807     // Move to the next index in the array that we'll be initializing.
2808     ++DesignatedStartIndex;
2809     ElementIndex = DesignatedStartIndex.getZExtValue();
2810   }
2811 
2812   // If this the first designator, our caller will continue checking
2813   // the rest of this array subobject.
2814   if (IsFirstDesignator) {
2815     if (NextElementIndex)
2816       *NextElementIndex = DesignatedStartIndex;
2817     StructuredIndex = ElementIndex;
2818     return false;
2819   }
2820 
2821   if (!FinishSubobjectInit)
2822     return false;
2823 
2824   // Check the remaining elements within this array subobject.
2825   bool prevHadError = hadError;
2826   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2827                  /*SubobjectIsDesignatorContext=*/false, Index,
2828                  StructuredList, ElementIndex);
2829   return hadError && !prevHadError;
2830 }
2831 
2832 // Get the structured initializer list for a subobject of type
2833 // @p CurrentObjectType.
2834 InitListExpr *
2835 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2836                                             QualType CurrentObjectType,
2837                                             InitListExpr *StructuredList,
2838                                             unsigned StructuredIndex,
2839                                             SourceRange InitRange,
2840                                             bool IsFullyOverwritten) {
2841   if (VerifyOnly)
2842     return nullptr; // No structured list in verification-only mode.
2843   Expr *ExistingInit = nullptr;
2844   if (!StructuredList)
2845     ExistingInit = SyntacticToSemantic.lookup(IList);
2846   else if (StructuredIndex < StructuredList->getNumInits())
2847     ExistingInit = StructuredList->getInit(StructuredIndex);
2848 
2849   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2850     // There might have already been initializers for subobjects of the current
2851     // object, but a subsequent initializer list will overwrite the entirety
2852     // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2853     //
2854     // struct P { char x[6]; };
2855     // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2856     //
2857     // The first designated initializer is ignored, and l.x is just "f".
2858     if (!IsFullyOverwritten)
2859       return Result;
2860 
2861   if (ExistingInit) {
2862     // We are creating an initializer list that initializes the
2863     // subobjects of the current object, but there was already an
2864     // initialization that completely initialized the current
2865     // subobject, e.g., by a compound literal:
2866     //
2867     // struct X { int a, b; };
2868     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2869     //
2870     // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2871     // designated initializer re-initializes the whole
2872     // subobject [0], overwriting previous initializers.
2873     SemaRef.Diag(InitRange.getBegin(),
2874                  diag::warn_subobject_initializer_overrides)
2875       << InitRange;
2876     SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2877         << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2878   }
2879 
2880   InitListExpr *Result
2881     = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2882                                          InitRange.getBegin(), None,
2883                                          InitRange.getEnd());
2884 
2885   QualType ResultType = CurrentObjectType;
2886   if (!ResultType->isArrayType())
2887     ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2888   Result->setType(ResultType);
2889 
2890   // Pre-allocate storage for the structured initializer list.
2891   unsigned NumElements = 0;
2892   unsigned NumInits = 0;
2893   bool GotNumInits = false;
2894   if (!StructuredList) {
2895     NumInits = IList->getNumInits();
2896     GotNumInits = true;
2897   } else if (Index < IList->getNumInits()) {
2898     if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2899       NumInits = SubList->getNumInits();
2900       GotNumInits = true;
2901     }
2902   }
2903 
2904   if (const ArrayType *AType
2905       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2906     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2907       NumElements = CAType->getSize().getZExtValue();
2908       // Simple heuristic so that we don't allocate a very large
2909       // initializer with many empty entries at the end.
2910       if (GotNumInits && NumElements > NumInits)
2911         NumElements = 0;
2912     }
2913   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2914     NumElements = VType->getNumElements();
2915   else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2916     RecordDecl *RDecl = RType->getDecl();
2917     if (RDecl->isUnion())
2918       NumElements = 1;
2919     else
2920       NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2921   }
2922 
2923   Result->reserveInits(SemaRef.Context, NumElements);
2924 
2925   // Link this new initializer list into the structured initializer
2926   // lists.
2927   if (StructuredList)
2928     StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2929   else {
2930     Result->setSyntacticForm(IList);
2931     SyntacticToSemantic[IList] = Result;
2932   }
2933 
2934   return Result;
2935 }
2936 
2937 /// Update the initializer at index @p StructuredIndex within the
2938 /// structured initializer list to the value @p expr.
2939 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2940                                                   unsigned &StructuredIndex,
2941                                                   Expr *expr) {
2942   // No structured initializer list to update
2943   if (!StructuredList)
2944     return;
2945 
2946   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2947                                                   StructuredIndex, expr)) {
2948     // This initializer overwrites a previous initializer. Warn.
2949     // We need to check on source range validity because the previous
2950     // initializer does not have to be an explicit initializer.
2951     // struct P { int a, b; };
2952     // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2953     // There is an overwrite taking place because the first braced initializer
2954     // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2955     if (PrevInit->getSourceRange().isValid()) {
2956       SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2957           << expr->getSourceRange();
2958 
2959       SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2960           << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
2961     }
2962   }
2963 
2964   ++StructuredIndex;
2965 }
2966 
2967 /// Check that the given Index expression is a valid array designator
2968 /// value. This is essentially just a wrapper around
2969 /// VerifyIntegerConstantExpression that also checks for negative values
2970 /// and produces a reasonable diagnostic if there is a
2971 /// failure. Returns the index expression, possibly with an implicit cast
2972 /// added, on success.  If everything went okay, Value will receive the
2973 /// value of the constant expression.
2974 static ExprResult
2975 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2976   SourceLocation Loc = Index->getBeginLoc();
2977 
2978   // Make sure this is an integer constant expression.
2979   ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2980   if (Result.isInvalid())
2981     return Result;
2982 
2983   if (Value.isSigned() && Value.isNegative())
2984     return S.Diag(Loc, diag::err_array_designator_negative)
2985       << Value.toString(10) << Index->getSourceRange();
2986 
2987   Value.setIsUnsigned(true);
2988   return Result;
2989 }
2990 
2991 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2992                                             SourceLocation Loc,
2993                                             bool GNUSyntax,
2994                                             ExprResult Init) {
2995   typedef DesignatedInitExpr::Designator ASTDesignator;
2996 
2997   bool Invalid = false;
2998   SmallVector<ASTDesignator, 32> Designators;
2999   SmallVector<Expr *, 32> InitExpressions;
3000 
3001   // Build designators and check array designator expressions.
3002   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3003     const Designator &D = Desig.getDesignator(Idx);
3004     switch (D.getKind()) {
3005     case Designator::FieldDesignator:
3006       Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
3007                                           D.getFieldLoc()));
3008       break;
3009 
3010     case Designator::ArrayDesignator: {
3011       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3012       llvm::APSInt IndexValue;
3013       if (!Index->isTypeDependent() && !Index->isValueDependent())
3014         Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3015       if (!Index)
3016         Invalid = true;
3017       else {
3018         Designators.push_back(ASTDesignator(InitExpressions.size(),
3019                                             D.getLBracketLoc(),
3020                                             D.getRBracketLoc()));
3021         InitExpressions.push_back(Index);
3022       }
3023       break;
3024     }
3025 
3026     case Designator::ArrayRangeDesignator: {
3027       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3028       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3029       llvm::APSInt StartValue;
3030       llvm::APSInt EndValue;
3031       bool StartDependent = StartIndex->isTypeDependent() ||
3032                             StartIndex->isValueDependent();
3033       bool EndDependent = EndIndex->isTypeDependent() ||
3034                           EndIndex->isValueDependent();
3035       if (!StartDependent)
3036         StartIndex =
3037             CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3038       if (!EndDependent)
3039         EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3040 
3041       if (!StartIndex || !EndIndex)
3042         Invalid = true;
3043       else {
3044         // Make sure we're comparing values with the same bit width.
3045         if (StartDependent || EndDependent) {
3046           // Nothing to compute.
3047         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3048           EndValue = EndValue.extend(StartValue.getBitWidth());
3049         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3050           StartValue = StartValue.extend(EndValue.getBitWidth());
3051 
3052         if (!StartDependent && !EndDependent && EndValue < StartValue) {
3053           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3054             << StartValue.toString(10) << EndValue.toString(10)
3055             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3056           Invalid = true;
3057         } else {
3058           Designators.push_back(ASTDesignator(InitExpressions.size(),
3059                                               D.getLBracketLoc(),
3060                                               D.getEllipsisLoc(),
3061                                               D.getRBracketLoc()));
3062           InitExpressions.push_back(StartIndex);
3063           InitExpressions.push_back(EndIndex);
3064         }
3065       }
3066       break;
3067     }
3068     }
3069   }
3070 
3071   if (Invalid || Init.isInvalid())
3072     return ExprError();
3073 
3074   // Clear out the expressions within the designation.
3075   Desig.ClearExprs(*this);
3076 
3077   DesignatedInitExpr *DIE
3078     = DesignatedInitExpr::Create(Context,
3079                                  Designators,
3080                                  InitExpressions, Loc, GNUSyntax,
3081                                  Init.getAs<Expr>());
3082 
3083   if (!getLangOpts().C99)
3084     Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3085         << DIE->getSourceRange();
3086 
3087   return DIE;
3088 }
3089 
3090 //===----------------------------------------------------------------------===//
3091 // Initialization entity
3092 //===----------------------------------------------------------------------===//
3093 
3094 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3095                                      const InitializedEntity &Parent)
3096   : Parent(&Parent), Index(Index)
3097 {
3098   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3099     Kind = EK_ArrayElement;
3100     Type = AT->getElementType();
3101   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3102     Kind = EK_VectorElement;
3103     Type = VT->getElementType();
3104   } else {
3105     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3106     assert(CT && "Unexpected type");
3107     Kind = EK_ComplexElement;
3108     Type = CT->getElementType();
3109   }
3110 }
3111 
3112 InitializedEntity
3113 InitializedEntity::InitializeBase(ASTContext &Context,
3114                                   const CXXBaseSpecifier *Base,
3115                                   bool IsInheritedVirtualBase,
3116                                   const InitializedEntity *Parent) {
3117   InitializedEntity Result;
3118   Result.Kind = EK_Base;
3119   Result.Parent = Parent;
3120   Result.Base = reinterpret_cast<uintptr_t>(Base);
3121   if (IsInheritedVirtualBase)
3122     Result.Base |= 0x01;
3123 
3124   Result.Type = Base->getType();
3125   return Result;
3126 }
3127 
3128 DeclarationName InitializedEntity::getName() const {
3129   switch (getKind()) {
3130   case EK_Parameter:
3131   case EK_Parameter_CF_Audited: {
3132     ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3133     return (D ? D->getDeclName() : DeclarationName());
3134   }
3135 
3136   case EK_Variable:
3137   case EK_Member:
3138   case EK_Binding:
3139     return Variable.VariableOrMember->getDeclName();
3140 
3141   case EK_LambdaCapture:
3142     return DeclarationName(Capture.VarID);
3143 
3144   case EK_Result:
3145   case EK_StmtExprResult:
3146   case EK_Exception:
3147   case EK_New:
3148   case EK_Temporary:
3149   case EK_Base:
3150   case EK_Delegating:
3151   case EK_ArrayElement:
3152   case EK_VectorElement:
3153   case EK_ComplexElement:
3154   case EK_BlockElement:
3155   case EK_LambdaToBlockConversionBlockElement:
3156   case EK_CompoundLiteralInit:
3157   case EK_RelatedResult:
3158     return DeclarationName();
3159   }
3160 
3161   llvm_unreachable("Invalid EntityKind!");
3162 }
3163 
3164 ValueDecl *InitializedEntity::getDecl() const {
3165   switch (getKind()) {
3166   case EK_Variable:
3167   case EK_Member:
3168   case EK_Binding:
3169     return Variable.VariableOrMember;
3170 
3171   case EK_Parameter:
3172   case EK_Parameter_CF_Audited:
3173     return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3174 
3175   case EK_Result:
3176   case EK_StmtExprResult:
3177   case EK_Exception:
3178   case EK_New:
3179   case EK_Temporary:
3180   case EK_Base:
3181   case EK_Delegating:
3182   case EK_ArrayElement:
3183   case EK_VectorElement:
3184   case EK_ComplexElement:
3185   case EK_BlockElement:
3186   case EK_LambdaToBlockConversionBlockElement:
3187   case EK_LambdaCapture:
3188   case EK_CompoundLiteralInit:
3189   case EK_RelatedResult:
3190     return nullptr;
3191   }
3192 
3193   llvm_unreachable("Invalid EntityKind!");
3194 }
3195 
3196 bool InitializedEntity::allowsNRVO() const {
3197   switch (getKind()) {
3198   case EK_Result:
3199   case EK_Exception:
3200     return LocAndNRVO.NRVO;
3201 
3202   case EK_StmtExprResult:
3203   case EK_Variable:
3204   case EK_Parameter:
3205   case EK_Parameter_CF_Audited:
3206   case EK_Member:
3207   case EK_Binding:
3208   case EK_New:
3209   case EK_Temporary:
3210   case EK_CompoundLiteralInit:
3211   case EK_Base:
3212   case EK_Delegating:
3213   case EK_ArrayElement:
3214   case EK_VectorElement:
3215   case EK_ComplexElement:
3216   case EK_BlockElement:
3217   case EK_LambdaToBlockConversionBlockElement:
3218   case EK_LambdaCapture:
3219   case EK_RelatedResult:
3220     break;
3221   }
3222 
3223   return false;
3224 }
3225 
3226 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3227   assert(getParent() != this);
3228   unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3229   for (unsigned I = 0; I != Depth; ++I)
3230     OS << "`-";
3231 
3232   switch (getKind()) {
3233   case EK_Variable: OS << "Variable"; break;
3234   case EK_Parameter: OS << "Parameter"; break;
3235   case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3236     break;
3237   case EK_Result: OS << "Result"; break;
3238   case EK_StmtExprResult: OS << "StmtExprResult"; break;
3239   case EK_Exception: OS << "Exception"; break;
3240   case EK_Member: OS << "Member"; break;
3241   case EK_Binding: OS << "Binding"; break;
3242   case EK_New: OS << "New"; break;
3243   case EK_Temporary: OS << "Temporary"; break;
3244   case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3245   case EK_RelatedResult: OS << "RelatedResult"; break;
3246   case EK_Base: OS << "Base"; break;
3247   case EK_Delegating: OS << "Delegating"; break;
3248   case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3249   case EK_VectorElement: OS << "VectorElement " << Index; break;
3250   case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3251   case EK_BlockElement: OS << "Block"; break;
3252   case EK_LambdaToBlockConversionBlockElement:
3253     OS << "Block (lambda)";
3254     break;
3255   case EK_LambdaCapture:
3256     OS << "LambdaCapture ";
3257     OS << DeclarationName(Capture.VarID);
3258     break;
3259   }
3260 
3261   if (auto *D = getDecl()) {
3262     OS << " ";
3263     D->printQualifiedName(OS);
3264   }
3265 
3266   OS << " '" << getType().getAsString() << "'\n";
3267 
3268   return Depth + 1;
3269 }
3270 
3271 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3272   dumpImpl(llvm::errs());
3273 }
3274 
3275 //===----------------------------------------------------------------------===//
3276 // Initialization sequence
3277 //===----------------------------------------------------------------------===//
3278 
3279 void InitializationSequence::Step::Destroy() {
3280   switch (Kind) {
3281   case SK_ResolveAddressOfOverloadedFunction:
3282   case SK_CastDerivedToBaseRValue:
3283   case SK_CastDerivedToBaseXValue:
3284   case SK_CastDerivedToBaseLValue:
3285   case SK_BindReference:
3286   case SK_BindReferenceToTemporary:
3287   case SK_FinalCopy:
3288   case SK_ExtraneousCopyToTemporary:
3289   case SK_UserConversion:
3290   case SK_QualificationConversionRValue:
3291   case SK_QualificationConversionXValue:
3292   case SK_QualificationConversionLValue:
3293   case SK_AtomicConversion:
3294   case SK_ListInitialization:
3295   case SK_UnwrapInitList:
3296   case SK_RewrapInitList:
3297   case SK_ConstructorInitialization:
3298   case SK_ConstructorInitializationFromList:
3299   case SK_ZeroInitialization:
3300   case SK_CAssignment:
3301   case SK_StringInit:
3302   case SK_ObjCObjectConversion:
3303   case SK_ArrayLoopIndex:
3304   case SK_ArrayLoopInit:
3305   case SK_ArrayInit:
3306   case SK_GNUArrayInit:
3307   case SK_ParenthesizedArrayInit:
3308   case SK_PassByIndirectCopyRestore:
3309   case SK_PassByIndirectRestore:
3310   case SK_ProduceObjCObject:
3311   case SK_StdInitializerList:
3312   case SK_StdInitializerListConstructorCall:
3313   case SK_OCLSamplerInit:
3314   case SK_OCLZeroOpaqueType:
3315     break;
3316 
3317   case SK_ConversionSequence:
3318   case SK_ConversionSequenceNoNarrowing:
3319     delete ICS;
3320   }
3321 }
3322 
3323 bool InitializationSequence::isDirectReferenceBinding() const {
3324   // There can be some lvalue adjustments after the SK_BindReference step.
3325   for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3326     if (I->Kind == SK_BindReference)
3327       return true;
3328     if (I->Kind == SK_BindReferenceToTemporary)
3329       return false;
3330   }
3331   return false;
3332 }
3333 
3334 bool InitializationSequence::isAmbiguous() const {
3335   if (!Failed())
3336     return false;
3337 
3338   switch (getFailureKind()) {
3339   case FK_TooManyInitsForReference:
3340   case FK_ParenthesizedListInitForReference:
3341   case FK_ArrayNeedsInitList:
3342   case FK_ArrayNeedsInitListOrStringLiteral:
3343   case FK_ArrayNeedsInitListOrWideStringLiteral:
3344   case FK_NarrowStringIntoWideCharArray:
3345   case FK_WideStringIntoCharArray:
3346   case FK_IncompatWideStringIntoWideChar:
3347   case FK_PlainStringIntoUTF8Char:
3348   case FK_UTF8StringIntoPlainChar:
3349   case FK_AddressOfOverloadFailed: // FIXME: Could do better
3350   case FK_NonConstLValueReferenceBindingToTemporary:
3351   case FK_NonConstLValueReferenceBindingToBitfield:
3352   case FK_NonConstLValueReferenceBindingToVectorElement:
3353   case FK_NonConstLValueReferenceBindingToUnrelated:
3354   case FK_RValueReferenceBindingToLValue:
3355   case FK_ReferenceAddrspaceMismatchTemporary:
3356   case FK_ReferenceInitDropsQualifiers:
3357   case FK_ReferenceInitFailed:
3358   case FK_ConversionFailed:
3359   case FK_ConversionFromPropertyFailed:
3360   case FK_TooManyInitsForScalar:
3361   case FK_ParenthesizedListInitForScalar:
3362   case FK_ReferenceBindingToInitList:
3363   case FK_InitListBadDestinationType:
3364   case FK_DefaultInitOfConst:
3365   case FK_Incomplete:
3366   case FK_ArrayTypeMismatch:
3367   case FK_NonConstantArrayInit:
3368   case FK_ListInitializationFailed:
3369   case FK_VariableLengthArrayHasInitializer:
3370   case FK_PlaceholderType:
3371   case FK_ExplicitConstructor:
3372   case FK_AddressOfUnaddressableFunction:
3373     return false;
3374 
3375   case FK_ReferenceInitOverloadFailed:
3376   case FK_UserConversionOverloadFailed:
3377   case FK_ConstructorOverloadFailed:
3378   case FK_ListConstructorOverloadFailed:
3379     return FailedOverloadResult == OR_Ambiguous;
3380   }
3381 
3382   llvm_unreachable("Invalid EntityKind!");
3383 }
3384 
3385 bool InitializationSequence::isConstructorInitialization() const {
3386   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3387 }
3388 
3389 void
3390 InitializationSequence
3391 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3392                                    DeclAccessPair Found,
3393                                    bool HadMultipleCandidates) {
3394   Step S;
3395   S.Kind = SK_ResolveAddressOfOverloadedFunction;
3396   S.Type = Function->getType();
3397   S.Function.HadMultipleCandidates = HadMultipleCandidates;
3398   S.Function.Function = Function;
3399   S.Function.FoundDecl = Found;
3400   Steps.push_back(S);
3401 }
3402 
3403 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3404                                                       ExprValueKind VK) {
3405   Step S;
3406   switch (VK) {
3407   case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3408   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3409   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3410   }
3411   S.Type = BaseType;
3412   Steps.push_back(S);
3413 }
3414 
3415 void InitializationSequence::AddReferenceBindingStep(QualType T,
3416                                                      bool BindingTemporary) {
3417   Step S;
3418   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3419   S.Type = T;
3420   Steps.push_back(S);
3421 }
3422 
3423 void InitializationSequence::AddFinalCopy(QualType T) {
3424   Step S;
3425   S.Kind = SK_FinalCopy;
3426   S.Type = T;
3427   Steps.push_back(S);
3428 }
3429 
3430 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3431   Step S;
3432   S.Kind = SK_ExtraneousCopyToTemporary;
3433   S.Type = T;
3434   Steps.push_back(S);
3435 }
3436 
3437 void
3438 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3439                                               DeclAccessPair FoundDecl,
3440                                               QualType T,
3441                                               bool HadMultipleCandidates) {
3442   Step S;
3443   S.Kind = SK_UserConversion;
3444   S.Type = T;
3445   S.Function.HadMultipleCandidates = HadMultipleCandidates;
3446   S.Function.Function = Function;
3447   S.Function.FoundDecl = FoundDecl;
3448   Steps.push_back(S);
3449 }
3450 
3451 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3452                                                             ExprValueKind VK) {
3453   Step S;
3454   S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3455   switch (VK) {
3456   case VK_RValue:
3457     S.Kind = SK_QualificationConversionRValue;
3458     break;
3459   case VK_XValue:
3460     S.Kind = SK_QualificationConversionXValue;
3461     break;
3462   case VK_LValue:
3463     S.Kind = SK_QualificationConversionLValue;
3464     break;
3465   }
3466   S.Type = Ty;
3467   Steps.push_back(S);
3468 }
3469 
3470 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3471   Step S;
3472   S.Kind = SK_AtomicConversion;
3473   S.Type = Ty;
3474   Steps.push_back(S);
3475 }
3476 
3477 void InitializationSequence::AddConversionSequenceStep(
3478     const ImplicitConversionSequence &ICS, QualType T,
3479     bool TopLevelOfInitList) {
3480   Step S;
3481   S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3482                               : SK_ConversionSequence;
3483   S.Type = T;
3484   S.ICS = new ImplicitConversionSequence(ICS);
3485   Steps.push_back(S);
3486 }
3487 
3488 void InitializationSequence::AddListInitializationStep(QualType T) {
3489   Step S;
3490   S.Kind = SK_ListInitialization;
3491   S.Type = T;
3492   Steps.push_back(S);
3493 }
3494 
3495 void InitializationSequence::AddConstructorInitializationStep(
3496     DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3497     bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3498   Step S;
3499   S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3500                                      : SK_ConstructorInitializationFromList
3501                         : SK_ConstructorInitialization;
3502   S.Type = T;
3503   S.Function.HadMultipleCandidates = HadMultipleCandidates;
3504   S.Function.Function = Constructor;
3505   S.Function.FoundDecl = FoundDecl;
3506   Steps.push_back(S);
3507 }
3508 
3509 void InitializationSequence::AddZeroInitializationStep(QualType T) {
3510   Step S;
3511   S.Kind = SK_ZeroInitialization;
3512   S.Type = T;
3513   Steps.push_back(S);
3514 }
3515 
3516 void InitializationSequence::AddCAssignmentStep(QualType T) {
3517   Step S;
3518   S.Kind = SK_CAssignment;
3519   S.Type = T;
3520   Steps.push_back(S);
3521 }
3522 
3523 void InitializationSequence::AddStringInitStep(QualType T) {
3524   Step S;
3525   S.Kind = SK_StringInit;
3526   S.Type = T;
3527   Steps.push_back(S);
3528 }
3529 
3530 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3531   Step S;
3532   S.Kind = SK_ObjCObjectConversion;
3533   S.Type = T;
3534   Steps.push_back(S);
3535 }
3536 
3537 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3538   Step S;
3539   S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3540   S.Type = T;
3541   Steps.push_back(S);
3542 }
3543 
3544 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3545   Step S;
3546   S.Kind = SK_ArrayLoopIndex;
3547   S.Type = EltT;
3548   Steps.insert(Steps.begin(), S);
3549 
3550   S.Kind = SK_ArrayLoopInit;
3551   S.Type = T;
3552   Steps.push_back(S);
3553 }
3554 
3555 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3556   Step S;
3557   S.Kind = SK_ParenthesizedArrayInit;
3558   S.Type = T;
3559   Steps.push_back(S);
3560 }
3561 
3562 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3563                                                               bool shouldCopy) {
3564   Step s;
3565   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3566                        : SK_PassByIndirectRestore);
3567   s.Type = type;
3568   Steps.push_back(s);
3569 }
3570 
3571 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3572   Step S;
3573   S.Kind = SK_ProduceObjCObject;
3574   S.Type = T;
3575   Steps.push_back(S);
3576 }
3577 
3578 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3579   Step S;
3580   S.Kind = SK_StdInitializerList;
3581   S.Type = T;
3582   Steps.push_back(S);
3583 }
3584 
3585 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3586   Step S;
3587   S.Kind = SK_OCLSamplerInit;
3588   S.Type = T;
3589   Steps.push_back(S);
3590 }
3591 
3592 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3593   Step S;
3594   S.Kind = SK_OCLZeroOpaqueType;
3595   S.Type = T;
3596   Steps.push_back(S);
3597 }
3598 
3599 void InitializationSequence::RewrapReferenceInitList(QualType T,
3600                                                      InitListExpr *Syntactic) {
3601   assert(Syntactic->getNumInits() == 1 &&
3602          "Can only rewrap trivial init lists.");
3603   Step S;
3604   S.Kind = SK_UnwrapInitList;
3605   S.Type = Syntactic->getInit(0)->getType();
3606   Steps.insert(Steps.begin(), S);
3607 
3608   S.Kind = SK_RewrapInitList;
3609   S.Type = T;
3610   S.WrappingSyntacticList = Syntactic;
3611   Steps.push_back(S);
3612 }
3613 
3614 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3615                                                 OverloadingResult Result) {
3616   setSequenceKind(FailedSequence);
3617   this->Failure = Failure;
3618   this->FailedOverloadResult = Result;
3619 }
3620 
3621 //===----------------------------------------------------------------------===//
3622 // Attempt initialization
3623 //===----------------------------------------------------------------------===//
3624 
3625 /// Tries to add a zero initializer. Returns true if that worked.
3626 static bool
3627 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3628                                    const InitializedEntity &Entity) {
3629   if (Entity.getKind() != InitializedEntity::EK_Variable)
3630     return false;
3631 
3632   VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3633   if (VD->getInit() || VD->getEndLoc().isMacroID())
3634     return false;
3635 
3636   QualType VariableTy = VD->getType().getCanonicalType();
3637   SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3638   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3639   if (!Init.empty()) {
3640     Sequence.AddZeroInitializationStep(Entity.getType());
3641     Sequence.SetZeroInitializationFixit(Init, Loc);
3642     return true;
3643   }
3644   return false;
3645 }
3646 
3647 static void MaybeProduceObjCObject(Sema &S,
3648                                    InitializationSequence &Sequence,
3649                                    const InitializedEntity &Entity) {
3650   if (!S.getLangOpts().ObjCAutoRefCount) return;
3651 
3652   /// When initializing a parameter, produce the value if it's marked
3653   /// __attribute__((ns_consumed)).
3654   if (Entity.isParameterKind()) {
3655     if (!Entity.isParameterConsumed())
3656       return;
3657 
3658     assert(Entity.getType()->isObjCRetainableType() &&
3659            "consuming an object of unretainable type?");
3660     Sequence.AddProduceObjCObjectStep(Entity.getType());
3661 
3662   /// When initializing a return value, if the return type is a
3663   /// retainable type, then returns need to immediately retain the
3664   /// object.  If an autorelease is required, it will be done at the
3665   /// last instant.
3666   } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3667              Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
3668     if (!Entity.getType()->isObjCRetainableType())
3669       return;
3670 
3671     Sequence.AddProduceObjCObjectStep(Entity.getType());
3672   }
3673 }
3674 
3675 static void TryListInitialization(Sema &S,
3676                                   const InitializedEntity &Entity,
3677                                   const InitializationKind &Kind,
3678                                   InitListExpr *InitList,
3679                                   InitializationSequence &Sequence,
3680                                   bool TreatUnavailableAsInvalid);
3681 
3682 /// When initializing from init list via constructor, handle
3683 /// initialization of an object of type std::initializer_list<T>.
3684 ///
3685 /// \return true if we have handled initialization of an object of type
3686 /// std::initializer_list<T>, false otherwise.
3687 static bool TryInitializerListConstruction(Sema &S,
3688                                            InitListExpr *List,
3689                                            QualType DestType,
3690                                            InitializationSequence &Sequence,
3691                                            bool TreatUnavailableAsInvalid) {
3692   QualType E;
3693   if (!S.isStdInitializerList(DestType, &E))
3694     return false;
3695 
3696   if (!S.isCompleteType(List->getExprLoc(), E)) {
3697     Sequence.setIncompleteTypeFailure(E);
3698     return true;
3699   }
3700 
3701   // Try initializing a temporary array from the init list.
3702   QualType ArrayType = S.Context.getConstantArrayType(
3703       E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3704                                  List->getNumInits()),
3705       clang::ArrayType::Normal, 0);
3706   InitializedEntity HiddenArray =
3707       InitializedEntity::InitializeTemporary(ArrayType);
3708   InitializationKind Kind = InitializationKind::CreateDirectList(
3709       List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3710   TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3711                         TreatUnavailableAsInvalid);
3712   if (Sequence)
3713     Sequence.AddStdInitializerListConstructionStep(DestType);
3714   return true;
3715 }
3716 
3717 /// Determine if the constructor has the signature of a copy or move
3718 /// constructor for the type T of the class in which it was found. That is,
3719 /// determine if its first parameter is of type T or reference to (possibly
3720 /// cv-qualified) T.
3721 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3722                                    const ConstructorInfo &Info) {
3723   if (Info.Constructor->getNumParams() == 0)
3724     return false;
3725 
3726   QualType ParmT =
3727       Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3728   QualType ClassT =
3729       Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3730 
3731   return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3732 }
3733 
3734 static OverloadingResult
3735 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3736                            MultiExprArg Args,
3737                            OverloadCandidateSet &CandidateSet,
3738                            QualType DestType,
3739                            DeclContext::lookup_result Ctors,
3740                            OverloadCandidateSet::iterator &Best,
3741                            bool CopyInitializing, bool AllowExplicit,
3742                            bool OnlyListConstructors, bool IsListInit,
3743                            bool SecondStepOfCopyInit = false) {
3744   CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3745   CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
3746 
3747   for (NamedDecl *D : Ctors) {
3748     auto Info = getConstructorInfo(D);
3749     if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3750       continue;
3751 
3752     if (!AllowExplicit && Info.Constructor->isExplicit())
3753       continue;
3754 
3755     if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3756       continue;
3757 
3758     // C++11 [over.best.ics]p4:
3759     //   ... and the constructor or user-defined conversion function is a
3760     //   candidate by
3761     //   - 13.3.1.3, when the argument is the temporary in the second step
3762     //     of a class copy-initialization, or
3763     //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3764     //   - the second phase of 13.3.1.7 when the initializer list has exactly
3765     //     one element that is itself an initializer list, and the target is
3766     //     the first parameter of a constructor of class X, and the conversion
3767     //     is to X or reference to (possibly cv-qualified X),
3768     //   user-defined conversion sequences are not considered.
3769     bool SuppressUserConversions =
3770         SecondStepOfCopyInit ||
3771         (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3772          hasCopyOrMoveCtorParam(S.Context, Info));
3773 
3774     if (Info.ConstructorTmpl)
3775       S.AddTemplateOverloadCandidate(
3776           Info.ConstructorTmpl, Info.FoundDecl,
3777           /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3778           /*PartialOverloading=*/false, AllowExplicit);
3779     else {
3780       // C++ [over.match.copy]p1:
3781       //   - When initializing a temporary to be bound to the first parameter
3782       //     of a constructor [for type T] that takes a reference to possibly
3783       //     cv-qualified T as its first argument, called with a single
3784       //     argument in the context of direct-initialization, explicit
3785       //     conversion functions are also considered.
3786       // FIXME: What if a constructor template instantiates to such a signature?
3787       bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3788                                Args.size() == 1 &&
3789                                hasCopyOrMoveCtorParam(S.Context, Info);
3790       S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3791                              CandidateSet, SuppressUserConversions,
3792                              /*PartialOverloading=*/false, AllowExplicit,
3793                              AllowExplicitConv);
3794     }
3795   }
3796 
3797   // FIXME: Work around a bug in C++17 guaranteed copy elision.
3798   //
3799   // When initializing an object of class type T by constructor
3800   // ([over.match.ctor]) or by list-initialization ([over.match.list])
3801   // from a single expression of class type U, conversion functions of
3802   // U that convert to the non-reference type cv T are candidates.
3803   // Explicit conversion functions are only candidates during
3804   // direct-initialization.
3805   //
3806   // Note: SecondStepOfCopyInit is only ever true in this case when
3807   // evaluating whether to produce a C++98 compatibility warning.
3808   if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
3809       !SecondStepOfCopyInit) {
3810     Expr *Initializer = Args[0];
3811     auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3812     if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3813       const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3814       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3815         NamedDecl *D = *I;
3816         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3817         D = D->getUnderlyingDecl();
3818 
3819         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3820         CXXConversionDecl *Conv;
3821         if (ConvTemplate)
3822           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3823         else
3824           Conv = cast<CXXConversionDecl>(D);
3825 
3826         if (AllowExplicit || !Conv->isExplicit()) {
3827           if (ConvTemplate)
3828             S.AddTemplateConversionCandidate(
3829                 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
3830                 CandidateSet, AllowExplicit, AllowExplicit,
3831                 /*AllowResultConversion*/ false);
3832           else
3833             S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3834                                      DestType, CandidateSet, AllowExplicit,
3835                                      AllowExplicit,
3836                                      /*AllowResultConversion*/ false);
3837         }
3838       }
3839     }
3840   }
3841 
3842   // Perform overload resolution and return the result.
3843   return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3844 }
3845 
3846 /// Attempt initialization by constructor (C++ [dcl.init]), which
3847 /// enumerates the constructors of the initialized entity and performs overload
3848 /// resolution to select the best.
3849 /// \param DestType       The destination class type.
3850 /// \param DestArrayType  The destination type, which is either DestType or
3851 ///                       a (possibly multidimensional) array of DestType.
3852 /// \param IsListInit     Is this list-initialization?
3853 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3854 ///                       list-initialization from {x} where x is the same
3855 ///                       type as the entity?
3856 static void TryConstructorInitialization(Sema &S,
3857                                          const InitializedEntity &Entity,
3858                                          const InitializationKind &Kind,
3859                                          MultiExprArg Args, QualType DestType,
3860                                          QualType DestArrayType,
3861                                          InitializationSequence &Sequence,
3862                                          bool IsListInit = false,
3863                                          bool IsInitListCopy = false) {
3864   assert(((!IsListInit && !IsInitListCopy) ||
3865           (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3866          "IsListInit/IsInitListCopy must come with a single initializer list "
3867          "argument.");
3868   InitListExpr *ILE =
3869       (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3870   MultiExprArg UnwrappedArgs =
3871       ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3872 
3873   // The type we're constructing needs to be complete.
3874   if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3875     Sequence.setIncompleteTypeFailure(DestType);
3876     return;
3877   }
3878 
3879   // C++17 [dcl.init]p17:
3880   //     - If the initializer expression is a prvalue and the cv-unqualified
3881   //       version of the source type is the same class as the class of the
3882   //       destination, the initializer expression is used to initialize the
3883   //       destination object.
3884   // Per DR (no number yet), this does not apply when initializing a base
3885   // class or delegating to another constructor from a mem-initializer.
3886   // ObjC++: Lambda captured by the block in the lambda to block conversion
3887   // should avoid copy elision.
3888   if (S.getLangOpts().CPlusPlus17 &&
3889       Entity.getKind() != InitializedEntity::EK_Base &&
3890       Entity.getKind() != InitializedEntity::EK_Delegating &&
3891       Entity.getKind() !=
3892           InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3893       UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3894       S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3895     // Convert qualifications if necessary.
3896     Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3897     if (ILE)
3898       Sequence.RewrapReferenceInitList(DestType, ILE);
3899     return;
3900   }
3901 
3902   const RecordType *DestRecordType = DestType->getAs<RecordType>();
3903   assert(DestRecordType && "Constructor initialization requires record type");
3904   CXXRecordDecl *DestRecordDecl
3905     = cast<CXXRecordDecl>(DestRecordType->getDecl());
3906 
3907   // Build the candidate set directly in the initialization sequence
3908   // structure, so that it will persist if we fail.
3909   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3910 
3911   // Determine whether we are allowed to call explicit constructors or
3912   // explicit conversion operators.
3913   bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3914   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3915 
3916   //   - Otherwise, if T is a class type, constructors are considered. The
3917   //     applicable constructors are enumerated, and the best one is chosen
3918   //     through overload resolution.
3919   DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3920 
3921   OverloadingResult Result = OR_No_Viable_Function;
3922   OverloadCandidateSet::iterator Best;
3923   bool AsInitializerList = false;
3924 
3925   // C++11 [over.match.list]p1, per DR1467:
3926   //   When objects of non-aggregate type T are list-initialized, such that
3927   //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
3928   //   according to the rules in this section, overload resolution selects
3929   //   the constructor in two phases:
3930   //
3931   //   - Initially, the candidate functions are the initializer-list
3932   //     constructors of the class T and the argument list consists of the
3933   //     initializer list as a single argument.
3934   if (IsListInit) {
3935     AsInitializerList = true;
3936 
3937     // If the initializer list has no elements and T has a default constructor,
3938     // the first phase is omitted.
3939     if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3940       Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3941                                           CandidateSet, DestType, Ctors, Best,
3942                                           CopyInitialization, AllowExplicit,
3943                                           /*OnlyListConstructors=*/true,
3944                                           IsListInit);
3945   }
3946 
3947   // C++11 [over.match.list]p1:
3948   //   - If no viable initializer-list constructor is found, overload resolution
3949   //     is performed again, where the candidate functions are all the
3950   //     constructors of the class T and the argument list consists of the
3951   //     elements of the initializer list.
3952   if (Result == OR_No_Viable_Function) {
3953     AsInitializerList = false;
3954     Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3955                                         CandidateSet, DestType, Ctors, Best,
3956                                         CopyInitialization, AllowExplicit,
3957                                         /*OnlyListConstructors=*/false,
3958                                         IsListInit);
3959   }
3960   if (Result) {
3961     Sequence.SetOverloadFailure(IsListInit ?
3962                       InitializationSequence::FK_ListConstructorOverloadFailed :
3963                       InitializationSequence::FK_ConstructorOverloadFailed,
3964                                 Result);
3965     return;
3966   }
3967 
3968   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3969 
3970   // In C++17, ResolveConstructorOverload can select a conversion function
3971   // instead of a constructor.
3972   if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3973     // Add the user-defined conversion step that calls the conversion function.
3974     QualType ConvType = CD->getConversionType();
3975     assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3976            "should not have selected this conversion function");
3977     Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3978                                    HadMultipleCandidates);
3979     if (!S.Context.hasSameType(ConvType, DestType))
3980       Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3981     if (IsListInit)
3982       Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3983     return;
3984   }
3985 
3986   // C++11 [dcl.init]p6:
3987   //   If a program calls for the default initialization of an object
3988   //   of a const-qualified type T, T shall be a class type with a
3989   //   user-provided default constructor.
3990   // C++ core issue 253 proposal:
3991   //   If the implicit default constructor initializes all subobjects, no
3992   //   initializer should be required.
3993   // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3994   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3995   if (Kind.getKind() == InitializationKind::IK_Default &&
3996       Entity.getType().isConstQualified()) {
3997     if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3998       if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3999         Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4000       return;
4001     }
4002   }
4003 
4004   // C++11 [over.match.list]p1:
4005   //   In copy-list-initialization, if an explicit constructor is chosen, the
4006   //   initializer is ill-formed.
4007   if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4008     Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4009     return;
4010   }
4011 
4012   // Add the constructor initialization step. Any cv-qualification conversion is
4013   // subsumed by the initialization.
4014   Sequence.AddConstructorInitializationStep(
4015       Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4016       IsListInit | IsInitListCopy, AsInitializerList);
4017 }
4018 
4019 static bool
4020 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4021                                              Expr *Initializer,
4022                                              QualType &SourceType,
4023                                              QualType &UnqualifiedSourceType,
4024                                              QualType UnqualifiedTargetType,
4025                                              InitializationSequence &Sequence) {
4026   if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4027         S.Context.OverloadTy) {
4028     DeclAccessPair Found;
4029     bool HadMultipleCandidates = false;
4030     if (FunctionDecl *Fn
4031         = S.ResolveAddressOfOverloadedFunction(Initializer,
4032                                                UnqualifiedTargetType,
4033                                                false, Found,
4034                                                &HadMultipleCandidates)) {
4035       Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4036                                                 HadMultipleCandidates);
4037       SourceType = Fn->getType();
4038       UnqualifiedSourceType = SourceType.getUnqualifiedType();
4039     } else if (!UnqualifiedTargetType->isRecordType()) {
4040       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4041       return true;
4042     }
4043   }
4044   return false;
4045 }
4046 
4047 static void TryReferenceInitializationCore(Sema &S,
4048                                            const InitializedEntity &Entity,
4049                                            const InitializationKind &Kind,
4050                                            Expr *Initializer,
4051                                            QualType cv1T1, QualType T1,
4052                                            Qualifiers T1Quals,
4053                                            QualType cv2T2, QualType T2,
4054                                            Qualifiers T2Quals,
4055                                            InitializationSequence &Sequence);
4056 
4057 static void TryValueInitialization(Sema &S,
4058                                    const InitializedEntity &Entity,
4059                                    const InitializationKind &Kind,
4060                                    InitializationSequence &Sequence,
4061                                    InitListExpr *InitList = nullptr);
4062 
4063 /// Attempt list initialization of a reference.
4064 static void TryReferenceListInitialization(Sema &S,
4065                                            const InitializedEntity &Entity,
4066                                            const InitializationKind &Kind,
4067                                            InitListExpr *InitList,
4068                                            InitializationSequence &Sequence,
4069                                            bool TreatUnavailableAsInvalid) {
4070   // First, catch C++03 where this isn't possible.
4071   if (!S.getLangOpts().CPlusPlus11) {
4072     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4073     return;
4074   }
4075   // Can't reference initialize a compound literal.
4076   if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4077     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4078     return;
4079   }
4080 
4081   QualType DestType = Entity.getType();
4082   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4083   Qualifiers T1Quals;
4084   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4085 
4086   // Reference initialization via an initializer list works thus:
4087   // If the initializer list consists of a single element that is
4088   // reference-related to the referenced type, bind directly to that element
4089   // (possibly creating temporaries).
4090   // Otherwise, initialize a temporary with the initializer list and
4091   // bind to that.
4092   if (InitList->getNumInits() == 1) {
4093     Expr *Initializer = InitList->getInit(0);
4094     QualType cv2T2 = Initializer->getType();
4095     Qualifiers T2Quals;
4096     QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4097 
4098     // If this fails, creating a temporary wouldn't work either.
4099     if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4100                                                      T1, Sequence))
4101       return;
4102 
4103     SourceLocation DeclLoc = Initializer->getBeginLoc();
4104     bool dummy1, dummy2, dummy3;
4105     Sema::ReferenceCompareResult RefRelationship
4106       = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4107                                        dummy2, dummy3);
4108     if (RefRelationship >= Sema::Ref_Related) {
4109       // Try to bind the reference here.
4110       TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4111                                      T1Quals, cv2T2, T2, T2Quals, Sequence);
4112       if (Sequence)
4113         Sequence.RewrapReferenceInitList(cv1T1, InitList);
4114       return;
4115     }
4116 
4117     // Update the initializer if we've resolved an overloaded function.
4118     if (Sequence.step_begin() != Sequence.step_end())
4119       Sequence.RewrapReferenceInitList(cv1T1, InitList);
4120   }
4121 
4122   // Not reference-related. Create a temporary and bind to that.
4123   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4124 
4125   TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4126                         TreatUnavailableAsInvalid);
4127   if (Sequence) {
4128     if (DestType->isRValueReferenceType() ||
4129         (T1Quals.hasConst() && !T1Quals.hasVolatile()))
4130       Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
4131     else
4132       Sequence.SetFailed(
4133           InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4134   }
4135 }
4136 
4137 /// Attempt list initialization (C++0x [dcl.init.list])
4138 static void TryListInitialization(Sema &S,
4139                                   const InitializedEntity &Entity,
4140                                   const InitializationKind &Kind,
4141                                   InitListExpr *InitList,
4142                                   InitializationSequence &Sequence,
4143                                   bool TreatUnavailableAsInvalid) {
4144   QualType DestType = Entity.getType();
4145 
4146   // C++ doesn't allow scalar initialization with more than one argument.
4147   // But C99 complex numbers are scalars and it makes sense there.
4148   if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4149       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4150     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4151     return;
4152   }
4153   if (DestType->isReferenceType()) {
4154     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4155                                    TreatUnavailableAsInvalid);
4156     return;
4157   }
4158 
4159   if (DestType->isRecordType() &&
4160       !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4161     Sequence.setIncompleteTypeFailure(DestType);
4162     return;
4163   }
4164 
4165   // C++11 [dcl.init.list]p3, per DR1467:
4166   // - If T is a class type and the initializer list has a single element of
4167   //   type cv U, where U is T or a class derived from T, the object is
4168   //   initialized from that element (by copy-initialization for
4169   //   copy-list-initialization, or by direct-initialization for
4170   //   direct-list-initialization).
4171   // - Otherwise, if T is a character array and the initializer list has a
4172   //   single element that is an appropriately-typed string literal
4173   //   (8.5.2 [dcl.init.string]), initialization is performed as described
4174   //   in that section.
4175   // - Otherwise, if T is an aggregate, [...] (continue below).
4176   if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4177     if (DestType->isRecordType()) {
4178       QualType InitType = InitList->getInit(0)->getType();
4179       if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4180           S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4181         Expr *InitListAsExpr = InitList;
4182         TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4183                                      DestType, Sequence,
4184                                      /*InitListSyntax*/false,
4185                                      /*IsInitListCopy*/true);
4186         return;
4187       }
4188     }
4189     if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4190       Expr *SubInit[1] = {InitList->getInit(0)};
4191       if (!isa<VariableArrayType>(DestAT) &&
4192           IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4193         InitializationKind SubKind =
4194             Kind.getKind() == InitializationKind::IK_DirectList
4195                 ? InitializationKind::CreateDirect(Kind.getLocation(),
4196                                                    InitList->getLBraceLoc(),
4197                                                    InitList->getRBraceLoc())
4198                 : Kind;
4199         Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4200                                 /*TopLevelOfInitList*/ true,
4201                                 TreatUnavailableAsInvalid);
4202 
4203         // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4204         // the element is not an appropriately-typed string literal, in which
4205         // case we should proceed as in C++11 (below).
4206         if (Sequence) {
4207           Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4208           return;
4209         }
4210       }
4211     }
4212   }
4213 
4214   // C++11 [dcl.init.list]p3:
4215   //   - If T is an aggregate, aggregate initialization is performed.
4216   if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4217       (S.getLangOpts().CPlusPlus11 &&
4218        S.isStdInitializerList(DestType, nullptr))) {
4219     if (S.getLangOpts().CPlusPlus11) {
4220       //   - Otherwise, if the initializer list has no elements and T is a
4221       //     class type with a default constructor, the object is
4222       //     value-initialized.
4223       if (InitList->getNumInits() == 0) {
4224         CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4225         if (RD->hasDefaultConstructor()) {
4226           TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4227           return;
4228         }
4229       }
4230 
4231       //   - Otherwise, if T is a specialization of std::initializer_list<E>,
4232       //     an initializer_list object constructed [...]
4233       if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4234                                          TreatUnavailableAsInvalid))
4235         return;
4236 
4237       //   - Otherwise, if T is a class type, constructors are considered.
4238       Expr *InitListAsExpr = InitList;
4239       TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4240                                    DestType, Sequence, /*InitListSyntax*/true);
4241     } else
4242       Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4243     return;
4244   }
4245 
4246   if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4247       InitList->getNumInits() == 1) {
4248     Expr *E = InitList->getInit(0);
4249 
4250     //   - Otherwise, if T is an enumeration with a fixed underlying type,
4251     //     the initializer-list has a single element v, and the initialization
4252     //     is direct-list-initialization, the object is initialized with the
4253     //     value T(v); if a narrowing conversion is required to convert v to
4254     //     the underlying type of T, the program is ill-formed.
4255     auto *ET = DestType->getAs<EnumType>();
4256     if (S.getLangOpts().CPlusPlus17 &&
4257         Kind.getKind() == InitializationKind::IK_DirectList &&
4258         ET && ET->getDecl()->isFixed() &&
4259         !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4260         (E->getType()->isIntegralOrEnumerationType() ||
4261          E->getType()->isFloatingType())) {
4262       // There are two ways that T(v) can work when T is an enumeration type.
4263       // If there is either an implicit conversion sequence from v to T or
4264       // a conversion function that can convert from v to T, then we use that.
4265       // Otherwise, if v is of integral, enumeration, or floating-point type,
4266       // it is converted to the enumeration type via its underlying type.
4267       // There is no overlap possible between these two cases (except when the
4268       // source value is already of the destination type), and the first
4269       // case is handled by the general case for single-element lists below.
4270       ImplicitConversionSequence ICS;
4271       ICS.setStandard();
4272       ICS.Standard.setAsIdentityConversion();
4273       if (!E->isRValue())
4274         ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4275       // If E is of a floating-point type, then the conversion is ill-formed
4276       // due to narrowing, but go through the motions in order to produce the
4277       // right diagnostic.
4278       ICS.Standard.Second = E->getType()->isFloatingType()
4279                                 ? ICK_Floating_Integral
4280                                 : ICK_Integral_Conversion;
4281       ICS.Standard.setFromType(E->getType());
4282       ICS.Standard.setToType(0, E->getType());
4283       ICS.Standard.setToType(1, DestType);
4284       ICS.Standard.setToType(2, DestType);
4285       Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4286                                          /*TopLevelOfInitList*/true);
4287       Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4288       return;
4289     }
4290 
4291     //   - Otherwise, if the initializer list has a single element of type E
4292     //     [...references are handled above...], the object or reference is
4293     //     initialized from that element (by copy-initialization for
4294     //     copy-list-initialization, or by direct-initialization for
4295     //     direct-list-initialization); if a narrowing conversion is required
4296     //     to convert the element to T, the program is ill-formed.
4297     //
4298     // Per core-24034, this is direct-initialization if we were performing
4299     // direct-list-initialization and copy-initialization otherwise.
4300     // We can't use InitListChecker for this, because it always performs
4301     // copy-initialization. This only matters if we might use an 'explicit'
4302     // conversion operator, so we only need to handle the cases where the source
4303     // is of record type.
4304     if (InitList->getInit(0)->getType()->isRecordType()) {
4305       InitializationKind SubKind =
4306           Kind.getKind() == InitializationKind::IK_DirectList
4307               ? InitializationKind::CreateDirect(Kind.getLocation(),
4308                                                  InitList->getLBraceLoc(),
4309                                                  InitList->getRBraceLoc())
4310               : Kind;
4311       Expr *SubInit[1] = { InitList->getInit(0) };
4312       Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4313                               /*TopLevelOfInitList*/true,
4314                               TreatUnavailableAsInvalid);
4315       if (Sequence)
4316         Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4317       return;
4318     }
4319   }
4320 
4321   InitListChecker CheckInitList(S, Entity, InitList,
4322           DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4323   if (CheckInitList.HadError()) {
4324     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4325     return;
4326   }
4327 
4328   // Add the list initialization step with the built init list.
4329   Sequence.AddListInitializationStep(DestType);
4330 }
4331 
4332 /// Try a reference initialization that involves calling a conversion
4333 /// function.
4334 static OverloadingResult TryRefInitWithConversionFunction(
4335     Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4336     Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4337     InitializationSequence &Sequence) {
4338   QualType DestType = Entity.getType();
4339   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4340   QualType T1 = cv1T1.getUnqualifiedType();
4341   QualType cv2T2 = Initializer->getType();
4342   QualType T2 = cv2T2.getUnqualifiedType();
4343 
4344   bool DerivedToBase;
4345   bool ObjCConversion;
4346   bool ObjCLifetimeConversion;
4347   assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4348                                          DerivedToBase, ObjCConversion,
4349                                          ObjCLifetimeConversion) &&
4350          "Must have incompatible references when binding via conversion");
4351   (void)DerivedToBase;
4352   (void)ObjCConversion;
4353   (void)ObjCLifetimeConversion;
4354 
4355   // Build the candidate set directly in the initialization sequence
4356   // structure, so that it will persist if we fail.
4357   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4358   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4359 
4360   // Determine whether we are allowed to call explicit conversion operators.
4361   // Note that none of [over.match.copy], [over.match.conv], nor
4362   // [over.match.ref] permit an explicit constructor to be chosen when
4363   // initializing a reference, not even for direct-initialization.
4364   bool AllowExplicitCtors = false;
4365   bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4366 
4367   const RecordType *T1RecordType = nullptr;
4368   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4369       S.isCompleteType(Kind.getLocation(), T1)) {
4370     // The type we're converting to is a class type. Enumerate its constructors
4371     // to see if there is a suitable conversion.
4372     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4373 
4374     for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4375       auto Info = getConstructorInfo(D);
4376       if (!Info.Constructor)
4377         continue;
4378 
4379       if (!Info.Constructor->isInvalidDecl() &&
4380           Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
4381         if (Info.ConstructorTmpl)
4382           S.AddTemplateOverloadCandidate(
4383               Info.ConstructorTmpl, Info.FoundDecl,
4384               /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4385               /*SuppressUserConversions=*/true,
4386               /*PartialOverloading*/ false, AllowExplicitCtors);
4387         else
4388           S.AddOverloadCandidate(
4389               Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4390               /*SuppressUserConversions=*/true,
4391               /*PartialOverloading*/ false, AllowExplicitCtors);
4392       }
4393     }
4394   }
4395   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4396     return OR_No_Viable_Function;
4397 
4398   const RecordType *T2RecordType = nullptr;
4399   if ((T2RecordType = T2->getAs<RecordType>()) &&
4400       S.isCompleteType(Kind.getLocation(), T2)) {
4401     // The type we're converting from is a class type, enumerate its conversion
4402     // functions.
4403     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4404 
4405     const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4406     for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4407       NamedDecl *D = *I;
4408       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4409       if (isa<UsingShadowDecl>(D))
4410         D = cast<UsingShadowDecl>(D)->getTargetDecl();
4411 
4412       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4413       CXXConversionDecl *Conv;
4414       if (ConvTemplate)
4415         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4416       else
4417         Conv = cast<CXXConversionDecl>(D);
4418 
4419       // If the conversion function doesn't return a reference type,
4420       // it can't be considered for this conversion unless we're allowed to
4421       // consider rvalues.
4422       // FIXME: Do we need to make sure that we only consider conversion
4423       // candidates with reference-compatible results? That might be needed to
4424       // break recursion.
4425       if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4426           (AllowRValues ||
4427            Conv->getConversionType()->isLValueReferenceType())) {
4428         if (ConvTemplate)
4429           S.AddTemplateConversionCandidate(
4430               ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4431               CandidateSet,
4432               /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4433         else
4434           S.AddConversionCandidate(
4435               Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4436               /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4437       }
4438     }
4439   }
4440   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4441     return OR_No_Viable_Function;
4442 
4443   SourceLocation DeclLoc = Initializer->getBeginLoc();
4444 
4445   // Perform overload resolution. If it fails, return the failed result.
4446   OverloadCandidateSet::iterator Best;
4447   if (OverloadingResult Result
4448         = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4449     return Result;
4450 
4451   FunctionDecl *Function = Best->Function;
4452   // This is the overload that will be used for this initialization step if we
4453   // use this initialization. Mark it as referenced.
4454   Function->setReferenced();
4455 
4456   // Compute the returned type and value kind of the conversion.
4457   QualType cv3T3;
4458   if (isa<CXXConversionDecl>(Function))
4459     cv3T3 = Function->getReturnType();
4460   else
4461     cv3T3 = T1;
4462 
4463   ExprValueKind VK = VK_RValue;
4464   if (cv3T3->isLValueReferenceType())
4465     VK = VK_LValue;
4466   else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4467     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4468   cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4469 
4470   // Add the user-defined conversion step.
4471   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4472   Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4473                                  HadMultipleCandidates);
4474 
4475   // Determine whether we'll need to perform derived-to-base adjustments or
4476   // other conversions.
4477   bool NewDerivedToBase = false;
4478   bool NewObjCConversion = false;
4479   bool NewObjCLifetimeConversion = false;
4480   Sema::ReferenceCompareResult NewRefRelationship
4481     = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4482                                      NewDerivedToBase, NewObjCConversion,
4483                                      NewObjCLifetimeConversion);
4484 
4485   // Add the final conversion sequence, if necessary.
4486   if (NewRefRelationship == Sema::Ref_Incompatible) {
4487     assert(!isa<CXXConstructorDecl>(Function) &&
4488            "should not have conversion after constructor");
4489 
4490     ImplicitConversionSequence ICS;
4491     ICS.setStandard();
4492     ICS.Standard = Best->FinalConversion;
4493     Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4494 
4495     // Every implicit conversion results in a prvalue, except for a glvalue
4496     // derived-to-base conversion, which we handle below.
4497     cv3T3 = ICS.Standard.getToType(2);
4498     VK = VK_RValue;
4499   }
4500 
4501   //   If the converted initializer is a prvalue, its type T4 is adjusted to
4502   //   type "cv1 T4" and the temporary materialization conversion is applied.
4503   //
4504   // We adjust the cv-qualifications to match the reference regardless of
4505   // whether we have a prvalue so that the AST records the change. In this
4506   // case, T4 is "cv3 T3".
4507   QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4508   if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4509     Sequence.AddQualificationConversionStep(cv1T4, VK);
4510   Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4511   VK = IsLValueRef ? VK_LValue : VK_XValue;
4512 
4513   if (NewDerivedToBase)
4514     Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4515   else if (NewObjCConversion)
4516     Sequence.AddObjCObjectConversionStep(cv1T1);
4517 
4518   return OR_Success;
4519 }
4520 
4521 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4522                                            const InitializedEntity &Entity,
4523                                            Expr *CurInitExpr);
4524 
4525 /// Attempt reference initialization (C++0x [dcl.init.ref])
4526 static void TryReferenceInitialization(Sema &S,
4527                                        const InitializedEntity &Entity,
4528                                        const InitializationKind &Kind,
4529                                        Expr *Initializer,
4530                                        InitializationSequence &Sequence) {
4531   QualType DestType = Entity.getType();
4532   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4533   Qualifiers T1Quals;
4534   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4535   QualType cv2T2 = Initializer->getType();
4536   Qualifiers T2Quals;
4537   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4538 
4539   // If the initializer is the address of an overloaded function, try
4540   // to resolve the overloaded function. If all goes well, T2 is the
4541   // type of the resulting function.
4542   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4543                                                    T1, Sequence))
4544     return;
4545 
4546   // Delegate everything else to a subfunction.
4547   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4548                                  T1Quals, cv2T2, T2, T2Quals, Sequence);
4549 }
4550 
4551 /// Determine whether an expression is a non-referenceable glvalue (one to
4552 /// which a reference can never bind). Attempting to bind a reference to
4553 /// such a glvalue will always create a temporary.
4554 static bool isNonReferenceableGLValue(Expr *E) {
4555   return E->refersToBitField() || E->refersToVectorElement();
4556 }
4557 
4558 /// Reference initialization without resolving overloaded functions.
4559 static void TryReferenceInitializationCore(Sema &S,
4560                                            const InitializedEntity &Entity,
4561                                            const InitializationKind &Kind,
4562                                            Expr *Initializer,
4563                                            QualType cv1T1, QualType T1,
4564                                            Qualifiers T1Quals,
4565                                            QualType cv2T2, QualType T2,
4566                                            Qualifiers T2Quals,
4567                                            InitializationSequence &Sequence) {
4568   QualType DestType = Entity.getType();
4569   SourceLocation DeclLoc = Initializer->getBeginLoc();
4570   // Compute some basic properties of the types and the initializer.
4571   bool isLValueRef = DestType->isLValueReferenceType();
4572   bool isRValueRef = !isLValueRef;
4573   bool DerivedToBase = false;
4574   bool ObjCConversion = false;
4575   bool ObjCLifetimeConversion = false;
4576   Expr::Classification InitCategory = Initializer->Classify(S.Context);
4577   Sema::ReferenceCompareResult RefRelationship
4578     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4579                                      ObjCConversion, ObjCLifetimeConversion);
4580 
4581   // C++0x [dcl.init.ref]p5:
4582   //   A reference to type "cv1 T1" is initialized by an expression of type
4583   //   "cv2 T2" as follows:
4584   //
4585   //     - If the reference is an lvalue reference and the initializer
4586   //       expression
4587   // Note the analogous bullet points for rvalue refs to functions. Because
4588   // there are no function rvalues in C++, rvalue refs to functions are treated
4589   // like lvalue refs.
4590   OverloadingResult ConvOvlResult = OR_Success;
4591   bool T1Function = T1->isFunctionType();
4592   if (isLValueRef || T1Function) {
4593     if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4594         (RefRelationship == Sema::Ref_Compatible ||
4595          (Kind.isCStyleOrFunctionalCast() &&
4596           RefRelationship == Sema::Ref_Related))) {
4597       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
4598       //     reference-compatible with "cv2 T2," or
4599       if (T1Quals != T2Quals)
4600         // Convert to cv1 T2. This should only add qualifiers unless this is a
4601         // c-style cast. The removal of qualifiers in that case notionally
4602         // happens after the reference binding, but that doesn't matter.
4603         Sequence.AddQualificationConversionStep(
4604             S.Context.getQualifiedType(T2, T1Quals),
4605             Initializer->getValueKind());
4606       if (DerivedToBase)
4607         Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4608       else if (ObjCConversion)
4609         Sequence.AddObjCObjectConversionStep(cv1T1);
4610 
4611       // We only create a temporary here when binding a reference to a
4612       // bit-field or vector element. Those cases are't supposed to be
4613       // handled by this bullet, but the outcome is the same either way.
4614       Sequence.AddReferenceBindingStep(cv1T1, false);
4615       return;
4616     }
4617 
4618     //     - has a class type (i.e., T2 is a class type), where T1 is not
4619     //       reference-related to T2, and can be implicitly converted to an
4620     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4621     //       with "cv3 T3" (this conversion is selected by enumerating the
4622     //       applicable conversion functions (13.3.1.6) and choosing the best
4623     //       one through overload resolution (13.3)),
4624     // If we have an rvalue ref to function type here, the rhs must be
4625     // an rvalue. DR1287 removed the "implicitly" here.
4626     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4627         (isLValueRef || InitCategory.isRValue())) {
4628       ConvOvlResult = TryRefInitWithConversionFunction(
4629           S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4630           /*IsLValueRef*/ isLValueRef, Sequence);
4631       if (ConvOvlResult == OR_Success)
4632         return;
4633       if (ConvOvlResult != OR_No_Viable_Function)
4634         Sequence.SetOverloadFailure(
4635             InitializationSequence::FK_ReferenceInitOverloadFailed,
4636             ConvOvlResult);
4637     }
4638   }
4639 
4640   //     - Otherwise, the reference shall be an lvalue reference to a
4641   //       non-volatile const type (i.e., cv1 shall be const), or the reference
4642   //       shall be an rvalue reference.
4643   //       For address spaces, we interpret this to mean that an addr space
4644   //       of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4645   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4646                        T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
4647     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4648       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4649     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4650       Sequence.SetOverloadFailure(
4651                         InitializationSequence::FK_ReferenceInitOverloadFailed,
4652                                   ConvOvlResult);
4653     else if (!InitCategory.isLValue())
4654       Sequence.SetFailed(
4655           T1Quals.isAddressSpaceSupersetOf(T2Quals)
4656               ? InitializationSequence::
4657                     FK_NonConstLValueReferenceBindingToTemporary
4658               : InitializationSequence::FK_ReferenceInitDropsQualifiers);
4659     else {
4660       InitializationSequence::FailureKind FK;
4661       switch (RefRelationship) {
4662       case Sema::Ref_Compatible:
4663         if (Initializer->refersToBitField())
4664           FK = InitializationSequence::
4665               FK_NonConstLValueReferenceBindingToBitfield;
4666         else if (Initializer->refersToVectorElement())
4667           FK = InitializationSequence::
4668               FK_NonConstLValueReferenceBindingToVectorElement;
4669         else
4670           llvm_unreachable("unexpected kind of compatible initializer");
4671         break;
4672       case Sema::Ref_Related:
4673         FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4674         break;
4675       case Sema::Ref_Incompatible:
4676         FK = InitializationSequence::
4677             FK_NonConstLValueReferenceBindingToUnrelated;
4678         break;
4679       }
4680       Sequence.SetFailed(FK);
4681     }
4682     return;
4683   }
4684 
4685   //    - If the initializer expression
4686   //      - is an
4687   // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4688   // [1z]   rvalue (but not a bit-field) or
4689   //        function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4690   //
4691   // Note: functions are handled above and below rather than here...
4692   if (!T1Function &&
4693       (RefRelationship == Sema::Ref_Compatible ||
4694        (Kind.isCStyleOrFunctionalCast() &&
4695         RefRelationship == Sema::Ref_Related)) &&
4696       ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4697        (InitCategory.isPRValue() &&
4698         (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4699          T2->isArrayType())))) {
4700     ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4701     if (InitCategory.isPRValue() && T2->isRecordType()) {
4702       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4703       // compiler the freedom to perform a copy here or bind to the
4704       // object, while C++0x requires that we bind directly to the
4705       // object. Hence, we always bind to the object without making an
4706       // extra copy. However, in C++03 requires that we check for the
4707       // presence of a suitable copy constructor:
4708       //
4709       //   The constructor that would be used to make the copy shall
4710       //   be callable whether or not the copy is actually done.
4711       if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4712         Sequence.AddExtraneousCopyToTemporary(cv2T2);
4713       else if (S.getLangOpts().CPlusPlus11)
4714         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4715     }
4716 
4717     // C++1z [dcl.init.ref]/5.2.1.2:
4718     //   If the converted initializer is a prvalue, its type T4 is adjusted
4719     //   to type "cv1 T4" and the temporary materialization conversion is
4720     //   applied.
4721     // Postpone address space conversions to after the temporary materialization
4722     // conversion to allow creating temporaries in the alloca address space.
4723     auto T1QualsIgnoreAS = T1Quals;
4724     auto T2QualsIgnoreAS = T2Quals;
4725     if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4726       T1QualsIgnoreAS.removeAddressSpace();
4727       T2QualsIgnoreAS.removeAddressSpace();
4728     }
4729     QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4730     if (T1QualsIgnoreAS != T2QualsIgnoreAS)
4731       Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4732     Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4733     ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4734     // Add addr space conversion if required.
4735     if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4736       auto T4Quals = cv1T4.getQualifiers();
4737       T4Quals.addAddressSpace(T1Quals.getAddressSpace());
4738       QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
4739       Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
4740     }
4741 
4742     //   In any case, the reference is bound to the resulting glvalue (or to
4743     //   an appropriate base class subobject).
4744     if (DerivedToBase)
4745       Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4746     else if (ObjCConversion)
4747       Sequence.AddObjCObjectConversionStep(cv1T1);
4748     return;
4749   }
4750 
4751   //       - has a class type (i.e., T2 is a class type), where T1 is not
4752   //         reference-related to T2, and can be implicitly converted to an
4753   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
4754   //         where "cv1 T1" is reference-compatible with "cv3 T3",
4755   //
4756   // DR1287 removes the "implicitly" here.
4757   if (T2->isRecordType()) {
4758     if (RefRelationship == Sema::Ref_Incompatible) {
4759       ConvOvlResult = TryRefInitWithConversionFunction(
4760           S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4761           /*IsLValueRef*/ isLValueRef, Sequence);
4762       if (ConvOvlResult)
4763         Sequence.SetOverloadFailure(
4764             InitializationSequence::FK_ReferenceInitOverloadFailed,
4765             ConvOvlResult);
4766 
4767       return;
4768     }
4769 
4770     if (RefRelationship == Sema::Ref_Compatible &&
4771         isRValueRef && InitCategory.isLValue()) {
4772       Sequence.SetFailed(
4773         InitializationSequence::FK_RValueReferenceBindingToLValue);
4774       return;
4775     }
4776 
4777     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4778     return;
4779   }
4780 
4781   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
4782   //        from the initializer expression using the rules for a non-reference
4783   //        copy-initialization (8.5). The reference is then bound to the
4784   //        temporary. [...]
4785 
4786   // Ignore address space of reference type at this point and perform address
4787   // space conversion after the reference binding step.
4788   QualType cv1T1IgnoreAS =
4789       T1Quals.hasAddressSpace()
4790           ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
4791           : cv1T1;
4792 
4793   InitializedEntity TempEntity =
4794       InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4795 
4796   // FIXME: Why do we use an implicit conversion here rather than trying
4797   // copy-initialization?
4798   ImplicitConversionSequence ICS
4799     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4800                               /*SuppressUserConversions=*/false,
4801                               /*AllowExplicit=*/false,
4802                               /*FIXME:InOverloadResolution=*/false,
4803                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4804                               /*AllowObjCWritebackConversion=*/false);
4805 
4806   if (ICS.isBad()) {
4807     // FIXME: Use the conversion function set stored in ICS to turn
4808     // this into an overloading ambiguity diagnostic. However, we need
4809     // to keep that set as an OverloadCandidateSet rather than as some
4810     // other kind of set.
4811     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4812       Sequence.SetOverloadFailure(
4813                         InitializationSequence::FK_ReferenceInitOverloadFailed,
4814                                   ConvOvlResult);
4815     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4816       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4817     else
4818       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4819     return;
4820   } else {
4821     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4822   }
4823 
4824   //        [...] If T1 is reference-related to T2, cv1 must be the
4825   //        same cv-qualification as, or greater cv-qualification
4826   //        than, cv2; otherwise, the program is ill-formed.
4827   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4828   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4829   if ((RefRelationship == Sema::Ref_Related &&
4830        (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
4831       !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4832     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4833     return;
4834   }
4835 
4836   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
4837   //   reference, the initializer expression shall not be an lvalue.
4838   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4839       InitCategory.isLValue()) {
4840     Sequence.SetFailed(
4841                     InitializationSequence::FK_RValueReferenceBindingToLValue);
4842     return;
4843   }
4844 
4845   Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
4846 
4847   if (T1Quals.hasAddressSpace()) {
4848     if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
4849                                               LangAS::Default)) {
4850       Sequence.SetFailed(
4851           InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
4852       return;
4853     }
4854     Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
4855                                                                : VK_XValue);
4856   }
4857 }
4858 
4859 /// Attempt character array initialization from a string literal
4860 /// (C++ [dcl.init.string], C99 6.7.8).
4861 static void TryStringLiteralInitialization(Sema &S,
4862                                            const InitializedEntity &Entity,
4863                                            const InitializationKind &Kind,
4864                                            Expr *Initializer,
4865                                        InitializationSequence &Sequence) {
4866   Sequence.AddStringInitStep(Entity.getType());
4867 }
4868 
4869 /// Attempt value initialization (C++ [dcl.init]p7).
4870 static void TryValueInitialization(Sema &S,
4871                                    const InitializedEntity &Entity,
4872                                    const InitializationKind &Kind,
4873                                    InitializationSequence &Sequence,
4874                                    InitListExpr *InitList) {
4875   assert((!InitList || InitList->getNumInits() == 0) &&
4876          "Shouldn't use value-init for non-empty init lists");
4877 
4878   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4879   //
4880   //   To value-initialize an object of type T means:
4881   QualType T = Entity.getType();
4882 
4883   //     -- if T is an array type, then each element is value-initialized;
4884   T = S.Context.getBaseElementType(T);
4885 
4886   if (const RecordType *RT = T->getAs<RecordType>()) {
4887     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4888       bool NeedZeroInitialization = true;
4889       // C++98:
4890       // -- if T is a class type (clause 9) with a user-declared constructor
4891       //    (12.1), then the default constructor for T is called (and the
4892       //    initialization is ill-formed if T has no accessible default
4893       //    constructor);
4894       // C++11:
4895       // -- if T is a class type (clause 9) with either no default constructor
4896       //    (12.1 [class.ctor]) or a default constructor that is user-provided
4897       //    or deleted, then the object is default-initialized;
4898       //
4899       // Note that the C++11 rule is the same as the C++98 rule if there are no
4900       // defaulted or deleted constructors, so we just use it unconditionally.
4901       CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4902       if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4903         NeedZeroInitialization = false;
4904 
4905       // -- if T is a (possibly cv-qualified) non-union class type without a
4906       //    user-provided or deleted default constructor, then the object is
4907       //    zero-initialized and, if T has a non-trivial default constructor,
4908       //    default-initialized;
4909       // The 'non-union' here was removed by DR1502. The 'non-trivial default
4910       // constructor' part was removed by DR1507.
4911       if (NeedZeroInitialization)
4912         Sequence.AddZeroInitializationStep(Entity.getType());
4913 
4914       // C++03:
4915       // -- if T is a non-union class type without a user-declared constructor,
4916       //    then every non-static data member and base class component of T is
4917       //    value-initialized;
4918       // [...] A program that calls for [...] value-initialization of an
4919       // entity of reference type is ill-formed.
4920       //
4921       // C++11 doesn't need this handling, because value-initialization does not
4922       // occur recursively there, and the implicit default constructor is
4923       // defined as deleted in the problematic cases.
4924       if (!S.getLangOpts().CPlusPlus11 &&
4925           ClassDecl->hasUninitializedReferenceMember()) {
4926         Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4927         return;
4928       }
4929 
4930       // If this is list-value-initialization, pass the empty init list on when
4931       // building the constructor call. This affects the semantics of a few
4932       // things (such as whether an explicit default constructor can be called).
4933       Expr *InitListAsExpr = InitList;
4934       MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4935       bool InitListSyntax = InitList;
4936 
4937       // FIXME: Instead of creating a CXXConstructExpr of array type here,
4938       // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4939       return TryConstructorInitialization(
4940           S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4941     }
4942   }
4943 
4944   Sequence.AddZeroInitializationStep(Entity.getType());
4945 }
4946 
4947 /// Attempt default initialization (C++ [dcl.init]p6).
4948 static void TryDefaultInitialization(Sema &S,
4949                                      const InitializedEntity &Entity,
4950                                      const InitializationKind &Kind,
4951                                      InitializationSequence &Sequence) {
4952   assert(Kind.getKind() == InitializationKind::IK_Default);
4953 
4954   // C++ [dcl.init]p6:
4955   //   To default-initialize an object of type T means:
4956   //     - if T is an array type, each element is default-initialized;
4957   QualType DestType = S.Context.getBaseElementType(Entity.getType());
4958 
4959   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
4960   //       constructor for T is called (and the initialization is ill-formed if
4961   //       T has no accessible default constructor);
4962   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4963     TryConstructorInitialization(S, Entity, Kind, None, DestType,
4964                                  Entity.getType(), Sequence);
4965     return;
4966   }
4967 
4968   //     - otherwise, no initialization is performed.
4969 
4970   //   If a program calls for the default initialization of an object of
4971   //   a const-qualified type T, T shall be a class type with a user-provided
4972   //   default constructor.
4973   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4974     if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4975       Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4976     return;
4977   }
4978 
4979   // If the destination type has a lifetime property, zero-initialize it.
4980   if (DestType.getQualifiers().hasObjCLifetime()) {
4981     Sequence.AddZeroInitializationStep(Entity.getType());
4982     return;
4983   }
4984 }
4985 
4986 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
4987 /// which enumerates all conversion functions and performs overload resolution
4988 /// to select the best.
4989 static void TryUserDefinedConversion(Sema &S,
4990                                      QualType DestType,
4991                                      const InitializationKind &Kind,
4992                                      Expr *Initializer,
4993                                      InitializationSequence &Sequence,
4994                                      bool TopLevelOfInitList) {
4995   assert(!DestType->isReferenceType() && "References are handled elsewhere");
4996   QualType SourceType = Initializer->getType();
4997   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4998          "Must have a class type to perform a user-defined conversion");
4999 
5000   // Build the candidate set directly in the initialization sequence
5001   // structure, so that it will persist if we fail.
5002   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5003   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5004   CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5005 
5006   // Determine whether we are allowed to call explicit constructors or
5007   // explicit conversion operators.
5008   bool AllowExplicit = Kind.AllowExplicit();
5009 
5010   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5011     // The type we're converting to is a class type. Enumerate its constructors
5012     // to see if there is a suitable conversion.
5013     CXXRecordDecl *DestRecordDecl
5014       = cast<CXXRecordDecl>(DestRecordType->getDecl());
5015 
5016     // Try to complete the type we're converting to.
5017     if (S.isCompleteType(Kind.getLocation(), DestType)) {
5018       for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5019         auto Info = getConstructorInfo(D);
5020         if (!Info.Constructor)
5021           continue;
5022 
5023         if (!Info.Constructor->isInvalidDecl() &&
5024             Info.Constructor->isConvertingConstructor(AllowExplicit)) {
5025           if (Info.ConstructorTmpl)
5026             S.AddTemplateOverloadCandidate(
5027                 Info.ConstructorTmpl, Info.FoundDecl,
5028                 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5029                 /*SuppressUserConversions=*/true,
5030                 /*PartialOverloading*/ false, AllowExplicit);
5031           else
5032             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5033                                    Initializer, CandidateSet,
5034                                    /*SuppressUserConversions=*/true,
5035                                    /*PartialOverloading*/ false, AllowExplicit);
5036         }
5037       }
5038     }
5039   }
5040 
5041   SourceLocation DeclLoc = Initializer->getBeginLoc();
5042 
5043   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5044     // The type we're converting from is a class type, enumerate its conversion
5045     // functions.
5046 
5047     // We can only enumerate the conversion functions for a complete type; if
5048     // the type isn't complete, simply skip this step.
5049     if (S.isCompleteType(DeclLoc, SourceType)) {
5050       CXXRecordDecl *SourceRecordDecl
5051         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5052 
5053       const auto &Conversions =
5054           SourceRecordDecl->getVisibleConversionFunctions();
5055       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5056         NamedDecl *D = *I;
5057         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5058         if (isa<UsingShadowDecl>(D))
5059           D = cast<UsingShadowDecl>(D)->getTargetDecl();
5060 
5061         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5062         CXXConversionDecl *Conv;
5063         if (ConvTemplate)
5064           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5065         else
5066           Conv = cast<CXXConversionDecl>(D);
5067 
5068         if (AllowExplicit || !Conv->isExplicit()) {
5069           if (ConvTemplate)
5070             S.AddTemplateConversionCandidate(
5071                 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5072                 CandidateSet, AllowExplicit, AllowExplicit);
5073           else
5074             S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5075                                      DestType, CandidateSet, AllowExplicit,
5076                                      AllowExplicit);
5077         }
5078       }
5079     }
5080   }
5081 
5082   // Perform overload resolution. If it fails, return the failed result.
5083   OverloadCandidateSet::iterator Best;
5084   if (OverloadingResult Result
5085         = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5086     Sequence.SetOverloadFailure(
5087                         InitializationSequence::FK_UserConversionOverloadFailed,
5088                                 Result);
5089     return;
5090   }
5091 
5092   FunctionDecl *Function = Best->Function;
5093   Function->setReferenced();
5094   bool HadMultipleCandidates = (CandidateSet.size() > 1);
5095 
5096   if (isa<CXXConstructorDecl>(Function)) {
5097     // Add the user-defined conversion step. Any cv-qualification conversion is
5098     // subsumed by the initialization. Per DR5, the created temporary is of the
5099     // cv-unqualified type of the destination.
5100     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5101                                    DestType.getUnqualifiedType(),
5102                                    HadMultipleCandidates);
5103 
5104     // C++14 and before:
5105     //   - if the function is a constructor, the call initializes a temporary
5106     //     of the cv-unqualified version of the destination type. The [...]
5107     //     temporary [...] is then used to direct-initialize, according to the
5108     //     rules above, the object that is the destination of the
5109     //     copy-initialization.
5110     // Note that this just performs a simple object copy from the temporary.
5111     //
5112     // C++17:
5113     //   - if the function is a constructor, the call is a prvalue of the
5114     //     cv-unqualified version of the destination type whose return object
5115     //     is initialized by the constructor. The call is used to
5116     //     direct-initialize, according to the rules above, the object that
5117     //     is the destination of the copy-initialization.
5118     // Therefore we need to do nothing further.
5119     //
5120     // FIXME: Mark this copy as extraneous.
5121     if (!S.getLangOpts().CPlusPlus17)
5122       Sequence.AddFinalCopy(DestType);
5123     else if (DestType.hasQualifiers())
5124       Sequence.AddQualificationConversionStep(DestType, VK_RValue);
5125     return;
5126   }
5127 
5128   // Add the user-defined conversion step that calls the conversion function.
5129   QualType ConvType = Function->getCallResultType();
5130   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5131                                  HadMultipleCandidates);
5132 
5133   if (ConvType->getAs<RecordType>()) {
5134     //   The call is used to direct-initialize [...] the object that is the
5135     //   destination of the copy-initialization.
5136     //
5137     // In C++17, this does not call a constructor if we enter /17.6.1:
5138     //   - If the initializer expression is a prvalue and the cv-unqualified
5139     //     version of the source type is the same as the class of the
5140     //     destination [... do not make an extra copy]
5141     //
5142     // FIXME: Mark this copy as extraneous.
5143     if (!S.getLangOpts().CPlusPlus17 ||
5144         Function->getReturnType()->isReferenceType() ||
5145         !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5146       Sequence.AddFinalCopy(DestType);
5147     else if (!S.Context.hasSameType(ConvType, DestType))
5148       Sequence.AddQualificationConversionStep(DestType, VK_RValue);
5149     return;
5150   }
5151 
5152   // If the conversion following the call to the conversion function
5153   // is interesting, add it as a separate step.
5154   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5155       Best->FinalConversion.Third) {
5156     ImplicitConversionSequence ICS;
5157     ICS.setStandard();
5158     ICS.Standard = Best->FinalConversion;
5159     Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5160   }
5161 }
5162 
5163 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5164 /// a function with a pointer return type contains a 'return false;' statement.
5165 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
5166 /// code using that header.
5167 ///
5168 /// Work around this by treating 'return false;' as zero-initializing the result
5169 /// if it's used in a pointer-returning function in a system header.
5170 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5171                                               const InitializedEntity &Entity,
5172                                               const Expr *Init) {
5173   return S.getLangOpts().CPlusPlus11 &&
5174          Entity.getKind() == InitializedEntity::EK_Result &&
5175          Entity.getType()->isPointerType() &&
5176          isa<CXXBoolLiteralExpr>(Init) &&
5177          !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5178          S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5179 }
5180 
5181 /// The non-zero enum values here are indexes into diagnostic alternatives.
5182 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5183 
5184 /// Determines whether this expression is an acceptable ICR source.
5185 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5186                                          bool isAddressOf, bool &isWeakAccess) {
5187   // Skip parens.
5188   e = e->IgnoreParens();
5189 
5190   // Skip address-of nodes.
5191   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5192     if (op->getOpcode() == UO_AddrOf)
5193       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5194                                 isWeakAccess);
5195 
5196   // Skip certain casts.
5197   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5198     switch (ce->getCastKind()) {
5199     case CK_Dependent:
5200     case CK_BitCast:
5201     case CK_LValueBitCast:
5202     case CK_NoOp:
5203       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5204 
5205     case CK_ArrayToPointerDecay:
5206       return IIK_nonscalar;
5207 
5208     case CK_NullToPointer:
5209       return IIK_okay;
5210 
5211     default:
5212       break;
5213     }
5214 
5215   // If we have a declaration reference, it had better be a local variable.
5216   } else if (isa<DeclRefExpr>(e)) {
5217     // set isWeakAccess to true, to mean that there will be an implicit
5218     // load which requires a cleanup.
5219     if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5220       isWeakAccess = true;
5221 
5222     if (!isAddressOf) return IIK_nonlocal;
5223 
5224     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5225     if (!var) return IIK_nonlocal;
5226 
5227     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5228 
5229   // If we have a conditional operator, check both sides.
5230   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5231     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5232                                                 isWeakAccess))
5233       return iik;
5234 
5235     return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5236 
5237   // These are never scalar.
5238   } else if (isa<ArraySubscriptExpr>(e)) {
5239     return IIK_nonscalar;
5240 
5241   // Otherwise, it needs to be a null pointer constant.
5242   } else {
5243     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5244             ? IIK_okay : IIK_nonlocal);
5245   }
5246 
5247   return IIK_nonlocal;
5248 }
5249 
5250 /// Check whether the given expression is a valid operand for an
5251 /// indirect copy/restore.
5252 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5253   assert(src->isRValue());
5254   bool isWeakAccess = false;
5255   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5256   // If isWeakAccess to true, there will be an implicit
5257   // load which requires a cleanup.
5258   if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5259     S.Cleanup.setExprNeedsCleanups(true);
5260 
5261   if (iik == IIK_okay) return;
5262 
5263   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5264     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
5265     << src->getSourceRange();
5266 }
5267 
5268 /// Determine whether we have compatible array types for the
5269 /// purposes of GNU by-copy array initialization.
5270 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5271                                     const ArrayType *Source) {
5272   // If the source and destination array types are equivalent, we're
5273   // done.
5274   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5275     return true;
5276 
5277   // Make sure that the element types are the same.
5278   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5279     return false;
5280 
5281   // The only mismatch we allow is when the destination is an
5282   // incomplete array type and the source is a constant array type.
5283   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5284 }
5285 
5286 static bool tryObjCWritebackConversion(Sema &S,
5287                                        InitializationSequence &Sequence,
5288                                        const InitializedEntity &Entity,
5289                                        Expr *Initializer) {
5290   bool ArrayDecay = false;
5291   QualType ArgType = Initializer->getType();
5292   QualType ArgPointee;
5293   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5294     ArrayDecay = true;
5295     ArgPointee = ArgArrayType->getElementType();
5296     ArgType = S.Context.getPointerType(ArgPointee);
5297   }
5298 
5299   // Handle write-back conversion.
5300   QualType ConvertedArgType;
5301   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5302                                    ConvertedArgType))
5303     return false;
5304 
5305   // We should copy unless we're passing to an argument explicitly
5306   // marked 'out'.
5307   bool ShouldCopy = true;
5308   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5309     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5310 
5311   // Do we need an lvalue conversion?
5312   if (ArrayDecay || Initializer->isGLValue()) {
5313     ImplicitConversionSequence ICS;
5314     ICS.setStandard();
5315     ICS.Standard.setAsIdentityConversion();
5316 
5317     QualType ResultType;
5318     if (ArrayDecay) {
5319       ICS.Standard.First = ICK_Array_To_Pointer;
5320       ResultType = S.Context.getPointerType(ArgPointee);
5321     } else {
5322       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5323       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5324     }
5325 
5326     Sequence.AddConversionSequenceStep(ICS, ResultType);
5327   }
5328 
5329   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5330   return true;
5331 }
5332 
5333 static bool TryOCLSamplerInitialization(Sema &S,
5334                                         InitializationSequence &Sequence,
5335                                         QualType DestType,
5336                                         Expr *Initializer) {
5337   if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5338       (!Initializer->isIntegerConstantExpr(S.Context) &&
5339       !Initializer->getType()->isSamplerT()))
5340     return false;
5341 
5342   Sequence.AddOCLSamplerInitStep(DestType);
5343   return true;
5344 }
5345 
5346 static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5347   return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5348     (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5349 }
5350 
5351 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5352                                                InitializationSequence &Sequence,
5353                                                QualType DestType,
5354                                                Expr *Initializer) {
5355   if (!S.getLangOpts().OpenCL)
5356     return false;
5357 
5358   //
5359   // OpenCL 1.2 spec, s6.12.10
5360   //
5361   // The event argument can also be used to associate the
5362   // async_work_group_copy with a previous async copy allowing
5363   // an event to be shared by multiple async copies; otherwise
5364   // event should be zero.
5365   //
5366   if (DestType->isEventT() || DestType->isQueueT()) {
5367     if (!IsZeroInitializer(Initializer, S))
5368       return false;
5369 
5370     Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5371     return true;
5372   }
5373 
5374   // We should allow zero initialization for all types defined in the
5375   // cl_intel_device_side_avc_motion_estimation extension, except
5376   // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5377   if (S.getOpenCLOptions().isEnabled(
5378           "cl_intel_device_side_avc_motion_estimation") &&
5379       DestType->isOCLIntelSubgroupAVCType()) {
5380     if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5381         DestType->isOCLIntelSubgroupAVCMceResultType())
5382       return false;
5383     if (!IsZeroInitializer(Initializer, S))
5384       return false;
5385 
5386     Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5387     return true;
5388   }
5389 
5390   return false;
5391 }
5392 
5393 InitializationSequence::InitializationSequence(Sema &S,
5394                                                const InitializedEntity &Entity,
5395                                                const InitializationKind &Kind,
5396                                                MultiExprArg Args,
5397                                                bool TopLevelOfInitList,
5398                                                bool TreatUnavailableAsInvalid)
5399     : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5400   InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5401                  TreatUnavailableAsInvalid);
5402 }
5403 
5404 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5405 /// address of that function, this returns true. Otherwise, it returns false.
5406 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5407   auto *DRE = dyn_cast<DeclRefExpr>(E);
5408   if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5409     return false;
5410 
5411   return !S.checkAddressOfFunctionIsAvailable(
5412       cast<FunctionDecl>(DRE->getDecl()));
5413 }
5414 
5415 /// Determine whether we can perform an elementwise array copy for this kind
5416 /// of entity.
5417 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5418   switch (Entity.getKind()) {
5419   case InitializedEntity::EK_LambdaCapture:
5420     // C++ [expr.prim.lambda]p24:
5421     //   For array members, the array elements are direct-initialized in
5422     //   increasing subscript order.
5423     return true;
5424 
5425   case InitializedEntity::EK_Variable:
5426     // C++ [dcl.decomp]p1:
5427     //   [...] each element is copy-initialized or direct-initialized from the
5428     //   corresponding element of the assignment-expression [...]
5429     return isa<DecompositionDecl>(Entity.getDecl());
5430 
5431   case InitializedEntity::EK_Member:
5432     // C++ [class.copy.ctor]p14:
5433     //   - if the member is an array, each element is direct-initialized with
5434     //     the corresponding subobject of x
5435     return Entity.isImplicitMemberInitializer();
5436 
5437   case InitializedEntity::EK_ArrayElement:
5438     // All the above cases are intended to apply recursively, even though none
5439     // of them actually say that.
5440     if (auto *E = Entity.getParent())
5441       return canPerformArrayCopy(*E);
5442     break;
5443 
5444   default:
5445     break;
5446   }
5447 
5448   return false;
5449 }
5450 
5451 void InitializationSequence::InitializeFrom(Sema &S,
5452                                             const InitializedEntity &Entity,
5453                                             const InitializationKind &Kind,
5454                                             MultiExprArg Args,
5455                                             bool TopLevelOfInitList,
5456                                             bool TreatUnavailableAsInvalid) {
5457   ASTContext &Context = S.Context;
5458 
5459   // Eliminate non-overload placeholder types in the arguments.  We
5460   // need to do this before checking whether types are dependent
5461   // because lowering a pseudo-object expression might well give us
5462   // something of dependent type.
5463   for (unsigned I = 0, E = Args.size(); I != E; ++I)
5464     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5465       // FIXME: should we be doing this here?
5466       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5467       if (result.isInvalid()) {
5468         SetFailed(FK_PlaceholderType);
5469         return;
5470       }
5471       Args[I] = result.get();
5472     }
5473 
5474   // C++0x [dcl.init]p16:
5475   //   The semantics of initializers are as follows. The destination type is
5476   //   the type of the object or reference being initialized and the source
5477   //   type is the type of the initializer expression. The source type is not
5478   //   defined when the initializer is a braced-init-list or when it is a
5479   //   parenthesized list of expressions.
5480   QualType DestType = Entity.getType();
5481 
5482   if (DestType->isDependentType() ||
5483       Expr::hasAnyTypeDependentArguments(Args)) {
5484     SequenceKind = DependentSequence;
5485     return;
5486   }
5487 
5488   // Almost everything is a normal sequence.
5489   setSequenceKind(NormalSequence);
5490 
5491   QualType SourceType;
5492   Expr *Initializer = nullptr;
5493   if (Args.size() == 1) {
5494     Initializer = Args[0];
5495     if (S.getLangOpts().ObjC) {
5496       if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
5497                                               DestType, Initializer->getType(),
5498                                               Initializer) ||
5499           S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5500         Args[0] = Initializer;
5501     }
5502     if (!isa<InitListExpr>(Initializer))
5503       SourceType = Initializer->getType();
5504   }
5505 
5506   //     - If the initializer is a (non-parenthesized) braced-init-list, the
5507   //       object is list-initialized (8.5.4).
5508   if (Kind.getKind() != InitializationKind::IK_Direct) {
5509     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5510       TryListInitialization(S, Entity, Kind, InitList, *this,
5511                             TreatUnavailableAsInvalid);
5512       return;
5513     }
5514   }
5515 
5516   //     - If the destination type is a reference type, see 8.5.3.
5517   if (DestType->isReferenceType()) {
5518     // C++0x [dcl.init.ref]p1:
5519     //   A variable declared to be a T& or T&&, that is, "reference to type T"
5520     //   (8.3.2), shall be initialized by an object, or function, of type T or
5521     //   by an object that can be converted into a T.
5522     // (Therefore, multiple arguments are not permitted.)
5523     if (Args.size() != 1)
5524       SetFailed(FK_TooManyInitsForReference);
5525     // C++17 [dcl.init.ref]p5:
5526     //   A reference [...] is initialized by an expression [...] as follows:
5527     // If the initializer is not an expression, presumably we should reject,
5528     // but the standard fails to actually say so.
5529     else if (isa<InitListExpr>(Args[0]))
5530       SetFailed(FK_ParenthesizedListInitForReference);
5531     else
5532       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5533     return;
5534   }
5535 
5536   //     - If the initializer is (), the object is value-initialized.
5537   if (Kind.getKind() == InitializationKind::IK_Value ||
5538       (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5539     TryValueInitialization(S, Entity, Kind, *this);
5540     return;
5541   }
5542 
5543   // Handle default initialization.
5544   if (Kind.getKind() == InitializationKind::IK_Default) {
5545     TryDefaultInitialization(S, Entity, Kind, *this);
5546     return;
5547   }
5548 
5549   //     - If the destination type is an array of characters, an array of
5550   //       char16_t, an array of char32_t, or an array of wchar_t, and the
5551   //       initializer is a string literal, see 8.5.2.
5552   //     - Otherwise, if the destination type is an array, the program is
5553   //       ill-formed.
5554   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5555     if (Initializer && isa<VariableArrayType>(DestAT)) {
5556       SetFailed(FK_VariableLengthArrayHasInitializer);
5557       return;
5558     }
5559 
5560     if (Initializer) {
5561       switch (IsStringInit(Initializer, DestAT, Context)) {
5562       case SIF_None:
5563         TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5564         return;
5565       case SIF_NarrowStringIntoWideChar:
5566         SetFailed(FK_NarrowStringIntoWideCharArray);
5567         return;
5568       case SIF_WideStringIntoChar:
5569         SetFailed(FK_WideStringIntoCharArray);
5570         return;
5571       case SIF_IncompatWideStringIntoWideChar:
5572         SetFailed(FK_IncompatWideStringIntoWideChar);
5573         return;
5574       case SIF_PlainStringIntoUTF8Char:
5575         SetFailed(FK_PlainStringIntoUTF8Char);
5576         return;
5577       case SIF_UTF8StringIntoPlainChar:
5578         SetFailed(FK_UTF8StringIntoPlainChar);
5579         return;
5580       case SIF_Other:
5581         break;
5582       }
5583     }
5584 
5585     // Some kinds of initialization permit an array to be initialized from
5586     // another array of the same type, and perform elementwise initialization.
5587     if (Initializer && isa<ConstantArrayType>(DestAT) &&
5588         S.Context.hasSameUnqualifiedType(Initializer->getType(),
5589                                          Entity.getType()) &&
5590         canPerformArrayCopy(Entity)) {
5591       // If source is a prvalue, use it directly.
5592       if (Initializer->getValueKind() == VK_RValue) {
5593         AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5594         return;
5595       }
5596 
5597       // Emit element-at-a-time copy loop.
5598       InitializedEntity Element =
5599           InitializedEntity::InitializeElement(S.Context, 0, Entity);
5600       QualType InitEltT =
5601           Context.getAsArrayType(Initializer->getType())->getElementType();
5602       OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5603                           Initializer->getValueKind(),
5604                           Initializer->getObjectKind());
5605       Expr *OVEAsExpr = &OVE;
5606       InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5607                      TreatUnavailableAsInvalid);
5608       if (!Failed())
5609         AddArrayInitLoopStep(Entity.getType(), InitEltT);
5610       return;
5611     }
5612 
5613     // Note: as an GNU C extension, we allow initialization of an
5614     // array from a compound literal that creates an array of the same
5615     // type, so long as the initializer has no side effects.
5616     if (!S.getLangOpts().CPlusPlus && Initializer &&
5617         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5618         Initializer->getType()->isArrayType()) {
5619       const ArrayType *SourceAT
5620         = Context.getAsArrayType(Initializer->getType());
5621       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5622         SetFailed(FK_ArrayTypeMismatch);
5623       else if (Initializer->HasSideEffects(S.Context))
5624         SetFailed(FK_NonConstantArrayInit);
5625       else {
5626         AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5627       }
5628     }
5629     // Note: as a GNU C++ extension, we allow list-initialization of a
5630     // class member of array type from a parenthesized initializer list.
5631     else if (S.getLangOpts().CPlusPlus &&
5632              Entity.getKind() == InitializedEntity::EK_Member &&
5633              Initializer && isa<InitListExpr>(Initializer)) {
5634       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5635                             *this, TreatUnavailableAsInvalid);
5636       AddParenthesizedArrayInitStep(DestType);
5637     } else if (DestAT->getElementType()->isCharType())
5638       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5639     else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5640       SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5641     else
5642       SetFailed(FK_ArrayNeedsInitList);
5643 
5644     return;
5645   }
5646 
5647   // Determine whether we should consider writeback conversions for
5648   // Objective-C ARC.
5649   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5650          Entity.isParameterKind();
5651 
5652   if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5653     return;
5654 
5655   // We're at the end of the line for C: it's either a write-back conversion
5656   // or it's a C assignment. There's no need to check anything else.
5657   if (!S.getLangOpts().CPlusPlus) {
5658     // If allowed, check whether this is an Objective-C writeback conversion.
5659     if (allowObjCWritebackConversion &&
5660         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5661       return;
5662     }
5663 
5664     if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
5665       return;
5666 
5667     // Handle initialization in C
5668     AddCAssignmentStep(DestType);
5669     MaybeProduceObjCObject(S, *this, Entity);
5670     return;
5671   }
5672 
5673   assert(S.getLangOpts().CPlusPlus);
5674 
5675   //     - If the destination type is a (possibly cv-qualified) class type:
5676   if (DestType->isRecordType()) {
5677     //     - If the initialization is direct-initialization, or if it is
5678     //       copy-initialization where the cv-unqualified version of the
5679     //       source type is the same class as, or a derived class of, the
5680     //       class of the destination, constructors are considered. [...]
5681     if (Kind.getKind() == InitializationKind::IK_Direct ||
5682         (Kind.getKind() == InitializationKind::IK_Copy &&
5683          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5684           S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
5685       TryConstructorInitialization(S, Entity, Kind, Args,
5686                                    DestType, DestType, *this);
5687     //     - Otherwise (i.e., for the remaining copy-initialization cases),
5688     //       user-defined conversion sequences that can convert from the source
5689     //       type to the destination type or (when a conversion function is
5690     //       used) to a derived class thereof are enumerated as described in
5691     //       13.3.1.4, and the best one is chosen through overload resolution
5692     //       (13.3).
5693     else
5694       TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5695                                TopLevelOfInitList);
5696     return;
5697   }
5698 
5699   assert(Args.size() >= 1 && "Zero-argument case handled above");
5700 
5701   // The remaining cases all need a source type.
5702   if (Args.size() > 1) {
5703     SetFailed(FK_TooManyInitsForScalar);
5704     return;
5705   } else if (isa<InitListExpr>(Args[0])) {
5706     SetFailed(FK_ParenthesizedListInitForScalar);
5707     return;
5708   }
5709 
5710   //    - Otherwise, if the source type is a (possibly cv-qualified) class
5711   //      type, conversion functions are considered.
5712   if (!SourceType.isNull() && SourceType->isRecordType()) {
5713     // For a conversion to _Atomic(T) from either T or a class type derived
5714     // from T, initialize the T object then convert to _Atomic type.
5715     bool NeedAtomicConversion = false;
5716     if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5717       if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5718           S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
5719                           Atomic->getValueType())) {
5720         DestType = Atomic->getValueType();
5721         NeedAtomicConversion = true;
5722       }
5723     }
5724 
5725     TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5726                              TopLevelOfInitList);
5727     MaybeProduceObjCObject(S, *this, Entity);
5728     if (!Failed() && NeedAtomicConversion)
5729       AddAtomicConversionStep(Entity.getType());
5730     return;
5731   }
5732 
5733   //    - Otherwise, the initial value of the object being initialized is the
5734   //      (possibly converted) value of the initializer expression. Standard
5735   //      conversions (Clause 4) will be used, if necessary, to convert the
5736   //      initializer expression to the cv-unqualified version of the
5737   //      destination type; no user-defined conversions are considered.
5738 
5739   ImplicitConversionSequence ICS
5740     = S.TryImplicitConversion(Initializer, DestType,
5741                               /*SuppressUserConversions*/true,
5742                               /*AllowExplicitConversions*/ false,
5743                               /*InOverloadResolution*/ false,
5744                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5745                               allowObjCWritebackConversion);
5746 
5747   if (ICS.isStandard() &&
5748       ICS.Standard.Second == ICK_Writeback_Conversion) {
5749     // Objective-C ARC writeback conversion.
5750 
5751     // We should copy unless we're passing to an argument explicitly
5752     // marked 'out'.
5753     bool ShouldCopy = true;
5754     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5755       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5756 
5757     // If there was an lvalue adjustment, add it as a separate conversion.
5758     if (ICS.Standard.First == ICK_Array_To_Pointer ||
5759         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5760       ImplicitConversionSequence LvalueICS;
5761       LvalueICS.setStandard();
5762       LvalueICS.Standard.setAsIdentityConversion();
5763       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5764       LvalueICS.Standard.First = ICS.Standard.First;
5765       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5766     }
5767 
5768     AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5769   } else if (ICS.isBad()) {
5770     DeclAccessPair dap;
5771     if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5772       AddZeroInitializationStep(Entity.getType());
5773     } else if (Initializer->getType() == Context.OverloadTy &&
5774                !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5775                                                      false, dap))
5776       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5777     else if (Initializer->getType()->isFunctionType() &&
5778              isExprAnUnaddressableFunction(S, Initializer))
5779       SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
5780     else
5781       SetFailed(InitializationSequence::FK_ConversionFailed);
5782   } else {
5783     AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5784 
5785     MaybeProduceObjCObject(S, *this, Entity);
5786   }
5787 }
5788 
5789 InitializationSequence::~InitializationSequence() {
5790   for (auto &S : Steps)
5791     S.Destroy();
5792 }
5793 
5794 //===----------------------------------------------------------------------===//
5795 // Perform initialization
5796 //===----------------------------------------------------------------------===//
5797 static Sema::AssignmentAction
5798 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5799   switch(Entity.getKind()) {
5800   case InitializedEntity::EK_Variable:
5801   case InitializedEntity::EK_New:
5802   case InitializedEntity::EK_Exception:
5803   case InitializedEntity::EK_Base:
5804   case InitializedEntity::EK_Delegating:
5805     return Sema::AA_Initializing;
5806 
5807   case InitializedEntity::EK_Parameter:
5808     if (Entity.getDecl() &&
5809         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5810       return Sema::AA_Sending;
5811 
5812     return Sema::AA_Passing;
5813 
5814   case InitializedEntity::EK_Parameter_CF_Audited:
5815     if (Entity.getDecl() &&
5816       isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5817       return Sema::AA_Sending;
5818 
5819     return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5820 
5821   case InitializedEntity::EK_Result:
5822   case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
5823     return Sema::AA_Returning;
5824 
5825   case InitializedEntity::EK_Temporary:
5826   case InitializedEntity::EK_RelatedResult:
5827     // FIXME: Can we tell apart casting vs. converting?
5828     return Sema::AA_Casting;
5829 
5830   case InitializedEntity::EK_Member:
5831   case InitializedEntity::EK_Binding:
5832   case InitializedEntity::EK_ArrayElement:
5833   case InitializedEntity::EK_VectorElement:
5834   case InitializedEntity::EK_ComplexElement:
5835   case InitializedEntity::EK_BlockElement:
5836   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5837   case InitializedEntity::EK_LambdaCapture:
5838   case InitializedEntity::EK_CompoundLiteralInit:
5839     return Sema::AA_Initializing;
5840   }
5841 
5842   llvm_unreachable("Invalid EntityKind!");
5843 }
5844 
5845 /// Whether we should bind a created object as a temporary when
5846 /// initializing the given entity.
5847 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5848   switch (Entity.getKind()) {
5849   case InitializedEntity::EK_ArrayElement:
5850   case InitializedEntity::EK_Member:
5851   case InitializedEntity::EK_Result:
5852   case InitializedEntity::EK_StmtExprResult:
5853   case InitializedEntity::EK_New:
5854   case InitializedEntity::EK_Variable:
5855   case InitializedEntity::EK_Base:
5856   case InitializedEntity::EK_Delegating:
5857   case InitializedEntity::EK_VectorElement:
5858   case InitializedEntity::EK_ComplexElement:
5859   case InitializedEntity::EK_Exception:
5860   case InitializedEntity::EK_BlockElement:
5861   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5862   case InitializedEntity::EK_LambdaCapture:
5863   case InitializedEntity::EK_CompoundLiteralInit:
5864     return false;
5865 
5866   case InitializedEntity::EK_Parameter:
5867   case InitializedEntity::EK_Parameter_CF_Audited:
5868   case InitializedEntity::EK_Temporary:
5869   case InitializedEntity::EK_RelatedResult:
5870   case InitializedEntity::EK_Binding:
5871     return true;
5872   }
5873 
5874   llvm_unreachable("missed an InitializedEntity kind?");
5875 }
5876 
5877 /// Whether the given entity, when initialized with an object
5878 /// created for that initialization, requires destruction.
5879 static bool shouldDestroyEntity(const InitializedEntity &Entity) {
5880   switch (Entity.getKind()) {
5881     case InitializedEntity::EK_Result:
5882     case InitializedEntity::EK_StmtExprResult:
5883     case InitializedEntity::EK_New:
5884     case InitializedEntity::EK_Base:
5885     case InitializedEntity::EK_Delegating:
5886     case InitializedEntity::EK_VectorElement:
5887     case InitializedEntity::EK_ComplexElement:
5888     case InitializedEntity::EK_BlockElement:
5889     case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5890     case InitializedEntity::EK_LambdaCapture:
5891       return false;
5892 
5893     case InitializedEntity::EK_Member:
5894     case InitializedEntity::EK_Binding:
5895     case InitializedEntity::EK_Variable:
5896     case InitializedEntity::EK_Parameter:
5897     case InitializedEntity::EK_Parameter_CF_Audited:
5898     case InitializedEntity::EK_Temporary:
5899     case InitializedEntity::EK_ArrayElement:
5900     case InitializedEntity::EK_Exception:
5901     case InitializedEntity::EK_CompoundLiteralInit:
5902     case InitializedEntity::EK_RelatedResult:
5903       return true;
5904   }
5905 
5906   llvm_unreachable("missed an InitializedEntity kind?");
5907 }
5908 
5909 /// Get the location at which initialization diagnostics should appear.
5910 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5911                                            Expr *Initializer) {
5912   switch (Entity.getKind()) {
5913   case InitializedEntity::EK_Result:
5914   case InitializedEntity::EK_StmtExprResult:
5915     return Entity.getReturnLoc();
5916 
5917   case InitializedEntity::EK_Exception:
5918     return Entity.getThrowLoc();
5919 
5920   case InitializedEntity::EK_Variable:
5921   case InitializedEntity::EK_Binding:
5922     return Entity.getDecl()->getLocation();
5923 
5924   case InitializedEntity::EK_LambdaCapture:
5925     return Entity.getCaptureLoc();
5926 
5927   case InitializedEntity::EK_ArrayElement:
5928   case InitializedEntity::EK_Member:
5929   case InitializedEntity::EK_Parameter:
5930   case InitializedEntity::EK_Parameter_CF_Audited:
5931   case InitializedEntity::EK_Temporary:
5932   case InitializedEntity::EK_New:
5933   case InitializedEntity::EK_Base:
5934   case InitializedEntity::EK_Delegating:
5935   case InitializedEntity::EK_VectorElement:
5936   case InitializedEntity::EK_ComplexElement:
5937   case InitializedEntity::EK_BlockElement:
5938   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5939   case InitializedEntity::EK_CompoundLiteralInit:
5940   case InitializedEntity::EK_RelatedResult:
5941     return Initializer->getBeginLoc();
5942   }
5943   llvm_unreachable("missed an InitializedEntity kind?");
5944 }
5945 
5946 /// Make a (potentially elidable) temporary copy of the object
5947 /// provided by the given initializer by calling the appropriate copy
5948 /// constructor.
5949 ///
5950 /// \param S The Sema object used for type-checking.
5951 ///
5952 /// \param T The type of the temporary object, which must either be
5953 /// the type of the initializer expression or a superclass thereof.
5954 ///
5955 /// \param Entity The entity being initialized.
5956 ///
5957 /// \param CurInit The initializer expression.
5958 ///
5959 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5960 /// is permitted in C++03 (but not C++0x) when binding a reference to
5961 /// an rvalue.
5962 ///
5963 /// \returns An expression that copies the initializer expression into
5964 /// a temporary object, or an error expression if a copy could not be
5965 /// created.
5966 static ExprResult CopyObject(Sema &S,
5967                              QualType T,
5968                              const InitializedEntity &Entity,
5969                              ExprResult CurInit,
5970                              bool IsExtraneousCopy) {
5971   if (CurInit.isInvalid())
5972     return CurInit;
5973   // Determine which class type we're copying to.
5974   Expr *CurInitExpr = (Expr *)CurInit.get();
5975   CXXRecordDecl *Class = nullptr;
5976   if (const RecordType *Record = T->getAs<RecordType>())
5977     Class = cast<CXXRecordDecl>(Record->getDecl());
5978   if (!Class)
5979     return CurInit;
5980 
5981   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5982 
5983   // Make sure that the type we are copying is complete.
5984   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5985     return CurInit;
5986 
5987   // Perform overload resolution using the class's constructors. Per
5988   // C++11 [dcl.init]p16, second bullet for class types, this initialization
5989   // is direct-initialization.
5990   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5991   DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
5992 
5993   OverloadCandidateSet::iterator Best;
5994   switch (ResolveConstructorOverload(
5995       S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
5996       /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5997       /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5998       /*SecondStepOfCopyInit=*/true)) {
5999   case OR_Success:
6000     break;
6001 
6002   case OR_No_Viable_Function:
6003     CandidateSet.NoteCandidates(
6004         PartialDiagnosticAt(
6005             Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6006                              ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6007                              : diag::err_temp_copy_no_viable)
6008                      << (int)Entity.getKind() << CurInitExpr->getType()
6009                      << CurInitExpr->getSourceRange()),
6010         S, OCD_AllCandidates, CurInitExpr);
6011     if (!IsExtraneousCopy || S.isSFINAEContext())
6012       return ExprError();
6013     return CurInit;
6014 
6015   case OR_Ambiguous:
6016     CandidateSet.NoteCandidates(
6017         PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6018                                      << (int)Entity.getKind()
6019                                      << CurInitExpr->getType()
6020                                      << CurInitExpr->getSourceRange()),
6021         S, OCD_ViableCandidates, CurInitExpr);
6022     return ExprError();
6023 
6024   case OR_Deleted:
6025     S.Diag(Loc, diag::err_temp_copy_deleted)
6026       << (int)Entity.getKind() << CurInitExpr->getType()
6027       << CurInitExpr->getSourceRange();
6028     S.NoteDeletedFunction(Best->Function);
6029     return ExprError();
6030   }
6031 
6032   bool HadMultipleCandidates = CandidateSet.size() > 1;
6033 
6034   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6035   SmallVector<Expr*, 8> ConstructorArgs;
6036   CurInit.get(); // Ownership transferred into MultiExprArg, below.
6037 
6038   S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6039                            IsExtraneousCopy);
6040 
6041   if (IsExtraneousCopy) {
6042     // If this is a totally extraneous copy for C++03 reference
6043     // binding purposes, just return the original initialization
6044     // expression. We don't generate an (elided) copy operation here
6045     // because doing so would require us to pass down a flag to avoid
6046     // infinite recursion, where each step adds another extraneous,
6047     // elidable copy.
6048 
6049     // Instantiate the default arguments of any extra parameters in
6050     // the selected copy constructor, as if we were going to create a
6051     // proper call to the copy constructor.
6052     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6053       ParmVarDecl *Parm = Constructor->getParamDecl(I);
6054       if (S.RequireCompleteType(Loc, Parm->getType(),
6055                                 diag::err_call_incomplete_argument))
6056         break;
6057 
6058       // Build the default argument expression; we don't actually care
6059       // if this succeeds or not, because this routine will complain
6060       // if there was a problem.
6061       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6062     }
6063 
6064     return CurInitExpr;
6065   }
6066 
6067   // Determine the arguments required to actually perform the
6068   // constructor call (we might have derived-to-base conversions, or
6069   // the copy constructor may have default arguments).
6070   if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
6071     return ExprError();
6072 
6073   // C++0x [class.copy]p32:
6074   //   When certain criteria are met, an implementation is allowed to
6075   //   omit the copy/move construction of a class object, even if the
6076   //   copy/move constructor and/or destructor for the object have
6077   //   side effects. [...]
6078   //     - when a temporary class object that has not been bound to a
6079   //       reference (12.2) would be copied/moved to a class object
6080   //       with the same cv-unqualified type, the copy/move operation
6081   //       can be omitted by constructing the temporary object
6082   //       directly into the target of the omitted copy/move
6083   //
6084   // Note that the other three bullets are handled elsewhere. Copy
6085   // elision for return statements and throw expressions are handled as part
6086   // of constructor initialization, while copy elision for exception handlers
6087   // is handled by the run-time.
6088   //
6089   // FIXME: If the function parameter is not the same type as the temporary, we
6090   // should still be able to elide the copy, but we don't have a way to
6091   // represent in the AST how much should be elided in this case.
6092   bool Elidable =
6093       CurInitExpr->isTemporaryObject(S.Context, Class) &&
6094       S.Context.hasSameUnqualifiedType(
6095           Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6096           CurInitExpr->getType());
6097 
6098   // Actually perform the constructor call.
6099   CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6100                                     Elidable,
6101                                     ConstructorArgs,
6102                                     HadMultipleCandidates,
6103                                     /*ListInit*/ false,
6104                                     /*StdInitListInit*/ false,
6105                                     /*ZeroInit*/ false,
6106                                     CXXConstructExpr::CK_Complete,
6107                                     SourceRange());
6108 
6109   // If we're supposed to bind temporaries, do so.
6110   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6111     CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6112   return CurInit;
6113 }
6114 
6115 /// Check whether elidable copy construction for binding a reference to
6116 /// a temporary would have succeeded if we were building in C++98 mode, for
6117 /// -Wc++98-compat.
6118 static void CheckCXX98CompatAccessibleCopy(Sema &S,
6119                                            const InitializedEntity &Entity,
6120                                            Expr *CurInitExpr) {
6121   assert(S.getLangOpts().CPlusPlus11);
6122 
6123   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6124   if (!Record)
6125     return;
6126 
6127   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6128   if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6129     return;
6130 
6131   // Find constructors which would have been considered.
6132   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6133   DeclContext::lookup_result Ctors =
6134       S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6135 
6136   // Perform overload resolution.
6137   OverloadCandidateSet::iterator Best;
6138   OverloadingResult OR = ResolveConstructorOverload(
6139       S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6140       /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6141       /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6142       /*SecondStepOfCopyInit=*/true);
6143 
6144   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6145     << OR << (int)Entity.getKind() << CurInitExpr->getType()
6146     << CurInitExpr->getSourceRange();
6147 
6148   switch (OR) {
6149   case OR_Success:
6150     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6151                              Best->FoundDecl, Entity, Diag);
6152     // FIXME: Check default arguments as far as that's possible.
6153     break;
6154 
6155   case OR_No_Viable_Function:
6156     CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6157                                 OCD_AllCandidates, CurInitExpr);
6158     break;
6159 
6160   case OR_Ambiguous:
6161     CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6162                                 OCD_ViableCandidates, CurInitExpr);
6163     break;
6164 
6165   case OR_Deleted:
6166     S.Diag(Loc, Diag);
6167     S.NoteDeletedFunction(Best->Function);
6168     break;
6169   }
6170 }
6171 
6172 void InitializationSequence::PrintInitLocationNote(Sema &S,
6173                                               const InitializedEntity &Entity) {
6174   if (Entity.isParameterKind() && Entity.getDecl()) {
6175     if (Entity.getDecl()->getLocation().isInvalid())
6176       return;
6177 
6178     if (Entity.getDecl()->getDeclName())
6179       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6180         << Entity.getDecl()->getDeclName();
6181     else
6182       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6183   }
6184   else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6185            Entity.getMethodDecl())
6186     S.Diag(Entity.getMethodDecl()->getLocation(),
6187            diag::note_method_return_type_change)
6188       << Entity.getMethodDecl()->getDeclName();
6189 }
6190 
6191 /// Returns true if the parameters describe a constructor initialization of
6192 /// an explicit temporary object, e.g. "Point(x, y)".
6193 static bool isExplicitTemporary(const InitializedEntity &Entity,
6194                                 const InitializationKind &Kind,
6195                                 unsigned NumArgs) {
6196   switch (Entity.getKind()) {
6197   case InitializedEntity::EK_Temporary:
6198   case InitializedEntity::EK_CompoundLiteralInit:
6199   case InitializedEntity::EK_RelatedResult:
6200     break;
6201   default:
6202     return false;
6203   }
6204 
6205   switch (Kind.getKind()) {
6206   case InitializationKind::IK_DirectList:
6207     return true;
6208   // FIXME: Hack to work around cast weirdness.
6209   case InitializationKind::IK_Direct:
6210   case InitializationKind::IK_Value:
6211     return NumArgs != 1;
6212   default:
6213     return false;
6214   }
6215 }
6216 
6217 static ExprResult
6218 PerformConstructorInitialization(Sema &S,
6219                                  const InitializedEntity &Entity,
6220                                  const InitializationKind &Kind,
6221                                  MultiExprArg Args,
6222                                  const InitializationSequence::Step& Step,
6223                                  bool &ConstructorInitRequiresZeroInit,
6224                                  bool IsListInitialization,
6225                                  bool IsStdInitListInitialization,
6226                                  SourceLocation LBraceLoc,
6227                                  SourceLocation RBraceLoc) {
6228   unsigned NumArgs = Args.size();
6229   CXXConstructorDecl *Constructor
6230     = cast<CXXConstructorDecl>(Step.Function.Function);
6231   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6232 
6233   // Build a call to the selected constructor.
6234   SmallVector<Expr*, 8> ConstructorArgs;
6235   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6236                          ? Kind.getEqualLoc()
6237                          : Kind.getLocation();
6238 
6239   if (Kind.getKind() == InitializationKind::IK_Default) {
6240     // Force even a trivial, implicit default constructor to be
6241     // semantically checked. We do this explicitly because we don't build
6242     // the definition for completely trivial constructors.
6243     assert(Constructor->getParent() && "No parent class for constructor.");
6244     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6245         Constructor->isTrivial() && !Constructor->isUsed(false))
6246       S.DefineImplicitDefaultConstructor(Loc, Constructor);
6247   }
6248 
6249   ExprResult CurInit((Expr *)nullptr);
6250 
6251   // C++ [over.match.copy]p1:
6252   //   - When initializing a temporary to be bound to the first parameter
6253   //     of a constructor that takes a reference to possibly cv-qualified
6254   //     T as its first argument, called with a single argument in the
6255   //     context of direct-initialization, explicit conversion functions
6256   //     are also considered.
6257   bool AllowExplicitConv =
6258       Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6259       hasCopyOrMoveCtorParam(S.Context,
6260                              getConstructorInfo(Step.Function.FoundDecl));
6261 
6262   // Determine the arguments required to actually perform the constructor
6263   // call.
6264   if (S.CompleteConstructorCall(Constructor, Args,
6265                                 Loc, ConstructorArgs,
6266                                 AllowExplicitConv,
6267                                 IsListInitialization))
6268     return ExprError();
6269 
6270 
6271   if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6272     // An explicitly-constructed temporary, e.g., X(1, 2).
6273     if (S.DiagnoseUseOfDecl(Constructor, Loc))
6274       return ExprError();
6275 
6276     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6277     if (!TSInfo)
6278       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6279     SourceRange ParenOrBraceRange =
6280         (Kind.getKind() == InitializationKind::IK_DirectList)
6281         ? SourceRange(LBraceLoc, RBraceLoc)
6282         : Kind.getParenOrBraceRange();
6283 
6284     if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6285             Step.Function.FoundDecl.getDecl())) {
6286       Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
6287       if (S.DiagnoseUseOfDecl(Constructor, Loc))
6288         return ExprError();
6289     }
6290     S.MarkFunctionReferenced(Loc, Constructor);
6291 
6292     CurInit = CXXTemporaryObjectExpr::Create(
6293         S.Context, Constructor,
6294         Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6295         ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6296         IsListInitialization, IsStdInitListInitialization,
6297         ConstructorInitRequiresZeroInit);
6298   } else {
6299     CXXConstructExpr::ConstructionKind ConstructKind =
6300       CXXConstructExpr::CK_Complete;
6301 
6302     if (Entity.getKind() == InitializedEntity::EK_Base) {
6303       ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6304         CXXConstructExpr::CK_VirtualBase :
6305         CXXConstructExpr::CK_NonVirtualBase;
6306     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6307       ConstructKind = CXXConstructExpr::CK_Delegating;
6308     }
6309 
6310     // Only get the parenthesis or brace range if it is a list initialization or
6311     // direct construction.
6312     SourceRange ParenOrBraceRange;
6313     if (IsListInitialization)
6314       ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6315     else if (Kind.getKind() == InitializationKind::IK_Direct)
6316       ParenOrBraceRange = Kind.getParenOrBraceRange();
6317 
6318     // If the entity allows NRVO, mark the construction as elidable
6319     // unconditionally.
6320     if (Entity.allowsNRVO())
6321       CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6322                                         Step.Function.FoundDecl,
6323                                         Constructor, /*Elidable=*/true,
6324                                         ConstructorArgs,
6325                                         HadMultipleCandidates,
6326                                         IsListInitialization,
6327                                         IsStdInitListInitialization,
6328                                         ConstructorInitRequiresZeroInit,
6329                                         ConstructKind,
6330                                         ParenOrBraceRange);
6331     else
6332       CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6333                                         Step.Function.FoundDecl,
6334                                         Constructor,
6335                                         ConstructorArgs,
6336                                         HadMultipleCandidates,
6337                                         IsListInitialization,
6338                                         IsStdInitListInitialization,
6339                                         ConstructorInitRequiresZeroInit,
6340                                         ConstructKind,
6341                                         ParenOrBraceRange);
6342   }
6343   if (CurInit.isInvalid())
6344     return ExprError();
6345 
6346   // Only check access if all of that succeeded.
6347   S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
6348   if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6349     return ExprError();
6350 
6351   if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
6352     if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
6353       return ExprError();
6354 
6355   if (shouldBindAsTemporary(Entity))
6356     CurInit = S.MaybeBindToTemporary(CurInit.get());
6357 
6358   return CurInit;
6359 }
6360 
6361 namespace {
6362 enum LifetimeKind {
6363   /// The lifetime of a temporary bound to this entity ends at the end of the
6364   /// full-expression, and that's (probably) fine.
6365   LK_FullExpression,
6366 
6367   /// The lifetime of a temporary bound to this entity is extended to the
6368   /// lifeitme of the entity itself.
6369   LK_Extended,
6370 
6371   /// The lifetime of a temporary bound to this entity probably ends too soon,
6372   /// because the entity is allocated in a new-expression.
6373   LK_New,
6374 
6375   /// The lifetime of a temporary bound to this entity ends too soon, because
6376   /// the entity is a return object.
6377   LK_Return,
6378 
6379   /// The lifetime of a temporary bound to this entity ends too soon, because
6380   /// the entity is the result of a statement expression.
6381   LK_StmtExprResult,
6382 
6383   /// This is a mem-initializer: if it would extend a temporary (other than via
6384   /// a default member initializer), the program is ill-formed.
6385   LK_MemInitializer,
6386 };
6387 using LifetimeResult =
6388     llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6389 }
6390 
6391 /// Determine the declaration which an initialized entity ultimately refers to,
6392 /// for the purpose of lifetime-extending a temporary bound to a reference in
6393 /// the initialization of \p Entity.
6394 static LifetimeResult getEntityLifetime(
6395     const InitializedEntity *Entity,
6396     const InitializedEntity *InitField = nullptr) {
6397   // C++11 [class.temporary]p5:
6398   switch (Entity->getKind()) {
6399   case InitializedEntity::EK_Variable:
6400     //   The temporary [...] persists for the lifetime of the reference
6401     return {Entity, LK_Extended};
6402 
6403   case InitializedEntity::EK_Member:
6404     // For subobjects, we look at the complete object.
6405     if (Entity->getParent())
6406       return getEntityLifetime(Entity->getParent(), Entity);
6407 
6408     //   except:
6409     // C++17 [class.base.init]p8:
6410     //   A temporary expression bound to a reference member in a
6411     //   mem-initializer is ill-formed.
6412     // C++17 [class.base.init]p11:
6413     //   A temporary expression bound to a reference member from a
6414     //   default member initializer is ill-formed.
6415     //
6416     // The context of p11 and its example suggest that it's only the use of a
6417     // default member initializer from a constructor that makes the program
6418     // ill-formed, not its mere existence, and that it can even be used by
6419     // aggregate initialization.
6420     return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6421                                                          : LK_MemInitializer};
6422 
6423   case InitializedEntity::EK_Binding:
6424     // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6425     // type.
6426     return {Entity, LK_Extended};
6427 
6428   case InitializedEntity::EK_Parameter:
6429   case InitializedEntity::EK_Parameter_CF_Audited:
6430     //   -- A temporary bound to a reference parameter in a function call
6431     //      persists until the completion of the full-expression containing
6432     //      the call.
6433     return {nullptr, LK_FullExpression};
6434 
6435   case InitializedEntity::EK_Result:
6436     //   -- The lifetime of a temporary bound to the returned value in a
6437     //      function return statement is not extended; the temporary is
6438     //      destroyed at the end of the full-expression in the return statement.
6439     return {nullptr, LK_Return};
6440 
6441   case InitializedEntity::EK_StmtExprResult:
6442     // FIXME: Should we lifetime-extend through the result of a statement
6443     // expression?
6444     return {nullptr, LK_StmtExprResult};
6445 
6446   case InitializedEntity::EK_New:
6447     //   -- A temporary bound to a reference in a new-initializer persists
6448     //      until the completion of the full-expression containing the
6449     //      new-initializer.
6450     return {nullptr, LK_New};
6451 
6452   case InitializedEntity::EK_Temporary:
6453   case InitializedEntity::EK_CompoundLiteralInit:
6454   case InitializedEntity::EK_RelatedResult:
6455     // We don't yet know the storage duration of the surrounding temporary.
6456     // Assume it's got full-expression duration for now, it will patch up our
6457     // storage duration if that's not correct.
6458     return {nullptr, LK_FullExpression};
6459 
6460   case InitializedEntity::EK_ArrayElement:
6461     // For subobjects, we look at the complete object.
6462     return getEntityLifetime(Entity->getParent(), InitField);
6463 
6464   case InitializedEntity::EK_Base:
6465     // For subobjects, we look at the complete object.
6466     if (Entity->getParent())
6467       return getEntityLifetime(Entity->getParent(), InitField);
6468     return {InitField, LK_MemInitializer};
6469 
6470   case InitializedEntity::EK_Delegating:
6471     // We can reach this case for aggregate initialization in a constructor:
6472     //   struct A { int &&r; };
6473     //   struct B : A { B() : A{0} {} };
6474     // In this case, use the outermost field decl as the context.
6475     return {InitField, LK_MemInitializer};
6476 
6477   case InitializedEntity::EK_BlockElement:
6478   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6479   case InitializedEntity::EK_LambdaCapture:
6480   case InitializedEntity::EK_VectorElement:
6481   case InitializedEntity::EK_ComplexElement:
6482     return {nullptr, LK_FullExpression};
6483 
6484   case InitializedEntity::EK_Exception:
6485     // FIXME: Can we diagnose lifetime problems with exceptions?
6486     return {nullptr, LK_FullExpression};
6487   }
6488   llvm_unreachable("unknown entity kind");
6489 }
6490 
6491 namespace {
6492 enum ReferenceKind {
6493   /// Lifetime would be extended by a reference binding to a temporary.
6494   RK_ReferenceBinding,
6495   /// Lifetime would be extended by a std::initializer_list object binding to
6496   /// its backing array.
6497   RK_StdInitializerList,
6498 };
6499 
6500 /// A temporary or local variable. This will be one of:
6501 ///  * A MaterializeTemporaryExpr.
6502 ///  * A DeclRefExpr whose declaration is a local.
6503 ///  * An AddrLabelExpr.
6504 ///  * A BlockExpr for a block with captures.
6505 using Local = Expr*;
6506 
6507 /// Expressions we stepped over when looking for the local state. Any steps
6508 /// that would inhibit lifetime extension or take us out of subexpressions of
6509 /// the initializer are included.
6510 struct IndirectLocalPathEntry {
6511   enum EntryKind {
6512     DefaultInit,
6513     AddressOf,
6514     VarInit,
6515     LValToRVal,
6516     LifetimeBoundCall,
6517     GslPointerInit
6518   } Kind;
6519   Expr *E;
6520   const Decl *D = nullptr;
6521   IndirectLocalPathEntry() {}
6522   IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
6523   IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6524       : Kind(K), E(E), D(D) {}
6525 };
6526 
6527 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
6528 
6529 struct RevertToOldSizeRAII {
6530   IndirectLocalPath &Path;
6531   unsigned OldSize = Path.size();
6532   RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
6533   ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6534 };
6535 
6536 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6537                                              ReferenceKind RK)>;
6538 }
6539 
6540 static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6541   for (auto E : Path)
6542     if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6543       return true;
6544   return false;
6545 }
6546 
6547 static bool pathContainsInit(IndirectLocalPath &Path) {
6548   return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
6549     return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6550            E.Kind == IndirectLocalPathEntry::VarInit;
6551   });
6552 }
6553 
6554 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6555                                              Expr *Init, LocalVisitor Visit,
6556                                              bool RevisitSubinits);
6557 
6558 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6559                                                   Expr *Init, ReferenceKind RK,
6560                                                   LocalVisitor Visit);
6561 
6562 template <typename T> static bool isRecordWithAttr(QualType Type) {
6563   if (auto *RD = Type->getAsCXXRecordDecl())
6564     return RD->getCanonicalDecl()->hasAttr<T>();
6565   return false;
6566 }
6567 
6568 // Decl::isInStdNamespace will return false for iterators in some STL
6569 // implementations due to them being defined in a namespace outside of the std
6570 // namespace.
6571 static bool isInStlNamespace(const Decl *D) {
6572   const DeclContext *DC = D->getDeclContext();
6573   if (!DC)
6574     return false;
6575   if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
6576     if (const IdentifierInfo *II = ND->getIdentifier()) {
6577       StringRef Name = II->getName();
6578       if (Name.size() >= 2 && Name.front() == '_' &&
6579           (Name[1] == '_' || isUppercase(Name[1])))
6580         return true;
6581     }
6582 
6583   return DC->isStdNamespace();
6584 }
6585 
6586 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
6587   if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
6588     if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
6589       return true;
6590   if (!isInStlNamespace(Callee->getParent()))
6591     return false;
6592   if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
6593       !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
6594     return false;
6595   if (Callee->getReturnType()->isPointerType() ||
6596       isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
6597     if (!Callee->getIdentifier())
6598       return false;
6599     return llvm::StringSwitch<bool>(Callee->getName())
6600         .Cases("begin", "rbegin", "cbegin", "crbegin", true)
6601         .Cases("end", "rend", "cend", "crend", true)
6602         .Cases("c_str", "data", "get", true)
6603         // Map and set types.
6604         .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
6605         .Default(false);
6606   } else if (Callee->getReturnType()->isReferenceType()) {
6607     if (!Callee->getIdentifier()) {
6608       auto OO = Callee->getOverloadedOperator();
6609       return OO == OverloadedOperatorKind::OO_Subscript ||
6610              OO == OverloadedOperatorKind::OO_Star;
6611     }
6612     return llvm::StringSwitch<bool>(Callee->getName())
6613         .Cases("front", "back", "at", "top", "value", true)
6614         .Default(false);
6615   }
6616   return false;
6617 }
6618 
6619 static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
6620                                     LocalVisitor Visit) {
6621   auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
6622     Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
6623     if (Arg->isGLValue())
6624       visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6625                                             Visit);
6626     else
6627       visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6628     Path.pop_back();
6629   };
6630 
6631   if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6632     const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
6633     if (MD && shouldTrackImplicitObjectArg(MD))
6634       VisitPointerArg(MD, MCE->getImplicitObjectArgument());
6635     return;
6636   } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
6637     FunctionDecl *Callee = OCE->getDirectCallee();
6638     if (Callee && Callee->isCXXInstanceMember() &&
6639         shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
6640       VisitPointerArg(Callee, OCE->getArg(0));
6641     return;
6642   }
6643 
6644   if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
6645     const auto *Ctor = CCE->getConstructor();
6646     const CXXRecordDecl *RD = Ctor->getParent()->getCanonicalDecl();
6647     if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
6648       VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0]);
6649   }
6650 }
6651 
6652 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
6653   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6654   if (!TSI)
6655     return false;
6656   // Don't declare this variable in the second operand of the for-statement;
6657   // GCC miscompiles that by ending its lifetime before evaluating the
6658   // third operand. See gcc.gnu.org/PR86769.
6659   AttributedTypeLoc ATL;
6660   for (TypeLoc TL = TSI->getTypeLoc();
6661        (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6662        TL = ATL.getModifiedLoc()) {
6663     if (ATL.getAttrAs<LifetimeBoundAttr>())
6664       return true;
6665   }
6666   return false;
6667 }
6668 
6669 static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
6670                                         LocalVisitor Visit) {
6671   const FunctionDecl *Callee;
6672   ArrayRef<Expr*> Args;
6673 
6674   if (auto *CE = dyn_cast<CallExpr>(Call)) {
6675     Callee = CE->getDirectCallee();
6676     Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
6677   } else {
6678     auto *CCE = cast<CXXConstructExpr>(Call);
6679     Callee = CCE->getConstructor();
6680     Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
6681   }
6682   if (!Callee)
6683     return;
6684 
6685   Expr *ObjectArg = nullptr;
6686   if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
6687     ObjectArg = Args[0];
6688     Args = Args.slice(1);
6689   } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6690     ObjectArg = MCE->getImplicitObjectArgument();
6691   }
6692 
6693   auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
6694     Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
6695     if (Arg->isGLValue())
6696       visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6697                                             Visit);
6698     else
6699       visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6700     Path.pop_back();
6701   };
6702 
6703   if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
6704     VisitLifetimeBoundArg(Callee, ObjectArg);
6705 
6706   for (unsigned I = 0,
6707                 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
6708        I != N; ++I) {
6709     if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
6710       VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
6711   }
6712 }
6713 
6714 /// Visit the locals that would be reachable through a reference bound to the
6715 /// glvalue expression \c Init.
6716 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6717                                                   Expr *Init, ReferenceKind RK,
6718                                                   LocalVisitor Visit) {
6719   RevertToOldSizeRAII RAII(Path);
6720 
6721   // Walk past any constructs which we can lifetime-extend across.
6722   Expr *Old;
6723   do {
6724     Old = Init;
6725 
6726     if (auto *FE = dyn_cast<FullExpr>(Init))
6727       Init = FE->getSubExpr();
6728 
6729     if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6730       // If this is just redundant braces around an initializer, step over it.
6731       if (ILE->isTransparent())
6732         Init = ILE->getInit(0);
6733     }
6734 
6735     // Step over any subobject adjustments; we may have a materialized
6736     // temporary inside them.
6737     Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6738 
6739     // Per current approach for DR1376, look through casts to reference type
6740     // when performing lifetime extension.
6741     if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6742       if (CE->getSubExpr()->isGLValue())
6743         Init = CE->getSubExpr();
6744 
6745     // Per the current approach for DR1299, look through array element access
6746     // on array glvalues when performing lifetime extension.
6747     if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
6748       Init = ASE->getBase();
6749       auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6750       if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6751         Init = ICE->getSubExpr();
6752       else
6753         // We can't lifetime extend through this but we might still find some
6754         // retained temporaries.
6755         return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
6756     }
6757 
6758     // Step into CXXDefaultInitExprs so we can diagnose cases where a
6759     // constructor inherits one as an implicit mem-initializer.
6760     if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6761       Path.push_back(
6762           {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6763       Init = DIE->getExpr();
6764     }
6765   } while (Init != Old);
6766 
6767   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6768     if (Visit(Path, Local(MTE), RK))
6769       visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6770                                        true);
6771   }
6772 
6773   if (isa<CallExpr>(Init)) {
6774     handleGslAnnotatedTypes(Path, Init, Visit);
6775     return visitLifetimeBoundArguments(Path, Init, Visit);
6776   }
6777 
6778   switch (Init->getStmtClass()) {
6779   case Stmt::DeclRefExprClass: {
6780     // If we find the name of a local non-reference parameter, we could have a
6781     // lifetime problem.
6782     auto *DRE = cast<DeclRefExpr>(Init);
6783     auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6784     if (VD && VD->hasLocalStorage() &&
6785         !DRE->refersToEnclosingVariableOrCapture()) {
6786       if (!VD->getType()->isReferenceType()) {
6787         Visit(Path, Local(DRE), RK);
6788       } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6789         // The lifetime of a reference parameter is unknown; assume it's OK
6790         // for now.
6791         break;
6792       } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6793         Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6794         visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6795                                               RK_ReferenceBinding, Visit);
6796       }
6797     }
6798     break;
6799   }
6800 
6801   case Stmt::UnaryOperatorClass: {
6802     // The only unary operator that make sense to handle here
6803     // is Deref.  All others don't resolve to a "name."  This includes
6804     // handling all sorts of rvalues passed to a unary operator.
6805     const UnaryOperator *U = cast<UnaryOperator>(Init);
6806     if (U->getOpcode() == UO_Deref)
6807       visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6808     break;
6809   }
6810 
6811   case Stmt::OMPArraySectionExprClass: {
6812     visitLocalsRetainedByInitializer(
6813         Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6814     break;
6815   }
6816 
6817   case Stmt::ConditionalOperatorClass:
6818   case Stmt::BinaryConditionalOperatorClass: {
6819     auto *C = cast<AbstractConditionalOperator>(Init);
6820     if (!C->getTrueExpr()->getType()->isVoidType())
6821       visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6822     if (!C->getFalseExpr()->getType()->isVoidType())
6823       visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6824     break;
6825   }
6826 
6827   // FIXME: Visit the left-hand side of an -> or ->*.
6828 
6829   default:
6830     break;
6831   }
6832 }
6833 
6834 /// Visit the locals that would be reachable through an object initialized by
6835 /// the prvalue expression \c Init.
6836 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6837                                              Expr *Init, LocalVisitor Visit,
6838                                              bool RevisitSubinits) {
6839   RevertToOldSizeRAII RAII(Path);
6840 
6841   Expr *Old;
6842   do {
6843     Old = Init;
6844 
6845     // Step into CXXDefaultInitExprs so we can diagnose cases where a
6846     // constructor inherits one as an implicit mem-initializer.
6847     if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6848       Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6849       Init = DIE->getExpr();
6850     }
6851 
6852     if (auto *FE = dyn_cast<FullExpr>(Init))
6853       Init = FE->getSubExpr();
6854 
6855     // Dig out the expression which constructs the extended temporary.
6856     Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6857 
6858     if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6859       Init = BTE->getSubExpr();
6860 
6861     Init = Init->IgnoreParens();
6862 
6863     // Step over value-preserving rvalue casts.
6864     if (auto *CE = dyn_cast<CastExpr>(Init)) {
6865       switch (CE->getCastKind()) {
6866       case CK_LValueToRValue:
6867         // If we can match the lvalue to a const object, we can look at its
6868         // initializer.
6869         Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6870         return visitLocalsRetainedByReferenceBinding(
6871             Path, Init, RK_ReferenceBinding,
6872             [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6873           if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6874             auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6875             if (VD && VD->getType().isConstQualified() && VD->getInit() &&
6876                 !isVarOnPath(Path, VD)) {
6877               Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6878               visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6879             }
6880           } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6881             if (MTE->getType().isConstQualified())
6882               visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6883                                                Visit, true);
6884           }
6885           return false;
6886         });
6887 
6888         // We assume that objects can be retained by pointers cast to integers,
6889         // but not if the integer is cast to floating-point type or to _Complex.
6890         // We assume that casts to 'bool' do not preserve enough information to
6891         // retain a local object.
6892       case CK_NoOp:
6893       case CK_BitCast:
6894       case CK_BaseToDerived:
6895       case CK_DerivedToBase:
6896       case CK_UncheckedDerivedToBase:
6897       case CK_Dynamic:
6898       case CK_ToUnion:
6899       case CK_UserDefinedConversion:
6900       case CK_ConstructorConversion:
6901       case CK_IntegralToPointer:
6902       case CK_PointerToIntegral:
6903       case CK_VectorSplat:
6904       case CK_IntegralCast:
6905       case CK_CPointerToObjCPointerCast:
6906       case CK_BlockPointerToObjCPointerCast:
6907       case CK_AnyPointerToBlockPointerCast:
6908       case CK_AddressSpaceConversion:
6909         break;
6910 
6911       case CK_ArrayToPointerDecay:
6912         // Model array-to-pointer decay as taking the address of the array
6913         // lvalue.
6914         Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6915         return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
6916                                                      RK_ReferenceBinding, Visit);
6917 
6918       default:
6919         return;
6920       }
6921 
6922       Init = CE->getSubExpr();
6923     }
6924   } while (Old != Init);
6925 
6926   // C++17 [dcl.init.list]p6:
6927   //   initializing an initializer_list object from the array extends the
6928   //   lifetime of the array exactly like binding a reference to a temporary.
6929   if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
6930     return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6931                                                  RK_StdInitializerList, Visit);
6932 
6933   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6934     // We already visited the elements of this initializer list while
6935     // performing the initialization. Don't visit them again unless we've
6936     // changed the lifetime of the initialized entity.
6937     if (!RevisitSubinits)
6938       return;
6939 
6940     if (ILE->isTransparent())
6941       return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6942                                               RevisitSubinits);
6943 
6944     if (ILE->getType()->isArrayType()) {
6945       for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
6946         visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6947                                          RevisitSubinits);
6948       return;
6949     }
6950 
6951     if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
6952       assert(RD->isAggregate() && "aggregate init on non-aggregate");
6953 
6954       // If we lifetime-extend a braced initializer which is initializing an
6955       // aggregate, and that aggregate contains reference members which are
6956       // bound to temporaries, those temporaries are also lifetime-extended.
6957       if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6958           ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
6959         visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6960                                               RK_ReferenceBinding, Visit);
6961       else {
6962         unsigned Index = 0;
6963         for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
6964           visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
6965                                            RevisitSubinits);
6966         for (const auto *I : RD->fields()) {
6967           if (Index >= ILE->getNumInits())
6968             break;
6969           if (I->isUnnamedBitfield())
6970             continue;
6971           Expr *SubInit = ILE->getInit(Index);
6972           if (I->getType()->isReferenceType())
6973             visitLocalsRetainedByReferenceBinding(Path, SubInit,
6974                                                   RK_ReferenceBinding, Visit);
6975           else
6976             // This might be either aggregate-initialization of a member or
6977             // initialization of a std::initializer_list object. Regardless,
6978             // we should recursively lifetime-extend that initializer.
6979             visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6980                                              RevisitSubinits);
6981           ++Index;
6982         }
6983       }
6984     }
6985     return;
6986   }
6987 
6988   // The lifetime of an init-capture is that of the closure object constructed
6989   // by a lambda-expression.
6990   if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
6991     for (Expr *E : LE->capture_inits()) {
6992       if (!E)
6993         continue;
6994       if (E->isGLValue())
6995         visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
6996                                               Visit);
6997       else
6998         visitLocalsRetainedByInitializer(Path, E, Visit, true);
6999     }
7000   }
7001 
7002   if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7003     handleGslAnnotatedTypes(Path, Init, Visit);
7004     return visitLifetimeBoundArguments(Path, Init, Visit);
7005   }
7006 
7007   switch (Init->getStmtClass()) {
7008   case Stmt::UnaryOperatorClass: {
7009     auto *UO = cast<UnaryOperator>(Init);
7010     // If the initializer is the address of a local, we could have a lifetime
7011     // problem.
7012     if (UO->getOpcode() == UO_AddrOf) {
7013       // If this is &rvalue, then it's ill-formed and we have already diagnosed
7014       // it. Don't produce a redundant warning about the lifetime of the
7015       // temporary.
7016       if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7017         return;
7018 
7019       Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7020       visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7021                                             RK_ReferenceBinding, Visit);
7022     }
7023     break;
7024   }
7025 
7026   case Stmt::BinaryOperatorClass: {
7027     // Handle pointer arithmetic.
7028     auto *BO = cast<BinaryOperator>(Init);
7029     BinaryOperatorKind BOK = BO->getOpcode();
7030     if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7031       break;
7032 
7033     if (BO->getLHS()->getType()->isPointerType())
7034       visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
7035     else if (BO->getRHS()->getType()->isPointerType())
7036       visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
7037     break;
7038   }
7039 
7040   case Stmt::ConditionalOperatorClass:
7041   case Stmt::BinaryConditionalOperatorClass: {
7042     auto *C = cast<AbstractConditionalOperator>(Init);
7043     // In C++, we can have a throw-expression operand, which has 'void' type
7044     // and isn't interesting from a lifetime perspective.
7045     if (!C->getTrueExpr()->getType()->isVoidType())
7046       visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
7047     if (!C->getFalseExpr()->getType()->isVoidType())
7048       visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
7049     break;
7050   }
7051 
7052   case Stmt::BlockExprClass:
7053     if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7054       // This is a local block, whose lifetime is that of the function.
7055       Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7056     }
7057     break;
7058 
7059   case Stmt::AddrLabelExprClass:
7060     // We want to warn if the address of a label would escape the function.
7061     Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7062     break;
7063 
7064   default:
7065     break;
7066   }
7067 }
7068 
7069 /// Determine whether this is an indirect path to a temporary that we are
7070 /// supposed to lifetime-extend along (but don't).
7071 static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
7072   for (auto Elem : Path) {
7073     if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
7074       return false;
7075   }
7076   return true;
7077 }
7078 
7079 /// Find the range for the first interesting entry in the path at or after I.
7080 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
7081                                       Expr *E) {
7082   for (unsigned N = Path.size(); I != N; ++I) {
7083     switch (Path[I].Kind) {
7084     case IndirectLocalPathEntry::AddressOf:
7085     case IndirectLocalPathEntry::LValToRVal:
7086     case IndirectLocalPathEntry::LifetimeBoundCall:
7087     case IndirectLocalPathEntry::GslPointerInit:
7088       // These exist primarily to mark the path as not permitting or
7089       // supporting lifetime extension.
7090       break;
7091 
7092     case IndirectLocalPathEntry::VarInit:
7093       if (cast<VarDecl>(Path[I].D)->isImplicit())
7094         return SourceRange();
7095       LLVM_FALLTHROUGH;
7096     case IndirectLocalPathEntry::DefaultInit:
7097       return Path[I].E->getSourceRange();
7098     }
7099   }
7100   return E->getSourceRange();
7101 }
7102 
7103 static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
7104   for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
7105     if (It->Kind == IndirectLocalPathEntry::VarInit)
7106       continue;
7107     return It->Kind == IndirectLocalPathEntry::GslPointerInit;
7108   }
7109   return false;
7110 }
7111 
7112 void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7113                                     Expr *Init) {
7114   LifetimeResult LR = getEntityLifetime(&Entity);
7115   LifetimeKind LK = LR.getInt();
7116   const InitializedEntity *ExtendingEntity = LR.getPointer();
7117 
7118   // If this entity doesn't have an interesting lifetime, don't bother looking
7119   // for temporaries within its initializer.
7120   if (LK == LK_FullExpression)
7121     return;
7122 
7123   auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
7124                               ReferenceKind RK) -> bool {
7125     SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
7126     SourceLocation DiagLoc = DiagRange.getBegin();
7127 
7128     auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
7129 
7130     bool IsGslPtrInitWithGslTempOwner = false;
7131     bool IsLocalGslOwner = false;
7132     if (pathOnlyInitializesGslPointer(Path)) {
7133       if (isa<DeclRefExpr>(L)) {
7134         // We do not want to follow the references when returning a pointer originating
7135         // from a local owner to avoid the following false positive:
7136         //   int &p = *localUniquePtr;
7137         //   someContainer.add(std::move(localUniquePtr));
7138         //   return p;
7139         IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
7140         if (pathContainsInit(Path) || !IsLocalGslOwner)
7141           return false;
7142       } else {
7143         IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
7144                             isRecordWithAttr<OwnerAttr>(MTE->getType());
7145         // Skipping a chain of initializing gsl::Pointer annotated objects.
7146         // We are looking only for the final source to find out if it was
7147         // a local or temporary owner or the address of a local variable/param.
7148         if (!IsGslPtrInitWithGslTempOwner)
7149           return true;
7150       }
7151     }
7152 
7153     switch (LK) {
7154     case LK_FullExpression:
7155       llvm_unreachable("already handled this");
7156 
7157     case LK_Extended: {
7158       if (!MTE) {
7159         // The initialized entity has lifetime beyond the full-expression,
7160         // and the local entity does too, so don't warn.
7161         //
7162         // FIXME: We should consider warning if a static / thread storage
7163         // duration variable retains an automatic storage duration local.
7164         return false;
7165       }
7166 
7167       if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
7168         Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7169         return false;
7170       }
7171 
7172       // Lifetime-extend the temporary.
7173       if (Path.empty()) {
7174         // Update the storage duration of the materialized temporary.
7175         // FIXME: Rebuild the expression instead of mutating it.
7176         MTE->setExtendingDecl(ExtendingEntity->getDecl(),
7177                               ExtendingEntity->allocateManglingNumber());
7178         // Also visit the temporaries lifetime-extended by this initializer.
7179         return true;
7180       }
7181 
7182       if (shouldLifetimeExtendThroughPath(Path)) {
7183         // We're supposed to lifetime-extend the temporary along this path (per
7184         // the resolution of DR1815), but we don't support that yet.
7185         //
7186         // FIXME: Properly handle this situation. Perhaps the easiest approach
7187         // would be to clone the initializer expression on each use that would
7188         // lifetime extend its temporaries.
7189         Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
7190             << RK << DiagRange;
7191       } else {
7192         // If the path goes through the initialization of a variable or field,
7193         // it can't possibly reach a temporary created in this full-expression.
7194         // We will have already diagnosed any problems with the initializer.
7195         if (pathContainsInit(Path))
7196           return false;
7197 
7198         Diag(DiagLoc, diag::warn_dangling_variable)
7199             << RK << !Entity.getParent()
7200             << ExtendingEntity->getDecl()->isImplicit()
7201             << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
7202       }
7203       break;
7204     }
7205 
7206     case LK_MemInitializer: {
7207       if (isa<MaterializeTemporaryExpr>(L)) {
7208         // Under C++ DR1696, if a mem-initializer (or a default member
7209         // initializer used by the absence of one) would lifetime-extend a
7210         // temporary, the program is ill-formed.
7211         if (auto *ExtendingDecl =
7212                 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7213           if (IsGslPtrInitWithGslTempOwner) {
7214             Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
7215                 << ExtendingDecl << DiagRange;
7216             Diag(ExtendingDecl->getLocation(),
7217                  diag::note_ref_or_ptr_member_declared_here)
7218                 << true;
7219             return false;
7220           }
7221           bool IsSubobjectMember = ExtendingEntity != &Entity;
7222           Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
7223                             ? diag::err_dangling_member
7224                             : diag::warn_dangling_member)
7225               << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
7226           // Don't bother adding a note pointing to the field if we're inside
7227           // its default member initializer; our primary diagnostic points to
7228           // the same place in that case.
7229           if (Path.empty() ||
7230               Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
7231             Diag(ExtendingDecl->getLocation(),
7232                  diag::note_lifetime_extending_member_declared_here)
7233                 << RK << IsSubobjectMember;
7234           }
7235         } else {
7236           // We have a mem-initializer but no particular field within it; this
7237           // is either a base class or a delegating initializer directly
7238           // initializing the base-class from something that doesn't live long
7239           // enough.
7240           //
7241           // FIXME: Warn on this.
7242           return false;
7243         }
7244       } else {
7245         // Paths via a default initializer can only occur during error recovery
7246         // (there's no other way that a default initializer can refer to a
7247         // local). Don't produce a bogus warning on those cases.
7248         if (pathContainsInit(Path))
7249           return false;
7250 
7251         // Suppress false positives for code like the one below:
7252         //   Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
7253         if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
7254           return false;
7255 
7256         auto *DRE = dyn_cast<DeclRefExpr>(L);
7257         auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7258         if (!VD) {
7259           // A member was initialized to a local block.
7260           // FIXME: Warn on this.
7261           return false;
7262         }
7263 
7264         if (auto *Member =
7265                 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7266           bool IsPointer = !Member->getType()->isReferenceType();
7267           Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
7268                                   : diag::warn_bind_ref_member_to_parameter)
7269               << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
7270           Diag(Member->getLocation(),
7271                diag::note_ref_or_ptr_member_declared_here)
7272               << (unsigned)IsPointer;
7273         }
7274       }
7275       break;
7276     }
7277 
7278     case LK_New:
7279       if (isa<MaterializeTemporaryExpr>(L)) {
7280         if (IsGslPtrInitWithGslTempOwner)
7281           Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
7282         else
7283           Diag(DiagLoc, RK == RK_ReferenceBinding
7284                             ? diag::warn_new_dangling_reference
7285                             : diag::warn_new_dangling_initializer_list)
7286               << !Entity.getParent() << DiagRange;
7287       } else {
7288         // We can't determine if the allocation outlives the local declaration.
7289         return false;
7290       }
7291       break;
7292 
7293     case LK_Return:
7294     case LK_StmtExprResult:
7295       if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7296         // We can't determine if the local variable outlives the statement
7297         // expression.
7298         if (LK == LK_StmtExprResult)
7299           return false;
7300         Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7301             << Entity.getType()->isReferenceType() << DRE->getDecl()
7302             << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7303       } else if (isa<BlockExpr>(L)) {
7304         Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7305       } else if (isa<AddrLabelExpr>(L)) {
7306         // Don't warn when returning a label from a statement expression.
7307         // Leaving the scope doesn't end its lifetime.
7308         if (LK == LK_StmtExprResult)
7309           return false;
7310         Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7311       } else {
7312         Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7313          << Entity.getType()->isReferenceType() << DiagRange;
7314       }
7315       break;
7316     }
7317 
7318     for (unsigned I = 0; I != Path.size(); ++I) {
7319       auto Elem = Path[I];
7320 
7321       switch (Elem.Kind) {
7322       case IndirectLocalPathEntry::AddressOf:
7323       case IndirectLocalPathEntry::LValToRVal:
7324         // These exist primarily to mark the path as not permitting or
7325         // supporting lifetime extension.
7326         break;
7327 
7328       case IndirectLocalPathEntry::LifetimeBoundCall:
7329       case IndirectLocalPathEntry::GslPointerInit:
7330         // FIXME: Consider adding a note for these.
7331         break;
7332 
7333       case IndirectLocalPathEntry::DefaultInit: {
7334         auto *FD = cast<FieldDecl>(Elem.D);
7335         Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
7336             << FD << nextPathEntryRange(Path, I + 1, L);
7337         break;
7338       }
7339 
7340       case IndirectLocalPathEntry::VarInit:
7341         const VarDecl *VD = cast<VarDecl>(Elem.D);
7342         Diag(VD->getLocation(), diag::note_local_var_initializer)
7343             << VD->getType()->isReferenceType()
7344             << VD->isImplicit() << VD->getDeclName()
7345             << nextPathEntryRange(Path, I + 1, L);
7346         break;
7347       }
7348     }
7349 
7350     // We didn't lifetime-extend, so don't go any further; we don't need more
7351     // warnings or errors on inner temporaries within this one's initializer.
7352     return false;
7353   };
7354 
7355   llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
7356   if (Init->isGLValue())
7357     visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7358                                           TemporaryVisitor);
7359   else
7360     visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
7361 }
7362 
7363 static void DiagnoseNarrowingInInitList(Sema &S,
7364                                         const ImplicitConversionSequence &ICS,
7365                                         QualType PreNarrowingType,
7366                                         QualType EntityType,
7367                                         const Expr *PostInit);
7368 
7369 /// Provide warnings when std::move is used on construction.
7370 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7371                                     bool IsReturnStmt) {
7372   if (!InitExpr)
7373     return;
7374 
7375   if (S.inTemplateInstantiation())
7376     return;
7377 
7378   QualType DestType = InitExpr->getType();
7379   if (!DestType->isRecordType())
7380     return;
7381 
7382   const CXXConstructExpr *CCE =
7383       dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7384   if (!CCE || CCE->getNumArgs() != 1)
7385     return;
7386 
7387   if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7388     return;
7389 
7390   InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7391 
7392   // Find the std::move call and get the argument.
7393   const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7394   if (!CE || !CE->isCallToStdMove())
7395     return;
7396 
7397   const Expr *Arg = CE->getArg(0);
7398 
7399   unsigned DiagID = 0;
7400 
7401   if (!IsReturnStmt && !isa<MaterializeTemporaryExpr>(Arg))
7402     return;
7403 
7404   if (isa<MaterializeTemporaryExpr>(Arg)) {
7405     DiagID = diag::warn_pessimizing_move_on_initialization;
7406     const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7407     if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
7408       return;
7409   } else { // IsReturnStmt
7410     const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7411     if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7412       return;
7413 
7414     const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7415     if (!VD || !VD->hasLocalStorage())
7416       return;
7417 
7418     // __block variables are not moved implicitly.
7419     if (VD->hasAttr<BlocksAttr>())
7420       return;
7421 
7422     QualType SourceType = VD->getType();
7423     if (!SourceType->isRecordType())
7424       return;
7425 
7426     if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7427       return;
7428     }
7429 
7430     // If we're returning a function parameter, copy elision
7431     // is not possible.
7432     if (isa<ParmVarDecl>(VD))
7433       DiagID = diag::warn_redundant_move_on_return;
7434     else
7435       DiagID = diag::warn_pessimizing_move_on_return;
7436   }
7437 
7438   S.Diag(CE->getBeginLoc(), DiagID);
7439 
7440   // Get all the locations for a fix-it.  Don't emit the fix-it if any location
7441   // is within a macro.
7442   SourceLocation BeginLoc = CCE->getBeginLoc();
7443   if (BeginLoc.isMacroID())
7444     return;
7445   SourceLocation RParen = CE->getRParenLoc();
7446   if (RParen.isMacroID())
7447     return;
7448   SourceLocation ArgLoc = Arg->getBeginLoc();
7449 
7450   // Special testing for the argument location.  Since the fix-it needs the
7451   // location right before the argument, the argument location can be in a
7452   // macro only if it is at the beginning of the macro.
7453   while (ArgLoc.isMacroID() &&
7454          S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
7455     ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
7456   }
7457 
7458   SourceLocation LParen = ArgLoc.getLocWithOffset(-1);
7459   if (LParen.isMacroID())
7460     return;
7461   SourceLocation EndLoc = CCE->getEndLoc();
7462   if (EndLoc.isMacroID())
7463     return;
7464 
7465   S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7466       << FixItHint::CreateRemoval(SourceRange(BeginLoc, LParen))
7467       << FixItHint::CreateRemoval(SourceRange(RParen, EndLoc));
7468 }
7469 
7470 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7471   // Check to see if we are dereferencing a null pointer.  If so, this is
7472   // undefined behavior, so warn about it.  This only handles the pattern
7473   // "*null", which is a very syntactic check.
7474   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7475     if (UO->getOpcode() == UO_Deref &&
7476         UO->getSubExpr()->IgnoreParenCasts()->
7477         isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7478     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7479                           S.PDiag(diag::warn_binding_null_to_reference)
7480                             << UO->getSubExpr()->getSourceRange());
7481   }
7482 }
7483 
7484 MaterializeTemporaryExpr *
7485 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7486                                      bool BoundToLvalueReference) {
7487   auto MTE = new (Context)
7488       MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7489 
7490   // Order an ExprWithCleanups for lifetime marks.
7491   //
7492   // TODO: It'll be good to have a single place to check the access of the
7493   // destructor and generate ExprWithCleanups for various uses. Currently these
7494   // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7495   // but there may be a chance to merge them.
7496   Cleanup.setExprNeedsCleanups(false);
7497   return MTE;
7498 }
7499 
7500 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7501   // In C++98, we don't want to implicitly create an xvalue.
7502   // FIXME: This means that AST consumers need to deal with "prvalues" that
7503   // denote materialized temporaries. Maybe we should add another ValueKind
7504   // for "xvalue pretending to be a prvalue" for C++98 support.
7505   if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7506     return E;
7507 
7508   // C++1z [conv.rval]/1: T shall be a complete type.
7509   // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7510   // If so, we should check for a non-abstract class type here too.
7511   QualType T = E->getType();
7512   if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7513     return ExprError();
7514 
7515   return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7516 }
7517 
7518 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7519                                                 ExprValueKind VK,
7520                                                 CheckedConversionKind CCK) {
7521 
7522   CastKind CK = CK_NoOp;
7523 
7524   if (VK == VK_RValue) {
7525     auto PointeeTy = Ty->getPointeeType();
7526     auto ExprPointeeTy = E->getType()->getPointeeType();
7527     if (!PointeeTy.isNull() &&
7528         PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7529       CK = CK_AddressSpaceConversion;
7530   } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7531     CK = CK_AddressSpaceConversion;
7532   }
7533 
7534   return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7535 }
7536 
7537 ExprResult InitializationSequence::Perform(Sema &S,
7538                                            const InitializedEntity &Entity,
7539                                            const InitializationKind &Kind,
7540                                            MultiExprArg Args,
7541                                            QualType *ResultType) {
7542   if (Failed()) {
7543     Diagnose(S, Entity, Kind, Args);
7544     return ExprError();
7545   }
7546   if (!ZeroInitializationFixit.empty()) {
7547     unsigned DiagID = diag::err_default_init_const;
7548     if (Decl *D = Entity.getDecl())
7549       if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7550         DiagID = diag::ext_default_init_const;
7551 
7552     // The initialization would have succeeded with this fixit. Since the fixit
7553     // is on the error, we need to build a valid AST in this case, so this isn't
7554     // handled in the Failed() branch above.
7555     QualType DestType = Entity.getType();
7556     S.Diag(Kind.getLocation(), DiagID)
7557         << DestType << (bool)DestType->getAs<RecordType>()
7558         << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7559                                       ZeroInitializationFixit);
7560   }
7561 
7562   if (getKind() == DependentSequence) {
7563     // If the declaration is a non-dependent, incomplete array type
7564     // that has an initializer, then its type will be completed once
7565     // the initializer is instantiated.
7566     if (ResultType && !Entity.getType()->isDependentType() &&
7567         Args.size() == 1) {
7568       QualType DeclType = Entity.getType();
7569       if (const IncompleteArrayType *ArrayT
7570                            = S.Context.getAsIncompleteArrayType(DeclType)) {
7571         // FIXME: We don't currently have the ability to accurately
7572         // compute the length of an initializer list without
7573         // performing full type-checking of the initializer list
7574         // (since we have to determine where braces are implicitly
7575         // introduced and such).  So, we fall back to making the array
7576         // type a dependently-sized array type with no specified
7577         // bound.
7578         if (isa<InitListExpr>((Expr *)Args[0])) {
7579           SourceRange Brackets;
7580 
7581           // Scavange the location of the brackets from the entity, if we can.
7582           if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
7583             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7584               TypeLoc TL = TInfo->getTypeLoc();
7585               if (IncompleteArrayTypeLoc ArrayLoc =
7586                       TL.getAs<IncompleteArrayTypeLoc>())
7587                 Brackets = ArrayLoc.getBracketsRange();
7588             }
7589           }
7590 
7591           *ResultType
7592             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
7593                                                    /*NumElts=*/nullptr,
7594                                                    ArrayT->getSizeModifier(),
7595                                        ArrayT->getIndexTypeCVRQualifiers(),
7596                                                    Brackets);
7597         }
7598 
7599       }
7600     }
7601     if (Kind.getKind() == InitializationKind::IK_Direct &&
7602         !Kind.isExplicitCast()) {
7603       // Rebuild the ParenListExpr.
7604       SourceRange ParenRange = Kind.getParenOrBraceRange();
7605       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7606                                   Args);
7607     }
7608     assert(Kind.getKind() == InitializationKind::IK_Copy ||
7609            Kind.isExplicitCast() ||
7610            Kind.getKind() == InitializationKind::IK_DirectList);
7611     return ExprResult(Args[0]);
7612   }
7613 
7614   // No steps means no initialization.
7615   if (Steps.empty())
7616     return ExprResult((Expr *)nullptr);
7617 
7618   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7619       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7620       !Entity.isParameterKind()) {
7621     // Produce a C++98 compatibility warning if we are initializing a reference
7622     // from an initializer list. For parameters, we produce a better warning
7623     // elsewhere.
7624     Expr *Init = Args[0];
7625     S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7626         << Init->getSourceRange();
7627   }
7628 
7629   // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7630   QualType ETy = Entity.getType();
7631   Qualifiers TyQualifiers = ETy.getQualifiers();
7632   bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7633                      TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7634 
7635   if (S.getLangOpts().OpenCLVersion >= 200 &&
7636       ETy->isAtomicType() && !HasGlobalAS &&
7637       Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7638     S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7639         << 1
7640         << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7641     return ExprError();
7642   }
7643 
7644   QualType DestType = Entity.getType().getNonReferenceType();
7645   // FIXME: Ugly hack around the fact that Entity.getType() is not
7646   // the same as Entity.getDecl()->getType() in cases involving type merging,
7647   //  and we want latter when it makes sense.
7648   if (ResultType)
7649     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
7650                                      Entity.getType();
7651 
7652   ExprResult CurInit((Expr *)nullptr);
7653   SmallVector<Expr*, 4> ArrayLoopCommonExprs;
7654 
7655   // For initialization steps that start with a single initializer,
7656   // grab the only argument out the Args and place it into the "current"
7657   // initializer.
7658   switch (Steps.front().Kind) {
7659   case SK_ResolveAddressOfOverloadedFunction:
7660   case SK_CastDerivedToBaseRValue:
7661   case SK_CastDerivedToBaseXValue:
7662   case SK_CastDerivedToBaseLValue:
7663   case SK_BindReference:
7664   case SK_BindReferenceToTemporary:
7665   case SK_FinalCopy:
7666   case SK_ExtraneousCopyToTemporary:
7667   case SK_UserConversion:
7668   case SK_QualificationConversionLValue:
7669   case SK_QualificationConversionXValue:
7670   case SK_QualificationConversionRValue:
7671   case SK_AtomicConversion:
7672   case SK_ConversionSequence:
7673   case SK_ConversionSequenceNoNarrowing:
7674   case SK_ListInitialization:
7675   case SK_UnwrapInitList:
7676   case SK_RewrapInitList:
7677   case SK_CAssignment:
7678   case SK_StringInit:
7679   case SK_ObjCObjectConversion:
7680   case SK_ArrayLoopIndex:
7681   case SK_ArrayLoopInit:
7682   case SK_ArrayInit:
7683   case SK_GNUArrayInit:
7684   case SK_ParenthesizedArrayInit:
7685   case SK_PassByIndirectCopyRestore:
7686   case SK_PassByIndirectRestore:
7687   case SK_ProduceObjCObject:
7688   case SK_StdInitializerList:
7689   case SK_OCLSamplerInit:
7690   case SK_OCLZeroOpaqueType: {
7691     assert(Args.size() == 1);
7692     CurInit = Args[0];
7693     if (!CurInit.get()) return ExprError();
7694     break;
7695   }
7696 
7697   case SK_ConstructorInitialization:
7698   case SK_ConstructorInitializationFromList:
7699   case SK_StdInitializerListConstructorCall:
7700   case SK_ZeroInitialization:
7701     break;
7702   }
7703 
7704   // Promote from an unevaluated context to an unevaluated list context in
7705   // C++11 list-initialization; we need to instantiate entities usable in
7706   // constant expressions here in order to perform narrowing checks =(
7707   EnterExpressionEvaluationContext Evaluated(
7708       S, EnterExpressionEvaluationContext::InitList,
7709       CurInit.get() && isa<InitListExpr>(CurInit.get()));
7710 
7711   // C++ [class.abstract]p2:
7712   //   no objects of an abstract class can be created except as subobjects
7713   //   of a class derived from it
7714   auto checkAbstractType = [&](QualType T) -> bool {
7715     if (Entity.getKind() == InitializedEntity::EK_Base ||
7716         Entity.getKind() == InitializedEntity::EK_Delegating)
7717       return false;
7718     return S.RequireNonAbstractType(Kind.getLocation(), T,
7719                                     diag::err_allocation_of_abstract_type);
7720   };
7721 
7722   // Walk through the computed steps for the initialization sequence,
7723   // performing the specified conversions along the way.
7724   bool ConstructorInitRequiresZeroInit = false;
7725   for (step_iterator Step = step_begin(), StepEnd = step_end();
7726        Step != StepEnd; ++Step) {
7727     if (CurInit.isInvalid())
7728       return ExprError();
7729 
7730     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
7731 
7732     switch (Step->Kind) {
7733     case SK_ResolveAddressOfOverloadedFunction:
7734       // Overload resolution determined which function invoke; update the
7735       // initializer to reflect that choice.
7736       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
7737       if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7738         return ExprError();
7739       CurInit = S.FixOverloadedFunctionReference(CurInit,
7740                                                  Step->Function.FoundDecl,
7741                                                  Step->Function.Function);
7742       break;
7743 
7744     case SK_CastDerivedToBaseRValue:
7745     case SK_CastDerivedToBaseXValue:
7746     case SK_CastDerivedToBaseLValue: {
7747       // We have a derived-to-base cast that produces either an rvalue or an
7748       // lvalue. Perform that cast.
7749 
7750       CXXCastPath BasePath;
7751 
7752       // Casts to inaccessible base classes are allowed with C-style casts.
7753       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
7754       if (S.CheckDerivedToBaseConversion(
7755               SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7756               CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
7757         return ExprError();
7758 
7759       ExprValueKind VK =
7760           Step->Kind == SK_CastDerivedToBaseLValue ?
7761               VK_LValue :
7762               (Step->Kind == SK_CastDerivedToBaseXValue ?
7763                    VK_XValue :
7764                    VK_RValue);
7765       CurInit =
7766           ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7767                                    CurInit.get(), &BasePath, VK);
7768       break;
7769     }
7770 
7771     case SK_BindReference:
7772       // Reference binding does not have any corresponding ASTs.
7773 
7774       // Check exception specifications
7775       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
7776         return ExprError();
7777 
7778       // We don't check for e.g. function pointers here, since address
7779       // availability checks should only occur when the function first decays
7780       // into a pointer or reference.
7781       if (CurInit.get()->getType()->isFunctionProtoType()) {
7782         if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7783           if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7784             if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7785                                                      DRE->getBeginLoc()))
7786               return ExprError();
7787           }
7788         }
7789       }
7790 
7791       CheckForNullPointerDereference(S, CurInit.get());
7792       break;
7793 
7794     case SK_BindReferenceToTemporary: {
7795       // Make sure the "temporary" is actually an rvalue.
7796       assert(CurInit.get()->isRValue() && "not a temporary");
7797 
7798       // Check exception specifications
7799       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
7800         return ExprError();
7801 
7802       // Materialize the temporary into memory.
7803       MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7804           Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
7805       CurInit = MTE;
7806 
7807       // If we're extending this temporary to automatic storage duration -- we
7808       // need to register its cleanup during the full-expression's cleanups.
7809       if (MTE->getStorageDuration() == SD_Automatic &&
7810           MTE->getType().isDestructedType())
7811         S.Cleanup.setExprNeedsCleanups(true);
7812       break;
7813     }
7814 
7815     case SK_FinalCopy:
7816       if (checkAbstractType(Step->Type))
7817         return ExprError();
7818 
7819       // If the overall initialization is initializing a temporary, we already
7820       // bound our argument if it was necessary to do so. If not (if we're
7821       // ultimately initializing a non-temporary), our argument needs to be
7822       // bound since it's initializing a function parameter.
7823       // FIXME: This is a mess. Rationalize temporary destruction.
7824       if (!shouldBindAsTemporary(Entity))
7825         CurInit = S.MaybeBindToTemporary(CurInit.get());
7826       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7827                            /*IsExtraneousCopy=*/false);
7828       break;
7829 
7830     case SK_ExtraneousCopyToTemporary:
7831       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7832                            /*IsExtraneousCopy=*/true);
7833       break;
7834 
7835     case SK_UserConversion: {
7836       // We have a user-defined conversion that invokes either a constructor
7837       // or a conversion function.
7838       CastKind CastKind;
7839       FunctionDecl *Fn = Step->Function.Function;
7840       DeclAccessPair FoundFn = Step->Function.FoundDecl;
7841       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
7842       bool CreatedObject = false;
7843       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
7844         // Build a call to the selected constructor.
7845         SmallVector<Expr*, 8> ConstructorArgs;
7846         SourceLocation Loc = CurInit.get()->getBeginLoc();
7847 
7848         // Determine the arguments required to actually perform the constructor
7849         // call.
7850         Expr *Arg = CurInit.get();
7851         if (S.CompleteConstructorCall(Constructor,
7852                                       MultiExprArg(&Arg, 1),
7853                                       Loc, ConstructorArgs))
7854           return ExprError();
7855 
7856         // Build an expression that constructs a temporary.
7857         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7858                                           FoundFn, Constructor,
7859                                           ConstructorArgs,
7860                                           HadMultipleCandidates,
7861                                           /*ListInit*/ false,
7862                                           /*StdInitListInit*/ false,
7863                                           /*ZeroInit*/ false,
7864                                           CXXConstructExpr::CK_Complete,
7865                                           SourceRange());
7866         if (CurInit.isInvalid())
7867           return ExprError();
7868 
7869         S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7870                                  Entity);
7871         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7872           return ExprError();
7873 
7874         CastKind = CK_ConstructorConversion;
7875         CreatedObject = true;
7876       } else {
7877         // Build a call to the conversion function.
7878         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
7879         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
7880                                     FoundFn);
7881         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7882           return ExprError();
7883 
7884         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7885                                            HadMultipleCandidates);
7886         if (CurInit.isInvalid())
7887           return ExprError();
7888 
7889         CastKind = CK_UserDefinedConversion;
7890         CreatedObject = Conversion->getReturnType()->isRecordType();
7891       }
7892 
7893       if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7894         return ExprError();
7895 
7896       CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7897                                          CastKind, CurInit.get(), nullptr,
7898                                          CurInit.get()->getValueKind());
7899 
7900       if (shouldBindAsTemporary(Entity))
7901         // The overall entity is temporary, so this expression should be
7902         // destroyed at the end of its full-expression.
7903         CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7904       else if (CreatedObject && shouldDestroyEntity(Entity)) {
7905         // The object outlasts the full-expression, but we need to prepare for
7906         // a destructor being run on it.
7907         // FIXME: It makes no sense to do this here. This should happen
7908         // regardless of how we initialized the entity.
7909         QualType T = CurInit.get()->getType();
7910         if (const RecordType *Record = T->getAs<RecordType>()) {
7911           CXXDestructorDecl *Destructor
7912             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
7913           S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
7914                                   S.PDiag(diag::err_access_dtor_temp) << T);
7915           S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7916           if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
7917             return ExprError();
7918         }
7919       }
7920       break;
7921     }
7922 
7923     case SK_QualificationConversionLValue:
7924     case SK_QualificationConversionXValue:
7925     case SK_QualificationConversionRValue: {
7926       // Perform a qualification conversion; these can never go wrong.
7927       ExprValueKind VK =
7928           Step->Kind == SK_QualificationConversionLValue
7929               ? VK_LValue
7930               : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
7931                                                                 : VK_RValue);
7932       CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
7933       break;
7934     }
7935 
7936     case SK_AtomicConversion: {
7937       assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7938       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7939                                     CK_NonAtomicToAtomic, VK_RValue);
7940       break;
7941     }
7942 
7943     case SK_ConversionSequence:
7944     case SK_ConversionSequenceNoNarrowing: {
7945       if (const auto *FromPtrType =
7946               CurInit.get()->getType()->getAs<PointerType>()) {
7947         if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
7948           if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
7949               !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
7950             S.Diag(CurInit.get()->getExprLoc(),
7951                    diag::warn_noderef_to_dereferenceable_pointer)
7952                 << CurInit.get()->getSourceRange();
7953           }
7954         }
7955       }
7956 
7957       Sema::CheckedConversionKind CCK
7958         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7959         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
7960         : Kind.isExplicitCast()? Sema::CCK_OtherCast
7961         : Sema::CCK_ImplicitConversion;
7962       ExprResult CurInitExprRes =
7963         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
7964                                     getAssignmentAction(Entity), CCK);
7965       if (CurInitExprRes.isInvalid())
7966         return ExprError();
7967 
7968       S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7969 
7970       CurInit = CurInitExprRes;
7971 
7972       if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
7973           S.getLangOpts().CPlusPlus)
7974         DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7975                                     CurInit.get());
7976 
7977       break;
7978     }
7979 
7980     case SK_ListInitialization: {
7981       if (checkAbstractType(Step->Type))
7982         return ExprError();
7983 
7984       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
7985       // If we're not initializing the top-level entity, we need to create an
7986       // InitializeTemporary entity for our target type.
7987       QualType Ty = Step->Type;
7988       bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
7989       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
7990       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7991       InitListChecker PerformInitList(S, InitEntity,
7992           InitList, Ty, /*VerifyOnly=*/false,
7993           /*TreatUnavailableAsInvalid=*/false);
7994       if (PerformInitList.HadError())
7995         return ExprError();
7996 
7997       // Hack: We must update *ResultType if available in order to set the
7998       // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7999       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8000       if (ResultType &&
8001           ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8002         if ((*ResultType)->isRValueReferenceType())
8003           Ty = S.Context.getRValueReferenceType(Ty);
8004         else if ((*ResultType)->isLValueReferenceType())
8005           Ty = S.Context.getLValueReferenceType(Ty,
8006             (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
8007         *ResultType = Ty;
8008       }
8009 
8010       InitListExpr *StructuredInitList =
8011           PerformInitList.getFullyStructuredList();
8012       CurInit.get();
8013       CurInit = shouldBindAsTemporary(InitEntity)
8014           ? S.MaybeBindToTemporary(StructuredInitList)
8015           : StructuredInitList;
8016       break;
8017     }
8018 
8019     case SK_ConstructorInitializationFromList: {
8020       if (checkAbstractType(Step->Type))
8021         return ExprError();
8022 
8023       // When an initializer list is passed for a parameter of type "reference
8024       // to object", we don't get an EK_Temporary entity, but instead an
8025       // EK_Parameter entity with reference type.
8026       // FIXME: This is a hack. What we really should do is create a user
8027       // conversion step for this case, but this makes it considerably more
8028       // complicated. For now, this will do.
8029       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8030                                         Entity.getType().getNonReferenceType());
8031       bool UseTemporary = Entity.getType()->isReferenceType();
8032       assert(Args.size() == 1 && "expected a single argument for list init");
8033       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8034       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8035         << InitList->getSourceRange();
8036       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8037       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8038                                                                    Entity,
8039                                                  Kind, Arg, *Step,
8040                                                ConstructorInitRequiresZeroInit,
8041                                                /*IsListInitialization*/true,
8042                                                /*IsStdInitListInit*/false,
8043                                                InitList->getLBraceLoc(),
8044                                                InitList->getRBraceLoc());
8045       break;
8046     }
8047 
8048     case SK_UnwrapInitList:
8049       CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8050       break;
8051 
8052     case SK_RewrapInitList: {
8053       Expr *E = CurInit.get();
8054       InitListExpr *Syntactic = Step->WrappingSyntacticList;
8055       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8056           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8057       ILE->setSyntacticForm(Syntactic);
8058       ILE->setType(E->getType());
8059       ILE->setValueKind(E->getValueKind());
8060       CurInit = ILE;
8061       break;
8062     }
8063 
8064     case SK_ConstructorInitialization:
8065     case SK_StdInitializerListConstructorCall: {
8066       if (checkAbstractType(Step->Type))
8067         return ExprError();
8068 
8069       // When an initializer list is passed for a parameter of type "reference
8070       // to object", we don't get an EK_Temporary entity, but instead an
8071       // EK_Parameter entity with reference type.
8072       // FIXME: This is a hack. What we really should do is create a user
8073       // conversion step for this case, but this makes it considerably more
8074       // complicated. For now, this will do.
8075       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8076                                         Entity.getType().getNonReferenceType());
8077       bool UseTemporary = Entity.getType()->isReferenceType();
8078       bool IsStdInitListInit =
8079           Step->Kind == SK_StdInitializerListConstructorCall;
8080       Expr *Source = CurInit.get();
8081       SourceRange Range = Kind.hasParenOrBraceRange()
8082                               ? Kind.getParenOrBraceRange()
8083                               : SourceRange();
8084       CurInit = PerformConstructorInitialization(
8085           S, UseTemporary ? TempEntity : Entity, Kind,
8086           Source ? MultiExprArg(Source) : Args, *Step,
8087           ConstructorInitRequiresZeroInit,
8088           /*IsListInitialization*/ IsStdInitListInit,
8089           /*IsStdInitListInitialization*/ IsStdInitListInit,
8090           /*LBraceLoc*/ Range.getBegin(),
8091           /*RBraceLoc*/ Range.getEnd());
8092       break;
8093     }
8094 
8095     case SK_ZeroInitialization: {
8096       step_iterator NextStep = Step;
8097       ++NextStep;
8098       if (NextStep != StepEnd &&
8099           (NextStep->Kind == SK_ConstructorInitialization ||
8100            NextStep->Kind == SK_ConstructorInitializationFromList)) {
8101         // The need for zero-initialization is recorded directly into
8102         // the call to the object's constructor within the next step.
8103         ConstructorInitRequiresZeroInit = true;
8104       } else if (Kind.getKind() == InitializationKind::IK_Value &&
8105                  S.getLangOpts().CPlusPlus &&
8106                  !Kind.isImplicitValueInit()) {
8107         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8108         if (!TSInfo)
8109           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
8110                                                     Kind.getRange().getBegin());
8111 
8112         CurInit = new (S.Context) CXXScalarValueInitExpr(
8113             Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8114             Kind.getRange().getEnd());
8115       } else {
8116         CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8117       }
8118       break;
8119     }
8120 
8121     case SK_CAssignment: {
8122       QualType SourceType = CurInit.get()->getType();
8123 
8124       // Save off the initial CurInit in case we need to emit a diagnostic
8125       ExprResult InitialCurInit = CurInit;
8126       ExprResult Result = CurInit;
8127       Sema::AssignConvertType ConvTy =
8128         S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
8129             Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
8130       if (Result.isInvalid())
8131         return ExprError();
8132       CurInit = Result;
8133 
8134       // If this is a call, allow conversion to a transparent union.
8135       ExprResult CurInitExprRes = CurInit;
8136       if (ConvTy != Sema::Compatible &&
8137           Entity.isParameterKind() &&
8138           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
8139             == Sema::Compatible)
8140         ConvTy = Sema::Compatible;
8141       if (CurInitExprRes.isInvalid())
8142         return ExprError();
8143       CurInit = CurInitExprRes;
8144 
8145       bool Complained;
8146       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8147                                      Step->Type, SourceType,
8148                                      InitialCurInit.get(),
8149                                      getAssignmentAction(Entity, true),
8150                                      &Complained)) {
8151         PrintInitLocationNote(S, Entity);
8152         return ExprError();
8153       } else if (Complained)
8154         PrintInitLocationNote(S, Entity);
8155       break;
8156     }
8157 
8158     case SK_StringInit: {
8159       QualType Ty = Step->Type;
8160       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
8161                       S.Context.getAsArrayType(Ty), S);
8162       break;
8163     }
8164 
8165     case SK_ObjCObjectConversion:
8166       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8167                           CK_ObjCObjectLValueCast,
8168                           CurInit.get()->getValueKind());
8169       break;
8170 
8171     case SK_ArrayLoopIndex: {
8172       Expr *Cur = CurInit.get();
8173       Expr *BaseExpr = new (S.Context)
8174           OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8175                           Cur->getValueKind(), Cur->getObjectKind(), Cur);
8176       Expr *IndexExpr =
8177           new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8178       CurInit = S.CreateBuiltinArraySubscriptExpr(
8179           BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8180       ArrayLoopCommonExprs.push_back(BaseExpr);
8181       break;
8182     }
8183 
8184     case SK_ArrayLoopInit: {
8185       assert(!ArrayLoopCommonExprs.empty() &&
8186              "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8187       Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8188       CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8189                                                   CurInit.get());
8190       break;
8191     }
8192 
8193     case SK_GNUArrayInit:
8194       // Okay: we checked everything before creating this step. Note that
8195       // this is a GNU extension.
8196       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8197         << Step->Type << CurInit.get()->getType()
8198         << CurInit.get()->getSourceRange();
8199       updateGNUCompoundLiteralRValue(CurInit.get());
8200       LLVM_FALLTHROUGH;
8201     case SK_ArrayInit:
8202       // If the destination type is an incomplete array type, update the
8203       // type accordingly.
8204       if (ResultType) {
8205         if (const IncompleteArrayType *IncompleteDest
8206                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
8207           if (const ConstantArrayType *ConstantSource
8208                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8209             *ResultType = S.Context.getConstantArrayType(
8210                                              IncompleteDest->getElementType(),
8211                                              ConstantSource->getSize(),
8212                                              ArrayType::Normal, 0);
8213           }
8214         }
8215       }
8216       break;
8217 
8218     case SK_ParenthesizedArrayInit:
8219       // Okay: we checked everything before creating this step. Note that
8220       // this is a GNU extension.
8221       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8222         << CurInit.get()->getSourceRange();
8223       break;
8224 
8225     case SK_PassByIndirectCopyRestore:
8226     case SK_PassByIndirectRestore:
8227       checkIndirectCopyRestoreSource(S, CurInit.get());
8228       CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8229           CurInit.get(), Step->Type,
8230           Step->Kind == SK_PassByIndirectCopyRestore);
8231       break;
8232 
8233     case SK_ProduceObjCObject:
8234       CurInit =
8235           ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
8236                                    CurInit.get(), nullptr, VK_RValue);
8237       break;
8238 
8239     case SK_StdInitializerList: {
8240       S.Diag(CurInit.get()->getExprLoc(),
8241              diag::warn_cxx98_compat_initializer_list_init)
8242         << CurInit.get()->getSourceRange();
8243 
8244       // Materialize the temporary into memory.
8245       MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8246           CurInit.get()->getType(), CurInit.get(),
8247           /*BoundToLvalueReference=*/false);
8248 
8249       // Wrap it in a construction of a std::initializer_list<T>.
8250       CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8251 
8252       // Bind the result, in case the library has given initializer_list a
8253       // non-trivial destructor.
8254       if (shouldBindAsTemporary(Entity))
8255         CurInit = S.MaybeBindToTemporary(CurInit.get());
8256       break;
8257     }
8258 
8259     case SK_OCLSamplerInit: {
8260       // Sampler initialization have 5 cases:
8261       //   1. function argument passing
8262       //      1a. argument is a file-scope variable
8263       //      1b. argument is a function-scope variable
8264       //      1c. argument is one of caller function's parameters
8265       //   2. variable initialization
8266       //      2a. initializing a file-scope variable
8267       //      2b. initializing a function-scope variable
8268       //
8269       // For file-scope variables, since they cannot be initialized by function
8270       // call of __translate_sampler_initializer in LLVM IR, their references
8271       // need to be replaced by a cast from their literal initializers to
8272       // sampler type. Since sampler variables can only be used in function
8273       // calls as arguments, we only need to replace them when handling the
8274       // argument passing.
8275       assert(Step->Type->isSamplerT() &&
8276              "Sampler initialization on non-sampler type.");
8277       Expr *Init = CurInit.get()->IgnoreParens();
8278       QualType SourceType = Init->getType();
8279       // Case 1
8280       if (Entity.isParameterKind()) {
8281         if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8282           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8283             << SourceType;
8284           break;
8285         } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8286           auto Var = cast<VarDecl>(DRE->getDecl());
8287           // Case 1b and 1c
8288           // No cast from integer to sampler is needed.
8289           if (!Var->hasGlobalStorage()) {
8290             CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8291                                                CK_LValueToRValue, Init,
8292                                                /*BasePath=*/nullptr, VK_RValue);
8293             break;
8294           }
8295           // Case 1a
8296           // For function call with a file-scope sampler variable as argument,
8297           // get the integer literal.
8298           // Do not diagnose if the file-scope variable does not have initializer
8299           // since this has already been diagnosed when parsing the variable
8300           // declaration.
8301           if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8302             break;
8303           Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8304             Var->getInit()))->getSubExpr();
8305           SourceType = Init->getType();
8306         }
8307       } else {
8308         // Case 2
8309         // Check initializer is 32 bit integer constant.
8310         // If the initializer is taken from global variable, do not diagnose since
8311         // this has already been done when parsing the variable declaration.
8312         if (!Init->isConstantInitializer(S.Context, false))
8313           break;
8314 
8315         if (!SourceType->isIntegerType() ||
8316             32 != S.Context.getIntWidth(SourceType)) {
8317           S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8318             << SourceType;
8319           break;
8320         }
8321 
8322         Expr::EvalResult EVResult;
8323         Init->EvaluateAsInt(EVResult, S.Context);
8324         llvm::APSInt Result = EVResult.Val.getInt();
8325         const uint64_t SamplerValue = Result.getLimitedValue();
8326         // 32-bit value of sampler's initializer is interpreted as
8327         // bit-field with the following structure:
8328         // |unspecified|Filter|Addressing Mode| Normalized Coords|
8329         // |31        6|5    4|3             1|                 0|
8330         // This structure corresponds to enum values of sampler properties
8331         // defined in SPIR spec v1.2 and also opencl-c.h
8332         unsigned AddressingMode  = (0x0E & SamplerValue) >> 1;
8333         unsigned FilterMode      = (0x30 & SamplerValue) >> 4;
8334         if (FilterMode != 1 && FilterMode != 2 &&
8335             !S.getOpenCLOptions().isEnabled(
8336                 "cl_intel_device_side_avc_motion_estimation"))
8337           S.Diag(Kind.getLocation(),
8338                  diag::warn_sampler_initializer_invalid_bits)
8339                  << "Filter Mode";
8340         if (AddressingMode > 4)
8341           S.Diag(Kind.getLocation(),
8342                  diag::warn_sampler_initializer_invalid_bits)
8343                  << "Addressing Mode";
8344       }
8345 
8346       // Cases 1a, 2a and 2b
8347       // Insert cast from integer to sampler.
8348       CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8349                                       CK_IntToOCLSampler);
8350       break;
8351     }
8352     case SK_OCLZeroOpaqueType: {
8353       assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8354               Step->Type->isOCLIntelSubgroupAVCType()) &&
8355              "Wrong type for initialization of OpenCL opaque type.");
8356 
8357       CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8358                                     CK_ZeroToOCLOpaqueType,
8359                                     CurInit.get()->getValueKind());
8360       break;
8361     }
8362     }
8363   }
8364 
8365   // Check whether the initializer has a shorter lifetime than the initialized
8366   // entity, and if not, either lifetime-extend or warn as appropriate.
8367   if (auto *Init = CurInit.get())
8368     S.checkInitializerLifetime(Entity, Init);
8369 
8370   // Diagnose non-fatal problems with the completed initialization.
8371   if (Entity.getKind() == InitializedEntity::EK_Member &&
8372       cast<FieldDecl>(Entity.getDecl())->isBitField())
8373     S.CheckBitFieldInitialization(Kind.getLocation(),
8374                                   cast<FieldDecl>(Entity.getDecl()),
8375                                   CurInit.get());
8376 
8377   // Check for std::move on construction.
8378   if (const Expr *E = CurInit.get()) {
8379     CheckMoveOnConstruction(S, E,
8380                             Entity.getKind() == InitializedEntity::EK_Result);
8381   }
8382 
8383   return CurInit;
8384 }
8385 
8386 /// Somewhere within T there is an uninitialized reference subobject.
8387 /// Dig it out and diagnose it.
8388 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8389                                            QualType T) {
8390   if (T->isReferenceType()) {
8391     S.Diag(Loc, diag::err_reference_without_init)
8392       << T.getNonReferenceType();
8393     return true;
8394   }
8395 
8396   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8397   if (!RD || !RD->hasUninitializedReferenceMember())
8398     return false;
8399 
8400   for (const auto *FI : RD->fields()) {
8401     if (FI->isUnnamedBitfield())
8402       continue;
8403 
8404     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8405       S.Diag(Loc, diag::note_value_initialization_here) << RD;
8406       return true;
8407     }
8408   }
8409 
8410   for (const auto &BI : RD->bases()) {
8411     if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8412       S.Diag(Loc, diag::note_value_initialization_here) << RD;
8413       return true;
8414     }
8415   }
8416 
8417   return false;
8418 }
8419 
8420 
8421 //===----------------------------------------------------------------------===//
8422 // Diagnose initialization failures
8423 //===----------------------------------------------------------------------===//
8424 
8425 /// Emit notes associated with an initialization that failed due to a
8426 /// "simple" conversion failure.
8427 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8428                                    Expr *op) {
8429   QualType destType = entity.getType();
8430   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8431       op->getType()->isObjCObjectPointerType()) {
8432 
8433     // Emit a possible note about the conversion failing because the
8434     // operand is a message send with a related result type.
8435     S.EmitRelatedResultTypeNote(op);
8436 
8437     // Emit a possible note about a return failing because we're
8438     // expecting a related result type.
8439     if (entity.getKind() == InitializedEntity::EK_Result)
8440       S.EmitRelatedResultTypeNoteForReturn(destType);
8441   }
8442 }
8443 
8444 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8445                              InitListExpr *InitList) {
8446   QualType DestType = Entity.getType();
8447 
8448   QualType E;
8449   if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8450     QualType ArrayType = S.Context.getConstantArrayType(
8451         E.withConst(),
8452         llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8453                     InitList->getNumInits()),
8454         clang::ArrayType::Normal, 0);
8455     InitializedEntity HiddenArray =
8456         InitializedEntity::InitializeTemporary(ArrayType);
8457     return diagnoseListInit(S, HiddenArray, InitList);
8458   }
8459 
8460   if (DestType->isReferenceType()) {
8461     // A list-initialization failure for a reference means that we tried to
8462     // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8463     // inner initialization failed.
8464     QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8465     diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
8466     SourceLocation Loc = InitList->getBeginLoc();
8467     if (auto *D = Entity.getDecl())
8468       Loc = D->getLocation();
8469     S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8470     return;
8471   }
8472 
8473   InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8474                                    /*VerifyOnly=*/false,
8475                                    /*TreatUnavailableAsInvalid=*/false);
8476   assert(DiagnoseInitList.HadError() &&
8477          "Inconsistent init list check result.");
8478 }
8479 
8480 bool InitializationSequence::Diagnose(Sema &S,
8481                                       const InitializedEntity &Entity,
8482                                       const InitializationKind &Kind,
8483                                       ArrayRef<Expr *> Args) {
8484   if (!Failed())
8485     return false;
8486 
8487   // When we want to diagnose only one element of a braced-init-list,
8488   // we need to factor it out.
8489   Expr *OnlyArg;
8490   if (Args.size() == 1) {
8491     auto *List = dyn_cast<InitListExpr>(Args[0]);
8492     if (List && List->getNumInits() == 1)
8493       OnlyArg = List->getInit(0);
8494     else
8495       OnlyArg = Args[0];
8496   }
8497   else
8498     OnlyArg = nullptr;
8499 
8500   QualType DestType = Entity.getType();
8501   switch (Failure) {
8502   case FK_TooManyInitsForReference:
8503     // FIXME: Customize for the initialized entity?
8504     if (Args.empty()) {
8505       // Dig out the reference subobject which is uninitialized and diagnose it.
8506       // If this is value-initialization, this could be nested some way within
8507       // the target type.
8508       assert(Kind.getKind() == InitializationKind::IK_Value ||
8509              DestType->isReferenceType());
8510       bool Diagnosed =
8511         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8512       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8513       (void)Diagnosed;
8514     } else  // FIXME: diagnostic below could be better!
8515       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
8516           << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8517     break;
8518   case FK_ParenthesizedListInitForReference:
8519     S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8520       << 1 << Entity.getType() << Args[0]->getSourceRange();
8521     break;
8522 
8523   case FK_ArrayNeedsInitList:
8524     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
8525     break;
8526   case FK_ArrayNeedsInitListOrStringLiteral:
8527     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8528     break;
8529   case FK_ArrayNeedsInitListOrWideStringLiteral:
8530     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8531     break;
8532   case FK_NarrowStringIntoWideCharArray:
8533     S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8534     break;
8535   case FK_WideStringIntoCharArray:
8536     S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8537     break;
8538   case FK_IncompatWideStringIntoWideChar:
8539     S.Diag(Kind.getLocation(),
8540            diag::err_array_init_incompat_wide_string_into_wchar);
8541     break;
8542   case FK_PlainStringIntoUTF8Char:
8543     S.Diag(Kind.getLocation(),
8544            diag::err_array_init_plain_string_into_char8_t);
8545     S.Diag(Args.front()->getBeginLoc(),
8546            diag::note_array_init_plain_string_into_char8_t)
8547         << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
8548     break;
8549   case FK_UTF8StringIntoPlainChar:
8550     S.Diag(Kind.getLocation(),
8551            diag::err_array_init_utf8_string_into_char)
8552       << S.getLangOpts().CPlusPlus2a;
8553     break;
8554   case FK_ArrayTypeMismatch:
8555   case FK_NonConstantArrayInit:
8556     S.Diag(Kind.getLocation(),
8557            (Failure == FK_ArrayTypeMismatch
8558               ? diag::err_array_init_different_type
8559               : diag::err_array_init_non_constant_array))
8560       << DestType.getNonReferenceType()
8561       << OnlyArg->getType()
8562       << Args[0]->getSourceRange();
8563     break;
8564 
8565   case FK_VariableLengthArrayHasInitializer:
8566     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8567       << Args[0]->getSourceRange();
8568     break;
8569 
8570   case FK_AddressOfOverloadFailed: {
8571     DeclAccessPair Found;
8572     S.ResolveAddressOfOverloadedFunction(OnlyArg,
8573                                          DestType.getNonReferenceType(),
8574                                          true,
8575                                          Found);
8576     break;
8577   }
8578 
8579   case FK_AddressOfUnaddressableFunction: {
8580     auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8581     S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8582                                         OnlyArg->getBeginLoc());
8583     break;
8584   }
8585 
8586   case FK_ReferenceInitOverloadFailed:
8587   case FK_UserConversionOverloadFailed:
8588     switch (FailedOverloadResult) {
8589     case OR_Ambiguous:
8590 
8591       FailedCandidateSet.NoteCandidates(
8592           PartialDiagnosticAt(
8593               Kind.getLocation(),
8594               Failure == FK_UserConversionOverloadFailed
8595                   ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8596                      << OnlyArg->getType() << DestType
8597                      << Args[0]->getSourceRange())
8598                   : (S.PDiag(diag::err_ref_init_ambiguous)
8599                      << DestType << OnlyArg->getType()
8600                      << Args[0]->getSourceRange())),
8601           S, OCD_ViableCandidates, Args);
8602       break;
8603 
8604     case OR_No_Viable_Function: {
8605       auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
8606       if (!S.RequireCompleteType(Kind.getLocation(),
8607                                  DestType.getNonReferenceType(),
8608                           diag::err_typecheck_nonviable_condition_incomplete,
8609                                OnlyArg->getType(), Args[0]->getSourceRange()))
8610         S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
8611           << (Entity.getKind() == InitializedEntity::EK_Result)
8612           << OnlyArg->getType() << Args[0]->getSourceRange()
8613           << DestType.getNonReferenceType();
8614 
8615       FailedCandidateSet.NoteCandidates(S, Args, Cands);
8616       break;
8617     }
8618     case OR_Deleted: {
8619       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
8620         << OnlyArg->getType() << DestType.getNonReferenceType()
8621         << Args[0]->getSourceRange();
8622       OverloadCandidateSet::iterator Best;
8623       OverloadingResult Ovl
8624         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8625       if (Ovl == OR_Deleted) {
8626         S.NoteDeletedFunction(Best->Function);
8627       } else {
8628         llvm_unreachable("Inconsistent overload resolution?");
8629       }
8630       break;
8631     }
8632 
8633     case OR_Success:
8634       llvm_unreachable("Conversion did not fail!");
8635     }
8636     break;
8637 
8638   case FK_NonConstLValueReferenceBindingToTemporary:
8639     if (isa<InitListExpr>(Args[0])) {
8640       S.Diag(Kind.getLocation(),
8641              diag::err_lvalue_reference_bind_to_initlist)
8642       << DestType.getNonReferenceType().isVolatileQualified()
8643       << DestType.getNonReferenceType()
8644       << Args[0]->getSourceRange();
8645       break;
8646     }
8647     LLVM_FALLTHROUGH;
8648 
8649   case FK_NonConstLValueReferenceBindingToUnrelated:
8650     S.Diag(Kind.getLocation(),
8651            Failure == FK_NonConstLValueReferenceBindingToTemporary
8652              ? diag::err_lvalue_reference_bind_to_temporary
8653              : diag::err_lvalue_reference_bind_to_unrelated)
8654       << DestType.getNonReferenceType().isVolatileQualified()
8655       << DestType.getNonReferenceType()
8656       << OnlyArg->getType()
8657       << Args[0]->getSourceRange();
8658     break;
8659 
8660   case FK_NonConstLValueReferenceBindingToBitfield: {
8661     // We don't necessarily have an unambiguous source bit-field.
8662     FieldDecl *BitField = Args[0]->getSourceBitField();
8663     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8664       << DestType.isVolatileQualified()
8665       << (BitField ? BitField->getDeclName() : DeclarationName())
8666       << (BitField != nullptr)
8667       << Args[0]->getSourceRange();
8668     if (BitField)
8669       S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8670     break;
8671   }
8672 
8673   case FK_NonConstLValueReferenceBindingToVectorElement:
8674     S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8675       << DestType.isVolatileQualified()
8676       << Args[0]->getSourceRange();
8677     break;
8678 
8679   case FK_RValueReferenceBindingToLValue:
8680     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
8681       << DestType.getNonReferenceType() << OnlyArg->getType()
8682       << Args[0]->getSourceRange();
8683     break;
8684 
8685   case FK_ReferenceAddrspaceMismatchTemporary:
8686     S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
8687         << DestType << Args[0]->getSourceRange();
8688     break;
8689 
8690   case FK_ReferenceInitDropsQualifiers: {
8691     QualType SourceType = OnlyArg->getType();
8692     QualType NonRefType = DestType.getNonReferenceType();
8693     Qualifiers DroppedQualifiers =
8694         SourceType.getQualifiers() - NonRefType.getQualifiers();
8695 
8696     if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
8697             SourceType.getQualifiers()))
8698       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8699           << NonRefType << SourceType << 1 /*addr space*/
8700           << Args[0]->getSourceRange();
8701     else
8702       S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8703           << NonRefType << SourceType << 0 /*cv quals*/
8704           << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
8705           << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
8706     break;
8707   }
8708 
8709   case FK_ReferenceInitFailed:
8710     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8711       << DestType.getNonReferenceType()
8712       << DestType.getNonReferenceType()->isIncompleteType()
8713       << OnlyArg->isLValue()
8714       << OnlyArg->getType()
8715       << Args[0]->getSourceRange();
8716     emitBadConversionNotes(S, Entity, Args[0]);
8717     break;
8718 
8719   case FK_ConversionFailed: {
8720     QualType FromType = OnlyArg->getType();
8721     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
8722       << (int)Entity.getKind()
8723       << DestType
8724       << OnlyArg->isLValue()
8725       << FromType
8726       << Args[0]->getSourceRange();
8727     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8728     S.Diag(Kind.getLocation(), PDiag);
8729     emitBadConversionNotes(S, Entity, Args[0]);
8730     break;
8731   }
8732 
8733   case FK_ConversionFromPropertyFailed:
8734     // No-op. This error has already been reported.
8735     break;
8736 
8737   case FK_TooManyInitsForScalar: {
8738     SourceRange R;
8739 
8740     auto *InitList = dyn_cast<InitListExpr>(Args[0]);
8741     if (InitList && InitList->getNumInits() >= 1) {
8742       R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
8743     } else {
8744       assert(Args.size() > 1 && "Expected multiple initializers!");
8745       R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
8746     }
8747 
8748     R.setBegin(S.getLocForEndOfToken(R.getBegin()));
8749     if (Kind.isCStyleOrFunctionalCast())
8750       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8751         << R;
8752     else
8753       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8754         << /*scalar=*/2 << R;
8755     break;
8756   }
8757 
8758   case FK_ParenthesizedListInitForScalar:
8759     S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8760       << 0 << Entity.getType() << Args[0]->getSourceRange();
8761     break;
8762 
8763   case FK_ReferenceBindingToInitList:
8764     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8765       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8766     break;
8767 
8768   case FK_InitListBadDestinationType:
8769     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8770       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8771     break;
8772 
8773   case FK_ListConstructorOverloadFailed:
8774   case FK_ConstructorOverloadFailed: {
8775     SourceRange ArgsRange;
8776     if (Args.size())
8777       ArgsRange =
8778           SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8779 
8780     if (Failure == FK_ListConstructorOverloadFailed) {
8781       assert(Args.size() == 1 &&
8782              "List construction from other than 1 argument.");
8783       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8784       Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
8785     }
8786 
8787     // FIXME: Using "DestType" for the entity we're printing is probably
8788     // bad.
8789     switch (FailedOverloadResult) {
8790       case OR_Ambiguous:
8791         FailedCandidateSet.NoteCandidates(
8792             PartialDiagnosticAt(Kind.getLocation(),
8793                                 S.PDiag(diag::err_ovl_ambiguous_init)
8794                                     << DestType << ArgsRange),
8795             S, OCD_ViableCandidates, Args);
8796         break;
8797 
8798       case OR_No_Viable_Function:
8799         if (Kind.getKind() == InitializationKind::IK_Default &&
8800             (Entity.getKind() == InitializedEntity::EK_Base ||
8801              Entity.getKind() == InitializedEntity::EK_Member) &&
8802             isa<CXXConstructorDecl>(S.CurContext)) {
8803           // This is implicit default initialization of a member or
8804           // base within a constructor. If no viable function was
8805           // found, notify the user that they need to explicitly
8806           // initialize this base/member.
8807           CXXConstructorDecl *Constructor
8808             = cast<CXXConstructorDecl>(S.CurContext);
8809           const CXXRecordDecl *InheritedFrom = nullptr;
8810           if (auto Inherited = Constructor->getInheritedConstructor())
8811             InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
8812           if (Entity.getKind() == InitializedEntity::EK_Base) {
8813             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
8814               << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8815               << S.Context.getTypeDeclType(Constructor->getParent())
8816               << /*base=*/0
8817               << Entity.getType()
8818               << InheritedFrom;
8819 
8820             RecordDecl *BaseDecl
8821               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8822                                                                   ->getDecl();
8823             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8824               << S.Context.getTagDeclType(BaseDecl);
8825           } else {
8826             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
8827               << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8828               << S.Context.getTypeDeclType(Constructor->getParent())
8829               << /*member=*/1
8830               << Entity.getName()
8831               << InheritedFrom;
8832             S.Diag(Entity.getDecl()->getLocation(),
8833                    diag::note_member_declared_at);
8834 
8835             if (const RecordType *Record
8836                                  = Entity.getType()->getAs<RecordType>())
8837               S.Diag(Record->getDecl()->getLocation(),
8838                      diag::note_previous_decl)
8839                 << S.Context.getTagDeclType(Record->getDecl());
8840           }
8841           break;
8842         }
8843 
8844         FailedCandidateSet.NoteCandidates(
8845             PartialDiagnosticAt(
8846                 Kind.getLocation(),
8847                 S.PDiag(diag::err_ovl_no_viable_function_in_init)
8848                     << DestType << ArgsRange),
8849             S, OCD_AllCandidates, Args);
8850         break;
8851 
8852       case OR_Deleted: {
8853         OverloadCandidateSet::iterator Best;
8854         OverloadingResult Ovl
8855           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8856         if (Ovl != OR_Deleted) {
8857           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8858               << DestType << ArgsRange;
8859           llvm_unreachable("Inconsistent overload resolution?");
8860           break;
8861         }
8862 
8863         // If this is a defaulted or implicitly-declared function, then
8864         // it was implicitly deleted. Make it clear that the deletion was
8865         // implicit.
8866         if (S.isImplicitlyDeleted(Best->Function))
8867           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
8868             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
8869             << DestType << ArgsRange;
8870         else
8871           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8872               << DestType << ArgsRange;
8873 
8874         S.NoteDeletedFunction(Best->Function);
8875         break;
8876       }
8877 
8878       case OR_Success:
8879         llvm_unreachable("Conversion did not fail!");
8880     }
8881   }
8882   break;
8883 
8884   case FK_DefaultInitOfConst:
8885     if (Entity.getKind() == InitializedEntity::EK_Member &&
8886         isa<CXXConstructorDecl>(S.CurContext)) {
8887       // This is implicit default-initialization of a const member in
8888       // a constructor. Complain that it needs to be explicitly
8889       // initialized.
8890       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8891       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
8892         << (Constructor->getInheritedConstructor() ? 2 :
8893             Constructor->isImplicit() ? 1 : 0)
8894         << S.Context.getTypeDeclType(Constructor->getParent())
8895         << /*const=*/1
8896         << Entity.getName();
8897       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8898         << Entity.getName();
8899     } else {
8900       S.Diag(Kind.getLocation(), diag::err_default_init_const)
8901           << DestType << (bool)DestType->getAs<RecordType>();
8902     }
8903     break;
8904 
8905   case FK_Incomplete:
8906     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
8907                           diag::err_init_incomplete_type);
8908     break;
8909 
8910   case FK_ListInitializationFailed: {
8911     // Run the init list checker again to emit diagnostics.
8912     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8913     diagnoseListInit(S, Entity, InitList);
8914     break;
8915   }
8916 
8917   case FK_PlaceholderType: {
8918     // FIXME: Already diagnosed!
8919     break;
8920   }
8921 
8922   case FK_ExplicitConstructor: {
8923     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8924       << Args[0]->getSourceRange();
8925     OverloadCandidateSet::iterator Best;
8926     OverloadingResult Ovl
8927       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8928     (void)Ovl;
8929     assert(Ovl == OR_Success && "Inconsistent overload resolution");
8930     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
8931     S.Diag(CtorDecl->getLocation(),
8932            diag::note_explicit_ctor_deduction_guide_here) << false;
8933     break;
8934   }
8935   }
8936 
8937   PrintInitLocationNote(S, Entity);
8938   return true;
8939 }
8940 
8941 void InitializationSequence::dump(raw_ostream &OS) const {
8942   switch (SequenceKind) {
8943   case FailedSequence: {
8944     OS << "Failed sequence: ";
8945     switch (Failure) {
8946     case FK_TooManyInitsForReference:
8947       OS << "too many initializers for reference";
8948       break;
8949 
8950     case FK_ParenthesizedListInitForReference:
8951       OS << "parenthesized list init for reference";
8952       break;
8953 
8954     case FK_ArrayNeedsInitList:
8955       OS << "array requires initializer list";
8956       break;
8957 
8958     case FK_AddressOfUnaddressableFunction:
8959       OS << "address of unaddressable function was taken";
8960       break;
8961 
8962     case FK_ArrayNeedsInitListOrStringLiteral:
8963       OS << "array requires initializer list or string literal";
8964       break;
8965 
8966     case FK_ArrayNeedsInitListOrWideStringLiteral:
8967       OS << "array requires initializer list or wide string literal";
8968       break;
8969 
8970     case FK_NarrowStringIntoWideCharArray:
8971       OS << "narrow string into wide char array";
8972       break;
8973 
8974     case FK_WideStringIntoCharArray:
8975       OS << "wide string into char array";
8976       break;
8977 
8978     case FK_IncompatWideStringIntoWideChar:
8979       OS << "incompatible wide string into wide char array";
8980       break;
8981 
8982     case FK_PlainStringIntoUTF8Char:
8983       OS << "plain string literal into char8_t array";
8984       break;
8985 
8986     case FK_UTF8StringIntoPlainChar:
8987       OS << "u8 string literal into char array";
8988       break;
8989 
8990     case FK_ArrayTypeMismatch:
8991       OS << "array type mismatch";
8992       break;
8993 
8994     case FK_NonConstantArrayInit:
8995       OS << "non-constant array initializer";
8996       break;
8997 
8998     case FK_AddressOfOverloadFailed:
8999       OS << "address of overloaded function failed";
9000       break;
9001 
9002     case FK_ReferenceInitOverloadFailed:
9003       OS << "overload resolution for reference initialization failed";
9004       break;
9005 
9006     case FK_NonConstLValueReferenceBindingToTemporary:
9007       OS << "non-const lvalue reference bound to temporary";
9008       break;
9009 
9010     case FK_NonConstLValueReferenceBindingToBitfield:
9011       OS << "non-const lvalue reference bound to bit-field";
9012       break;
9013 
9014     case FK_NonConstLValueReferenceBindingToVectorElement:
9015       OS << "non-const lvalue reference bound to vector element";
9016       break;
9017 
9018     case FK_NonConstLValueReferenceBindingToUnrelated:
9019       OS << "non-const lvalue reference bound to unrelated type";
9020       break;
9021 
9022     case FK_RValueReferenceBindingToLValue:
9023       OS << "rvalue reference bound to an lvalue";
9024       break;
9025 
9026     case FK_ReferenceInitDropsQualifiers:
9027       OS << "reference initialization drops qualifiers";
9028       break;
9029 
9030     case FK_ReferenceAddrspaceMismatchTemporary:
9031       OS << "reference with mismatching address space bound to temporary";
9032       break;
9033 
9034     case FK_ReferenceInitFailed:
9035       OS << "reference initialization failed";
9036       break;
9037 
9038     case FK_ConversionFailed:
9039       OS << "conversion failed";
9040       break;
9041 
9042     case FK_ConversionFromPropertyFailed:
9043       OS << "conversion from property failed";
9044       break;
9045 
9046     case FK_TooManyInitsForScalar:
9047       OS << "too many initializers for scalar";
9048       break;
9049 
9050     case FK_ParenthesizedListInitForScalar:
9051       OS << "parenthesized list init for reference";
9052       break;
9053 
9054     case FK_ReferenceBindingToInitList:
9055       OS << "referencing binding to initializer list";
9056       break;
9057 
9058     case FK_InitListBadDestinationType:
9059       OS << "initializer list for non-aggregate, non-scalar type";
9060       break;
9061 
9062     case FK_UserConversionOverloadFailed:
9063       OS << "overloading failed for user-defined conversion";
9064       break;
9065 
9066     case FK_ConstructorOverloadFailed:
9067       OS << "constructor overloading failed";
9068       break;
9069 
9070     case FK_DefaultInitOfConst:
9071       OS << "default initialization of a const variable";
9072       break;
9073 
9074     case FK_Incomplete:
9075       OS << "initialization of incomplete type";
9076       break;
9077 
9078     case FK_ListInitializationFailed:
9079       OS << "list initialization checker failure";
9080       break;
9081 
9082     case FK_VariableLengthArrayHasInitializer:
9083       OS << "variable length array has an initializer";
9084       break;
9085 
9086     case FK_PlaceholderType:
9087       OS << "initializer expression isn't contextually valid";
9088       break;
9089 
9090     case FK_ListConstructorOverloadFailed:
9091       OS << "list constructor overloading failed";
9092       break;
9093 
9094     case FK_ExplicitConstructor:
9095       OS << "list copy initialization chose explicit constructor";
9096       break;
9097     }
9098     OS << '\n';
9099     return;
9100   }
9101 
9102   case DependentSequence:
9103     OS << "Dependent sequence\n";
9104     return;
9105 
9106   case NormalSequence:
9107     OS << "Normal sequence: ";
9108     break;
9109   }
9110 
9111   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9112     if (S != step_begin()) {
9113       OS << " -> ";
9114     }
9115 
9116     switch (S->Kind) {
9117     case SK_ResolveAddressOfOverloadedFunction:
9118       OS << "resolve address of overloaded function";
9119       break;
9120 
9121     case SK_CastDerivedToBaseRValue:
9122       OS << "derived-to-base (rvalue)";
9123       break;
9124 
9125     case SK_CastDerivedToBaseXValue:
9126       OS << "derived-to-base (xvalue)";
9127       break;
9128 
9129     case SK_CastDerivedToBaseLValue:
9130       OS << "derived-to-base (lvalue)";
9131       break;
9132 
9133     case SK_BindReference:
9134       OS << "bind reference to lvalue";
9135       break;
9136 
9137     case SK_BindReferenceToTemporary:
9138       OS << "bind reference to a temporary";
9139       break;
9140 
9141     case SK_FinalCopy:
9142       OS << "final copy in class direct-initialization";
9143       break;
9144 
9145     case SK_ExtraneousCopyToTemporary:
9146       OS << "extraneous C++03 copy to temporary";
9147       break;
9148 
9149     case SK_UserConversion:
9150       OS << "user-defined conversion via " << *S->Function.Function;
9151       break;
9152 
9153     case SK_QualificationConversionRValue:
9154       OS << "qualification conversion (rvalue)";
9155       break;
9156 
9157     case SK_QualificationConversionXValue:
9158       OS << "qualification conversion (xvalue)";
9159       break;
9160 
9161     case SK_QualificationConversionLValue:
9162       OS << "qualification conversion (lvalue)";
9163       break;
9164 
9165     case SK_AtomicConversion:
9166       OS << "non-atomic-to-atomic conversion";
9167       break;
9168 
9169     case SK_ConversionSequence:
9170       OS << "implicit conversion sequence (";
9171       S->ICS->dump(); // FIXME: use OS
9172       OS << ")";
9173       break;
9174 
9175     case SK_ConversionSequenceNoNarrowing:
9176       OS << "implicit conversion sequence with narrowing prohibited (";
9177       S->ICS->dump(); // FIXME: use OS
9178       OS << ")";
9179       break;
9180 
9181     case SK_ListInitialization:
9182       OS << "list aggregate initialization";
9183       break;
9184 
9185     case SK_UnwrapInitList:
9186       OS << "unwrap reference initializer list";
9187       break;
9188 
9189     case SK_RewrapInitList:
9190       OS << "rewrap reference initializer list";
9191       break;
9192 
9193     case SK_ConstructorInitialization:
9194       OS << "constructor initialization";
9195       break;
9196 
9197     case SK_ConstructorInitializationFromList:
9198       OS << "list initialization via constructor";
9199       break;
9200 
9201     case SK_ZeroInitialization:
9202       OS << "zero initialization";
9203       break;
9204 
9205     case SK_CAssignment:
9206       OS << "C assignment";
9207       break;
9208 
9209     case SK_StringInit:
9210       OS << "string initialization";
9211       break;
9212 
9213     case SK_ObjCObjectConversion:
9214       OS << "Objective-C object conversion";
9215       break;
9216 
9217     case SK_ArrayLoopIndex:
9218       OS << "indexing for array initialization loop";
9219       break;
9220 
9221     case SK_ArrayLoopInit:
9222       OS << "array initialization loop";
9223       break;
9224 
9225     case SK_ArrayInit:
9226       OS << "array initialization";
9227       break;
9228 
9229     case SK_GNUArrayInit:
9230       OS << "array initialization (GNU extension)";
9231       break;
9232 
9233     case SK_ParenthesizedArrayInit:
9234       OS << "parenthesized array initialization";
9235       break;
9236 
9237     case SK_PassByIndirectCopyRestore:
9238       OS << "pass by indirect copy and restore";
9239       break;
9240 
9241     case SK_PassByIndirectRestore:
9242       OS << "pass by indirect restore";
9243       break;
9244 
9245     case SK_ProduceObjCObject:
9246       OS << "Objective-C object retension";
9247       break;
9248 
9249     case SK_StdInitializerList:
9250       OS << "std::initializer_list from initializer list";
9251       break;
9252 
9253     case SK_StdInitializerListConstructorCall:
9254       OS << "list initialization from std::initializer_list";
9255       break;
9256 
9257     case SK_OCLSamplerInit:
9258       OS << "OpenCL sampler_t from integer constant";
9259       break;
9260 
9261     case SK_OCLZeroOpaqueType:
9262       OS << "OpenCL opaque type from zero";
9263       break;
9264     }
9265 
9266     OS << " [" << S->Type.getAsString() << ']';
9267   }
9268 
9269   OS << '\n';
9270 }
9271 
9272 void InitializationSequence::dump() const {
9273   dump(llvm::errs());
9274 }
9275 
9276 static bool NarrowingErrs(const LangOptions &L) {
9277   return L.CPlusPlus11 &&
9278          (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
9279 }
9280 
9281 static void DiagnoseNarrowingInInitList(Sema &S,
9282                                         const ImplicitConversionSequence &ICS,
9283                                         QualType PreNarrowingType,
9284                                         QualType EntityType,
9285                                         const Expr *PostInit) {
9286   const StandardConversionSequence *SCS = nullptr;
9287   switch (ICS.getKind()) {
9288   case ImplicitConversionSequence::StandardConversion:
9289     SCS = &ICS.Standard;
9290     break;
9291   case ImplicitConversionSequence::UserDefinedConversion:
9292     SCS = &ICS.UserDefined.After;
9293     break;
9294   case ImplicitConversionSequence::AmbiguousConversion:
9295   case ImplicitConversionSequence::EllipsisConversion:
9296   case ImplicitConversionSequence::BadConversion:
9297     return;
9298   }
9299 
9300   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9301   APValue ConstantValue;
9302   QualType ConstantType;
9303   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9304                                 ConstantType)) {
9305   case NK_Not_Narrowing:
9306   case NK_Dependent_Narrowing:
9307     // No narrowing occurred.
9308     return;
9309 
9310   case NK_Type_Narrowing:
9311     // This was a floating-to-integer conversion, which is always considered a
9312     // narrowing conversion even if the value is a constant and can be
9313     // represented exactly as an integer.
9314     S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
9315                                         ? diag::ext_init_list_type_narrowing
9316                                         : diag::warn_init_list_type_narrowing)
9317         << PostInit->getSourceRange()
9318         << PreNarrowingType.getLocalUnqualifiedType()
9319         << EntityType.getLocalUnqualifiedType();
9320     break;
9321 
9322   case NK_Constant_Narrowing:
9323     // A constant value was narrowed.
9324     S.Diag(PostInit->getBeginLoc(),
9325            NarrowingErrs(S.getLangOpts())
9326                ? diag::ext_init_list_constant_narrowing
9327                : diag::warn_init_list_constant_narrowing)
9328         << PostInit->getSourceRange()
9329         << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9330         << EntityType.getLocalUnqualifiedType();
9331     break;
9332 
9333   case NK_Variable_Narrowing:
9334     // A variable's value may have been narrowed.
9335     S.Diag(PostInit->getBeginLoc(),
9336            NarrowingErrs(S.getLangOpts())
9337                ? diag::ext_init_list_variable_narrowing
9338                : diag::warn_init_list_variable_narrowing)
9339         << PostInit->getSourceRange()
9340         << PreNarrowingType.getLocalUnqualifiedType()
9341         << EntityType.getLocalUnqualifiedType();
9342     break;
9343   }
9344 
9345   SmallString<128> StaticCast;
9346   llvm::raw_svector_ostream OS(StaticCast);
9347   OS << "static_cast<";
9348   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9349     // It's important to use the typedef's name if there is one so that the
9350     // fixit doesn't break code using types like int64_t.
9351     //
9352     // FIXME: This will break if the typedef requires qualification.  But
9353     // getQualifiedNameAsString() includes non-machine-parsable components.
9354     OS << *TT->getDecl();
9355   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9356     OS << BT->getName(S.getLangOpts());
9357   else {
9358     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
9359     // with a broken cast.
9360     return;
9361   }
9362   OS << ">(";
9363   S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9364       << PostInit->getSourceRange()
9365       << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9366       << FixItHint::CreateInsertion(
9367              S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9368 }
9369 
9370 //===----------------------------------------------------------------------===//
9371 // Initialization helper functions
9372 //===----------------------------------------------------------------------===//
9373 bool
9374 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9375                                    ExprResult Init) {
9376   if (Init.isInvalid())
9377     return false;
9378 
9379   Expr *InitE = Init.get();
9380   assert(InitE && "No initialization expression");
9381 
9382   InitializationKind Kind =
9383       InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
9384   InitializationSequence Seq(*this, Entity, Kind, InitE);
9385   return !Seq.Failed();
9386 }
9387 
9388 ExprResult
9389 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9390                                 SourceLocation EqualLoc,
9391                                 ExprResult Init,
9392                                 bool TopLevelOfInitList,
9393                                 bool AllowExplicit) {
9394   if (Init.isInvalid())
9395     return ExprError();
9396 
9397   Expr *InitE = Init.get();
9398   assert(InitE && "No initialization expression?");
9399 
9400   if (EqualLoc.isInvalid())
9401     EqualLoc = InitE->getBeginLoc();
9402 
9403   InitializationKind Kind = InitializationKind::CreateCopy(
9404       InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9405   InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
9406 
9407   // Prevent infinite recursion when performing parameter copy-initialization.
9408   const bool ShouldTrackCopy =
9409       Entity.isParameterKind() && Seq.isConstructorInitialization();
9410   if (ShouldTrackCopy) {
9411     if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
9412         CurrentParameterCopyTypes.end()) {
9413       Seq.SetOverloadFailure(
9414           InitializationSequence::FK_ConstructorOverloadFailed,
9415           OR_No_Viable_Function);
9416 
9417       // Try to give a meaningful diagnostic note for the problematic
9418       // constructor.
9419       const auto LastStep = Seq.step_end() - 1;
9420       assert(LastStep->Kind ==
9421              InitializationSequence::SK_ConstructorInitialization);
9422       const FunctionDecl *Function = LastStep->Function.Function;
9423       auto Candidate =
9424           llvm::find_if(Seq.getFailedCandidateSet(),
9425                         [Function](const OverloadCandidate &Candidate) -> bool {
9426                           return Candidate.Viable &&
9427                                  Candidate.Function == Function &&
9428                                  Candidate.Conversions.size() > 0;
9429                         });
9430       if (Candidate != Seq.getFailedCandidateSet().end() &&
9431           Function->getNumParams() > 0) {
9432         Candidate->Viable = false;
9433         Candidate->FailureKind = ovl_fail_bad_conversion;
9434         Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9435                                          InitE,
9436                                          Function->getParamDecl(0)->getType());
9437       }
9438     }
9439     CurrentParameterCopyTypes.push_back(Entity.getType());
9440   }
9441 
9442   ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
9443 
9444   if (ShouldTrackCopy)
9445     CurrentParameterCopyTypes.pop_back();
9446 
9447   return Result;
9448 }
9449 
9450 /// Determine whether RD is, or is derived from, a specialization of CTD.
9451 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9452                                               ClassTemplateDecl *CTD) {
9453   auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9454     auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9455     return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9456   };
9457   return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9458 }
9459 
9460 QualType Sema::DeduceTemplateSpecializationFromInitializer(
9461     TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9462     const InitializationKind &Kind, MultiExprArg Inits) {
9463   auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9464       TSInfo->getType()->getContainedDeducedType());
9465   assert(DeducedTST && "not a deduced template specialization type");
9466 
9467   auto TemplateName = DeducedTST->getTemplateName();
9468   if (TemplateName.isDependent())
9469     return Context.DependentTy;
9470 
9471   // We can only perform deduction for class templates.
9472   auto *Template =
9473       dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9474   if (!Template) {
9475     Diag(Kind.getLocation(),
9476          diag::err_deduced_non_class_template_specialization_type)
9477       << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
9478     if (auto *TD = TemplateName.getAsTemplateDecl())
9479       Diag(TD->getLocation(), diag::note_template_decl_here);
9480     return QualType();
9481   }
9482 
9483   // Can't deduce from dependent arguments.
9484   if (Expr::hasAnyTypeDependentArguments(Inits)) {
9485     Diag(TSInfo->getTypeLoc().getBeginLoc(),
9486          diag::warn_cxx14_compat_class_template_argument_deduction)
9487         << TSInfo->getTypeLoc().getSourceRange() << 0;
9488     return Context.DependentTy;
9489   }
9490 
9491   // FIXME: Perform "exact type" matching first, per CWG discussion?
9492   //        Or implement this via an implied 'T(T) -> T' deduction guide?
9493 
9494   // FIXME: Do we need/want a std::initializer_list<T> special case?
9495 
9496   // Look up deduction guides, including those synthesized from constructors.
9497   //
9498   // C++1z [over.match.class.deduct]p1:
9499   //   A set of functions and function templates is formed comprising:
9500   //   - For each constructor of the class template designated by the
9501   //     template-name, a function template [...]
9502   //  - For each deduction-guide, a function or function template [...]
9503   DeclarationNameInfo NameInfo(
9504       Context.DeclarationNames.getCXXDeductionGuideName(Template),
9505       TSInfo->getTypeLoc().getEndLoc());
9506   LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9507   LookupQualifiedName(Guides, Template->getDeclContext());
9508 
9509   // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9510   // clear on this, but they're not found by name so access does not apply.
9511   Guides.suppressDiagnostics();
9512 
9513   // Figure out if this is list-initialization.
9514   InitListExpr *ListInit =
9515       (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9516           ? dyn_cast<InitListExpr>(Inits[0])
9517           : nullptr;
9518 
9519   // C++1z [over.match.class.deduct]p1:
9520   //   Initialization and overload resolution are performed as described in
9521   //   [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9522   //   (as appropriate for the type of initialization performed) for an object
9523   //   of a hypothetical class type, where the selected functions and function
9524   //   templates are considered to be the constructors of that class type
9525   //
9526   // Since we know we're initializing a class type of a type unrelated to that
9527   // of the initializer, this reduces to something fairly reasonable.
9528   OverloadCandidateSet Candidates(Kind.getLocation(),
9529                                   OverloadCandidateSet::CSK_Normal);
9530   OverloadCandidateSet::iterator Best;
9531 
9532   bool HasAnyDeductionGuide = false;
9533   bool AllowExplicit = !Kind.isCopyInit() || ListInit;
9534 
9535   auto tryToResolveOverload =
9536       [&](bool OnlyListConstructors) -> OverloadingResult {
9537     Candidates.clear(OverloadCandidateSet::CSK_Normal);
9538     HasAnyDeductionGuide = false;
9539 
9540     for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9541       NamedDecl *D = (*I)->getUnderlyingDecl();
9542       if (D->isInvalidDecl())
9543         continue;
9544 
9545       auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9546       auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9547           TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9548       if (!GD)
9549         continue;
9550 
9551       if (!GD->isImplicit())
9552         HasAnyDeductionGuide = true;
9553 
9554       // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9555       //   For copy-initialization, the candidate functions are all the
9556       //   converting constructors (12.3.1) of that class.
9557       // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9558       //   The converting constructors of T are candidate functions.
9559       if (!AllowExplicit) {
9560         // Only consider converting constructors.
9561         if (GD->isExplicit())
9562           continue;
9563 
9564         // When looking for a converting constructor, deduction guides that
9565         // could never be called with one argument are not interesting to
9566         // check or note.
9567         if (GD->getMinRequiredArguments() > 1 ||
9568             (GD->getNumParams() == 0 && !GD->isVariadic()))
9569           continue;
9570       }
9571 
9572       // C++ [over.match.list]p1.1: (first phase list initialization)
9573       //   Initially, the candidate functions are the initializer-list
9574       //   constructors of the class T
9575       if (OnlyListConstructors && !isInitListConstructor(GD))
9576         continue;
9577 
9578       // C++ [over.match.list]p1.2: (second phase list initialization)
9579       //   the candidate functions are all the constructors of the class T
9580       // C++ [over.match.ctor]p1: (all other cases)
9581       //   the candidate functions are all the constructors of the class of
9582       //   the object being initialized
9583 
9584       // C++ [over.best.ics]p4:
9585       //   When [...] the constructor [...] is a candidate by
9586       //    - [over.match.copy] (in all cases)
9587       // FIXME: The "second phase of [over.match.list] case can also
9588       // theoretically happen here, but it's not clear whether we can
9589       // ever have a parameter of the right type.
9590       bool SuppressUserConversions = Kind.isCopyInit();
9591 
9592       if (TD)
9593         AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
9594                                      Inits, Candidates, SuppressUserConversions,
9595                                      /*PartialOverloading*/ false,
9596                                      AllowExplicit);
9597       else
9598         AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
9599                              SuppressUserConversions,
9600                              /*PartialOverloading*/ false, AllowExplicit);
9601     }
9602     return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9603   };
9604 
9605   OverloadingResult Result = OR_No_Viable_Function;
9606 
9607   // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9608   // try initializer-list constructors.
9609   if (ListInit) {
9610     bool TryListConstructors = true;
9611 
9612     // Try list constructors unless the list is empty and the class has one or
9613     // more default constructors, in which case those constructors win.
9614     if (!ListInit->getNumInits()) {
9615       for (NamedDecl *D : Guides) {
9616         auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9617         if (FD && FD->getMinRequiredArguments() == 0) {
9618           TryListConstructors = false;
9619           break;
9620         }
9621       }
9622     } else if (ListInit->getNumInits() == 1) {
9623       // C++ [over.match.class.deduct]:
9624       //   As an exception, the first phase in [over.match.list] (considering
9625       //   initializer-list constructors) is omitted if the initializer list
9626       //   consists of a single expression of type cv U, where U is a
9627       //   specialization of C or a class derived from a specialization of C.
9628       Expr *E = ListInit->getInit(0);
9629       auto *RD = E->getType()->getAsCXXRecordDecl();
9630       if (!isa<InitListExpr>(E) && RD &&
9631           isCompleteType(Kind.getLocation(), E->getType()) &&
9632           isOrIsDerivedFromSpecializationOf(RD, Template))
9633         TryListConstructors = false;
9634     }
9635 
9636     if (TryListConstructors)
9637       Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9638     // Then unwrap the initializer list and try again considering all
9639     // constructors.
9640     Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9641   }
9642 
9643   // If list-initialization fails, or if we're doing any other kind of
9644   // initialization, we (eventually) consider constructors.
9645   if (Result == OR_No_Viable_Function)
9646     Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9647 
9648   switch (Result) {
9649   case OR_Ambiguous:
9650     // FIXME: For list-initialization candidates, it'd usually be better to
9651     // list why they were not viable when given the initializer list itself as
9652     // an argument.
9653     Candidates.NoteCandidates(
9654         PartialDiagnosticAt(
9655             Kind.getLocation(),
9656             PDiag(diag::err_deduced_class_template_ctor_ambiguous)
9657                 << TemplateName),
9658         *this, OCD_ViableCandidates, Inits);
9659     return QualType();
9660 
9661   case OR_No_Viable_Function: {
9662     CXXRecordDecl *Primary =
9663         cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9664     bool Complete =
9665         isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
9666     Candidates.NoteCandidates(
9667         PartialDiagnosticAt(
9668             Kind.getLocation(),
9669             PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
9670                            : diag::err_deduced_class_template_incomplete)
9671                 << TemplateName << !Guides.empty()),
9672         *this, OCD_AllCandidates, Inits);
9673     return QualType();
9674   }
9675 
9676   case OR_Deleted: {
9677     Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9678       << TemplateName;
9679     NoteDeletedFunction(Best->Function);
9680     return QualType();
9681   }
9682 
9683   case OR_Success:
9684     // C++ [over.match.list]p1:
9685     //   In copy-list-initialization, if an explicit constructor is chosen, the
9686     //   initialization is ill-formed.
9687     if (Kind.isCopyInit() && ListInit &&
9688         cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
9689       bool IsDeductionGuide = !Best->Function->isImplicit();
9690       Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9691           << TemplateName << IsDeductionGuide;
9692       Diag(Best->Function->getLocation(),
9693            diag::note_explicit_ctor_deduction_guide_here)
9694           << IsDeductionGuide;
9695       return QualType();
9696     }
9697 
9698     // Make sure we didn't select an unusable deduction guide, and mark it
9699     // as referenced.
9700     DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9701     MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9702     break;
9703   }
9704 
9705   // C++ [dcl.type.class.deduct]p1:
9706   //  The placeholder is replaced by the return type of the function selected
9707   //  by overload resolution for class template deduction.
9708   QualType DeducedType =
9709       SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9710   Diag(TSInfo->getTypeLoc().getBeginLoc(),
9711        diag::warn_cxx14_compat_class_template_argument_deduction)
9712       << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
9713 
9714   // Warn if CTAD was used on a type that does not have any user-defined
9715   // deduction guides.
9716   if (!HasAnyDeductionGuide) {
9717     Diag(TSInfo->getTypeLoc().getBeginLoc(),
9718          diag::warn_ctad_maybe_unsupported)
9719         << TemplateName;
9720     Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
9721   }
9722 
9723   return DeducedType;
9724 }
9725