clang 19.0.0git
SemaInit.cpp
Go to the documentation of this file.
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
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeLoc.h"
28#include "clang/Sema/Lookup.h"
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/PointerIntPair.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// Sema Initialization Checking
44//===----------------------------------------------------------------------===//
45
46/// Check whether T is compatible with a wide character type (wchar_t,
47/// char16_t or char32_t).
48static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
49 if (Context.typesAreCompatible(Context.getWideCharType(), T))
50 return true;
51 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
52 return Context.typesAreCompatible(Context.Char16Ty, T) ||
53 Context.typesAreCompatible(Context.Char32Ty, T);
54 }
55 return false;
56}
57
66};
67
68/// Check whether the array of type AT can be initialized by the Init
69/// expression by means of string initialization. Returns SIF_None if so,
70/// otherwise returns a StringInitFailureKind that describes why the
71/// initialization would not work.
73 ASTContext &Context) {
74 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
75 return SIF_Other;
76
77 // See if this is a string literal or @encode.
78 Init = Init->IgnoreParens();
79
80 // Handle @encode, which is a narrow string.
81 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
82 return SIF_None;
83
84 // Otherwise we can only handle string literals.
85 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
86 if (!SL)
87 return SIF_Other;
88
89 const QualType ElemTy =
91
92 auto IsCharOrUnsignedChar = [](const QualType &T) {
93 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
94 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
95 };
96
97 switch (SL->getKind()) {
98 case StringLiteralKind::UTF8:
99 // char8_t array can be initialized with a UTF-8 string.
100 // - C++20 [dcl.init.string] (DR)
101 // Additionally, an array of char or unsigned char may be initialized
102 // by a UTF-8 string literal.
103 if (ElemTy->isChar8Type() ||
104 (Context.getLangOpts().Char8 &&
105 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
106 return SIF_None;
107 [[fallthrough]];
108 case StringLiteralKind::Ordinary:
109 // char array can be initialized with a narrow string.
110 // Only allow char x[] = "foo"; not char x[] = L"foo";
111 if (ElemTy->isCharType())
112 return (SL->getKind() == StringLiteralKind::UTF8 &&
113 Context.getLangOpts().Char8)
115 : SIF_None;
116 if (ElemTy->isChar8Type())
118 if (IsWideCharCompatible(ElemTy, Context))
120 return SIF_Other;
121 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
122 // "An array with element type compatible with a qualified or unqualified
123 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
124 // string literal with the corresponding encoding prefix (L, u, or U,
125 // respectively), optionally enclosed in braces.
126 case StringLiteralKind::UTF16:
127 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
128 return SIF_None;
129 if (ElemTy->isCharType() || ElemTy->isChar8Type())
131 if (IsWideCharCompatible(ElemTy, Context))
133 return SIF_Other;
134 case StringLiteralKind::UTF32:
135 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
136 return SIF_None;
137 if (ElemTy->isCharType() || ElemTy->isChar8Type())
139 if (IsWideCharCompatible(ElemTy, Context))
141 return SIF_Other;
142 case StringLiteralKind::Wide:
143 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
144 return SIF_None;
145 if (ElemTy->isCharType() || ElemTy->isChar8Type())
147 if (IsWideCharCompatible(ElemTy, Context))
149 return SIF_Other;
150 case StringLiteralKind::Unevaluated:
151 assert(false && "Unevaluated string literal in initialization");
152 break;
153 }
154
155 llvm_unreachable("missed a StringLiteral kind?");
156}
157
159 ASTContext &Context) {
160 const ArrayType *arrayType = Context.getAsArrayType(declType);
161 if (!arrayType)
162 return SIF_Other;
163 return IsStringInit(init, arrayType, Context);
164}
165
167 return ::IsStringInit(Init, AT, Context) == SIF_None;
168}
169
170/// Update the type of a string literal, including any surrounding parentheses,
171/// to match the type of the object which it is initializing.
173 while (true) {
174 E->setType(Ty);
176 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
177 break;
179 }
180}
181
182/// Fix a compound literal initializing an array so it's correctly marked
183/// as an rvalue.
185 while (true) {
187 if (isa<CompoundLiteralExpr>(E))
188 break;
190 }
191}
192
193static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
194 Sema &S) {
195 // Get the length of the string as parsed.
196 auto *ConstantArrayTy =
197 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
198 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
199
200 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
201 // C99 6.7.8p14. We have an array of character type with unknown size
202 // being initialized to a string literal.
203 llvm::APInt ConstVal(32, StrLength);
204 // Return a new array type (C99 6.7.8p22).
206 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
207 updateStringLiteralType(Str, DeclT);
208 return;
209 }
210
211 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
212
213 // We have an array of character type with known size. However,
214 // the size may be smaller or larger than the string we are initializing.
215 // FIXME: Avoid truncation for 64-bit length strings.
216 if (S.getLangOpts().CPlusPlus) {
217 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
218 // For Pascal strings it's OK to strip off the terminating null character,
219 // so the example below is valid:
220 //
221 // unsigned char a[2] = "\pa";
222 if (SL->isPascal())
223 StrLength--;
224 }
225
226 // [dcl.init.string]p2
227 if (StrLength > CAT->getSize().getZExtValue())
228 S.Diag(Str->getBeginLoc(),
229 diag::err_initializer_string_for_char_array_too_long)
230 << CAT->getSize().getZExtValue() << StrLength
231 << Str->getSourceRange();
232 } else {
233 // C99 6.7.8p14.
234 if (StrLength-1 > CAT->getSize().getZExtValue())
235 S.Diag(Str->getBeginLoc(),
236 diag::ext_initializer_string_for_char_array_too_long)
237 << Str->getSourceRange();
238 }
239
240 // Set the type to the actual size that we are initializing. If we have
241 // something like:
242 // char x[1] = "foo";
243 // then this will set the string literal's type to char[1].
244 updateStringLiteralType(Str, DeclT);
245}
246
247//===----------------------------------------------------------------------===//
248// Semantic checking for initializer lists.
249//===----------------------------------------------------------------------===//
250
251namespace {
252
253/// Semantic checking for initializer lists.
254///
255/// The InitListChecker class contains a set of routines that each
256/// handle the initialization of a certain kind of entity, e.g.,
257/// arrays, vectors, struct/union types, scalars, etc. The
258/// InitListChecker itself performs a recursive walk of the subobject
259/// structure of the type to be initialized, while stepping through
260/// the initializer list one element at a time. The IList and Index
261/// parameters to each of the Check* routines contain the active
262/// (syntactic) initializer list and the index into that initializer
263/// list that represents the current initializer. Each routine is
264/// responsible for moving that Index forward as it consumes elements.
265///
266/// Each Check* routine also has a StructuredList/StructuredIndex
267/// arguments, which contains the current "structured" (semantic)
268/// initializer list and the index into that initializer list where we
269/// are copying initializers as we map them over to the semantic
270/// list. Once we have completed our recursive walk of the subobject
271/// structure, we will have constructed a full semantic initializer
272/// list.
273///
274/// C99 designators cause changes in the initializer list traversal,
275/// because they make the initialization "jump" into a specific
276/// subobject and then continue the initialization from that
277/// point. CheckDesignatedInitializer() recursively steps into the
278/// designated subobject and manages backing out the recursion to
279/// initialize the subobjects after the one designated.
280///
281/// If an initializer list contains any designators, we build a placeholder
282/// structured list even in 'verify only' mode, so that we can track which
283/// elements need 'empty' initializtion.
284class InitListChecker {
285 Sema &SemaRef;
286 bool hadError = false;
287 bool VerifyOnly; // No diagnostics.
288 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
289 bool InOverloadResolution;
290 InitListExpr *FullyStructuredList = nullptr;
291 NoInitExpr *DummyExpr = nullptr;
292 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
293
294 NoInitExpr *getDummyInit() {
295 if (!DummyExpr)
296 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
297 return DummyExpr;
298 }
299
300 void CheckImplicitInitList(const InitializedEntity &Entity,
301 InitListExpr *ParentIList, QualType T,
302 unsigned &Index, InitListExpr *StructuredList,
303 unsigned &StructuredIndex);
304 void CheckExplicitInitList(const InitializedEntity &Entity,
305 InitListExpr *IList, QualType &T,
306 InitListExpr *StructuredList,
307 bool TopLevelObject = false);
308 void CheckListElementTypes(const InitializedEntity &Entity,
309 InitListExpr *IList, QualType &DeclType,
310 bool SubobjectIsDesignatorContext,
311 unsigned &Index,
312 InitListExpr *StructuredList,
313 unsigned &StructuredIndex,
314 bool TopLevelObject = false);
315 void CheckSubElementType(const InitializedEntity &Entity,
316 InitListExpr *IList, QualType ElemType,
317 unsigned &Index,
318 InitListExpr *StructuredList,
319 unsigned &StructuredIndex,
320 bool DirectlyDesignated = false);
321 void CheckComplexType(const InitializedEntity &Entity,
322 InitListExpr *IList, QualType DeclType,
323 unsigned &Index,
324 InitListExpr *StructuredList,
325 unsigned &StructuredIndex);
326 void CheckScalarType(const InitializedEntity &Entity,
327 InitListExpr *IList, QualType DeclType,
328 unsigned &Index,
329 InitListExpr *StructuredList,
330 unsigned &StructuredIndex);
331 void CheckReferenceType(const InitializedEntity &Entity,
332 InitListExpr *IList, QualType DeclType,
333 unsigned &Index,
334 InitListExpr *StructuredList,
335 unsigned &StructuredIndex);
336 void CheckVectorType(const InitializedEntity &Entity,
337 InitListExpr *IList, QualType DeclType, unsigned &Index,
338 InitListExpr *StructuredList,
339 unsigned &StructuredIndex);
340 void CheckStructUnionTypes(const InitializedEntity &Entity,
341 InitListExpr *IList, QualType DeclType,
344 bool SubobjectIsDesignatorContext, unsigned &Index,
345 InitListExpr *StructuredList,
346 unsigned &StructuredIndex,
347 bool TopLevelObject = false);
348 void CheckArrayType(const InitializedEntity &Entity,
349 InitListExpr *IList, QualType &DeclType,
350 llvm::APSInt elementIndex,
351 bool SubobjectIsDesignatorContext, unsigned &Index,
352 InitListExpr *StructuredList,
353 unsigned &StructuredIndex);
354 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
355 InitListExpr *IList, DesignatedInitExpr *DIE,
356 unsigned DesigIdx,
357 QualType &CurrentObjectType,
359 llvm::APSInt *NextElementIndex,
360 unsigned &Index,
361 InitListExpr *StructuredList,
362 unsigned &StructuredIndex,
363 bool FinishSubobjectInit,
364 bool TopLevelObject);
365 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
366 QualType CurrentObjectType,
367 InitListExpr *StructuredList,
368 unsigned StructuredIndex,
369 SourceRange InitRange,
370 bool IsFullyOverwritten = false);
371 void UpdateStructuredListElement(InitListExpr *StructuredList,
372 unsigned &StructuredIndex,
373 Expr *expr);
374 InitListExpr *createInitListExpr(QualType CurrentObjectType,
375 SourceRange InitRange,
376 unsigned ExpectedNumInits);
377 int numArrayElements(QualType DeclType);
378 int numStructUnionElements(QualType DeclType);
379 static RecordDecl *getRecordDecl(QualType DeclType);
380
381 ExprResult PerformEmptyInit(SourceLocation Loc,
382 const InitializedEntity &Entity);
383
384 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
385 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
386 bool UnionOverride = false,
387 bool FullyOverwritten = true) {
388 // Overriding an initializer via a designator is valid with C99 designated
389 // initializers, but ill-formed with C++20 designated initializers.
390 unsigned DiagID =
391 SemaRef.getLangOpts().CPlusPlus
392 ? (UnionOverride ? diag::ext_initializer_union_overrides
393 : diag::ext_initializer_overrides)
394 : diag::warn_initializer_overrides;
395
396 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
397 // In overload resolution, we have to strictly enforce the rules, and so
398 // don't allow any overriding of prior initializers. This matters for a
399 // case such as:
400 //
401 // union U { int a, b; };
402 // struct S { int a, b; };
403 // void f(U), f(S);
404 //
405 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
406 // consistency, we disallow all overriding of prior initializers in
407 // overload resolution, not only overriding of union members.
408 hadError = true;
409 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
410 // If we'll be keeping around the old initializer but overwriting part of
411 // the object it initialized, and that object is not trivially
412 // destructible, this can leak. Don't allow that, not even as an
413 // extension.
414 //
415 // FIXME: It might be reasonable to allow this in cases where the part of
416 // the initializer that we're overriding has trivial destruction.
417 DiagID = diag::err_initializer_overrides_destructed;
418 } else if (!OldInit->getSourceRange().isValid()) {
419 // We need to check on source range validity because the previous
420 // initializer does not have to be an explicit initializer. e.g.,
421 //
422 // struct P { int a, b; };
423 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
424 //
425 // There is an overwrite taking place because the first braced initializer
426 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
427 //
428 // Such overwrites are harmless, so we don't diagnose them. (Note that in
429 // C++, this cannot be reached unless we've already seen and diagnosed a
430 // different conformance issue, such as a mixture of designated and
431 // non-designated initializers or a multi-level designator.)
432 return;
433 }
434
435 if (!VerifyOnly) {
436 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
437 << NewInitRange << FullyOverwritten << OldInit->getType();
438 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
439 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
440 << OldInit->getSourceRange();
441 }
442 }
443
444 // Explanation on the "FillWithNoInit" mode:
445 //
446 // Assume we have the following definitions (Case#1):
447 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
448 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
449 //
450 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
451 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
452 //
453 // But if we have (Case#2):
454 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
455 //
456 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
457 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
458 //
459 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
460 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
461 // initializers but with special "NoInitExpr" place holders, which tells the
462 // CodeGen not to generate any initializers for these parts.
463 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
464 const InitializedEntity &ParentEntity,
465 InitListExpr *ILE, bool &RequiresSecondPass,
466 bool FillWithNoInit);
467 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
468 const InitializedEntity &ParentEntity,
469 InitListExpr *ILE, bool &RequiresSecondPass,
470 bool FillWithNoInit = false);
471 void FillInEmptyInitializations(const InitializedEntity &Entity,
472 InitListExpr *ILE, bool &RequiresSecondPass,
473 InitListExpr *OuterILE, unsigned OuterIndex,
474 bool FillWithNoInit = false);
475 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
476 Expr *InitExpr, FieldDecl *Field,
477 bool TopLevelObject);
478 void CheckEmptyInitializable(const InitializedEntity &Entity,
479 SourceLocation Loc);
480
481public:
482 InitListChecker(
483 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
484 bool VerifyOnly, bool TreatUnavailableAsInvalid,
485 bool InOverloadResolution = false,
486 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
487 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
488 QualType &T,
489 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
490 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
491 /*TreatUnavailableAsInvalid=*/false,
492 /*InOverloadResolution=*/false,
493 &AggrDeductionCandidateParamTypes){};
494
495 bool HadError() { return hadError; }
496
497 // Retrieves the fully-structured initializer list used for
498 // semantic analysis and code generation.
499 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
500};
501
502} // end anonymous namespace
503
504ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
505 const InitializedEntity &Entity) {
507 true);
508 MultiExprArg SubInit;
509 Expr *InitExpr;
510 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
511
512 // C++ [dcl.init.aggr]p7:
513 // If there are fewer initializer-clauses in the list than there are
514 // members in the aggregate, then each member not explicitly initialized
515 // ...
516 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
518 if (EmptyInitList) {
519 // C++1y / DR1070:
520 // shall be initialized [...] from an empty initializer list.
521 //
522 // We apply the resolution of this DR to C++11 but not C++98, since C++98
523 // does not have useful semantics for initialization from an init list.
524 // We treat this as copy-initialization, because aggregate initialization
525 // always performs copy-initialization on its elements.
526 //
527 // Only do this if we're initializing a class type, to avoid filling in
528 // the initializer list where possible.
529 InitExpr = VerifyOnly
530 ? &DummyInitList
531 : new (SemaRef.Context)
532 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
533 InitExpr->setType(SemaRef.Context.VoidTy);
534 SubInit = InitExpr;
536 } else {
537 // C++03:
538 // shall be value-initialized.
539 }
540
541 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
542 // libstdc++4.6 marks the vector default constructor as explicit in
543 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
544 // stlport does so too. Look for std::__debug for libstdc++, and for
545 // std:: for stlport. This is effectively a compiler-side implementation of
546 // LWG2193.
547 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
551 InitSeq.getFailedCandidateSet()
552 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
553 (void)O;
554 assert(O == OR_Success && "Inconsistent overload resolution");
555 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
556 CXXRecordDecl *R = CtorDecl->getParent();
557
558 if (CtorDecl->getMinRequiredArguments() == 0 &&
559 CtorDecl->isExplicit() && R->getDeclName() &&
560 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
561 bool IsInStd = false;
562 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
563 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
565 IsInStd = true;
566 }
567
568 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
569 .Cases("basic_string", "deque", "forward_list", true)
570 .Cases("list", "map", "multimap", "multiset", true)
571 .Cases("priority_queue", "queue", "set", "stack", true)
572 .Cases("unordered_map", "unordered_set", "vector", true)
573 .Default(false)) {
574 InitSeq.InitializeFrom(
575 SemaRef, Entity,
576 InitializationKind::CreateValue(Loc, Loc, Loc, true),
577 MultiExprArg(), /*TopLevelOfInitList=*/false,
578 TreatUnavailableAsInvalid);
579 // Emit a warning for this. System header warnings aren't shown
580 // by default, but people working on system headers should see it.
581 if (!VerifyOnly) {
582 SemaRef.Diag(CtorDecl->getLocation(),
583 diag::warn_invalid_initializer_from_system_header);
585 SemaRef.Diag(Entity.getDecl()->getLocation(),
586 diag::note_used_in_initialization_here);
587 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
588 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
589 }
590 }
591 }
592 }
593 if (!InitSeq) {
594 if (!VerifyOnly) {
595 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
597 SemaRef.Diag(Entity.getDecl()->getLocation(),
598 diag::note_in_omitted_aggregate_initializer)
599 << /*field*/1 << Entity.getDecl();
600 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
601 bool IsTrailingArrayNewMember =
602 Entity.getParent() &&
604 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
605 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
606 << Entity.getElementIndex();
607 }
608 }
609 hadError = true;
610 return ExprError();
611 }
612
613 return VerifyOnly ? ExprResult()
614 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
615}
616
617void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
618 SourceLocation Loc) {
619 // If we're building a fully-structured list, we'll check this at the end
620 // once we know which elements are actually initialized. Otherwise, we know
621 // that there are no designators so we can just check now.
622 if (FullyStructuredList)
623 return;
624 PerformEmptyInit(Loc, Entity);
625}
626
627void InitListChecker::FillInEmptyInitForBase(
628 unsigned Init, const CXXBaseSpecifier &Base,
629 const InitializedEntity &ParentEntity, InitListExpr *ILE,
630 bool &RequiresSecondPass, bool FillWithNoInit) {
632 SemaRef.Context, &Base, false, &ParentEntity);
633
634 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
635 ExprResult BaseInit = FillWithNoInit
636 ? new (SemaRef.Context) NoInitExpr(Base.getType())
637 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
638 if (BaseInit.isInvalid()) {
639 hadError = true;
640 return;
641 }
642
643 if (!VerifyOnly) {
644 assert(Init < ILE->getNumInits() && "should have been expanded");
645 ILE->setInit(Init, BaseInit.getAs<Expr>());
646 }
647 } else if (InitListExpr *InnerILE =
648 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
649 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
650 ILE, Init, FillWithNoInit);
651 } else if (DesignatedInitUpdateExpr *InnerDIUE =
652 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
653 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
654 RequiresSecondPass, ILE, Init,
655 /*FillWithNoInit =*/true);
656 }
657}
658
659void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
660 const InitializedEntity &ParentEntity,
661 InitListExpr *ILE,
662 bool &RequiresSecondPass,
663 bool FillWithNoInit) {
664 SourceLocation Loc = ILE->getEndLoc();
665 unsigned NumInits = ILE->getNumInits();
666 InitializedEntity MemberEntity
667 = InitializedEntity::InitializeMember(Field, &ParentEntity);
668
669 if (Init >= NumInits || !ILE->getInit(Init)) {
670 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
671 if (!RType->getDecl()->isUnion())
672 assert((Init < NumInits || VerifyOnly) &&
673 "This ILE should have been expanded");
674
675 if (FillWithNoInit) {
676 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
677 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
678 if (Init < NumInits)
679 ILE->setInit(Init, Filler);
680 else
681 ILE->updateInit(SemaRef.Context, Init, Filler);
682 return;
683 }
684 // C++1y [dcl.init.aggr]p7:
685 // If there are fewer initializer-clauses in the list than there are
686 // members in the aggregate, then each member not explicitly initialized
687 // shall be initialized from its brace-or-equal-initializer [...]
688 if (Field->hasInClassInitializer()) {
689 if (VerifyOnly)
690 return;
691
692 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
693 if (DIE.isInvalid()) {
694 hadError = true;
695 return;
696 }
697 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
698 if (Init < NumInits)
699 ILE->setInit(Init, DIE.get());
700 else {
701 ILE->updateInit(SemaRef.Context, Init, DIE.get());
702 RequiresSecondPass = true;
703 }
704 return;
705 }
706
707 if (Field->getType()->isReferenceType()) {
708 if (!VerifyOnly) {
709 // C++ [dcl.init.aggr]p9:
710 // If an incomplete or empty initializer-list leaves a
711 // member of reference type uninitialized, the program is
712 // ill-formed.
713 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
714 << Field->getType()
715 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
716 ->getSourceRange();
717 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
718 }
719 hadError = true;
720 return;
721 }
722
723 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
724 if (MemberInit.isInvalid()) {
725 hadError = true;
726 return;
727 }
728
729 if (hadError || VerifyOnly) {
730 // Do nothing
731 } else if (Init < NumInits) {
732 ILE->setInit(Init, MemberInit.getAs<Expr>());
733 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
734 // Empty initialization requires a constructor call, so
735 // extend the initializer list to include the constructor
736 // call and make a note that we'll need to take another pass
737 // through the initializer list.
738 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
739 RequiresSecondPass = true;
740 }
741 } else if (InitListExpr *InnerILE
742 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
743 FillInEmptyInitializations(MemberEntity, InnerILE,
744 RequiresSecondPass, ILE, Init, FillWithNoInit);
745 } else if (DesignatedInitUpdateExpr *InnerDIUE =
746 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
747 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
748 RequiresSecondPass, ILE, Init,
749 /*FillWithNoInit =*/true);
750 }
751}
752
753/// Recursively replaces NULL values within the given initializer list
754/// with expressions that perform value-initialization of the
755/// appropriate type, and finish off the InitListExpr formation.
756void
757InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
758 InitListExpr *ILE,
759 bool &RequiresSecondPass,
760 InitListExpr *OuterILE,
761 unsigned OuterIndex,
762 bool FillWithNoInit) {
763 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
764 "Should not have void type");
765
766 // We don't need to do any checks when just filling NoInitExprs; that can't
767 // fail.
768 if (FillWithNoInit && VerifyOnly)
769 return;
770
771 // If this is a nested initializer list, we might have changed its contents
772 // (and therefore some of its properties, such as instantiation-dependence)
773 // while filling it in. Inform the outer initializer list so that its state
774 // can be updated to match.
775 // FIXME: We should fully build the inner initializers before constructing
776 // the outer InitListExpr instead of mutating AST nodes after they have
777 // been used as subexpressions of other nodes.
778 struct UpdateOuterILEWithUpdatedInit {
779 InitListExpr *Outer;
780 unsigned OuterIndex;
781 ~UpdateOuterILEWithUpdatedInit() {
782 if (Outer)
783 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
784 }
785 } UpdateOuterRAII = {OuterILE, OuterIndex};
786
787 // A transparent ILE is not performing aggregate initialization and should
788 // not be filled in.
789 if (ILE->isTransparent())
790 return;
791
792 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
793 const RecordDecl *RDecl = RType->getDecl();
794 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
795 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
796 Entity, ILE, RequiresSecondPass, FillWithNoInit);
797 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
798 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
799 for (auto *Field : RDecl->fields()) {
800 if (Field->hasInClassInitializer()) {
801 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
802 FillWithNoInit);
803 break;
804 }
805 }
806 } else {
807 // The fields beyond ILE->getNumInits() are default initialized, so in
808 // order to leave them uninitialized, the ILE is expanded and the extra
809 // fields are then filled with NoInitExpr.
810 unsigned NumElems = numStructUnionElements(ILE->getType());
811 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
812 ++NumElems;
813 if (!VerifyOnly && ILE->getNumInits() < NumElems)
814 ILE->resizeInits(SemaRef.Context, NumElems);
815
816 unsigned Init = 0;
817
818 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
819 for (auto &Base : CXXRD->bases()) {
820 if (hadError)
821 return;
822
823 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
824 FillWithNoInit);
825 ++Init;
826 }
827 }
828
829 for (auto *Field : RDecl->fields()) {
830 if (Field->isUnnamedBitfield())
831 continue;
832
833 if (hadError)
834 return;
835
836 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
837 FillWithNoInit);
838 if (hadError)
839 return;
840
841 ++Init;
842
843 // Only look at the first initialization of a union.
844 if (RDecl->isUnion())
845 break;
846 }
847 }
848
849 return;
850 }
851
852 QualType ElementType;
853
854 InitializedEntity ElementEntity = Entity;
855 unsigned NumInits = ILE->getNumInits();
856 unsigned NumElements = NumInits;
857 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
858 ElementType = AType->getElementType();
859 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
860 NumElements = CAType->getSize().getZExtValue();
861 // For an array new with an unknown bound, ask for one additional element
862 // in order to populate the array filler.
863 if (Entity.isVariableLengthArrayNew())
864 ++NumElements;
865 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
866 0, Entity);
867 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
868 ElementType = VType->getElementType();
869 NumElements = VType->getNumElements();
870 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
871 0, Entity);
872 } else
873 ElementType = ILE->getType();
874
875 bool SkipEmptyInitChecks = false;
876 for (unsigned Init = 0; Init != NumElements; ++Init) {
877 if (hadError)
878 return;
879
880 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
882 ElementEntity.setElementIndex(Init);
883
884 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
885 return;
886
887 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
888 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
889 ILE->setInit(Init, ILE->getArrayFiller());
890 else if (!InitExpr && !ILE->hasArrayFiller()) {
891 // In VerifyOnly mode, there's no point performing empty initialization
892 // more than once.
893 if (SkipEmptyInitChecks)
894 continue;
895
896 Expr *Filler = nullptr;
897
898 if (FillWithNoInit)
899 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
900 else {
901 ExprResult ElementInit =
902 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
903 if (ElementInit.isInvalid()) {
904 hadError = true;
905 return;
906 }
907
908 Filler = ElementInit.getAs<Expr>();
909 }
910
911 if (hadError) {
912 // Do nothing
913 } else if (VerifyOnly) {
914 SkipEmptyInitChecks = true;
915 } else if (Init < NumInits) {
916 // For arrays, just set the expression used for value-initialization
917 // of the "holes" in the array.
918 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
919 ILE->setArrayFiller(Filler);
920 else
921 ILE->setInit(Init, Filler);
922 } else {
923 // For arrays, just set the expression used for value-initialization
924 // of the rest of elements and exit.
925 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
926 ILE->setArrayFiller(Filler);
927 return;
928 }
929
930 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
931 // Empty initialization requires a constructor call, so
932 // extend the initializer list to include the constructor
933 // call and make a note that we'll need to take another pass
934 // through the initializer list.
935 ILE->updateInit(SemaRef.Context, Init, Filler);
936 RequiresSecondPass = true;
937 }
938 }
939 } else if (InitListExpr *InnerILE
940 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
941 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
942 ILE, Init, FillWithNoInit);
943 } else if (DesignatedInitUpdateExpr *InnerDIUE =
944 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
945 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
946 RequiresSecondPass, ILE, Init,
947 /*FillWithNoInit =*/true);
948 }
949 }
950}
951
952static bool hasAnyDesignatedInits(const InitListExpr *IL) {
953 for (const Stmt *Init : *IL)
954 if (isa_and_nonnull<DesignatedInitExpr>(Init))
955 return true;
956 return false;
957}
958
959InitListChecker::InitListChecker(
960 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
961 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
962 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
963 : SemaRef(S), VerifyOnly(VerifyOnly),
964 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
965 InOverloadResolution(InOverloadResolution),
966 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
967 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
968 FullyStructuredList =
969 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
970
971 // FIXME: Check that IL isn't already the semantic form of some other
972 // InitListExpr. If it is, we'd create a broken AST.
973 if (!VerifyOnly)
974 FullyStructuredList->setSyntacticForm(IL);
975 }
976
977 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
978 /*TopLevelObject=*/true);
979
980 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
981 bool RequiresSecondPass = false;
982 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
983 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
984 if (RequiresSecondPass && !hadError)
985 FillInEmptyInitializations(Entity, FullyStructuredList,
986 RequiresSecondPass, nullptr, 0);
987 }
988 if (hadError && FullyStructuredList)
989 FullyStructuredList->markError();
990}
991
992int InitListChecker::numArrayElements(QualType DeclType) {
993 // FIXME: use a proper constant
994 int maxElements = 0x7FFFFFFF;
995 if (const ConstantArrayType *CAT =
996 SemaRef.Context.getAsConstantArrayType(DeclType)) {
997 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
998 }
999 return maxElements;
1000}
1001
1002int InitListChecker::numStructUnionElements(QualType DeclType) {
1003 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1004 int InitializableMembers = 0;
1005 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1006 InitializableMembers += CXXRD->getNumBases();
1007 for (const auto *Field : structDecl->fields())
1008 if (!Field->isUnnamedBitfield())
1009 ++InitializableMembers;
1010
1011 if (structDecl->isUnion())
1012 return std::min(InitializableMembers, 1);
1013 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1014}
1015
1016RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1017 if (const auto *RT = DeclType->getAs<RecordType>())
1018 return RT->getDecl();
1019 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1020 return Inject->getDecl();
1021 return nullptr;
1022}
1023
1024/// Determine whether Entity is an entity for which it is idiomatic to elide
1025/// the braces in aggregate initialization.
1027 // Recursive initialization of the one and only field within an aggregate
1028 // class is considered idiomatic. This case arises in particular for
1029 // initialization of std::array, where the C++ standard suggests the idiom of
1030 //
1031 // std::array<T, N> arr = {1, 2, 3};
1032 //
1033 // (where std::array is an aggregate struct containing a single array field.
1034
1035 if (!Entity.getParent())
1036 return false;
1037
1038 // Allows elide brace initialization for aggregates with empty base.
1039 if (Entity.getKind() == InitializedEntity::EK_Base) {
1040 auto *ParentRD =
1041 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1042 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1043 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1044 }
1045
1046 // Allow brace elision if the only subobject is a field.
1047 if (Entity.getKind() == InitializedEntity::EK_Member) {
1048 auto *ParentRD =
1049 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1050 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1051 if (CXXRD->getNumBases()) {
1052 return false;
1053 }
1054 }
1055 auto FieldIt = ParentRD->field_begin();
1056 assert(FieldIt != ParentRD->field_end() &&
1057 "no fields but have initializer for member?");
1058 return ++FieldIt == ParentRD->field_end();
1059 }
1060
1061 return false;
1062}
1063
1064/// Check whether the range of the initializer \p ParentIList from element
1065/// \p Index onwards can be used to initialize an object of type \p T. Update
1066/// \p Index to indicate how many elements of the list were consumed.
1067///
1068/// This also fills in \p StructuredList, from element \p StructuredIndex
1069/// onwards, with the fully-braced, desugared form of the initialization.
1070void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1071 InitListExpr *ParentIList,
1072 QualType T, unsigned &Index,
1073 InitListExpr *StructuredList,
1074 unsigned &StructuredIndex) {
1075 int maxElements = 0;
1076
1077 if (T->isArrayType())
1078 maxElements = numArrayElements(T);
1079 else if (T->isRecordType())
1080 maxElements = numStructUnionElements(T);
1081 else if (T->isVectorType())
1082 maxElements = T->castAs<VectorType>()->getNumElements();
1083 else
1084 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1085
1086 if (maxElements == 0) {
1087 if (!VerifyOnly)
1088 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1089 diag::err_implicit_empty_initializer);
1090 ++Index;
1091 hadError = true;
1092 return;
1093 }
1094
1095 // Build a structured initializer list corresponding to this subobject.
1096 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1097 ParentIList, Index, T, StructuredList, StructuredIndex,
1098 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1099 ParentIList->getSourceRange().getEnd()));
1100 unsigned StructuredSubobjectInitIndex = 0;
1101
1102 // Check the element types and build the structural subobject.
1103 unsigned StartIndex = Index;
1104 CheckListElementTypes(Entity, ParentIList, T,
1105 /*SubobjectIsDesignatorContext=*/false, Index,
1106 StructuredSubobjectInitList,
1107 StructuredSubobjectInitIndex);
1108
1109 if (StructuredSubobjectInitList) {
1110 StructuredSubobjectInitList->setType(T);
1111
1112 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1113 // Update the structured sub-object initializer so that it's ending
1114 // range corresponds with the end of the last initializer it used.
1115 if (EndIndex < ParentIList->getNumInits() &&
1116 ParentIList->getInit(EndIndex)) {
1117 SourceLocation EndLoc
1118 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1119 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1120 }
1121
1122 // Complain about missing braces.
1123 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1124 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1126 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1127 diag::warn_missing_braces)
1128 << StructuredSubobjectInitList->getSourceRange()
1130 StructuredSubobjectInitList->getBeginLoc(), "{")
1132 SemaRef.getLocForEndOfToken(
1133 StructuredSubobjectInitList->getEndLoc()),
1134 "}");
1135 }
1136
1137 // Warn if this type won't be an aggregate in future versions of C++.
1138 auto *CXXRD = T->getAsCXXRecordDecl();
1139 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1140 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1141 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1142 << StructuredSubobjectInitList->getSourceRange() << T;
1143 }
1144 }
1145}
1146
1147/// Warn that \p Entity was of scalar type and was initialized by a
1148/// single-element braced initializer list.
1149static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1151 // Don't warn during template instantiation. If the initialization was
1152 // non-dependent, we warned during the initial parse; otherwise, the
1153 // type might not be scalar in some uses of the template.
1155 return;
1156
1157 unsigned DiagID = 0;
1158
1159 switch (Entity.getKind()) {
1168 // Extra braces here are suspicious.
1169 DiagID = diag::warn_braces_around_init;
1170 break;
1171
1173 // Warn on aggregate initialization but not on ctor init list or
1174 // default member initializer.
1175 if (Entity.getParent())
1176 DiagID = diag::warn_braces_around_init;
1177 break;
1178
1181 // No warning, might be direct-list-initialization.
1182 // FIXME: Should we warn for copy-list-initialization in these cases?
1183 break;
1184
1188 // No warning, braces are part of the syntax of the underlying construct.
1189 break;
1190
1192 // No warning, we already warned when initializing the result.
1193 break;
1194
1202 llvm_unreachable("unexpected braced scalar init");
1203 }
1204
1205 if (DiagID) {
1206 S.Diag(Braces.getBegin(), DiagID)
1207 << Entity.getType()->isSizelessBuiltinType() << Braces
1208 << FixItHint::CreateRemoval(Braces.getBegin())
1209 << FixItHint::CreateRemoval(Braces.getEnd());
1210 }
1211}
1212
1213/// Check whether the initializer \p IList (that was written with explicit
1214/// braces) can be used to initialize an object of type \p T.
1215///
1216/// This also fills in \p StructuredList with the fully-braced, desugared
1217/// form of the initialization.
1218void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1219 InitListExpr *IList, QualType &T,
1220 InitListExpr *StructuredList,
1221 bool TopLevelObject) {
1222 unsigned Index = 0, StructuredIndex = 0;
1223 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1224 Index, StructuredList, StructuredIndex, TopLevelObject);
1225 if (StructuredList) {
1226 QualType ExprTy = T;
1227 if (!ExprTy->isArrayType())
1228 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1229 if (!VerifyOnly)
1230 IList->setType(ExprTy);
1231 StructuredList->setType(ExprTy);
1232 }
1233 if (hadError)
1234 return;
1235
1236 // Don't complain for incomplete types, since we'll get an error elsewhere.
1237 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1238 // We have leftover initializers
1239 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1240 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1241 hadError = ExtraInitsIsError;
1242 if (VerifyOnly) {
1243 return;
1244 } else if (StructuredIndex == 1 &&
1245 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1246 SIF_None) {
1247 unsigned DK =
1248 ExtraInitsIsError
1249 ? diag::err_excess_initializers_in_char_array_initializer
1250 : diag::ext_excess_initializers_in_char_array_initializer;
1251 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1252 << IList->getInit(Index)->getSourceRange();
1253 } else if (T->isSizelessBuiltinType()) {
1254 unsigned DK = ExtraInitsIsError
1255 ? diag::err_excess_initializers_for_sizeless_type
1256 : diag::ext_excess_initializers_for_sizeless_type;
1257 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1258 << T << IList->getInit(Index)->getSourceRange();
1259 } else {
1260 int initKind = T->isArrayType() ? 0 :
1261 T->isVectorType() ? 1 :
1262 T->isScalarType() ? 2 :
1263 T->isUnionType() ? 3 :
1264 4;
1265
1266 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1267 : diag::ext_excess_initializers;
1268 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1269 << initKind << IList->getInit(Index)->getSourceRange();
1270 }
1271 }
1272
1273 if (!VerifyOnly) {
1274 if (T->isScalarType() && IList->getNumInits() == 1 &&
1275 !isa<InitListExpr>(IList->getInit(0)))
1276 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1277
1278 // Warn if this is a class type that won't be an aggregate in future
1279 // versions of C++.
1280 auto *CXXRD = T->getAsCXXRecordDecl();
1281 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1282 // Don't warn if there's an equivalent default constructor that would be
1283 // used instead.
1284 bool HasEquivCtor = false;
1285 if (IList->getNumInits() == 0) {
1286 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1287 HasEquivCtor = CD && !CD->isDeleted();
1288 }
1289
1290 if (!HasEquivCtor) {
1291 SemaRef.Diag(IList->getBeginLoc(),
1292 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1293 << IList->getSourceRange() << T;
1294 }
1295 }
1296 }
1297}
1298
1299void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1300 InitListExpr *IList,
1301 QualType &DeclType,
1302 bool SubobjectIsDesignatorContext,
1303 unsigned &Index,
1304 InitListExpr *StructuredList,
1305 unsigned &StructuredIndex,
1306 bool TopLevelObject) {
1307 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1308 // Explicitly braced initializer for complex type can be real+imaginary
1309 // parts.
1310 CheckComplexType(Entity, IList, DeclType, Index,
1311 StructuredList, StructuredIndex);
1312 } else if (DeclType->isScalarType()) {
1313 CheckScalarType(Entity, IList, DeclType, Index,
1314 StructuredList, StructuredIndex);
1315 } else if (DeclType->isVectorType()) {
1316 CheckVectorType(Entity, IList, DeclType, Index,
1317 StructuredList, StructuredIndex);
1318 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1319 auto Bases =
1322 if (DeclType->isRecordType()) {
1323 assert(DeclType->isAggregateType() &&
1324 "non-aggregate records should be handed in CheckSubElementType");
1325 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1326 Bases = CXXRD->bases();
1327 } else {
1328 Bases = cast<CXXRecordDecl>(RD)->bases();
1329 }
1330 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1331 SubobjectIsDesignatorContext, Index, StructuredList,
1332 StructuredIndex, TopLevelObject);
1333 } else if (DeclType->isArrayType()) {
1334 llvm::APSInt Zero(
1335 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1336 false);
1337 CheckArrayType(Entity, IList, DeclType, Zero,
1338 SubobjectIsDesignatorContext, Index,
1339 StructuredList, StructuredIndex);
1340 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1341 // This type is invalid, issue a diagnostic.
1342 ++Index;
1343 if (!VerifyOnly)
1344 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1345 << DeclType;
1346 hadError = true;
1347 } else if (DeclType->isReferenceType()) {
1348 CheckReferenceType(Entity, IList, DeclType, Index,
1349 StructuredList, StructuredIndex);
1350 } else if (DeclType->isObjCObjectType()) {
1351 if (!VerifyOnly)
1352 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1353 hadError = true;
1354 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1355 DeclType->isSizelessBuiltinType()) {
1356 // Checks for scalar type are sufficient for these types too.
1357 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1358 StructuredIndex);
1359 } else if (DeclType->isDependentType()) {
1360 // C++ [over.match.class.deduct]p1.5:
1361 // brace elision is not considered for any aggregate element that has a
1362 // dependent non-array type or an array type with a value-dependent bound
1363 ++Index;
1364 assert(AggrDeductionCandidateParamTypes);
1365 AggrDeductionCandidateParamTypes->push_back(DeclType);
1366 } else {
1367 if (!VerifyOnly)
1368 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1369 << DeclType;
1370 hadError = true;
1371 }
1372}
1373
1374void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1375 InitListExpr *IList,
1376 QualType ElemType,
1377 unsigned &Index,
1378 InitListExpr *StructuredList,
1379 unsigned &StructuredIndex,
1380 bool DirectlyDesignated) {
1381 Expr *expr = IList->getInit(Index);
1382
1383 if (ElemType->isReferenceType())
1384 return CheckReferenceType(Entity, IList, ElemType, Index,
1385 StructuredList, StructuredIndex);
1386
1387 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1388 if (SubInitList->getNumInits() == 1 &&
1389 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1390 SIF_None) {
1391 // FIXME: It would be more faithful and no less correct to include an
1392 // InitListExpr in the semantic form of the initializer list in this case.
1393 expr = SubInitList->getInit(0);
1394 }
1395 // Nested aggregate initialization and C++ initialization are handled later.
1396 } else if (isa<ImplicitValueInitExpr>(expr)) {
1397 // This happens during template instantiation when we see an InitListExpr
1398 // that we've already checked once.
1399 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1400 "found implicit initialization for the wrong type");
1401 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1402 ++Index;
1403 return;
1404 }
1405
1406 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1407 // C++ [dcl.init.aggr]p2:
1408 // Each member is copy-initialized from the corresponding
1409 // initializer-clause.
1410
1411 // FIXME: Better EqualLoc?
1414
1415 // Vector elements can be initialized from other vectors in which case
1416 // we need initialization entity with a type of a vector (and not a vector
1417 // element!) initializing multiple vector elements.
1418 auto TmpEntity =
1419 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1421 : Entity;
1422
1423 if (TmpEntity.getType()->isDependentType()) {
1424 // C++ [over.match.class.deduct]p1.5:
1425 // brace elision is not considered for any aggregate element that has a
1426 // dependent non-array type or an array type with a value-dependent
1427 // bound
1428 assert(AggrDeductionCandidateParamTypes);
1429 if (!isa_and_nonnull<ConstantArrayType>(
1430 SemaRef.Context.getAsArrayType(ElemType))) {
1431 ++Index;
1432 AggrDeductionCandidateParamTypes->push_back(ElemType);
1433 return;
1434 }
1435 } else {
1436 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1437 /*TopLevelOfInitList*/ true);
1438 // C++14 [dcl.init.aggr]p13:
1439 // If the assignment-expression can initialize a member, the member is
1440 // initialized. Otherwise [...] brace elision is assumed
1441 //
1442 // Brace elision is never performed if the element is not an
1443 // assignment-expression.
1444 if (Seq || isa<InitListExpr>(expr)) {
1445 if (!VerifyOnly) {
1446 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1447 if (Result.isInvalid())
1448 hadError = true;
1449
1450 UpdateStructuredListElement(StructuredList, StructuredIndex,
1451 Result.getAs<Expr>());
1452 } else if (!Seq) {
1453 hadError = true;
1454 } else if (StructuredList) {
1455 UpdateStructuredListElement(StructuredList, StructuredIndex,
1456 getDummyInit());
1457 }
1458 ++Index;
1459 if (AggrDeductionCandidateParamTypes)
1460 AggrDeductionCandidateParamTypes->push_back(ElemType);
1461 return;
1462 }
1463 }
1464
1465 // Fall through for subaggregate initialization
1466 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1467 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1468 return CheckScalarType(Entity, IList, ElemType, Index,
1469 StructuredList, StructuredIndex);
1470 } else if (const ArrayType *arrayType =
1471 SemaRef.Context.getAsArrayType(ElemType)) {
1472 // arrayType can be incomplete if we're initializing a flexible
1473 // array member. There's nothing we can do with the completed
1474 // type here, though.
1475
1476 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1477 // FIXME: Should we do this checking in verify-only mode?
1478 if (!VerifyOnly)
1479 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1480 if (StructuredList)
1481 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1482 ++Index;
1483 return;
1484 }
1485
1486 // Fall through for subaggregate initialization.
1487
1488 } else {
1489 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1490 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1491
1492 // C99 6.7.8p13:
1493 //
1494 // The initializer for a structure or union object that has
1495 // automatic storage duration shall be either an initializer
1496 // list as described below, or a single expression that has
1497 // compatible structure or union type. In the latter case, the
1498 // initial value of the object, including unnamed members, is
1499 // that of the expression.
1500 ExprResult ExprRes = expr;
1502 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1503 if (ExprRes.isInvalid())
1504 hadError = true;
1505 else {
1506 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1507 if (ExprRes.isInvalid())
1508 hadError = true;
1509 }
1510 UpdateStructuredListElement(StructuredList, StructuredIndex,
1511 ExprRes.getAs<Expr>());
1512 ++Index;
1513 return;
1514 }
1515 ExprRes.get();
1516 // Fall through for subaggregate initialization
1517 }
1518
1519 // C++ [dcl.init.aggr]p12:
1520 //
1521 // [...] Otherwise, if the member is itself a non-empty
1522 // subaggregate, brace elision is assumed and the initializer is
1523 // considered for the initialization of the first member of
1524 // the subaggregate.
1525 // OpenCL vector initializer is handled elsewhere.
1526 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1527 ElemType->isAggregateType()) {
1528 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1529 StructuredIndex);
1530 ++StructuredIndex;
1531
1532 // In C++20, brace elision is not permitted for a designated initializer.
1533 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1534 if (InOverloadResolution)
1535 hadError = true;
1536 if (!VerifyOnly) {
1537 SemaRef.Diag(expr->getBeginLoc(),
1538 diag::ext_designated_init_brace_elision)
1539 << expr->getSourceRange()
1540 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1542 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1543 }
1544 }
1545 } else {
1546 if (!VerifyOnly) {
1547 // We cannot initialize this element, so let PerformCopyInitialization
1548 // produce the appropriate diagnostic. We already checked that this
1549 // initialization will fail.
1552 /*TopLevelOfInitList=*/true);
1553 (void)Copy;
1554 assert(Copy.isInvalid() &&
1555 "expected non-aggregate initialization to fail");
1556 }
1557 hadError = true;
1558 ++Index;
1559 ++StructuredIndex;
1560 }
1561}
1562
1563void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1564 InitListExpr *IList, QualType DeclType,
1565 unsigned &Index,
1566 InitListExpr *StructuredList,
1567 unsigned &StructuredIndex) {
1568 assert(Index == 0 && "Index in explicit init list must be zero");
1569
1570 // As an extension, clang supports complex initializers, which initialize
1571 // a complex number component-wise. When an explicit initializer list for
1572 // a complex number contains two initializers, this extension kicks in:
1573 // it expects the initializer list to contain two elements convertible to
1574 // the element type of the complex type. The first element initializes
1575 // the real part, and the second element intitializes the imaginary part.
1576
1577 if (IList->getNumInits() < 2)
1578 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1579 StructuredIndex);
1580
1581 // This is an extension in C. (The builtin _Complex type does not exist
1582 // in the C++ standard.)
1583 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1584 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1585 << IList->getSourceRange();
1586
1587 // Initialize the complex number.
1588 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1589 InitializedEntity ElementEntity =
1591
1592 for (unsigned i = 0; i < 2; ++i) {
1593 ElementEntity.setElementIndex(Index);
1594 CheckSubElementType(ElementEntity, IList, elementType, Index,
1595 StructuredList, StructuredIndex);
1596 }
1597}
1598
1599void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1600 InitListExpr *IList, QualType DeclType,
1601 unsigned &Index,
1602 InitListExpr *StructuredList,
1603 unsigned &StructuredIndex) {
1604 if (Index >= IList->getNumInits()) {
1605 if (!VerifyOnly) {
1606 if (SemaRef.getLangOpts().CPlusPlus) {
1607 if (DeclType->isSizelessBuiltinType())
1608 SemaRef.Diag(IList->getBeginLoc(),
1609 SemaRef.getLangOpts().CPlusPlus11
1610 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1611 : diag::err_empty_sizeless_initializer)
1612 << DeclType << IList->getSourceRange();
1613 else
1614 SemaRef.Diag(IList->getBeginLoc(),
1615 SemaRef.getLangOpts().CPlusPlus11
1616 ? diag::warn_cxx98_compat_empty_scalar_initializer
1617 : diag::err_empty_scalar_initializer)
1618 << IList->getSourceRange();
1619 }
1620 }
1621 hadError =
1622 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1623 ++Index;
1624 ++StructuredIndex;
1625 return;
1626 }
1627
1628 Expr *expr = IList->getInit(Index);
1629 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1630 // FIXME: This is invalid, and accepting it causes overload resolution
1631 // to pick the wrong overload in some corner cases.
1632 if (!VerifyOnly)
1633 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1634 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1635
1636 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1637 StructuredIndex);
1638 return;
1639 } else if (isa<DesignatedInitExpr>(expr)) {
1640 if (!VerifyOnly)
1641 SemaRef.Diag(expr->getBeginLoc(),
1642 diag::err_designator_for_scalar_or_sizeless_init)
1643 << DeclType->isSizelessBuiltinType() << DeclType
1644 << expr->getSourceRange();
1645 hadError = true;
1646 ++Index;
1647 ++StructuredIndex;
1648 return;
1649 }
1650
1651 ExprResult Result;
1652 if (VerifyOnly) {
1653 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1654 Result = getDummyInit();
1655 else
1656 Result = ExprError();
1657 } else {
1658 Result =
1659 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1660 /*TopLevelOfInitList=*/true);
1661 }
1662
1663 Expr *ResultExpr = nullptr;
1664
1665 if (Result.isInvalid())
1666 hadError = true; // types weren't compatible.
1667 else {
1668 ResultExpr = Result.getAs<Expr>();
1669
1670 if (ResultExpr != expr && !VerifyOnly) {
1671 // The type was promoted, update initializer list.
1672 // FIXME: Why are we updating the syntactic init list?
1673 IList->setInit(Index, ResultExpr);
1674 }
1675 }
1676 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1677 ++Index;
1678 if (AggrDeductionCandidateParamTypes)
1679 AggrDeductionCandidateParamTypes->push_back(DeclType);
1680}
1681
1682void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1683 InitListExpr *IList, QualType DeclType,
1684 unsigned &Index,
1685 InitListExpr *StructuredList,
1686 unsigned &StructuredIndex) {
1687 if (Index >= IList->getNumInits()) {
1688 // FIXME: It would be wonderful if we could point at the actual member. In
1689 // general, it would be useful to pass location information down the stack,
1690 // so that we know the location (or decl) of the "current object" being
1691 // initialized.
1692 if (!VerifyOnly)
1693 SemaRef.Diag(IList->getBeginLoc(),
1694 diag::err_init_reference_member_uninitialized)
1695 << DeclType << IList->getSourceRange();
1696 hadError = true;
1697 ++Index;
1698 ++StructuredIndex;
1699 return;
1700 }
1701
1702 Expr *expr = IList->getInit(Index);
1703 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1704 if (!VerifyOnly)
1705 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1706 << DeclType << IList->getSourceRange();
1707 hadError = true;
1708 ++Index;
1709 ++StructuredIndex;
1710 return;
1711 }
1712
1713 ExprResult Result;
1714 if (VerifyOnly) {
1715 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1716 Result = getDummyInit();
1717 else
1718 Result = ExprError();
1719 } else {
1720 Result =
1721 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1722 /*TopLevelOfInitList=*/true);
1723 }
1724
1725 if (Result.isInvalid())
1726 hadError = true;
1727
1728 expr = Result.getAs<Expr>();
1729 // FIXME: Why are we updating the syntactic init list?
1730 if (!VerifyOnly && expr)
1731 IList->setInit(Index, expr);
1732
1733 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1734 ++Index;
1735 if (AggrDeductionCandidateParamTypes)
1736 AggrDeductionCandidateParamTypes->push_back(DeclType);
1737}
1738
1739void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1740 InitListExpr *IList, QualType DeclType,
1741 unsigned &Index,
1742 InitListExpr *StructuredList,
1743 unsigned &StructuredIndex) {
1744 const VectorType *VT = DeclType->castAs<VectorType>();
1745 unsigned maxElements = VT->getNumElements();
1746 unsigned numEltsInit = 0;
1747 QualType elementType = VT->getElementType();
1748
1749 if (Index >= IList->getNumInits()) {
1750 // Make sure the element type can be value-initialized.
1751 CheckEmptyInitializable(
1753 IList->getEndLoc());
1754 return;
1755 }
1756
1757 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1758 // If the initializing element is a vector, try to copy-initialize
1759 // instead of breaking it apart (which is doomed to failure anyway).
1760 Expr *Init = IList->getInit(Index);
1761 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1762 ExprResult Result;
1763 if (VerifyOnly) {
1764 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1765 Result = getDummyInit();
1766 else
1767 Result = ExprError();
1768 } else {
1769 Result =
1770 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1771 /*TopLevelOfInitList=*/true);
1772 }
1773
1774 Expr *ResultExpr = nullptr;
1775 if (Result.isInvalid())
1776 hadError = true; // types weren't compatible.
1777 else {
1778 ResultExpr = Result.getAs<Expr>();
1779
1780 if (ResultExpr != Init && !VerifyOnly) {
1781 // The type was promoted, update initializer list.
1782 // FIXME: Why are we updating the syntactic init list?
1783 IList->setInit(Index, ResultExpr);
1784 }
1785 }
1786 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1787 ++Index;
1788 if (AggrDeductionCandidateParamTypes)
1789 AggrDeductionCandidateParamTypes->push_back(elementType);
1790 return;
1791 }
1792
1793 InitializedEntity ElementEntity =
1795
1796 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1797 // Don't attempt to go past the end of the init list
1798 if (Index >= IList->getNumInits()) {
1799 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1800 break;
1801 }
1802
1803 ElementEntity.setElementIndex(Index);
1804 CheckSubElementType(ElementEntity, IList, elementType, Index,
1805 StructuredList, StructuredIndex);
1806 }
1807
1808 if (VerifyOnly)
1809 return;
1810
1811 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1812 const VectorType *T = Entity.getType()->castAs<VectorType>();
1813 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1814 T->getVectorKind() == VectorKind::NeonPoly)) {
1815 // The ability to use vector initializer lists is a GNU vector extension
1816 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1817 // endian machines it works fine, however on big endian machines it
1818 // exhibits surprising behaviour:
1819 //
1820 // uint32x2_t x = {42, 64};
1821 // return vget_lane_u32(x, 0); // Will return 64.
1822 //
1823 // Because of this, explicitly call out that it is non-portable.
1824 //
1825 SemaRef.Diag(IList->getBeginLoc(),
1826 diag::warn_neon_vector_initializer_non_portable);
1827
1828 const char *typeCode;
1829 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1830
1831 if (elementType->isFloatingType())
1832 typeCode = "f";
1833 else if (elementType->isSignedIntegerType())
1834 typeCode = "s";
1835 else if (elementType->isUnsignedIntegerType())
1836 typeCode = "u";
1837 else
1838 llvm_unreachable("Invalid element type!");
1839
1840 SemaRef.Diag(IList->getBeginLoc(),
1841 SemaRef.Context.getTypeSize(VT) > 64
1842 ? diag::note_neon_vector_initializer_non_portable_q
1843 : diag::note_neon_vector_initializer_non_portable)
1844 << typeCode << typeSize;
1845 }
1846
1847 return;
1848 }
1849
1850 InitializedEntity ElementEntity =
1852
1853 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1854 for (unsigned i = 0; i < maxElements; ++i) {
1855 // Don't attempt to go past the end of the init list
1856 if (Index >= IList->getNumInits())
1857 break;
1858
1859 ElementEntity.setElementIndex(Index);
1860
1861 QualType IType = IList->getInit(Index)->getType();
1862 if (!IType->isVectorType()) {
1863 CheckSubElementType(ElementEntity, IList, elementType, Index,
1864 StructuredList, StructuredIndex);
1865 ++numEltsInit;
1866 } else {
1867 QualType VecType;
1868 const VectorType *IVT = IType->castAs<VectorType>();
1869 unsigned numIElts = IVT->getNumElements();
1870
1871 if (IType->isExtVectorType())
1872 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1873 else
1874 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1875 IVT->getVectorKind());
1876 CheckSubElementType(ElementEntity, IList, VecType, Index,
1877 StructuredList, StructuredIndex);
1878 numEltsInit += numIElts;
1879 }
1880 }
1881
1882 // OpenCL and HLSL require all elements to be initialized.
1883 if (numEltsInit != maxElements) {
1884 if (!VerifyOnly)
1885 SemaRef.Diag(IList->getBeginLoc(),
1886 diag::err_vector_incorrect_num_initializers)
1887 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1888 hadError = true;
1889 }
1890}
1891
1892/// Check if the type of a class element has an accessible destructor, and marks
1893/// it referenced. Returns true if we shouldn't form a reference to the
1894/// destructor.
1895///
1896/// Aggregate initialization requires a class element's destructor be
1897/// accessible per 11.6.1 [dcl.init.aggr]:
1898///
1899/// The destructor for each element of class type is potentially invoked
1900/// (15.4 [class.dtor]) from the context where the aggregate initialization
1901/// occurs.
1903 Sema &SemaRef) {
1904 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1905 if (!CXXRD)
1906 return false;
1907
1908 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1909 SemaRef.CheckDestructorAccess(Loc, Destructor,
1910 SemaRef.PDiag(diag::err_access_dtor_temp)
1911 << ElementType);
1912 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1913 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1914}
1915
1916void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1917 InitListExpr *IList, QualType &DeclType,
1918 llvm::APSInt elementIndex,
1919 bool SubobjectIsDesignatorContext,
1920 unsigned &Index,
1921 InitListExpr *StructuredList,
1922 unsigned &StructuredIndex) {
1923 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1924
1925 if (!VerifyOnly) {
1926 if (checkDestructorReference(arrayType->getElementType(),
1927 IList->getEndLoc(), SemaRef)) {
1928 hadError = true;
1929 return;
1930 }
1931 }
1932
1933 // Check for the special-case of initializing an array with a string.
1934 if (Index < IList->getNumInits()) {
1935 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1936 SIF_None) {
1937 // We place the string literal directly into the resulting
1938 // initializer list. This is the only place where the structure
1939 // of the structured initializer list doesn't match exactly,
1940 // because doing so would involve allocating one character
1941 // constant for each string.
1942 // FIXME: Should we do these checks in verify-only mode too?
1943 if (!VerifyOnly)
1944 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1945 if (StructuredList) {
1946 UpdateStructuredListElement(StructuredList, StructuredIndex,
1947 IList->getInit(Index));
1948 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1949 }
1950 ++Index;
1951 if (AggrDeductionCandidateParamTypes)
1952 AggrDeductionCandidateParamTypes->push_back(DeclType);
1953 return;
1954 }
1955 }
1956 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1957 // Check for VLAs; in standard C it would be possible to check this
1958 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1959 // them in all sorts of strange places).
1960 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1961 if (!VerifyOnly) {
1962 // C23 6.7.10p4: An entity of variable length array type shall not be
1963 // initialized except by an empty initializer.
1964 //
1965 // The C extension warnings are issued from ParseBraceInitializer() and
1966 // do not need to be issued here. However, we continue to issue an error
1967 // in the case there are initializers or we are compiling C++. We allow
1968 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1969 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1970 // FIXME: should we allow this construct in C++ when it makes sense to do
1971 // so?
1972 if (HasErr)
1973 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1974 diag::err_variable_object_no_init)
1975 << VAT->getSizeExpr()->getSourceRange();
1976 }
1977 hadError = HasErr;
1978 ++Index;
1979 ++StructuredIndex;
1980 return;
1981 }
1982
1983 // We might know the maximum number of elements in advance.
1984 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1985 elementIndex.isUnsigned());
1986 bool maxElementsKnown = false;
1987 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1988 maxElements = CAT->getSize();
1989 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1990 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1991 maxElementsKnown = true;
1992 }
1993
1994 QualType elementType = arrayType->getElementType();
1995 while (Index < IList->getNumInits()) {
1996 Expr *Init = IList->getInit(Index);
1997 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1998 // If we're not the subobject that matches up with the '{' for
1999 // the designator, we shouldn't be handling the
2000 // designator. Return immediately.
2001 if (!SubobjectIsDesignatorContext)
2002 return;
2003
2004 // Handle this designated initializer. elementIndex will be
2005 // updated to be the next array element we'll initialize.
2006 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2007 DeclType, nullptr, &elementIndex, Index,
2008 StructuredList, StructuredIndex, true,
2009 false)) {
2010 hadError = true;
2011 continue;
2012 }
2013
2014 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2015 maxElements = maxElements.extend(elementIndex.getBitWidth());
2016 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2017 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2018 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2019
2020 // If the array is of incomplete type, keep track of the number of
2021 // elements in the initializer.
2022 if (!maxElementsKnown && elementIndex > maxElements)
2023 maxElements = elementIndex;
2024
2025 continue;
2026 }
2027
2028 // If we know the maximum number of elements, and we've already
2029 // hit it, stop consuming elements in the initializer list.
2030 if (maxElementsKnown && elementIndex == maxElements)
2031 break;
2032
2033 InitializedEntity ElementEntity =
2034 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
2035 Entity);
2036 // Check this element.
2037 CheckSubElementType(ElementEntity, IList, elementType, Index,
2038 StructuredList, StructuredIndex);
2039 ++elementIndex;
2040
2041 // If the array is of incomplete type, keep track of the number of
2042 // elements in the initializer.
2043 if (!maxElementsKnown && elementIndex > maxElements)
2044 maxElements = elementIndex;
2045 }
2046 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2047 // If this is an incomplete array type, the actual type needs to
2048 // be calculated here.
2049 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2050 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2051 // Sizing an array implicitly to zero is not allowed by ISO C,
2052 // but is supported by GNU.
2053 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2054 }
2055
2056 DeclType = SemaRef.Context.getConstantArrayType(
2057 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2058 }
2059 if (!hadError) {
2060 // If there are any members of the array that get value-initialized, check
2061 // that is possible. That happens if we know the bound and don't have
2062 // enough elements, or if we're performing an array new with an unknown
2063 // bound.
2064 if ((maxElementsKnown && elementIndex < maxElements) ||
2065 Entity.isVariableLengthArrayNew())
2066 CheckEmptyInitializable(
2068 IList->getEndLoc());
2069 }
2070}
2071
2072bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2073 Expr *InitExpr,
2074 FieldDecl *Field,
2075 bool TopLevelObject) {
2076 // Handle GNU flexible array initializers.
2077 unsigned FlexArrayDiag;
2078 if (isa<InitListExpr>(InitExpr) &&
2079 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2080 // Empty flexible array init always allowed as an extension
2081 FlexArrayDiag = diag::ext_flexible_array_init;
2082 } else if (!TopLevelObject) {
2083 // Disallow flexible array init on non-top-level object
2084 FlexArrayDiag = diag::err_flexible_array_init;
2085 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2086 // Disallow flexible array init on anything which is not a variable.
2087 FlexArrayDiag = diag::err_flexible_array_init;
2088 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2089 // Disallow flexible array init on local variables.
2090 FlexArrayDiag = diag::err_flexible_array_init;
2091 } else {
2092 // Allow other cases.
2093 FlexArrayDiag = diag::ext_flexible_array_init;
2094 }
2095
2096 if (!VerifyOnly) {
2097 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2098 << InitExpr->getBeginLoc();
2099 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2100 << Field;
2101 }
2102
2103 return FlexArrayDiag != diag::ext_flexible_array_init;
2104}
2105
2106void InitListChecker::CheckStructUnionTypes(
2107 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2109 bool SubobjectIsDesignatorContext, unsigned &Index,
2110 InitListExpr *StructuredList, unsigned &StructuredIndex,
2111 bool TopLevelObject) {
2112 const RecordDecl *RD = getRecordDecl(DeclType);
2113
2114 // If the record is invalid, some of it's members are invalid. To avoid
2115 // confusion, we forgo checking the initializer for the entire record.
2116 if (RD->isInvalidDecl()) {
2117 // Assume it was supposed to consume a single initializer.
2118 ++Index;
2119 hadError = true;
2120 return;
2121 }
2122
2123 if (RD->isUnion() && IList->getNumInits() == 0) {
2124 if (!VerifyOnly)
2125 for (FieldDecl *FD : RD->fields()) {
2126 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2127 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2128 hadError = true;
2129 return;
2130 }
2131 }
2132
2133 // If there's a default initializer, use it.
2134 if (isa<CXXRecordDecl>(RD) &&
2135 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2136 if (!StructuredList)
2137 return;
2138 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2139 Field != FieldEnd; ++Field) {
2140 if (Field->hasInClassInitializer()) {
2141 StructuredList->setInitializedFieldInUnion(*Field);
2142 // FIXME: Actually build a CXXDefaultInitExpr?
2143 return;
2144 }
2145 }
2146 }
2147
2148 // Value-initialize the first member of the union that isn't an unnamed
2149 // bitfield.
2150 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2151 Field != FieldEnd; ++Field) {
2152 if (!Field->isUnnamedBitfield()) {
2153 CheckEmptyInitializable(
2154 InitializedEntity::InitializeMember(*Field, &Entity),
2155 IList->getEndLoc());
2156 if (StructuredList)
2157 StructuredList->setInitializedFieldInUnion(*Field);
2158 break;
2159 }
2160 }
2161 return;
2162 }
2163
2164 bool InitializedSomething = false;
2165
2166 // If we have any base classes, they are initialized prior to the fields.
2167 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2168 auto &Base = *I;
2169 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2170
2171 // Designated inits always initialize fields, so if we see one, all
2172 // remaining base classes have no explicit initializer.
2173 if (Init && isa<DesignatedInitExpr>(Init))
2174 Init = nullptr;
2175
2176 // C++ [over.match.class.deduct]p1.6:
2177 // each non-trailing aggregate element that is a pack expansion is assumed
2178 // to correspond to no elements of the initializer list, and (1.7) a
2179 // trailing aggregate element that is a pack expansion is assumed to
2180 // correspond to all remaining elements of the initializer list (if any).
2181
2182 // C++ [over.match.class.deduct]p1.9:
2183 // ... except that additional parameter packs of the form P_j... are
2184 // inserted into the parameter list in their original aggregate element
2185 // position corresponding to each non-trailing aggregate element of
2186 // type P_j that was skipped because it was a parameter pack, and the
2187 // trailing sequence of parameters corresponding to a trailing
2188 // aggregate element that is a pack expansion (if any) is replaced
2189 // by a single parameter of the form T_n....
2190 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2191 AggrDeductionCandidateParamTypes->push_back(
2192 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2193
2194 // Trailing pack expansion
2195 if (I + 1 == E && RD->field_empty()) {
2196 if (Index < IList->getNumInits())
2197 Index = IList->getNumInits();
2198 return;
2199 }
2200
2201 continue;
2202 }
2203
2204 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2206 SemaRef.Context, &Base, false, &Entity);
2207 if (Init) {
2208 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2209 StructuredList, StructuredIndex);
2210 InitializedSomething = true;
2211 } else {
2212 CheckEmptyInitializable(BaseEntity, InitLoc);
2213 }
2214
2215 if (!VerifyOnly)
2216 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2217 hadError = true;
2218 return;
2219 }
2220 }
2221
2222 // If structDecl is a forward declaration, this loop won't do
2223 // anything except look at designated initializers; That's okay,
2224 // because an error should get printed out elsewhere. It might be
2225 // worthwhile to skip over the rest of the initializer, though.
2226 RecordDecl::field_iterator FieldEnd = RD->field_end();
2227 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2228 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2229 });
2230 bool CheckForMissingFields =
2231 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2232 bool HasDesignatedInit = false;
2233
2234 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2235
2236 while (Index < IList->getNumInits()) {
2237 Expr *Init = IList->getInit(Index);
2238 SourceLocation InitLoc = Init->getBeginLoc();
2239
2240 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2241 // If we're not the subobject that matches up with the '{' for
2242 // the designator, we shouldn't be handling the
2243 // designator. Return immediately.
2244 if (!SubobjectIsDesignatorContext)
2245 return;
2246
2247 HasDesignatedInit = true;
2248
2249 // Handle this designated initializer. Field will be updated to
2250 // the next field that we'll be initializing.
2251 bool DesignatedInitFailed = CheckDesignatedInitializer(
2252 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2253 StructuredList, StructuredIndex, true, TopLevelObject);
2254 if (DesignatedInitFailed)
2255 hadError = true;
2256
2257 // Find the field named by the designated initializer.
2258 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2259 if (!VerifyOnly && D->isFieldDesignator()) {
2260 FieldDecl *F = D->getFieldDecl();
2261 InitializedFields.insert(F);
2262 if (!DesignatedInitFailed) {
2263 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2264 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2265 hadError = true;
2266 return;
2267 }
2268 }
2269 }
2270
2271 InitializedSomething = true;
2272
2273 // Disable check for missing fields when designators are used.
2274 // This matches gcc behaviour.
2275 if (!SemaRef.getLangOpts().CPlusPlus)
2276 CheckForMissingFields = false;
2277 continue;
2278 }
2279
2280 // Check if this is an initializer of forms:
2281 //
2282 // struct foo f = {};
2283 // struct foo g = {0};
2284 //
2285 // These are okay for randomized structures. [C99 6.7.8p19]
2286 //
2287 // Also, if there is only one element in the structure, we allow something
2288 // like this, because it's really not randomized in the tranditional sense.
2289 //
2290 // struct foo h = {bar};
2291 auto IsZeroInitializer = [&](const Expr *I) {
2292 if (IList->getNumInits() == 1) {
2293 if (NumRecordDecls == 1)
2294 return true;
2295 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2296 return IL->getValue().isZero();
2297 }
2298 return false;
2299 };
2300
2301 // Don't allow non-designated initializers on randomized structures.
2302 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2303 if (!VerifyOnly)
2304 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2305 hadError = true;
2306 break;
2307 }
2308
2309 if (Field == FieldEnd) {
2310 // We've run out of fields. We're done.
2311 break;
2312 }
2313
2314 // We've already initialized a member of a union. We're done.
2315 if (InitializedSomething && RD->isUnion())
2316 break;
2317
2318 // If we've hit the flexible array member at the end, we're done.
2319 if (Field->getType()->isIncompleteArrayType())
2320 break;
2321
2322 if (Field->isUnnamedBitfield()) {
2323 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2324 ++Field;
2325 continue;
2326 }
2327
2328 // Make sure we can use this declaration.
2329 bool InvalidUse;
2330 if (VerifyOnly)
2331 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2332 else
2333 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2334 *Field, IList->getInit(Index)->getBeginLoc());
2335 if (InvalidUse) {
2336 ++Index;
2337 ++Field;
2338 hadError = true;
2339 continue;
2340 }
2341
2342 if (!VerifyOnly) {
2343 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2344 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2345 hadError = true;
2346 return;
2347 }
2348 }
2349
2350 InitializedEntity MemberEntity =
2351 InitializedEntity::InitializeMember(*Field, &Entity);
2352 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2353 StructuredList, StructuredIndex);
2354 InitializedSomething = true;
2355 InitializedFields.insert(*Field);
2356
2357 if (RD->isUnion() && StructuredList) {
2358 // Initialize the first field within the union.
2359 StructuredList->setInitializedFieldInUnion(*Field);
2360 }
2361
2362 ++Field;
2363 }
2364
2365 // Emit warnings for missing struct field initializers.
2366 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2367 !RD->isUnion()) {
2368 // It is possible we have one or more unnamed bitfields remaining.
2369 // Find first (if any) named field and emit warning.
2370 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2371 : Field,
2372 end = RD->field_end();
2373 it != end; ++it) {
2374 if (HasDesignatedInit && InitializedFields.count(*it))
2375 continue;
2376
2377 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&
2378 !it->getType()->isIncompleteArrayType()) {
2379 SemaRef.Diag(IList->getSourceRange().getEnd(),
2380 diag::warn_missing_field_initializers)
2381 << *it;
2382 break;
2383 }
2384 }
2385 }
2386
2387 // Check that any remaining fields can be value-initialized if we're not
2388 // building a structured list. (If we are, we'll check this later.)
2389 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2390 !Field->getType()->isIncompleteArrayType()) {
2391 for (; Field != FieldEnd && !hadError; ++Field) {
2392 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2393 CheckEmptyInitializable(
2394 InitializedEntity::InitializeMember(*Field, &Entity),
2395 IList->getEndLoc());
2396 }
2397 }
2398
2399 // Check that the types of the remaining fields have accessible destructors.
2400 if (!VerifyOnly) {
2401 // If the initializer expression has a designated initializer, check the
2402 // elements for which a designated initializer is not provided too.
2403 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2404 : Field;
2405 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2406 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2407 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2408 hadError = true;
2409 return;
2410 }
2411 }
2412 }
2413
2414 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2415 Index >= IList->getNumInits())
2416 return;
2417
2418 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2419 TopLevelObject)) {
2420 hadError = true;
2421 ++Index;
2422 return;
2423 }
2424
2425 InitializedEntity MemberEntity =
2426 InitializedEntity::InitializeMember(*Field, &Entity);
2427
2428 if (isa<InitListExpr>(IList->getInit(Index)) ||
2429 AggrDeductionCandidateParamTypes)
2430 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2431 StructuredList, StructuredIndex);
2432 else
2433 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2434 StructuredList, StructuredIndex);
2435}
2436
2437/// Expand a field designator that refers to a member of an
2438/// anonymous struct or union into a series of field designators that
2439/// refers to the field within the appropriate subobject.
2440///
2442 DesignatedInitExpr *DIE,
2443 unsigned DesigIdx,
2444 IndirectFieldDecl *IndirectField) {
2446
2447 // Build the replacement designators.
2448 SmallVector<Designator, 4> Replacements;
2449 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2450 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2451 if (PI + 1 == PE)
2452 Replacements.push_back(Designator::CreateFieldDesignator(
2453 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2454 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2455 else
2456 Replacements.push_back(Designator::CreateFieldDesignator(
2457 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2458 assert(isa<FieldDecl>(*PI));
2459 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2460 }
2461
2462 // Expand the current designator into the set of replacement
2463 // designators, so we have a full subobject path down to where the
2464 // member of the anonymous struct/union is actually stored.
2465 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2466 &Replacements[0] + Replacements.size());
2467}
2468
2470 DesignatedInitExpr *DIE) {
2471 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2472 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2473 for (unsigned I = 0; I < NumIndexExprs; ++I)
2474 IndexExprs[I] = DIE->getSubExpr(I + 1);
2475 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2476 IndexExprs,
2477 DIE->getEqualOrColonLoc(),
2478 DIE->usesGNUSyntax(), DIE->getInit());
2479}
2480
2481namespace {
2482
2483// Callback to only accept typo corrections that are for field members of
2484// the given struct or union.
2485class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2486 public:
2487 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2488 : Record(RD) {}
2489
2490 bool ValidateCandidate(const TypoCorrection &candidate) override {
2491 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2492 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2493 }
2494
2495 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2496 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2497 }
2498
2499 private:
2500 const RecordDecl *Record;
2501};
2502
2503} // end anonymous namespace
2504
2505/// Check the well-formedness of a C99 designated initializer.
2506///
2507/// Determines whether the designated initializer @p DIE, which
2508/// resides at the given @p Index within the initializer list @p
2509/// IList, is well-formed for a current object of type @p DeclType
2510/// (C99 6.7.8). The actual subobject that this designator refers to
2511/// within the current subobject is returned in either
2512/// @p NextField or @p NextElementIndex (whichever is appropriate).
2513///
2514/// @param IList The initializer list in which this designated
2515/// initializer occurs.
2516///
2517/// @param DIE The designated initializer expression.
2518///
2519/// @param DesigIdx The index of the current designator.
2520///
2521/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2522/// into which the designation in @p DIE should refer.
2523///
2524/// @param NextField If non-NULL and the first designator in @p DIE is
2525/// a field, this will be set to the field declaration corresponding
2526/// to the field named by the designator. On input, this is expected to be
2527/// the next field that would be initialized in the absence of designation,
2528/// if the complete object being initialized is a struct.
2529///
2530/// @param NextElementIndex If non-NULL and the first designator in @p
2531/// DIE is an array designator or GNU array-range designator, this
2532/// will be set to the last index initialized by this designator.
2533///
2534/// @param Index Index into @p IList where the designated initializer
2535/// @p DIE occurs.
2536///
2537/// @param StructuredList The initializer list expression that
2538/// describes all of the subobject initializers in the order they'll
2539/// actually be initialized.
2540///
2541/// @returns true if there was an error, false otherwise.
2542bool
2543InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2544 InitListExpr *IList,
2545 DesignatedInitExpr *DIE,
2546 unsigned DesigIdx,
2547 QualType &CurrentObjectType,
2548 RecordDecl::field_iterator *NextField,
2549 llvm::APSInt *NextElementIndex,
2550 unsigned &Index,
2551 InitListExpr *StructuredList,
2552 unsigned &StructuredIndex,
2553 bool FinishSubobjectInit,
2554 bool TopLevelObject) {
2555 if (DesigIdx == DIE->size()) {
2556 // C++20 designated initialization can result in direct-list-initialization
2557 // of the designated subobject. This is the only way that we can end up
2558 // performing direct initialization as part of aggregate initialization, so
2559 // it needs special handling.
2560 if (DIE->isDirectInit()) {
2561 Expr *Init = DIE->getInit();
2562 assert(isa<InitListExpr>(Init) &&
2563 "designator result in direct non-list initialization?");
2565 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2566 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2567 /*TopLevelOfInitList*/ true);
2568 if (StructuredList) {
2569 ExprResult Result = VerifyOnly
2570 ? getDummyInit()
2571 : Seq.Perform(SemaRef, Entity, Kind, Init);
2572 UpdateStructuredListElement(StructuredList, StructuredIndex,
2573 Result.get());
2574 }
2575 ++Index;
2576 if (AggrDeductionCandidateParamTypes)
2577 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2578 return !Seq;
2579 }
2580
2581 // Check the actual initialization for the designated object type.
2582 bool prevHadError = hadError;
2583
2584 // Temporarily remove the designator expression from the
2585 // initializer list that the child calls see, so that we don't try
2586 // to re-process the designator.
2587 unsigned OldIndex = Index;
2588 IList->setInit(OldIndex, DIE->getInit());
2589
2590 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2591 StructuredIndex, /*DirectlyDesignated=*/true);
2592
2593 // Restore the designated initializer expression in the syntactic
2594 // form of the initializer list.
2595 if (IList->getInit(OldIndex) != DIE->getInit())
2596 DIE->setInit(IList->getInit(OldIndex));
2597 IList->setInit(OldIndex, DIE);
2598
2599 return hadError && !prevHadError;
2600 }
2601
2603 bool IsFirstDesignator = (DesigIdx == 0);
2604 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2605 // Determine the structural initializer list that corresponds to the
2606 // current subobject.
2607 if (IsFirstDesignator)
2608 StructuredList = FullyStructuredList;
2609 else {
2610 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2611 StructuredList->getInit(StructuredIndex) : nullptr;
2612 if (!ExistingInit && StructuredList->hasArrayFiller())
2613 ExistingInit = StructuredList->getArrayFiller();
2614
2615 if (!ExistingInit)
2616 StructuredList = getStructuredSubobjectInit(
2617 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2618 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2619 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2620 StructuredList = Result;
2621 else {
2622 // We are creating an initializer list that initializes the
2623 // subobjects of the current object, but there was already an
2624 // initialization that completely initialized the current
2625 // subobject, e.g., by a compound literal:
2626 //
2627 // struct X { int a, b; };
2628 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2629 //
2630 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2631 // designated initializer re-initializes only its current object
2632 // subobject [0].b.
2633 diagnoseInitOverride(ExistingInit,
2634 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2635 /*UnionOverride=*/false,
2636 /*FullyOverwritten=*/false);
2637
2638 if (!VerifyOnly) {
2640 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2641 StructuredList = E->getUpdater();
2642 else {
2643 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2645 ExistingInit, DIE->getEndLoc());
2646 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2647 StructuredList = DIUE->getUpdater();
2648 }
2649 } else {
2650 // We don't need to track the structured representation of a
2651 // designated init update of an already-fully-initialized object in
2652 // verify-only mode. The only reason we would need the structure is
2653 // to determine where the uninitialized "holes" are, and in this
2654 // case, we know there aren't any and we can't introduce any.
2655 StructuredList = nullptr;
2656 }
2657 }
2658 }
2659 }
2660
2661 if (D->isFieldDesignator()) {
2662 // C99 6.7.8p7:
2663 //
2664 // If a designator has the form
2665 //
2666 // . identifier
2667 //
2668 // then the current object (defined below) shall have
2669 // structure or union type and the identifier shall be the
2670 // name of a member of that type.
2671 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2672 if (!RD) {
2673 SourceLocation Loc = D->getDotLoc();
2674 if (Loc.isInvalid())
2675 Loc = D->getFieldLoc();
2676 if (!VerifyOnly)
2677 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2678 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2679 ++Index;
2680 return true;
2681 }
2682
2683 FieldDecl *KnownField = D->getFieldDecl();
2684 if (!KnownField) {
2685 const IdentifierInfo *FieldName = D->getFieldName();
2686 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2687 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2688 KnownField = FD;
2689 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2690 // In verify mode, don't modify the original.
2691 if (VerifyOnly)
2692 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2693 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2694 D = DIE->getDesignator(DesigIdx);
2695 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2696 }
2697 if (!KnownField) {
2698 if (VerifyOnly) {
2699 ++Index;
2700 return true; // No typo correction when just trying this out.
2701 }
2702
2703 // We found a placeholder variable
2704 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2705 FieldName)) {
2706 ++Index;
2707 return true;
2708 }
2709 // Name lookup found something, but it wasn't a field.
2710 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2711 !Lookup.empty()) {
2712 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2713 << FieldName;
2714 SemaRef.Diag(Lookup.front()->getLocation(),
2715 diag::note_field_designator_found);
2716 ++Index;
2717 return true;
2718 }
2719
2720 // Name lookup didn't find anything.
2721 // Determine whether this was a typo for another field name.
2722 FieldInitializerValidatorCCC CCC(RD);
2723 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2724 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2725 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2727 SemaRef.diagnoseTypo(
2728 Corrected,
2729 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2730 << FieldName << CurrentObjectType);
2731 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2732 hadError = true;
2733 } else {
2734 // Typo correction didn't find anything.
2735 SourceLocation Loc = D->getFieldLoc();
2736
2737 // The loc can be invalid with a "null" designator (i.e. an anonymous
2738 // union/struct). Do our best to approximate the location.
2739 if (Loc.isInvalid())
2740 Loc = IList->getBeginLoc();
2741
2742 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2743 << FieldName << CurrentObjectType << DIE->getSourceRange();
2744 ++Index;
2745 return true;
2746 }
2747 }
2748 }
2749
2750 unsigned NumBases = 0;
2751 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2752 NumBases = CXXRD->getNumBases();
2753
2754 unsigned FieldIndex = NumBases;
2755
2756 for (auto *FI : RD->fields()) {
2757 if (FI->isUnnamedBitfield())
2758 continue;
2759 if (declaresSameEntity(KnownField, FI)) {
2760 KnownField = FI;
2761 break;
2762 }
2763 ++FieldIndex;
2764 }
2765
2768
2769 // All of the fields of a union are located at the same place in
2770 // the initializer list.
2771 if (RD->isUnion()) {
2772 FieldIndex = 0;
2773 if (StructuredList) {
2774 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2775 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2776 assert(StructuredList->getNumInits() == 1
2777 && "A union should never have more than one initializer!");
2778
2779 Expr *ExistingInit = StructuredList->getInit(0);
2780 if (ExistingInit) {
2781 // We're about to throw away an initializer, emit warning.
2782 diagnoseInitOverride(
2783 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2784 /*UnionOverride=*/true,
2785 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2786 : true);
2787 }
2788
2789 // remove existing initializer
2790 StructuredList->resizeInits(SemaRef.Context, 0);
2791 StructuredList->setInitializedFieldInUnion(nullptr);
2792 }
2793
2794 StructuredList->setInitializedFieldInUnion(*Field);
2795 }
2796 }
2797
2798 // Make sure we can use this declaration.
2799 bool InvalidUse;
2800 if (VerifyOnly)
2801 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2802 else
2803 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2804 if (InvalidUse) {
2805 ++Index;
2806 return true;
2807 }
2808
2809 // C++20 [dcl.init.list]p3:
2810 // The ordered identifiers in the designators of the designated-
2811 // initializer-list shall form a subsequence of the ordered identifiers
2812 // in the direct non-static data members of T.
2813 //
2814 // Note that this is not a condition on forming the aggregate
2815 // initialization, only on actually performing initialization,
2816 // so it is not checked in VerifyOnly mode.
2817 //
2818 // FIXME: This is the only reordering diagnostic we produce, and it only
2819 // catches cases where we have a top-level field designator that jumps
2820 // backwards. This is the only such case that is reachable in an
2821 // otherwise-valid C++20 program, so is the only case that's required for
2822 // conformance, but for consistency, we should diagnose all the other
2823 // cases where a designator takes us backwards too.
2824 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2825 NextField &&
2826 (*NextField == RD->field_end() ||
2827 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2828 // Find the field that we just initialized.
2829 FieldDecl *PrevField = nullptr;
2830 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2831 if (FI->isUnnamedBitfield())
2832 continue;
2833 if (*NextField != RD->field_end() &&
2834 declaresSameEntity(*FI, **NextField))
2835 break;
2836 PrevField = *FI;
2837 }
2838
2839 if (PrevField &&
2840 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2841 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2842 diag::ext_designated_init_reordered)
2843 << KnownField << PrevField << DIE->getSourceRange();
2844
2845 unsigned OldIndex = StructuredIndex - 1;
2846 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2847 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2848 SemaRef.Diag(PrevInit->getBeginLoc(),
2849 diag::note_previous_field_init)
2850 << PrevField << PrevInit->getSourceRange();
2851 }
2852 }
2853 }
2854 }
2855
2856
2857 // Update the designator with the field declaration.
2858 if (!VerifyOnly)
2859 D->setFieldDecl(*Field);
2860
2861 // Make sure that our non-designated initializer list has space
2862 // for a subobject corresponding to this field.
2863 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2864 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2865
2866 // This designator names a flexible array member.
2867 if (Field->getType()->isIncompleteArrayType()) {
2868 bool Invalid = false;
2869 if ((DesigIdx + 1) != DIE->size()) {
2870 // We can't designate an object within the flexible array
2871 // member (because GCC doesn't allow it).
2872 if (!VerifyOnly) {
2874 = DIE->getDesignator(DesigIdx + 1);
2875 SemaRef.Diag(NextD->getBeginLoc(),
2876 diag::err_designator_into_flexible_array_member)
2877 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2878 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2879 << *Field;
2880 }
2881 Invalid = true;
2882 }
2883
2884 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2885 !isa<StringLiteral>(DIE->getInit())) {
2886 // The initializer is not an initializer list.
2887 if (!VerifyOnly) {
2888 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2889 diag::err_flexible_array_init_needs_braces)
2890 << DIE->getInit()->getSourceRange();
2891 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2892 << *Field;
2893 }
2894 Invalid = true;
2895 }
2896
2897 // Check GNU flexible array initializer.
2898 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2899 TopLevelObject))
2900 Invalid = true;
2901
2902 if (Invalid) {
2903 ++Index;
2904 return true;
2905 }
2906
2907 // Initialize the array.
2908 bool prevHadError = hadError;
2909 unsigned newStructuredIndex = FieldIndex;
2910 unsigned OldIndex = Index;
2911 IList->setInit(Index, DIE->getInit());
2912
2913 InitializedEntity MemberEntity =
2914 InitializedEntity::InitializeMember(*Field, &Entity);
2915 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2916 StructuredList, newStructuredIndex);
2917
2918 IList->setInit(OldIndex, DIE);
2919 if (hadError && !prevHadError) {
2920 ++Field;
2921 ++FieldIndex;
2922 if (NextField)
2923 *NextField = Field;
2924 StructuredIndex = FieldIndex;
2925 return true;
2926 }
2927 } else {
2928 // Recurse to check later designated subobjects.
2929 QualType FieldType = Field->getType();
2930 unsigned newStructuredIndex = FieldIndex;
2931
2932 InitializedEntity MemberEntity =
2933 InitializedEntity::InitializeMember(*Field, &Entity);
2934 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2935 FieldType, nullptr, nullptr, Index,
2936 StructuredList, newStructuredIndex,
2937 FinishSubobjectInit, false))
2938 return true;
2939 }
2940
2941 // Find the position of the next field to be initialized in this
2942 // subobject.
2943 ++Field;
2944 ++FieldIndex;
2945
2946 // If this the first designator, our caller will continue checking
2947 // the rest of this struct/class/union subobject.
2948 if (IsFirstDesignator) {
2949 if (Field != RD->field_end() && Field->isUnnamedBitfield())
2950 ++Field;
2951
2952 if (NextField)
2953 *NextField = Field;
2954
2955 StructuredIndex = FieldIndex;
2956 return false;
2957 }
2958
2959 if (!FinishSubobjectInit)
2960 return false;
2961
2962 // We've already initialized something in the union; we're done.
2963 if (RD->isUnion())
2964 return hadError;
2965
2966 // Check the remaining fields within this class/struct/union subobject.
2967 bool prevHadError = hadError;
2968
2969 auto NoBases =
2972 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2973 false, Index, StructuredList, FieldIndex);
2974 return hadError && !prevHadError;
2975 }
2976
2977 // C99 6.7.8p6:
2978 //
2979 // If a designator has the form
2980 //
2981 // [ constant-expression ]
2982 //
2983 // then the current object (defined below) shall have array
2984 // type and the expression shall be an integer constant
2985 // expression. If the array is of unknown size, any
2986 // nonnegative value is valid.
2987 //
2988 // Additionally, cope with the GNU extension that permits
2989 // designators of the form
2990 //
2991 // [ constant-expression ... constant-expression ]
2992 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2993 if (!AT) {
2994 if (!VerifyOnly)
2995 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2996 << CurrentObjectType;
2997 ++Index;
2998 return true;
2999 }
3000
3001 Expr *IndexExpr = nullptr;
3002 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3003 if (D->isArrayDesignator()) {
3004 IndexExpr = DIE->getArrayIndex(*D);
3005 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3006 DesignatedEndIndex = DesignatedStartIndex;
3007 } else {
3008 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3009
3010 DesignatedStartIndex =
3012 DesignatedEndIndex =
3014 IndexExpr = DIE->getArrayRangeEnd(*D);
3015
3016 // Codegen can't handle evaluating array range designators that have side
3017 // effects, because we replicate the AST value for each initialized element.
3018 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3019 // elements with something that has a side effect, so codegen can emit an
3020 // "error unsupported" error instead of miscompiling the app.
3021 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3022 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3023 FullyStructuredList->sawArrayRangeDesignator();
3024 }
3025
3026 if (isa<ConstantArrayType>(AT)) {
3027 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3028 DesignatedStartIndex
3029 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3030 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3031 DesignatedEndIndex
3032 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3033 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3034 if (DesignatedEndIndex >= MaxElements) {
3035 if (!VerifyOnly)
3036 SemaRef.Diag(IndexExpr->getBeginLoc(),
3037 diag::err_array_designator_too_large)
3038 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3039 << IndexExpr->getSourceRange();
3040 ++Index;
3041 return true;
3042 }
3043 } else {
3044 unsigned DesignatedIndexBitWidth =
3046 DesignatedStartIndex =
3047 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3048 DesignatedEndIndex =
3049 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3050 DesignatedStartIndex.setIsUnsigned(true);
3051 DesignatedEndIndex.setIsUnsigned(true);
3052 }
3053
3054 bool IsStringLiteralInitUpdate =
3055 StructuredList && StructuredList->isStringLiteralInit();
3056 if (IsStringLiteralInitUpdate && VerifyOnly) {
3057 // We're just verifying an update to a string literal init. We don't need
3058 // to split the string up into individual characters to do that.
3059 StructuredList = nullptr;
3060 } else if (IsStringLiteralInitUpdate) {
3061 // We're modifying a string literal init; we have to decompose the string
3062 // so we can modify the individual characters.
3063 ASTContext &Context = SemaRef.Context;
3064 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3065
3066 // Compute the character type
3067 QualType CharTy = AT->getElementType();
3068
3069 // Compute the type of the integer literals.
3070 QualType PromotedCharTy = CharTy;
3071 if (Context.isPromotableIntegerType(CharTy))
3072 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3073 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3074
3075 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3076 // Get the length of the string.
3077 uint64_t StrLen = SL->getLength();
3078 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3079 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3080 StructuredList->resizeInits(Context, StrLen);
3081
3082 // Build a literal for each character in the string, and put them into
3083 // the init list.
3084 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3085 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3086 Expr *Init = new (Context) IntegerLiteral(
3087 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3088 if (CharTy != PromotedCharTy)
3089 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3090 Init, nullptr, VK_PRValue,
3092 StructuredList->updateInit(Context, i, Init);
3093 }
3094 } else {
3095 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3096 std::string Str;
3097 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3098
3099 // Get the length of the string.
3100 uint64_t StrLen = Str.size();
3101 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3102 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3103 StructuredList->resizeInits(Context, StrLen);
3104
3105 // Build a literal for each character in the string, and put them into
3106 // the init list.
3107 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3108 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3109 Expr *Init = new (Context) IntegerLiteral(
3110 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3111 if (CharTy != PromotedCharTy)
3112 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3113 Init, nullptr, VK_PRValue,
3115 StructuredList->updateInit(Context, i, Init);
3116 }
3117 }
3118 }
3119
3120 // Make sure that our non-designated initializer list has space
3121 // for a subobject corresponding to this array element.
3122 if (StructuredList &&
3123 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3124 StructuredList->resizeInits(SemaRef.Context,
3125 DesignatedEndIndex.getZExtValue() + 1);
3126
3127 // Repeatedly perform subobject initializations in the range
3128 // [DesignatedStartIndex, DesignatedEndIndex].
3129
3130 // Move to the next designator
3131 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3132 unsigned OldIndex = Index;
3133
3134 InitializedEntity ElementEntity =
3136
3137 while (DesignatedStartIndex <= DesignatedEndIndex) {
3138 // Recurse to check later designated subobjects.
3139 QualType ElementType = AT->getElementType();
3140 Index = OldIndex;
3141
3142 ElementEntity.setElementIndex(ElementIndex);
3143 if (CheckDesignatedInitializer(
3144 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3145 nullptr, Index, StructuredList, ElementIndex,
3146 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3147 false))
3148 return true;
3149
3150 // Move to the next index in the array that we'll be initializing.
3151 ++DesignatedStartIndex;
3152 ElementIndex = DesignatedStartIndex.getZExtValue();
3153 }
3154
3155 // If this the first designator, our caller will continue checking
3156 // the rest of this array subobject.
3157 if (IsFirstDesignator) {
3158 if (NextElementIndex)
3159 *NextElementIndex = DesignatedStartIndex;
3160 StructuredIndex = ElementIndex;
3161 return false;
3162 }
3163
3164 if (!FinishSubobjectInit)
3165 return false;
3166
3167 // Check the remaining elements within this array subobject.
3168 bool prevHadError = hadError;
3169 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3170 /*SubobjectIsDesignatorContext=*/false, Index,
3171 StructuredList, ElementIndex);
3172 return hadError && !prevHadError;
3173}
3174
3175// Get the structured initializer list for a subobject of type
3176// @p CurrentObjectType.
3178InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3179 QualType CurrentObjectType,
3180 InitListExpr *StructuredList,
3181 unsigned StructuredIndex,
3182 SourceRange InitRange,
3183 bool IsFullyOverwritten) {
3184 if (!StructuredList)
3185 return nullptr;
3186
3187 Expr *ExistingInit = nullptr;
3188 if (StructuredIndex < StructuredList->getNumInits())
3189 ExistingInit = StructuredList->getInit(StructuredIndex);
3190
3191 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3192 // There might have already been initializers for subobjects of the current
3193 // object, but a subsequent initializer list will overwrite the entirety
3194 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3195 //
3196 // struct P { char x[6]; };
3197 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3198 //
3199 // The first designated initializer is ignored, and l.x is just "f".
3200 if (!IsFullyOverwritten)
3201 return Result;
3202
3203 if (ExistingInit) {
3204 // We are creating an initializer list that initializes the
3205 // subobjects of the current object, but there was already an
3206 // initialization that completely initialized the current
3207 // subobject:
3208 //
3209 // struct X { int a, b; };
3210 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3211 //
3212 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3213 // designated initializer overwrites the [0].b initializer
3214 // from the prior initialization.
3215 //
3216 // When the existing initializer is an expression rather than an
3217 // initializer list, we cannot decompose and update it in this way.
3218 // For example:
3219 //
3220 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3221 //
3222 // This case is handled by CheckDesignatedInitializer.
3223 diagnoseInitOverride(ExistingInit, InitRange);
3224 }
3225
3226 unsigned ExpectedNumInits = 0;
3227 if (Index < IList->getNumInits()) {
3228 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3229 ExpectedNumInits = Init->getNumInits();
3230 else
3231 ExpectedNumInits = IList->getNumInits() - Index;
3232 }
3233
3234 InitListExpr *Result =
3235 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3236
3237 // Link this new initializer list into the structured initializer
3238 // lists.
3239 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3240 return Result;
3241}
3242
3244InitListChecker::createInitListExpr(QualType CurrentObjectType,
3245 SourceRange InitRange,
3246 unsigned ExpectedNumInits) {
3247 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3248 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3249
3250 QualType ResultType = CurrentObjectType;
3251 if (!ResultType->isArrayType())
3252 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3253 Result->setType(ResultType);
3254
3255 // Pre-allocate storage for the structured initializer list.
3256 unsigned NumElements = 0;
3257
3258 if (const ArrayType *AType
3259 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3260 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3261 NumElements = CAType->getSize().getZExtValue();
3262 // Simple heuristic so that we don't allocate a very large
3263 // initializer with many empty entries at the end.
3264 if (NumElements > ExpectedNumInits)
3265 NumElements = 0;
3266 }
3267 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3268 NumElements = VType->getNumElements();
3269 } else if (CurrentObjectType->isRecordType()) {
3270 NumElements = numStructUnionElements(CurrentObjectType);
3271 } else if (CurrentObjectType->isDependentType()) {
3272 NumElements = 1;
3273 }
3274
3275 Result->reserveInits(SemaRef.Context, NumElements);
3276
3277 return Result;
3278}
3279
3280/// Update the initializer at index @p StructuredIndex within the
3281/// structured initializer list to the value @p expr.
3282void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3283 unsigned &StructuredIndex,
3284 Expr *expr) {
3285 // No structured initializer list to update
3286 if (!StructuredList)
3287 return;
3288
3289 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3290 StructuredIndex, expr)) {
3291 // This initializer overwrites a previous initializer.
3292 // No need to diagnose when `expr` is nullptr because a more relevant
3293 // diagnostic has already been issued and this diagnostic is potentially
3294 // noise.
3295 if (expr)
3296 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3297 }
3298
3299 ++StructuredIndex;
3300}
3301
3302/// Determine whether we can perform aggregate initialization for the purposes
3303/// of overload resolution.
3305 const InitializedEntity &Entity, InitListExpr *From) {
3306 QualType Type = Entity.getType();
3307 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3308 /*TreatUnavailableAsInvalid=*/false,
3309 /*InOverloadResolution=*/true);
3310 return !Check.HadError();
3311}
3312
3313/// Check that the given Index expression is a valid array designator
3314/// value. This is essentially just a wrapper around
3315/// VerifyIntegerConstantExpression that also checks for negative values
3316/// and produces a reasonable diagnostic if there is a
3317/// failure. Returns the index expression, possibly with an implicit cast
3318/// added, on success. If everything went okay, Value will receive the
3319/// value of the constant expression.
3320static ExprResult
3321CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3322 SourceLocation Loc = Index->getBeginLoc();
3323
3324 // Make sure this is an integer constant expression.
3327 if (Result.isInvalid())
3328 return Result;
3329
3330 if (Value.isSigned() && Value.isNegative())
3331 return S.Diag(Loc, diag::err_array_designator_negative)
3332 << toString(Value, 10) << Index->getSourceRange();
3333
3334 Value.setIsUnsigned(true);
3335 return Result;
3336}
3337
3339 SourceLocation EqualOrColonLoc,
3340 bool GNUSyntax,
3341 ExprResult Init) {
3342 typedef DesignatedInitExpr::Designator ASTDesignator;
3343
3344 bool Invalid = false;
3346 SmallVector<Expr *, 32> InitExpressions;
3347
3348 // Build designators and check array designator expressions.
3349 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3350 const Designator &D = Desig.getDesignator(Idx);
3351
3352 if (D.isFieldDesignator()) {
3353 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3354 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3355 } else if (D.isArrayDesignator()) {
3356 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3357 llvm::APSInt IndexValue;
3358 if (!Index->isTypeDependent() && !Index->isValueDependent())
3359 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3360 if (!Index)
3361 Invalid = true;
3362 else {
3363 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3364 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3365 InitExpressions.push_back(Index);
3366 }
3367 } else if (D.isArrayRangeDesignator()) {
3368 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3369 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3370 llvm::APSInt StartValue;
3371 llvm::APSInt EndValue;
3372 bool StartDependent = StartIndex->isTypeDependent() ||
3373 StartIndex->isValueDependent();
3374 bool EndDependent = EndIndex->isTypeDependent() ||
3375 EndIndex->isValueDependent();
3376 if (!StartDependent)
3377 StartIndex =
3378 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3379 if (!EndDependent)
3380 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3381
3382 if (!StartIndex || !EndIndex)
3383 Invalid = true;
3384 else {
3385 // Make sure we're comparing values with the same bit width.
3386 if (StartDependent || EndDependent) {
3387 // Nothing to compute.
3388 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3389 EndValue = EndValue.extend(StartValue.getBitWidth());
3390 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3391 StartValue = StartValue.extend(EndValue.getBitWidth());
3392
3393 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3394 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3395 << toString(StartValue, 10) << toString(EndValue, 10)
3396 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3397 Invalid = true;
3398 } else {
3399 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3400 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3401 D.getRBracketLoc()));
3402 InitExpressions.push_back(StartIndex);
3403 InitExpressions.push_back(EndIndex);
3404 }
3405 }
3406 }
3407 }
3408
3409 if (Invalid || Init.isInvalid())
3410 return ExprError();
3411
3412 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3413 EqualOrColonLoc, GNUSyntax,
3414 Init.getAs<Expr>());
3415}
3416
3417//===----------------------------------------------------------------------===//
3418// Initialization entity
3419//===----------------------------------------------------------------------===//
3420
3421InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3423 : Parent(&Parent), Index(Index)
3424{
3425 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3426 Kind = EK_ArrayElement;
3427 Type = AT->getElementType();
3428 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3429 Kind = EK_VectorElement;
3430 Type = VT->getElementType();
3431 } else {
3432 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3433 assert(CT && "Unexpected type");
3434 Kind = EK_ComplexElement;
3435 Type = CT->getElementType();
3436 }
3437}
3438
3441 const CXXBaseSpecifier *Base,
3442 bool IsInheritedVirtualBase,
3443 const InitializedEntity *Parent) {
3445 Result.Kind = EK_Base;
3446 Result.Parent = Parent;
3447 Result.Base = {Base, IsInheritedVirtualBase};
3448 Result.Type = Base->getType();
3449 return Result;
3450}
3451
3453 switch (getKind()) {
3454 case EK_Parameter:
3456 ParmVarDecl *D = Parameter.getPointer();
3457 return (D ? D->getDeclName() : DeclarationName());
3458 }
3459
3460 case EK_Variable:
3461 case EK_Member:
3463 case EK_Binding:
3465 return Variable.VariableOrMember->getDeclName();
3466
3467 case EK_LambdaCapture:
3468 return DeclarationName(Capture.VarID);
3469
3470 case EK_Result:
3471 case EK_StmtExprResult:
3472 case EK_Exception:
3473 case EK_New:
3474 case EK_Temporary:
3475 case EK_Base:
3476 case EK_Delegating:
3477 case EK_ArrayElement:
3478 case EK_VectorElement:
3479 case EK_ComplexElement:
3480 case EK_BlockElement:
3483 case EK_RelatedResult:
3484 return DeclarationName();
3485 }
3486
3487 llvm_unreachable("Invalid EntityKind!");
3488}
3489
3491 switch (getKind()) {
3492 case EK_Variable:
3493 case EK_Member:
3495 case EK_Binding:
3497 return Variable.VariableOrMember;
3498
3499 case EK_Parameter:
3501 return Parameter.getPointer();
3502
3503 case EK_Result:
3504 case EK_StmtExprResult:
3505 case EK_Exception:
3506 case EK_New:
3507 case EK_Temporary:
3508 case EK_Base:
3509 case EK_Delegating:
3510 case EK_ArrayElement:
3511 case EK_VectorElement:
3512 case EK_ComplexElement:
3513 case EK_BlockElement:
3515 case EK_LambdaCapture:
3517 case EK_RelatedResult:
3518 return nullptr;
3519 }
3520
3521 llvm_unreachable("Invalid EntityKind!");
3522}
3523
3525 switch (getKind()) {
3526 case EK_Result:
3527 case EK_Exception:
3528 return LocAndNRVO.NRVO;
3529
3530 case EK_StmtExprResult:
3531 case EK_Variable:
3532 case EK_Parameter:
3535 case EK_Member:
3537 case EK_Binding:
3538 case EK_New:
3539 case EK_Temporary:
3541 case EK_Base:
3542 case EK_Delegating:
3543 case EK_ArrayElement:
3544 case EK_VectorElement:
3545 case EK_ComplexElement:
3546 case EK_BlockElement:
3548 case EK_LambdaCapture:
3549 case EK_RelatedResult:
3550 break;
3551 }
3552
3553 return false;
3554}
3555
3556unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3557 assert(getParent() != this);
3558 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3559 for (unsigned I = 0; I != Depth; ++I)
3560 OS << "`-";
3561
3562 switch (getKind()) {
3563 case EK_Variable: OS << "Variable"; break;
3564 case EK_Parameter: OS << "Parameter"; break;
3565 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3566 break;
3567 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3568 case EK_Result: OS << "Result"; break;
3569 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3570 case EK_Exception: OS << "Exception"; break;
3571 case EK_Member:
3573 OS << "Member";
3574 break;
3575 case EK_Binding: OS << "Binding"; break;
3576 case EK_New: OS << "New"; break;
3577 case EK_Temporary: OS << "Temporary"; break;
3578 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3579 case EK_RelatedResult: OS << "RelatedResult"; break;
3580 case EK_Base: OS << "Base"; break;
3581 case EK_Delegating: OS << "Delegating"; break;
3582 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3583 case EK_VectorElement: OS << "VectorElement " << Index; break;
3584 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3585 case EK_BlockElement: OS << "Block"; break;
3587 OS << "Block (lambda)";
3588 break;
3589 case EK_LambdaCapture:
3590 OS << "LambdaCapture ";
3591 OS << DeclarationName(Capture.VarID);
3592 break;
3593 }
3594
3595 if (auto *D = getDecl()) {
3596 OS << " ";
3597 D->printQualifiedName(OS);
3598 }
3599
3600 OS << " '" << getType() << "'\n";
3601
3602 return Depth + 1;
3603}
3604
3605LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3606 dumpImpl(llvm::errs());
3607}
3608
3609//===----------------------------------------------------------------------===//
3610// Initialization sequence
3611//===----------------------------------------------------------------------===//
3612
3614 switch (Kind) {
3619 case SK_BindReference:
3621 case SK_FinalCopy:
3623 case SK_UserConversion:
3630 case SK_UnwrapInitList:
3631 case SK_RewrapInitList:
3635 case SK_CAssignment:
3636 case SK_StringInit:
3638 case SK_ArrayLoopIndex:
3639 case SK_ArrayLoopInit:
3640 case SK_ArrayInit:
3641 case SK_GNUArrayInit:
3648 case SK_OCLSamplerInit:
3651 break;
3652
3655 delete ICS;
3656 }
3657}
3658
3660 // There can be some lvalue adjustments after the SK_BindReference step.
3661 for (const Step &S : llvm::reverse(Steps)) {
3662 if (S.Kind == SK_BindReference)
3663 return true;
3664 if (S.Kind == SK_BindReferenceToTemporary)
3665 return false;
3666 }
3667 return false;
3668}
3669
3671 if (!Failed())
3672 return false;
3673
3674 switch (getFailureKind()) {
3685 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3702 case FK_Incomplete:
3707 case FK_PlaceholderType:
3712 return false;
3713
3718 return FailedOverloadResult == OR_Ambiguous;
3719 }
3720
3721 llvm_unreachable("Invalid EntityKind!");
3722}
3723
3725 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3726}
3727
3728void
3729InitializationSequence
3730::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3731 DeclAccessPair Found,
3732 bool HadMultipleCandidates) {
3733 Step S;
3735 S.Type = Function->getType();
3736 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3737 S.Function.Function = Function;
3738 S.Function.FoundDecl = Found;
3739 Steps.push_back(S);
3740}
3741
3743 ExprValueKind VK) {
3744 Step S;
3745 switch (VK) {
3746 case VK_PRValue:
3748 break;
3749 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3750 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3751 }
3752 S.Type = BaseType;
3753 Steps.push_back(S);
3754}
3755
3757 bool BindingTemporary) {
3758 Step S;
3759 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3760 S.Type = T;
3761 Steps.push_back(S);
3762}
3763
3765 Step S;
3766 S.Kind = SK_FinalCopy;
3767 S.Type = T;
3768 Steps.push_back(S);
3769}
3770
3772 Step S;
3774 S.Type = T;
3775 Steps.push_back(S);
3776}
3777
3778void
3780 DeclAccessPair FoundDecl,
3781 QualType T,
3782 bool HadMultipleCandidates) {
3783 Step S;
3784 S.Kind = SK_UserConversion;
3785 S.Type = T;
3786 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3787 S.Function.Function = Function;
3788 S.Function.FoundDecl = FoundDecl;
3789 Steps.push_back(S);
3790}
3791
3793 ExprValueKind VK) {
3794 Step S;
3795 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3796 switch (VK) {
3797 case VK_PRValue:
3799 break;
3800 case VK_XValue:
3802 break;
3803 case VK_LValue:
3805 break;
3806 }
3807 S.Type = Ty;
3808 Steps.push_back(S);
3809}
3810
3812 Step S;
3814 S.Type = Ty;
3815 Steps.push_back(S);
3816}
3817
3819 Step S;
3820 S.Kind = SK_AtomicConversion;
3821 S.Type = Ty;
3822 Steps.push_back(S);
3823}
3824
3827 bool TopLevelOfInitList) {
3828 Step S;
3829 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3831 S.Type = T;
3832 S.ICS = new ImplicitConversionSequence(ICS);
3833 Steps.push_back(S);
3834}
3835
3837 Step S;
3838 S.Kind = SK_ListInitialization;
3839 S.Type = T;
3840 Steps.push_back(S);
3841}
3842
3844 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3845 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3846 Step S;
3847 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3850 S.Type = T;
3851 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3852 S.Function.Function = Constructor;
3853 S.Function.FoundDecl = FoundDecl;
3854 Steps.push_back(S);
3855}
3856
3858 Step S;
3859 S.Kind = SK_ZeroInitialization;
3860 S.Type = T;
3861 Steps.push_back(S);
3862}
3863
3865 Step S;
3866 S.Kind = SK_CAssignment;
3867 S.Type = T;
3868 Steps.push_back(S);
3869}
3870
3872 Step S;
3873 S.Kind = SK_StringInit;
3874 S.Type = T;
3875 Steps.push_back(S);
3876}
3877
3879 Step S;
3880 S.Kind = SK_ObjCObjectConversion;
3881 S.Type = T;
3882 Steps.push_back(S);
3883}
3884
3886 Step S;
3887 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3888 S.Type = T;
3889 Steps.push_back(S);
3890}
3891
3893 Step S;
3894 S.Kind = SK_ArrayLoopIndex;
3895 S.Type = EltT;
3896 Steps.insert(Steps.begin(), S);
3897
3898 S.Kind = SK_ArrayLoopInit;
3899 S.Type = T;
3900 Steps.push_back(S);
3901}
3902
3904 Step S;
3906 S.Type = T;
3907 Steps.push_back(S);
3908}
3909
3911 bool shouldCopy) {
3912 Step s;
3913 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3915 s.Type = type;
3916 Steps.push_back(s);
3917}
3918
3920 Step S;
3921 S.Kind = SK_ProduceObjCObject;
3922 S.Type = T;
3923 Steps.push_back(S);
3924}
3925
3927 Step S;
3928 S.Kind = SK_StdInitializerList;
3929 S.Type = T;
3930 Steps.push_back(S);
3931}
3932
3934 Step S;
3935 S.Kind = SK_OCLSamplerInit;
3936 S.Type = T;
3937 Steps.push_back(S);
3938}
3939
3941 Step S;
3942 S.Kind = SK_OCLZeroOpaqueType;
3943 S.Type = T;
3944 Steps.push_back(S);
3945}
3946
3948 Step S;
3949 S.Kind = SK_ParenthesizedListInit;
3950 S.Type = T;
3951 Steps.push_back(S);
3952}
3953
3955 InitListExpr *Syntactic) {
3956 assert(Syntactic->getNumInits() == 1 &&
3957 "Can only rewrap trivial init lists.");
3958 Step S;
3959 S.Kind = SK_UnwrapInitList;
3960 S.Type = Syntactic->getInit(0)->getType();
3961 Steps.insert(Steps.begin(), S);
3962
3963 S.Kind = SK_RewrapInitList;
3964 S.Type = T;
3965 S.WrappingSyntacticList = Syntactic;
3966 Steps.push_back(S);
3967}
3968
3972 this->Failure = Failure;
3973 this->FailedOverloadResult = Result;
3974}
3975
3976//===----------------------------------------------------------------------===//
3977// Attempt initialization
3978//===----------------------------------------------------------------------===//
3979
3980/// Tries to add a zero initializer. Returns true if that worked.
3981static bool
3983 const InitializedEntity &Entity) {
3985 return false;
3986
3987 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3988 if (VD->getInit() || VD->getEndLoc().isMacroID())
3989 return false;
3990
3991 QualType VariableTy = VD->getType().getCanonicalType();
3993 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3994 if (!Init.empty()) {
3995 Sequence.AddZeroInitializationStep(Entity.getType());
3996 Sequence.SetZeroInitializationFixit(Init, Loc);
3997 return true;
3998 }
3999 return false;
4000}
4001
4003 InitializationSequence &Sequence,
4004 const InitializedEntity &Entity) {
4005 if (!S.getLangOpts().ObjCAutoRefCount) return;
4006
4007 /// When initializing a parameter, produce the value if it's marked
4008 /// __attribute__((ns_consumed)).
4009 if (Entity.isParameterKind()) {
4010 if (!Entity.isParameterConsumed())
4011 return;
4012
4013 assert(Entity.getType()->isObjCRetainableType() &&
4014 "consuming an object of unretainable type?");
4015 Sequence.AddProduceObjCObjectStep(Entity.getType());
4016
4017 /// When initializing a return value, if the return type is a
4018 /// retainable type, then returns need to immediately retain the
4019 /// object. If an autorelease is required, it will be done at the
4020 /// last instant.
4021 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4023 if (!Entity.getType()->isObjCRetainableType())
4024 return;
4025
4026 Sequence.AddProduceObjCObjectStep(Entity.getType());
4027 }
4028}
4029
4030static void TryListInitialization(Sema &S,
4031 const InitializedEntity &Entity,
4032 const InitializationKind &Kind,
4033 InitListExpr *InitList,
4034 InitializationSequence &Sequence,
4035 bool TreatUnavailableAsInvalid);
4036
4037/// When initializing from init list via constructor, handle
4038/// initialization of an object of type std::initializer_list<T>.
4039///
4040/// \return true if we have handled initialization of an object of type
4041/// std::initializer_list<T>, false otherwise.
4043 InitListExpr *List,
4044 QualType DestType,
4045 InitializationSequence &Sequence,
4046 bool TreatUnavailableAsInvalid) {
4047 QualType E;
4048 if (!S.isStdInitializerList(DestType, &E))
4049 return false;
4050
4051 if (!S.isCompleteType(List->getExprLoc(), E)) {
4052 Sequence.setIncompleteTypeFailure(E);
4053 return true;
4054 }
4055
4056 // Try initializing a temporary array from the init list.
4058 E.withConst(),
4059 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4060 List->getNumInits()),
4062 InitializedEntity HiddenArray =
4065 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4066 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4067 TreatUnavailableAsInvalid);
4068 if (Sequence)
4069 Sequence.AddStdInitializerListConstructionStep(DestType);
4070 return true;
4071}
4072
4073/// Determine if the constructor has the signature of a copy or move
4074/// constructor for the type T of the class in which it was found. That is,
4075/// determine if its first parameter is of type T or reference to (possibly
4076/// cv-qualified) T.
4078 const ConstructorInfo &Info) {
4079 if (Info.Constructor->getNumParams() == 0)
4080 return false;
4081
4082 QualType ParmT =
4084 QualType ClassT =
4085 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4086
4087 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4088}
4089
4091 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4092 OverloadCandidateSet &CandidateSet, QualType DestType,
4094 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4095 bool IsListInit, bool RequireActualConstructor,
4096 bool SecondStepOfCopyInit = false) {
4098 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4099
4100 for (NamedDecl *D : Ctors) {
4101 auto Info = getConstructorInfo(D);
4102 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4103 continue;
4104
4105 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4106 continue;
4107
4108 // C++11 [over.best.ics]p4:
4109 // ... and the constructor or user-defined conversion function is a
4110 // candidate by
4111 // - 13.3.1.3, when the argument is the temporary in the second step
4112 // of a class copy-initialization, or
4113 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4114 // - the second phase of 13.3.1.7 when the initializer list has exactly
4115 // one element that is itself an initializer list, and the target is
4116 // the first parameter of a constructor of class X, and the conversion
4117 // is to X or reference to (possibly cv-qualified X),
4118 // user-defined conversion sequences are not considered.
4119 bool SuppressUserConversions =
4120 SecondStepOfCopyInit ||
4121 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4123
4124 if (Info.ConstructorTmpl)
4126 Info.ConstructorTmpl, Info.FoundDecl,
4127 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4128 /*PartialOverloading=*/false, AllowExplicit);
4129 else {
4130 // C++ [over.match.copy]p1:
4131 // - When initializing a temporary to be bound to the first parameter
4132 // of a constructor [for type T] that takes a reference to possibly
4133 // cv-qualified T as its first argument, called with a single
4134 // argument in the context of direct-initialization, explicit
4135 // conversion functions are also considered.
4136 // FIXME: What if a constructor template instantiates to such a signature?
4137 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4138 Args.size() == 1 &&
4140 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4141 CandidateSet, SuppressUserConversions,
4142 /*PartialOverloading=*/false, AllowExplicit,
4143 AllowExplicitConv);
4144 }
4145 }
4146
4147 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4148 //
4149 // When initializing an object of class type T by constructor
4150 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4151 // from a single expression of class type U, conversion functions of
4152 // U that convert to the non-reference type cv T are candidates.
4153 // Explicit conversion functions are only candidates during
4154 // direct-initialization.
4155 //
4156 // Note: SecondStepOfCopyInit is only ever true in this case when
4157 // evaluating whether to produce a C++98 compatibility warning.
4158 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4159 !RequireActualConstructor && !SecondStepOfCopyInit) {
4160 Expr *Initializer = Args[0];
4161 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4162 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4163 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4164 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4165 NamedDecl *D = *I;
4166 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4167 D = D->getUnderlyingDecl();
4168
4169 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4170 CXXConversionDecl *Conv;
4171 if (ConvTemplate)
4172 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4173 else
4174 Conv = cast<CXXConversionDecl>(D);
4175
4176 if (ConvTemplate)
4178 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4179 CandidateSet, AllowExplicit, AllowExplicit,
4180 /*AllowResultConversion*/ false);
4181 else
4182 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4183 DestType, CandidateSet, AllowExplicit,
4184 AllowExplicit,
4185 /*AllowResultConversion*/ false);
4186 }
4187 }
4188 }
4189
4190 // Perform overload resolution and return the result.
4191 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4192}
4193
4194/// Attempt initialization by constructor (C++ [dcl.init]), which
4195/// enumerates the constructors of the initialized entity and performs overload
4196/// resolution to select the best.
4197/// \param DestType The destination class type.
4198/// \param DestArrayType The destination type, which is either DestType or
4199/// a (possibly multidimensional) array of DestType.
4200/// \param IsListInit Is this list-initialization?
4201/// \param IsInitListCopy Is this non-list-initialization resulting from a
4202/// list-initialization from {x} where x is the same
4203/// type as the entity?
4205 const InitializedEntity &Entity,
4206 const InitializationKind &Kind,
4207 MultiExprArg Args, QualType DestType,
4208 QualType DestArrayType,
4209 InitializationSequence &Sequence,
4210 bool IsListInit = false,
4211 bool IsInitListCopy = false) {
4212 assert(((!IsListInit && !IsInitListCopy) ||
4213 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4214 "IsListInit/IsInitListCopy must come with a single initializer list "
4215 "argument.");
4216 InitListExpr *ILE =
4217 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4218 MultiExprArg UnwrappedArgs =
4219 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4220
4221 // The type we're constructing needs to be complete.
4222 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4223 Sequence.setIncompleteTypeFailure(DestType);
4224 return;
4225 }
4226
4227 bool RequireActualConstructor =
4228 !(Entity.getKind() != InitializedEntity::EK_Base &&
4230 Entity.getKind() !=
4232
4233 // C++17 [dcl.init]p17:
4234 // - If the initializer expression is a prvalue and the cv-unqualified
4235 // version of the source type is the same class as the class of the
4236 // destination, the initializer expression is used to initialize the
4237 // destination object.
4238 // Per DR (no number yet), this does not apply when initializing a base
4239 // class or delegating to another constructor from a mem-initializer.
4240 // ObjC++: Lambda captured by the block in the lambda to block conversion
4241 // should avoid copy elision.
4242 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4243 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4244 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4245 // Convert qualifications if necessary.
4246 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4247 if (ILE)
4248 Sequence.RewrapReferenceInitList(DestType, ILE);
4249 return;
4250 }
4251
4252 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4253 assert(DestRecordType && "Constructor initialization requires record type");
4254 CXXRecordDecl *DestRecordDecl
4255 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4256
4257 // Build the candidate set directly in the initialization sequence
4258 // structure, so that it will persist if we fail.
4259 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4260
4261 // Determine whether we are allowed to call explicit constructors or
4262 // explicit conversion operators.
4263 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4264 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4265
4266 // - Otherwise, if T is a class type, constructors are considered. The
4267 // applicable constructors are enumerated, and the best one is chosen
4268 // through overload resolution.
4269 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4270
4273 bool AsInitializerList = false;
4274
4275 // C++11 [over.match.list]p1, per DR1467:
4276 // When objects of non-aggregate type T are list-initialized, such that
4277 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4278 // according to the rules in this section, overload resolution selects
4279 // the constructor in two phases:
4280 //
4281 // - Initially, the candidate functions are the initializer-list
4282 // constructors of the class T and the argument list consists of the
4283 // initializer list as a single argument.
4284 if (IsListInit) {
4285 AsInitializerList = true;
4286
4287 // If the initializer list has no elements and T has a default constructor,
4288 // the first phase is omitted.
4289 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4291 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4292 CopyInitialization, AllowExplicit,
4293 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4294 }
4295
4296 // C++11 [over.match.list]p1:
4297 // - If no viable initializer-list constructor is found, overload resolution
4298 // is performed again, where the candidate functions are all the
4299 // constructors of the class T and the argument list consists of the
4300 // elements of the initializer list.
4302 AsInitializerList = false;
4304 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4305 Best, CopyInitialization, AllowExplicit,
4306 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4307 }
4308 if (Result) {
4309 Sequence.SetOverloadFailure(
4312 Result);
4313
4314 if (Result != OR_Deleted)
4315 return;
4316 }
4317
4318 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4319
4320 // In C++17, ResolveConstructorOverload can select a conversion function
4321 // instead of a constructor.
4322 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4323 // Add the user-defined conversion step that calls the conversion function.
4324 QualType ConvType = CD->getConversionType();
4325 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4326 "should not have selected this conversion function");
4327 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4328 HadMultipleCandidates);
4329 if (!S.Context.hasSameType(ConvType, DestType))
4330 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4331 if (IsListInit)
4332 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4333 return;
4334 }
4335
4336 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4337 if (Result != OR_Deleted) {
4338 // C++11 [dcl.init]p6:
4339 // If a program calls for the default initialization of an object
4340 // of a const-qualified type T, T shall be a class type with a
4341 // user-provided default constructor.
4342 // C++ core issue 253 proposal:
4343 // If the implicit default constructor initializes all subobjects, no
4344 // initializer should be required.
4345 // The 253 proposal is for example needed to process libstdc++ headers
4346 // in 5.x.
4347 if (Kind.getKind() == InitializationKind::IK_Default &&
4348 Entity.getType().isConstQualified()) {
4349 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4350 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4352 return;
4353 }
4354 }
4355
4356 // C++11 [over.match.list]p1:
4357 // In copy-list-initialization, if an explicit constructor is chosen, the
4358 // initializer is ill-formed.
4359 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4361 return;
4362 }
4363 }
4364
4365 // [class.copy.elision]p3:
4366 // In some copy-initialization contexts, a two-stage overload resolution
4367 // is performed.
4368 // If the first overload resolution selects a deleted function, we also
4369 // need the initialization sequence to decide whether to perform the second
4370 // overload resolution.
4371 // For deleted functions in other contexts, there is no need to get the
4372 // initialization sequence.
4373 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4374 return;
4375
4376 // Add the constructor initialization step. Any cv-qualification conversion is
4377 // subsumed by the initialization.
4379 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4380 IsListInit | IsInitListCopy, AsInitializerList);
4381}
4382
4383static bool
4386 QualType &SourceType,
4387 QualType &UnqualifiedSourceType,
4388 QualType UnqualifiedTargetType,
4389 InitializationSequence &Sequence) {
4390 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4391 S.Context.OverloadTy) {
4392 DeclAccessPair Found;
4393 bool HadMultipleCandidates = false;
4394 if (FunctionDecl *Fn
4396 UnqualifiedTargetType,
4397 false, Found,
4398 &HadMultipleCandidates)) {
4399 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4400 HadMultipleCandidates);
4401 SourceType = Fn->getType();
4402 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4403 } else if (!UnqualifiedTargetType->isRecordType()) {
4405 return true;
4406 }
4407 }
4408 return false;
4409}
4410
4412 const InitializedEntity &Entity,
4413 const InitializationKind &Kind,
4415 QualType cv1T1, QualType T1,
4416 Qualifiers T1Quals,
4417 QualType cv2T2, QualType T2,
4418 Qualifiers T2Quals,
4419 InitializationSequence &Sequence,
4420 bool TopLevelOfInitList);
4421
4422static void TryValueInitialization(Sema &S,
4423 const InitializedEntity &Entity,
4424 const InitializationKind &Kind,
4425 InitializationSequence &Sequence,
4426 InitListExpr *InitList = nullptr);
4427
4428/// Attempt list initialization of a reference.
4430 const InitializedEntity &Entity,
4431 const InitializationKind &Kind,
4432 InitListExpr *InitList,
4433 InitializationSequence &Sequence,
4434 bool TreatUnavailableAsInvalid) {
4435 // First, catch C++03 where this isn't possible.
4436 if (!S.getLangOpts().CPlusPlus11) {
4438 return;
4439 }
4440 // Can't reference initialize a compound literal.
4443 return;
4444 }
4445
4446 QualType DestType = Entity.getType();
4447 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4448 Qualifiers T1Quals;
4449 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4450
4451 // Reference initialization via an initializer list works thus:
4452 // If the initializer list consists of a single element that is
4453 // reference-related to the referenced type, bind directly to that element
4454 // (possibly creating temporaries).
4455 // Otherwise, initialize a temporary with the initializer list and
4456 // bind to that.
4457 if (InitList->getNumInits() == 1) {
4458 Expr *Initializer = InitList->getInit(0);
4460 Qualifiers T2Quals;
4461 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4462
4463 // If this fails, creating a temporary wouldn't work either.
4465 T1, Sequence))
4466 return;
4467
4468 SourceLocation DeclLoc = Initializer->getBeginLoc();
4469 Sema::ReferenceCompareResult RefRelationship
4470 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4471 if (RefRelationship >= Sema::Ref_Related) {
4472 // Try to bind the reference here.
4473 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4474 T1Quals, cv2T2, T2, T2Quals, Sequence,
4475 /*TopLevelOfInitList=*/true);
4476 if (Sequence)
4477 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4478 return;
4479 }
4480
4481 // Update the initializer if we've resolved an overloaded function.
4482 if (Sequence.step_begin() != Sequence.step_end())
4483 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4484 }
4485 // Perform address space compatibility check.
4486 QualType cv1T1IgnoreAS = cv1T1;
4487 if (T1Quals.hasAddressSpace()) {
4488 Qualifiers T2Quals;
4489 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4490 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4491 Sequence.SetFailed(
4493 return;
4494 }
4495 // Ignore address space of reference type at this point and perform address
4496 // space conversion after the reference binding step.
4497 cv1T1IgnoreAS =
4499 }
4500 // Not reference-related. Create a temporary and bind to that.
4501 InitializedEntity TempEntity =
4503
4504 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4505 TreatUnavailableAsInvalid);
4506 if (Sequence) {
4507 if (DestType->isRValueReferenceType() ||
4508 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4509 if (S.getLangOpts().CPlusPlus20 &&
4510 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4511 DestType->isRValueReferenceType()) {
4512 // C++20 [dcl.init.list]p3.10:
4513 // List-initialization of an object or reference of type T is defined as
4514 // follows:
4515 // ..., unless T is “reference to array of unknown bound of U”, in which
4516 // case the type of the prvalue is the type of x in the declaration U
4517 // x[] H, where H is the initializer list.
4519 }
4520 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4521 /*BindingTemporary=*/true);
4522 if (T1Quals.hasAddressSpace())
4524 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4525 } else
4526 Sequence.SetFailed(
4528 }
4529}
4530
4531/// Attempt list initialization (C++0x [dcl.init.list])
4533 const InitializedEntity &Entity,
4534 const InitializationKind &Kind,
4535 InitListExpr *InitList,
4536 InitializationSequence &Sequence,
4537 bool TreatUnavailableAsInvalid) {
4538 QualType DestType = Entity.getType();
4539
4540 // C++ doesn't allow scalar initialization with more than one argument.
4541 // But C99 complex numbers are scalars and it makes sense there.
4542 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4543 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4545 return;
4546 }
4547 if (DestType->isReferenceType()) {
4548 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4549 TreatUnavailableAsInvalid);
4550 return;
4551 }
4552
4553 if (DestType->isRecordType() &&
4554 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4555 Sequence.setIncompleteTypeFailure(DestType);
4556 return;
4557 }
4558
4559 // C++20 [dcl.init.list]p3:
4560 // - If the braced-init-list contains a designated-initializer-list, T shall
4561 // be an aggregate class. [...] Aggregate initialization is performed.
4562 //
4563 // We allow arrays here too in order to support array designators.
4564 //
4565 // FIXME: This check should precede the handling of reference initialization.
4566 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4567 // as a tentative DR resolution.
4568 bool IsDesignatedInit = InitList->hasDesignatedInit();
4569 if (!DestType->isAggregateType() && IsDesignatedInit) {
4570 Sequence.SetFailed(
4572 return;
4573 }
4574
4575 // C++11 [dcl.init.list]p3, per DR1467:
4576 // - If T is a class type and the initializer list has a single element of
4577 // type cv U, where U is T or a class derived from T, the object is
4578 // initialized from that element (by copy-initialization for
4579 // copy-list-initialization, or by direct-initialization for
4580 // direct-list-initialization).
4581 // - Otherwise, if T is a character array and the initializer list has a
4582 // single element that is an appropriately-typed string literal
4583 // (8.5.2 [dcl.init.string]), initialization is performed as described
4584 // in that section.
4585 // - Otherwise, if T is an aggregate, [...] (continue below).
4586 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4587 !IsDesignatedInit) {
4588 if (DestType->isRecordType()) {
4589 QualType InitType = InitList->getInit(0)->getType();
4590 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4591 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4592 Expr *InitListAsExpr = InitList;
4593 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4594 DestType, Sequence,
4595 /*InitListSyntax*/false,
4596 /*IsInitListCopy*/true);
4597 return;
4598 }
4599 }
4600 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4601 Expr *SubInit[1] = {InitList->getInit(0)};
4602 if (!isa<VariableArrayType>(DestAT) &&
4603 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4604 InitializationKind SubKind =
4605 Kind.getKind() == InitializationKind::IK_DirectList
4606 ? InitializationKind::CreateDirect(Kind.getLocation(),
4607 InitList->getLBraceLoc(),
4608 InitList->getRBraceLoc())
4609 : Kind;
4610 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4611 /*TopLevelOfInitList*/ true,
4612 TreatUnavailableAsInvalid);
4613
4614 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4615 // the element is not an appropriately-typed string literal, in which
4616 // case we should proceed as in C++11 (below).
4617 if (Sequence) {
4618 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4619 return;
4620 }
4621 }
4622 }
4623 }
4624
4625 // C++11 [dcl.init.list]p3:
4626 // - If T is an aggregate, aggregate initialization is performed.
4627 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4628 (S.getLangOpts().CPlusPlus11 &&
4629 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4630 if (S.getLangOpts().CPlusPlus11) {
4631 // - Otherwise, if the initializer list has no elements and T is a
4632 // class type with a default constructor, the object is
4633 // value-initialized.
4634 if (InitList->getNumInits() == 0) {
4635 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4636 if (S.LookupDefaultConstructor(RD)) {
4637 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4638 return;
4639 }
4640 }
4641
4642 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4643 // an initializer_list object constructed [...]
4644 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4645 TreatUnavailableAsInvalid))
4646 return;
4647
4648 // - Otherwise, if T is a class type, constructors are considered.
4649 Expr *InitListAsExpr = InitList;
4650 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4651 DestType, Sequence, /*InitListSyntax*/true);
4652 } else
4654 return;
4655 }
4656
4657 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4658 InitList->getNumInits() == 1) {
4659 Expr *E = InitList->getInit(0);
4660
4661 // - Otherwise, if T is an enumeration with a fixed underlying type,
4662 // the initializer-list has a single element v, and the initialization
4663 // is direct-list-initialization, the object is initialized with the
4664 // value T(v); if a narrowing conversion is required to convert v to
4665 // the underlying type of T, the program is ill-formed.
4666 auto *ET = DestType->getAs<EnumType>();
4667 if (S.getLangOpts().CPlusPlus17 &&
4668 Kind.getKind() == InitializationKind::IK_DirectList &&
4669 ET && ET->getDecl()->isFixed() &&
4670 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4672 E->getType()->isFloatingType())) {
4673 // There are two ways that T(v) can work when T is an enumeration type.
4674 // If there is either an implicit conversion sequence from v to T or
4675 // a conversion function that can convert from v to T, then we use that.
4676 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4677 // type, it is converted to the enumeration type via its underlying type.
4678 // There is no overlap possible between these two cases (except when the
4679 // source value is already of the destination type), and the first
4680 // case is handled by the general case for single-element lists below.
4682 ICS.setStandard();
4684 if (!E->isPRValue())
4686 // If E is of a floating-point type, then the conversion is ill-formed
4687 // due to narrowing, but go through the motions in order to produce the
4688 // right diagnostic.
4692 ICS.Standard.setFromType(E->getType());
4693 ICS.Standard.setToType(0, E->getType());
4694 ICS.Standard.setToType(1, DestType);
4695 ICS.Standard.setToType(2, DestType);
4696 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4697 /*TopLevelOfInitList*/true);
4698 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4699 return;
4700 }
4701
4702 // - Otherwise, if the initializer list has a single element of type E
4703 // [...references are handled above...], the object or reference is
4704 // initialized from that element (by copy-initialization for
4705 // copy-list-initialization, or by direct-initialization for
4706 // direct-list-initialization); if a narrowing conversion is required
4707 // to convert the element to T, the program is ill-formed.
4708 //
4709 // Per core-24034, this is direct-initialization if we were performing
4710 // direct-list-initialization and copy-initialization otherwise.
4711 // We can't use InitListChecker for this, because it always performs
4712 // copy-initialization. This only matters if we might use an 'explicit'
4713 // conversion operator, or for the special case conversion of nullptr_t to
4714 // bool, so we only need to handle those cases.
4715 //
4716 // FIXME: Why not do this in all cases?
4717 Expr *Init = InitList->getInit(0);
4718 if (Init->getType()->isRecordType() ||
4719 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4720 InitializationKind SubKind =
4721 Kind.getKind() == InitializationKind::IK_DirectList
4722 ? InitializationKind::CreateDirect(Kind.getLocation(),
4723 InitList->getLBraceLoc(),
4724 InitList->getRBraceLoc())
4725 : Kind;
4726 Expr *SubInit[1] = { Init };
4727 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4728 /*TopLevelOfInitList*/true,
4729 TreatUnavailableAsInvalid);
4730 if (Sequence)
4731 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4732 return;
4733 }
4734 }
4735
4736 InitListChecker CheckInitList(S, Entity, InitList,
4737 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4738 if (CheckInitList.HadError()) {
4740 return;
4741 }
4742
4743 // Add the list initialization step with the built init list.
4744 Sequence.AddListInitializationStep(DestType);
4745}
4746
4747/// Try a reference initialization that involves calling a conversion
4748/// function.
4750 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4751 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4752 InitializationSequence &Sequence) {
4753 QualType DestType = Entity.getType();
4754 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4755 QualType T1 = cv1T1.getUnqualifiedType();
4756 QualType cv2T2 = Initializer->getType();
4757 QualType T2 = cv2T2.getUnqualifiedType();
4758
4759 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4760 "Must have incompatible references when binding via conversion");
4761
4762 // Build the candidate set directly in the initialization sequence
4763 // structure, so that it will persist if we fail.
4764 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4766
4767 // Determine whether we are allowed to call explicit conversion operators.
4768 // Note that none of [over.match.copy], [over.match.conv], nor
4769 // [over.match.ref] permit an explicit constructor to be chosen when
4770 // initializing a reference, not even for direct-initialization.
4771 bool AllowExplicitCtors = false;
4772 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4773
4774 const RecordType *T1RecordType = nullptr;
4775 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4776 S.isCompleteType(Kind.getLocation(), T1)) {
4777 // The type we're converting to is a class type. Enumerate its constructors
4778 // to see if there is a suitable conversion.
4779 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4780
4781 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4782 auto Info = getConstructorInfo(D);
4783 if (!Info.Constructor)
4784 continue;
4785
4786 if (!Info.Constructor->isInvalidDecl() &&
4787 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4788 if (Info.ConstructorTmpl)
4790 Info.ConstructorTmpl, Info.FoundDecl,
4791 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4792 /*SuppressUserConversions=*/true,
4793 /*PartialOverloading*/ false, AllowExplicitCtors);
4794 else
4796 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4797 /*SuppressUserConversions=*/true,
4798 /*PartialOverloading*/ false, AllowExplicitCtors);
4799 }
4800 }
4801 }
4802 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4803 return OR_No_Viable_Function;
4804
4805 const RecordType *T2RecordType = nullptr;
4806 if ((T2RecordType = T2->getAs<RecordType>()) &&
4807 S.isCompleteType(Kind.getLocation(), T2)) {
4808 // The type we're converting from is a class type, enumerate its conversion
4809 // functions.
4810 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4811
4812 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4813 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4814 NamedDecl *D = *I;
4815 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4816 if (isa<UsingShadowDecl>(D))
4817 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4818
4819 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4820 CXXConversionDecl *Conv;
4821 if (ConvTemplate)
4822 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4823 else
4824 Conv = cast<CXXConversionDecl>(D);
4825
4826 // If the conversion function doesn't return a reference type,
4827 // it can't be considered for this conversion unless we're allowed to
4828 // consider rvalues.
4829 // FIXME: Do we need to make sure that we only consider conversion
4830 // candidates with reference-compatible results? That might be needed to
4831 // break recursion.
4832 if ((AllowRValues ||
4834 if (ConvTemplate)
4836 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4837 CandidateSet,
4838 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4839 else
4841 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4842 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4843 }
4844 }
4845 }
4846 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4847 return OR_No_Viable_Function;
4848
4849 SourceLocation DeclLoc = Initializer->getBeginLoc();
4850
4851 // Perform overload resolution. If it fails, return the failed result.
4854 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4855 return Result;
4856
4857 FunctionDecl *Function = Best->Function;
4858 // This is the overload that will be used for this initialization step if we
4859 // use this initialization. Mark it as referenced.
4860 Function->setReferenced();
4861
4862 // Compute the returned type and value kind of the conversion.
4863 QualType cv3T3;
4864 if (isa<CXXConversionDecl>(Function))
4865 cv3T3 = Function->getReturnType();
4866 else
4867 cv3T3 = T1;
4868
4870 if (cv3T3->isLValueReferenceType())
4871 VK = VK_LValue;
4872 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4873 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4874 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4875
4876 // Add the user-defined conversion step.
4877 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4878 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4879 HadMultipleCandidates);
4880
4881 // Determine whether we'll need to perform derived-to-base adjustments or
4882 // other conversions.
4884 Sema::ReferenceCompareResult NewRefRelationship =
4885 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4886
4887 // Add the final conversion sequence, if necessary.
4888 if (NewRefRelationship == Sema::Ref_Incompatible) {
4889 assert(!isa<CXXConstructorDecl>(Function) &&
4890 "should not have conversion after constructor");
4891
4893 ICS.setStandard();
4894 ICS.Standard = Best->FinalConversion;
4895 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4896
4897 // Every implicit conversion results in a prvalue, except for a glvalue
4898 // derived-to-base conversion, which we handle below.
4899 cv3T3 = ICS.Standard.getToType(2);
4900 VK = VK_PRValue;
4901 }
4902
4903 // If the converted initializer is a prvalue, its type T4 is adjusted to
4904 // type "cv1 T4" and the temporary materialization conversion is applied.
4905 //
4906 // We adjust the cv-qualifications to match the reference regardless of
4907 // whether we have a prvalue so that the AST records the change. In this
4908 // case, T4 is "cv3 T3".
4909 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4910 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4911 Sequence.AddQualificationConversionStep(cv1T4, VK);
4912 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4913 VK = IsLValueRef ? VK_LValue : VK_XValue;
4914
4915 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4916 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4917 else if (RefConv & Sema::ReferenceConversions::ObjC)
4918 Sequence.AddObjCObjectConversionStep(cv1T1);
4919 else if (RefConv & Sema::ReferenceConversions::Function)
4920 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4921 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4922 if (!S.Context.hasSameType(cv1T4, cv1T1))
4923 Sequence.AddQualificationConversionStep(cv1T1, VK);
4924 }
4925
4926 return OR_Success;
4927}
4928
4930 const InitializedEntity &Entity,
4931 Expr *CurInitExpr);
4932
4933/// Attempt reference initialization (C++0x [dcl.init.ref])
4935 const InitializationKind &Kind,
4937 InitializationSequence &Sequence,
4938 bool TopLevelOfInitList) {
4939 QualType DestType = Entity.getType();
4940 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4941 Qualifiers T1Quals;
4942 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4944 Qualifiers T2Quals;
4945 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4946
4947 // If the initializer is the address of an overloaded function, try
4948 // to resolve the overloaded function. If all goes well, T2 is the
4949 // type of the resulting function.
4951 T1, Sequence))
4952 return;
4953
4954 // Delegate everything else to a subfunction.
4955 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4956 T1Quals, cv2T2, T2, T2Quals, Sequence,
4957 TopLevelOfInitList);
4958}
4959
4960/// Determine whether an expression is a non-referenceable glvalue (one to
4961/// which a reference can never bind). Attempting to bind a reference to
4962/// such a glvalue will always create a temporary.
4964 return E->refersToBitField() || E->refersToVectorElement() ||
4966}
4967
4968/// Reference initialization without resolving overloaded functions.
4969///
4970/// We also can get here in C if we call a builtin which is declared as
4971/// a function with a parameter of reference type (such as __builtin_va_end()).
4973 const InitializedEntity &Entity,
4974 const InitializationKind &Kind,
4976 QualType cv1T1, QualType T1,
4977 Qualifiers T1Quals,
4978 QualType cv2T2, QualType T2,
4979 Qualifiers T2Quals,
4980 InitializationSequence &Sequence,
4981 bool TopLevelOfInitList) {
4982 QualType DestType = Entity.getType();
4983 SourceLocation DeclLoc = Initializer->getBeginLoc();
4984
4985 // Compute some basic properties of the types and the initializer.
4986 bool isLValueRef = DestType->isLValueReferenceType();
4987 bool isRValueRef = !isLValueRef;
4988 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4989
4991 Sema::ReferenceCompareResult RefRelationship =
4992 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4993
4994 // C++0x [dcl.init.ref]p5:
4995 // A reference to type "cv1 T1" is initialized by an expression of type
4996 // "cv2 T2" as follows:
4997 //
4998 // - If the reference is an lvalue reference and the initializer
4999 // expression
5000 // Note the analogous bullet points for rvalue refs to functions. Because
5001 // there are no function rvalues in C++, rvalue refs to functions are treated
5002 // like lvalue refs.
5003 OverloadingResult ConvOvlResult = OR_Success;
5004 bool T1Function = T1->isFunctionType();
5005 if (isLValueRef || T1Function) {
5006 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5007 (RefRelationship == Sema::Ref_Compatible ||
5008 (Kind.isCStyleOrFunctionalCast() &&
5009 RefRelationship == Sema::Ref_Related))) {
5010 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5011 // reference-compatible with "cv2 T2," or
5012 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5013 Sema::ReferenceConversions::ObjC)) {
5014 // If we're converting the pointee, add any qualifiers first;
5015 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5016 if (RefConv & (Sema::ReferenceConversions::Qualification))
5018 S.Context.getQualifiedType(T2, T1Quals),
5019 Initializer->getValueKind());
5020 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5021 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5022 else
5023 Sequence.AddObjCObjectConversionStep(cv1T1);
5024 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5025 // Perform a (possibly multi-level) qualification conversion.
5026 Sequence.AddQualificationConversionStep(cv1T1,
5027 Initializer->getValueKind());
5028 } else if (RefConv & Sema::ReferenceConversions::Function) {
5029 Sequence.AddFunctionReferenceConversionStep(cv1T1);
<