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