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