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