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