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