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