clang 23.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
13#include "CheckExprLifetime.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeBase.h"
21#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/Lookup.h"
31#include "clang/Sema/SemaHLSL.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/PointerIntPair.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// Sema Initialization Checking
47//===----------------------------------------------------------------------===//
48
49/// Check whether T is compatible with a wide character type (wchar_t,
50/// char16_t or char32_t).
51static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
52 if (Context.typesAreCompatible(Context.getWideCharType(), T))
53 return true;
54 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
55 return Context.typesAreCompatible(Context.Char16Ty, T) ||
56 Context.typesAreCompatible(Context.Char32Ty, T);
57 }
58 return false;
59}
60
70
71/// Check whether the array of type AT can be initialized by the Init
72/// expression by means of string initialization. Returns SIF_None if so,
73/// otherwise returns a StringInitFailureKind that describes why the
74/// initialization would not work.
76 ASTContext &Context) {
78 return SIF_Other;
79
80 // See if this is a string literal or @encode.
81 Init = Init->IgnoreParens();
82
83 // Handle @encode, which is a narrow string.
85 return SIF_None;
86
87 // Otherwise we can only handle string literals.
88 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
89 if (!SL)
90 return SIF_Other;
91
92 const QualType ElemTy =
94
95 auto IsCharOrUnsignedChar = [](const QualType &T) {
96 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
97 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
98 };
99
100 switch (SL->getKind()) {
102 // char8_t array can be initialized with a UTF-8 string.
103 // - C++20 [dcl.init.string] (DR)
104 // Additionally, an array of char or unsigned char may be initialized
105 // by a UTF-8 string literal.
106 if (ElemTy->isChar8Type() ||
107 (Context.getLangOpts().Char8 &&
108 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
109 return SIF_None;
110 [[fallthrough]];
113 // char array can be initialized with a narrow string.
114 // Only allow char x[] = "foo"; not char x[] = L"foo";
115 if (ElemTy->isCharType())
116 return (SL->getKind() == StringLiteralKind::UTF8 &&
117 Context.getLangOpts().Char8)
119 : SIF_None;
120 if (ElemTy->isChar8Type())
122 if (IsWideCharCompatible(ElemTy, Context))
124 return SIF_Other;
125 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
126 // "An array with element type compatible with a qualified or unqualified
127 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
128 // string literal with the corresponding encoding prefix (L, u, or U,
129 // respectively), optionally enclosed in braces.
131 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
132 return SIF_None;
133 if (ElemTy->isCharType() || ElemTy->isChar8Type())
135 if (IsWideCharCompatible(ElemTy, Context))
137 return SIF_Other;
139 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
140 return SIF_None;
141 if (ElemTy->isCharType() || ElemTy->isChar8Type())
143 if (IsWideCharCompatible(ElemTy, Context))
145 return SIF_Other;
147 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
148 return SIF_None;
149 if (ElemTy->isCharType() || ElemTy->isChar8Type())
151 if (IsWideCharCompatible(ElemTy, Context))
153 return SIF_Other;
155 assert(false && "Unevaluated string literal in initialization");
156 break;
157 }
158
159 llvm_unreachable("missed a StringLiteral kind?");
160}
161
163 ASTContext &Context) {
164 const ArrayType *arrayType = Context.getAsArrayType(declType);
165 if (!arrayType)
166 return SIF_Other;
167 return IsStringInit(init, arrayType, Context);
168}
169
171 return ::IsStringInit(Init, AT, Context) == SIF_None;
172}
173
174/// Update the type of a string literal, including any surrounding parentheses,
175/// to match the type of the object which it is initializing.
177 while (true) {
178 E->setType(Ty);
181 break;
183 }
184}
185
186/// Fix a compound literal initializing an array so it's correctly marked
187/// as an rvalue.
189 while (true) {
192 break;
194 }
195}
196
198 Decl *D = Entity.getDecl();
199 const InitializedEntity *Parent = &Entity;
200
201 while (Parent) {
202 D = Parent->getDecl();
203 Parent = Parent->getParent();
204 }
205
206 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
207 return true;
208
209 return false;
210}
211
213 Sema &SemaRef, QualType &TT);
214
215static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
216 Sema &S, const InitializedEntity &Entity,
217 bool CheckC23ConstexprInit = false) {
218 // Get the length of the string as parsed.
219 auto *ConstantArrayTy =
221 uint64_t StrLength = ConstantArrayTy->getZExtSize();
222
223 if (CheckC23ConstexprInit)
224 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
226
227 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
228 // C99 6.7.8p14. We have an array of character type with unknown size
229 // being initialized to a string literal.
230 llvm::APInt ConstVal(32, StrLength);
231 // Return a new array type (C99 6.7.8p22).
233 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
234 updateStringLiteralType(Str, DeclT);
235 return;
236 }
237
239 uint64_t ArrayLen = CAT->getZExtSize();
240
241 // We have an array of character type with known size. However,
242 // the size may be smaller or larger than the string we are initializing.
243 // FIXME: Avoid truncation for 64-bit length strings.
244 if (S.getLangOpts().CPlusPlus) {
245 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
246 // For Pascal strings it's OK to strip off the terminating null character,
247 // so the example below is valid:
248 //
249 // unsigned char a[2] = "\pa";
250 if (SL->isPascal())
251 StrLength--;
252 }
253
254 // [dcl.init.string]p2
255 if (StrLength > ArrayLen)
256 S.Diag(Str->getBeginLoc(),
257 diag::err_initializer_string_for_char_array_too_long)
258 << ArrayLen << StrLength << Str->getSourceRange();
259 } else {
260 // C99 6.7.8p14.
261 if (StrLength - 1 > ArrayLen)
262 S.Diag(Str->getBeginLoc(),
263 diag::ext_initializer_string_for_char_array_too_long)
264 << Str->getSourceRange();
265 else if (StrLength - 1 == ArrayLen) {
266 // In C, if the string literal is null-terminated explicitly, e.g., `char
267 // a[4] = "ABC\0"`, there should be no warning:
268 const auto *SL = dyn_cast<StringLiteral>(Str->IgnoreParens());
269 bool IsSLSafe = SL && SL->getLength() > 0 &&
270 SL->getCodeUnit(SL->getLength() - 1) == 0;
271
272 if (!IsSLSafe) {
273 // If the entity being initialized has the nonstring attribute, then
274 // silence the "missing nonstring" diagnostic. If there's no entity,
275 // check whether we're initializing an array of arrays; if so, walk the
276 // parents to find an entity.
277 auto FindCorrectEntity =
278 [](const InitializedEntity *Entity) -> const ValueDecl * {
279 while (Entity) {
280 if (const ValueDecl *VD = Entity->getDecl())
281 return VD;
282 if (!Entity->getType()->isArrayType())
283 return nullptr;
284 Entity = Entity->getParent();
285 }
286
287 return nullptr;
288 };
289 if (const ValueDecl *D = FindCorrectEntity(&Entity);
290 !D || !D->hasAttr<NonStringAttr>())
291 S.Diag(
292 Str->getBeginLoc(),
293 diag::
294 warn_initializer_string_for_char_array_too_long_no_nonstring)
295 << ArrayLen << StrLength << Str->getSourceRange();
296 }
297 // Always emit the C++ compatibility diagnostic.
298 S.Diag(Str->getBeginLoc(),
299 diag::warn_initializer_string_for_char_array_too_long_for_cpp)
300 << ArrayLen << StrLength << Str->getSourceRange();
301 }
302 }
303
304 // Set the type to the actual size that we are initializing. If we have
305 // something like:
306 // char x[1] = "foo";
307 // then this will set the string literal's type to char[1].
308 updateStringLiteralType(Str, DeclT);
309}
310
312 for (const FieldDecl *Field : R->fields()) {
313 if (Field->hasAttr<ExplicitInitAttr>())
314 S.Diag(Field->getLocation(), diag::note_entity_declared_at) << Field;
315 }
316}
317
318//===----------------------------------------------------------------------===//
319// Semantic checking for initializer lists.
320//===----------------------------------------------------------------------===//
321
322namespace {
323
324/// Semantic checking for initializer lists.
325///
326/// The InitListChecker class contains a set of routines that each
327/// handle the initialization of a certain kind of entity, e.g.,
328/// arrays, vectors, struct/union types, scalars, etc. The
329/// InitListChecker itself performs a recursive walk of the subobject
330/// structure of the type to be initialized, while stepping through
331/// the initializer list one element at a time. The IList and Index
332/// parameters to each of the Check* routines contain the active
333/// (syntactic) initializer list and the index into that initializer
334/// list that represents the current initializer. Each routine is
335/// responsible for moving that Index forward as it consumes elements.
336///
337/// Each Check* routine also has a StructuredList/StructuredIndex
338/// arguments, which contains the current "structured" (semantic)
339/// initializer list and the index into that initializer list where we
340/// are copying initializers as we map them over to the semantic
341/// list. Once we have completed our recursive walk of the subobject
342/// structure, we will have constructed a full semantic initializer
343/// list.
344///
345/// C99 designators cause changes in the initializer list traversal,
346/// because they make the initialization "jump" into a specific
347/// subobject and then continue the initialization from that
348/// point. CheckDesignatedInitializer() recursively steps into the
349/// designated subobject and manages backing out the recursion to
350/// initialize the subobjects after the one designated.
351///
352/// If an initializer list contains any designators, we build a placeholder
353/// structured list even in 'verify only' mode, so that we can track which
354/// elements need 'empty' initializtion.
355class InitListChecker {
356 Sema &SemaRef;
357 bool hadError = false;
358 bool VerifyOnly; // No diagnostics.
359 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
360 bool InOverloadResolution;
361 InitListExpr *FullyStructuredList = nullptr;
362 NoInitExpr *DummyExpr = nullptr;
363 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
364 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
365 unsigned CurEmbedIndex = 0;
366
367 NoInitExpr *getDummyInit() {
368 if (!DummyExpr)
369 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
370 return DummyExpr;
371 }
372
373 void CheckImplicitInitList(const InitializedEntity &Entity,
374 InitListExpr *ParentIList, QualType T,
375 unsigned &Index, InitListExpr *StructuredList,
376 unsigned &StructuredIndex);
377 void CheckExplicitInitList(const InitializedEntity &Entity,
378 InitListExpr *IList, QualType &T,
379 InitListExpr *StructuredList,
380 bool TopLevelObject = false);
381 void CheckListElementTypes(const InitializedEntity &Entity,
382 InitListExpr *IList, QualType &DeclType,
383 bool SubobjectIsDesignatorContext,
384 unsigned &Index,
385 InitListExpr *StructuredList,
386 unsigned &StructuredIndex,
387 bool TopLevelObject = false);
388 void CheckSubElementType(const InitializedEntity &Entity,
389 InitListExpr *IList, QualType ElemType,
390 unsigned &Index,
391 InitListExpr *StructuredList,
392 unsigned &StructuredIndex,
393 bool DirectlyDesignated = false);
394 void CheckComplexType(const InitializedEntity &Entity,
395 InitListExpr *IList, QualType DeclType,
396 unsigned &Index,
397 InitListExpr *StructuredList,
398 unsigned &StructuredIndex);
399 void CheckScalarType(const InitializedEntity &Entity,
400 InitListExpr *IList, QualType DeclType,
401 unsigned &Index,
402 InitListExpr *StructuredList,
403 unsigned &StructuredIndex);
404 void CheckReferenceType(const InitializedEntity &Entity,
405 InitListExpr *IList, QualType DeclType,
406 unsigned &Index,
407 InitListExpr *StructuredList,
408 unsigned &StructuredIndex);
409 void CheckMatrixType(const InitializedEntity &Entity, InitListExpr *IList,
410 QualType DeclType, unsigned &Index,
411 InitListExpr *StructuredList, unsigned &StructuredIndex);
412 void CheckVectorType(const InitializedEntity &Entity,
413 InitListExpr *IList, QualType DeclType, unsigned &Index,
414 InitListExpr *StructuredList,
415 unsigned &StructuredIndex);
416 void CheckStructUnionTypes(const InitializedEntity &Entity,
417 InitListExpr *IList, QualType DeclType,
420 bool SubobjectIsDesignatorContext, unsigned &Index,
421 InitListExpr *StructuredList,
422 unsigned &StructuredIndex,
423 bool TopLevelObject = false);
424 void CheckArrayType(const InitializedEntity &Entity,
425 InitListExpr *IList, QualType &DeclType,
426 llvm::APSInt elementIndex,
427 bool SubobjectIsDesignatorContext, unsigned &Index,
428 InitListExpr *StructuredList,
429 unsigned &StructuredIndex);
430 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
431 InitListExpr *IList, DesignatedInitExpr *DIE,
432 unsigned DesigIdx,
433 QualType &CurrentObjectType,
435 llvm::APSInt *NextElementIndex,
436 unsigned &Index,
437 InitListExpr *StructuredList,
438 unsigned &StructuredIndex,
439 bool FinishSubobjectInit,
440 bool TopLevelObject);
441 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
442 QualType CurrentObjectType,
443 InitListExpr *StructuredList,
444 unsigned StructuredIndex,
445 SourceRange InitRange,
446 bool IsFullyOverwritten = false);
447 void UpdateStructuredListElement(InitListExpr *StructuredList,
448 unsigned &StructuredIndex,
449 Expr *expr);
450 InitListExpr *createInitListExpr(QualType CurrentObjectType,
451 SourceRange InitRange,
452 unsigned ExpectedNumInits, bool IsExplicit);
453 int numArrayElements(QualType DeclType);
454 int numStructUnionElements(QualType DeclType);
455
456 ExprResult PerformEmptyInit(SourceLocation Loc,
457 const InitializedEntity &Entity);
458
459 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
460 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
461 bool UnionOverride = false,
462 bool FullyOverwritten = true) {
463 // Overriding an initializer via a designator is valid with C99 designated
464 // initializers, but ill-formed with C++20 designated initializers.
465 unsigned DiagID =
466 SemaRef.getLangOpts().CPlusPlus
467 ? (UnionOverride ? diag::ext_initializer_union_overrides
468 : diag::ext_initializer_overrides)
469 : diag::warn_initializer_overrides;
470
471 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
472 // In overload resolution, we have to strictly enforce the rules, and so
473 // don't allow any overriding of prior initializers. This matters for a
474 // case such as:
475 //
476 // union U { int a, b; };
477 // struct S { int a, b; };
478 // void f(U), f(S);
479 //
480 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
481 // consistency, we disallow all overriding of prior initializers in
482 // overload resolution, not only overriding of union members.
483 hadError = true;
484 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
485 // If we'll be keeping around the old initializer but overwriting part of
486 // the object it initialized, and that object is not trivially
487 // destructible, this can leak. Don't allow that, not even as an
488 // extension.
489 //
490 // FIXME: It might be reasonable to allow this in cases where the part of
491 // the initializer that we're overriding has trivial destruction.
492 DiagID = diag::err_initializer_overrides_destructed;
493 } else if (!OldInit->getSourceRange().isValid()) {
494 // We need to check on source range validity because the previous
495 // initializer does not have to be an explicit initializer. e.g.,
496 //
497 // struct P { int a, b; };
498 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
499 //
500 // There is an overwrite taking place because the first braced initializer
501 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
502 //
503 // Such overwrites are harmless, so we don't diagnose them. (Note that in
504 // C++, this cannot be reached unless we've already seen and diagnosed a
505 // different conformance issue, such as a mixture of designated and
506 // non-designated initializers or a multi-level designator.)
507 return;
508 }
509
510 if (!VerifyOnly) {
511 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
512 << NewInitRange << FullyOverwritten << OldInit->getType();
513 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
514 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
515 << OldInit->getSourceRange();
516 }
517 }
518
519 // Explanation on the "FillWithNoInit" mode:
520 //
521 // Assume we have the following definitions (Case#1):
522 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
523 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
524 //
525 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
526 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
527 //
528 // But if we have (Case#2):
529 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
530 //
531 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
532 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
533 //
534 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
535 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
536 // initializers but with special "NoInitExpr" place holders, which tells the
537 // CodeGen not to generate any initializers for these parts.
538 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
539 const InitializedEntity &ParentEntity,
540 InitListExpr *ILE, bool &RequiresSecondPass,
541 bool FillWithNoInit);
542 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
543 const InitializedEntity &ParentEntity,
544 InitListExpr *ILE, bool &RequiresSecondPass,
545 bool FillWithNoInit = false);
546 void FillInEmptyInitializations(const InitializedEntity &Entity,
547 InitListExpr *ILE, bool &RequiresSecondPass,
548 InitListExpr *OuterILE, unsigned OuterIndex,
549 bool FillWithNoInit = false);
550 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
551 Expr *InitExpr, FieldDecl *Field,
552 bool TopLevelObject);
553 void CheckEmptyInitializable(const InitializedEntity &Entity,
554 SourceLocation Loc);
555
556 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
557 Expr *Result = nullptr;
558 // Undrestand which part of embed we'd like to reference.
559 if (!CurEmbed) {
560 CurEmbed = Embed;
561 CurEmbedIndex = 0;
562 }
563 // Reference just one if we're initializing a single scalar.
564 uint64_t ElsCount = 1;
565 // Otherwise try to fill whole array with embed data.
567 unsigned ArrIndex = Entity.getElementIndex();
568 auto *AType =
569 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
570 assert(AType && "expected array type when initializing array");
571 ElsCount = Embed->getDataElementCount();
572 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
573 ElsCount = std::min(CAType->getSize().getZExtValue() - ArrIndex,
574 ElsCount - CurEmbedIndex);
575 if (ElsCount == Embed->getDataElementCount()) {
576 CurEmbed = nullptr;
577 CurEmbedIndex = 0;
578 return Embed;
579 }
580 }
581
582 Result = new (SemaRef.Context)
583 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
584 CurEmbedIndex, ElsCount);
585 CurEmbedIndex += ElsCount;
586 if (CurEmbedIndex >= Embed->getDataElementCount()) {
587 CurEmbed = nullptr;
588 CurEmbedIndex = 0;
589 }
590 return Result;
591 }
592
593public:
594 InitListChecker(
595 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
596 bool VerifyOnly, bool TreatUnavailableAsInvalid,
597 bool InOverloadResolution = false,
598 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
599 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
600 QualType &T,
601 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
602 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
603 /*TreatUnavailableAsInvalid=*/false,
604 /*InOverloadResolution=*/false,
605 &AggrDeductionCandidateParamTypes) {}
606
607 bool HadError() { return hadError; }
608
609 // Retrieves the fully-structured initializer list used for
610 // semantic analysis and code generation.
611 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
612};
613
614} // end anonymous namespace
615
616ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
617 const InitializedEntity &Entity) {
619 true);
620 MultiExprArg SubInit;
621 Expr *InitExpr;
622 InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc,
623 /*isExplicit=*/false);
624
625 // C++ [dcl.init.aggr]p7:
626 // If there are fewer initializer-clauses in the list than there are
627 // members in the aggregate, then each member not explicitly initialized
628 // ...
629 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
631 if (EmptyInitList) {
632 // C++1y / DR1070:
633 // shall be initialized [...] from an empty initializer list.
634 //
635 // We apply the resolution of this DR to C++11 but not C++98, since C++98
636 // does not have useful semantics for initialization from an init list.
637 // We treat this as copy-initialization, because aggregate initialization
638 // always performs copy-initialization on its elements.
639 //
640 // Only do this if we're initializing a class type, to avoid filling in
641 // the initializer list where possible.
642 InitExpr = VerifyOnly ? &DummyInitList
643 : new (SemaRef.Context)
644 InitListExpr(SemaRef.Context, Loc, {}, Loc,
645 /*isExplicit=*/false);
646 InitExpr->setType(SemaRef.Context.VoidTy);
647 SubInit = InitExpr;
649 } else {
650 // C++03:
651 // shall be value-initialized.
652 }
653
654 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
655 // HACK: libstdc++ prior to 4.9 marks the vector default constructor
656 // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic
657 // in that case. stlport does so too.
658 // Look for std::__debug for libstdc++, and for std:: for stlport.
659 // This is effectively a compiler-side implementation of LWG2193.
660 if (!InitSeq && EmptyInitList &&
661 InitSeq.getFailureKind() ==
663 SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(2014'04'22)) {
666 InitSeq.getFailedCandidateSet()
667 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
668 (void)O;
669 assert(O == OR_Success && "Inconsistent overload resolution");
670 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
671 CXXRecordDecl *R = CtorDecl->getParent();
672
673 if (CtorDecl->getMinRequiredArguments() == 0 &&
674 CtorDecl->isExplicit() && R->getDeclName() &&
675 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
676 bool IsInStd = false;
677 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
678 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
680 IsInStd = true;
681 }
682
683 if (IsInStd &&
684 llvm::StringSwitch<bool>(R->getName())
685 .Cases({"basic_string", "deque", "forward_list"}, true)
686 .Cases({"list", "map", "multimap", "multiset"}, true)
687 .Cases({"priority_queue", "queue", "set", "stack"}, true)
688 .Cases({"unordered_map", "unordered_set", "vector"}, true)
689 .Default(false)) {
690 InitSeq.InitializeFrom(
691 SemaRef, Entity,
692 InitializationKind::CreateValue(Loc, Loc, Loc, true),
693 MultiExprArg(), /*TopLevelOfInitList=*/false,
694 TreatUnavailableAsInvalid);
695 // Emit a warning for this. System header warnings aren't shown
696 // by default, but people working on system headers should see it.
697 if (!VerifyOnly) {
698 SemaRef.Diag(CtorDecl->getLocation(),
699 diag::warn_invalid_initializer_from_system_header);
701 SemaRef.Diag(Entity.getDecl()->getLocation(),
702 diag::note_used_in_initialization_here);
703 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
704 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
705 }
706 }
707 }
708 }
709 if (!InitSeq) {
710 if (!VerifyOnly) {
711 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
713 SemaRef.Diag(Entity.getDecl()->getLocation(),
714 diag::note_in_omitted_aggregate_initializer)
715 << /*field*/1 << Entity.getDecl();
716 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
717 bool IsTrailingArrayNewMember =
718 Entity.getParent() &&
720 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
721 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
722 << Entity.getElementIndex();
723 }
724 }
725 hadError = true;
726 return ExprError();
727 }
728
729 return VerifyOnly ? ExprResult()
730 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
731}
732
733void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
734 SourceLocation Loc) {
735 // If we're building a fully-structured list, we'll check this at the end
736 // once we know which elements are actually initialized. Otherwise, we know
737 // that there are no designators so we can just check now.
738 if (FullyStructuredList)
739 return;
740 PerformEmptyInit(Loc, Entity);
741}
742
743void InitListChecker::FillInEmptyInitForBase(
744 unsigned Init, const CXXBaseSpecifier &Base,
745 const InitializedEntity &ParentEntity, InitListExpr *ILE,
746 bool &RequiresSecondPass, bool FillWithNoInit) {
748 SemaRef.Context, &Base, false, &ParentEntity);
749
750 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
751 ExprResult BaseInit = FillWithNoInit
752 ? new (SemaRef.Context) NoInitExpr(Base.getType())
753 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
754 if (BaseInit.isInvalid()) {
755 hadError = true;
756 return;
757 }
758
759 if (!VerifyOnly) {
760 assert(Init < ILE->getNumInits() && "should have been expanded");
761 ILE->setInit(Init, BaseInit.getAs<Expr>());
762 }
763 } else if (InitListExpr *InnerILE =
764 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
765 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
766 ILE, Init, FillWithNoInit);
767 } else if (DesignatedInitUpdateExpr *InnerDIUE =
768 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
769 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
770 RequiresSecondPass, ILE, Init,
771 /*FillWithNoInit =*/true);
772 }
773}
774
775void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
776 const InitializedEntity &ParentEntity,
777 InitListExpr *ILE,
778 bool &RequiresSecondPass,
779 bool FillWithNoInit) {
780 SourceLocation Loc = ILE->getEndLoc();
781 unsigned NumInits = ILE->getNumInits();
782 InitializedEntity MemberEntity
783 = InitializedEntity::InitializeMember(Field, &ParentEntity);
784
785 if (Init >= NumInits || !ILE->getInit(Init)) {
786 if (const RecordType *RType = ILE->getType()->getAsCanonical<RecordType>())
787 if (!RType->getDecl()->isUnion())
788 assert((Init < NumInits || VerifyOnly) &&
789 "This ILE should have been expanded");
790
791 if (FillWithNoInit) {
792 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
793 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
794 if (Init < NumInits)
795 ILE->setInit(Init, Filler);
796 else
797 ILE->updateInit(SemaRef.Context, Init, Filler);
798 return;
799 }
800
801 if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() &&
802 !SemaRef.isUnevaluatedContext()) {
803 SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init)
804 << /* Var-in-Record */ 0 << Field;
805 SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at)
806 << Field;
807 }
808
809 // C++1y [dcl.init.aggr]p7:
810 // If there are fewer initializer-clauses in the list than there are
811 // members in the aggregate, then each member not explicitly initialized
812 // shall be initialized from its brace-or-equal-initializer [...]
813 if (Field->hasInClassInitializer()) {
814 if (VerifyOnly)
815 return;
816
817 ExprResult DIE;
818 {
819 // Enter a default initializer rebuild context, then we can support
820 // lifetime extension of temporary created by aggregate initialization
821 // using a default member initializer.
822 // CWG1815 (https://wg21.link/CWG1815).
823 EnterExpressionEvaluationContext RebuildDefaultInit(
826 true;
832 DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
833 }
834 if (DIE.isInvalid()) {
835 hadError = true;
836 return;
837 }
838 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
839 if (Init < NumInits)
840 ILE->setInit(Init, DIE.get());
841 else {
842 ILE->updateInit(SemaRef.Context, Init, DIE.get());
843 RequiresSecondPass = true;
844 }
845 return;
846 }
847
848 if (Field->getType()->isReferenceType()) {
849 if (!VerifyOnly) {
850 // C++ [dcl.init.aggr]p9:
851 // If an incomplete or empty initializer-list leaves a
852 // member of reference type uninitialized, the program is
853 // ill-formed.
854 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
855 << Field->getType()
856 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
857 ->getSourceRange();
858 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
859 }
860 hadError = true;
861 return;
862 }
863
864 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
865 if (MemberInit.isInvalid()) {
866 hadError = true;
867 return;
868 }
869
870 if (hadError || VerifyOnly) {
871 // Do nothing
872 } else if (Init < NumInits) {
873 ILE->setInit(Init, MemberInit.getAs<Expr>());
874 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
875 // Empty initialization requires a constructor call, so
876 // extend the initializer list to include the constructor
877 // call and make a note that we'll need to take another pass
878 // through the initializer list.
879 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
880 RequiresSecondPass = true;
881 }
882 } else if (InitListExpr *InnerILE
883 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
884 FillInEmptyInitializations(MemberEntity, InnerILE,
885 RequiresSecondPass, ILE, Init, FillWithNoInit);
886 } else if (DesignatedInitUpdateExpr *InnerDIUE =
887 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
888 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
889 RequiresSecondPass, ILE, Init,
890 /*FillWithNoInit =*/true);
891 }
892}
893
894/// Recursively replaces NULL values within the given initializer list
895/// with expressions that perform value-initialization of the
896/// appropriate type, and finish off the InitListExpr formation.
897void
898InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
899 InitListExpr *ILE,
900 bool &RequiresSecondPass,
901 InitListExpr *OuterILE,
902 unsigned OuterIndex,
903 bool FillWithNoInit) {
904 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
905 "Should not have void type");
906
907 // We don't need to do any checks when just filling NoInitExprs; that can't
908 // fail.
909 if (FillWithNoInit && VerifyOnly)
910 return;
911
912 // If this is a nested initializer list, we might have changed its contents
913 // (and therefore some of its properties, such as instantiation-dependence)
914 // while filling it in. Inform the outer initializer list so that its state
915 // can be updated to match.
916 // FIXME: We should fully build the inner initializers before constructing
917 // the outer InitListExpr instead of mutating AST nodes after they have
918 // been used as subexpressions of other nodes.
919 struct UpdateOuterILEWithUpdatedInit {
920 InitListExpr *Outer;
921 unsigned OuterIndex;
922 ~UpdateOuterILEWithUpdatedInit() {
923 if (Outer)
924 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
925 }
926 } UpdateOuterRAII = {OuterILE, OuterIndex};
927
928 // A transparent ILE is not performing aggregate initialization and should
929 // not be filled in.
930 if (ILE->isTransparent())
931 return;
932
933 if (const auto *RDecl = ILE->getType()->getAsRecordDecl()) {
934 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
935 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
936 RequiresSecondPass, FillWithNoInit);
937 } else {
938 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
939 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
940 "We should have computed initialized fields already");
941 // The fields beyond ILE->getNumInits() are default initialized, so in
942 // order to leave them uninitialized, the ILE is expanded and the extra
943 // fields are then filled with NoInitExpr.
944 unsigned NumElems = numStructUnionElements(ILE->getType());
945 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
946 ++NumElems;
947 if (!VerifyOnly && ILE->getNumInits() < NumElems)
948 ILE->resizeInits(SemaRef.Context, NumElems);
949
950 unsigned Init = 0;
951
952 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
953 for (auto &Base : CXXRD->bases()) {
954 if (hadError)
955 return;
956
957 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
958 FillWithNoInit);
959 ++Init;
960 }
961 }
962
963 for (auto *Field : RDecl->fields()) {
964 if (Field->isUnnamedBitField())
965 continue;
966
967 if (hadError)
968 return;
969
970 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
971 FillWithNoInit);
972 if (hadError)
973 return;
974
975 ++Init;
976
977 // Only look at the first initialization of a union.
978 if (RDecl->isUnion())
979 break;
980 }
981 }
982
983 return;
984 }
985
986 QualType ElementType;
987
988 InitializedEntity ElementEntity = Entity;
989 unsigned NumInits = ILE->getNumInits();
990 uint64_t NumElements = NumInits;
991 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
992 ElementType = AType->getElementType();
993 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
994 NumElements = CAType->getZExtSize();
995 // For an array new with an unknown bound, ask for one additional element
996 // in order to populate the array filler.
997 if (Entity.isVariableLengthArrayNew())
998 ++NumElements;
999 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
1000 0, Entity);
1001 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
1002 ElementType = VType->getElementType();
1003 NumElements = VType->getNumElements();
1004 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
1005 0, Entity);
1006 } else
1007 ElementType = ILE->getType();
1008
1009 bool SkipEmptyInitChecks = false;
1010 for (uint64_t Init = 0; Init != NumElements; ++Init) {
1011 if (hadError)
1012 return;
1013
1014 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
1015 ElementEntity.getKind() == InitializedEntity::EK_VectorElement ||
1017 ElementEntity.setElementIndex(Init);
1018
1019 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
1020 return;
1021
1022 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
1023 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1024 ILE->setInit(Init, ILE->getArrayFiller());
1025 else if (!InitExpr && !ILE->hasArrayFiller()) {
1026 // In VerifyOnly mode, there's no point performing empty initialization
1027 // more than once.
1028 if (SkipEmptyInitChecks)
1029 continue;
1030
1031 Expr *Filler = nullptr;
1032
1033 if (FillWithNoInit)
1034 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
1035 else {
1036 ExprResult ElementInit =
1037 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
1038 if (ElementInit.isInvalid()) {
1039 hadError = true;
1040 return;
1041 }
1042
1043 Filler = ElementInit.getAs<Expr>();
1044 }
1045
1046 if (hadError) {
1047 // Do nothing
1048 } else if (VerifyOnly) {
1049 SkipEmptyInitChecks = true;
1050 } else if (Init < NumInits) {
1051 // For arrays, just set the expression used for value-initialization
1052 // of the "holes" in the array.
1053 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
1054 ILE->setArrayFiller(Filler);
1055 else
1056 ILE->setInit(Init, Filler);
1057 } else {
1058 // For arrays, just set the expression used for value-initialization
1059 // of the rest of elements and exit.
1060 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
1061 ILE->setArrayFiller(Filler);
1062 return;
1063 }
1064
1065 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
1066 // Empty initialization requires a constructor call, so
1067 // extend the initializer list to include the constructor
1068 // call and make a note that we'll need to take another pass
1069 // through the initializer list.
1070 ILE->updateInit(SemaRef.Context, Init, Filler);
1071 RequiresSecondPass = true;
1072 }
1073 }
1074 } else if (InitListExpr *InnerILE
1075 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
1076 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
1077 ILE, Init, FillWithNoInit);
1078 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1079 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1080 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1081 RequiresSecondPass, ILE, Init,
1082 /*FillWithNoInit =*/true);
1083 }
1084 }
1085}
1086
1087static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1088 for (const Stmt *Init : *IL)
1089 if (isa_and_nonnull<DesignatedInitExpr>(Init))
1090 return true;
1091 return false;
1092}
1093
1094InitListChecker::InitListChecker(
1095 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1096 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1097 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1098 : SemaRef(S), VerifyOnly(VerifyOnly),
1099 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1100 InOverloadResolution(InOverloadResolution),
1101 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1102 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1103 FullyStructuredList = createInitListExpr(
1104 T, IL->getSourceRange(), IL->getNumInits(), IL->isExplicit());
1105
1106 // FIXME: Check that IL isn't already the semantic form of some other
1107 // InitListExpr. If it is, we'd create a broken AST.
1108 if (!VerifyOnly)
1109 FullyStructuredList->setSyntacticForm(IL);
1110 }
1111
1112 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1113 /*TopLevelObject=*/true);
1114
1115 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1116 bool RequiresSecondPass = false;
1117 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1118 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1119 if (RequiresSecondPass && !hadError)
1120 FillInEmptyInitializations(Entity, FullyStructuredList,
1121 RequiresSecondPass, nullptr, 0);
1122 }
1123 if (hadError && FullyStructuredList)
1124 FullyStructuredList->markError();
1125}
1126
1127int InitListChecker::numArrayElements(QualType DeclType) {
1128 // FIXME: use a proper constant
1129 int maxElements = 0x7FFFFFFF;
1130 if (const ConstantArrayType *CAT =
1131 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1132 maxElements = static_cast<int>(CAT->getZExtSize());
1133 }
1134 return maxElements;
1135}
1136
1137int InitListChecker::numStructUnionElements(QualType DeclType) {
1138 auto *structDecl = DeclType->castAsRecordDecl();
1139 int InitializableMembers = 0;
1140 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1141 InitializableMembers += CXXRD->getNumBases();
1142 for (const auto *Field : structDecl->fields())
1143 if (!Field->isUnnamedBitField())
1144 ++InitializableMembers;
1145
1146 if (structDecl->isUnion())
1147 return std::min(InitializableMembers, 1);
1148 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1149}
1150
1151/// Determine whether Entity is an entity for which it is idiomatic to elide
1152/// the braces in aggregate initialization.
1154 // Recursive initialization of the one and only field within an aggregate
1155 // class is considered idiomatic. This case arises in particular for
1156 // initialization of std::array, where the C++ standard suggests the idiom of
1157 //
1158 // std::array<T, N> arr = {1, 2, 3};
1159 //
1160 // (where std::array is an aggregate struct containing a single array field.
1161
1162 if (!Entity.getParent())
1163 return false;
1164
1165 // Allows elide brace initialization for aggregates with empty base.
1166 if (Entity.getKind() == InitializedEntity::EK_Base) {
1167 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1168 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1169 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1170 }
1171
1172 // Allow brace elision if the only subobject is a field.
1173 if (Entity.getKind() == InitializedEntity::EK_Member) {
1174 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1175 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1176 if (CXXRD->getNumBases()) {
1177 return false;
1178 }
1179 }
1180 auto FieldIt = ParentRD->field_begin();
1181 assert(FieldIt != ParentRD->field_end() &&
1182 "no fields but have initializer for member?");
1183 return ++FieldIt == ParentRD->field_end();
1184 }
1185
1186 return false;
1187}
1188
1189/// Check whether the range of the initializer \p ParentIList from element
1190/// \p Index onwards can be used to initialize an object of type \p T. Update
1191/// \p Index to indicate how many elements of the list were consumed.
1192///
1193/// This also fills in \p StructuredList, from element \p StructuredIndex
1194/// onwards, with the fully-braced, desugared form of the initialization.
1195void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1196 InitListExpr *ParentIList,
1197 QualType T, unsigned &Index,
1198 InitListExpr *StructuredList,
1199 unsigned &StructuredIndex) {
1200 int maxElements = 0;
1201
1202 if (T->isArrayType())
1203 maxElements = numArrayElements(T);
1204 else if (T->isRecordType())
1205 maxElements = numStructUnionElements(T);
1206 else if (T->isVectorType())
1207 maxElements = T->castAs<VectorType>()->getNumElements();
1208 else
1209 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1210
1211 if (maxElements == 0) {
1212 if (!VerifyOnly)
1213 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1214 diag::err_implicit_empty_initializer);
1215 ++Index;
1216 hadError = true;
1217 return;
1218 }
1219
1220 // Build a structured initializer list corresponding to this subobject.
1221 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1222 ParentIList, Index, T, StructuredList, StructuredIndex,
1223 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1224 ParentIList->getSourceRange().getEnd()));
1225 unsigned StructuredSubobjectInitIndex = 0;
1226
1227 // Check the element types and build the structural subobject.
1228 unsigned StartIndex = Index;
1229 CheckListElementTypes(Entity, ParentIList, T,
1230 /*SubobjectIsDesignatorContext=*/false, Index,
1231 StructuredSubobjectInitList,
1232 StructuredSubobjectInitIndex);
1233
1234 if (StructuredSubobjectInitList) {
1235 StructuredSubobjectInitList->setType(T);
1236
1237 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1238 // Update the structured sub-object initializer so that it's ending
1239 // range corresponds with the end of the last initializer it used.
1240 if (EndIndex < ParentIList->getNumInits() &&
1241 ParentIList->getInit(EndIndex)) {
1242 SourceLocation EndLoc
1243 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1244 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1245 }
1246
1247 // Complain about missing braces.
1248 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1249 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1251 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1252 diag::warn_missing_braces)
1253 << StructuredSubobjectInitList->getSourceRange()
1255 StructuredSubobjectInitList->getBeginLoc(), "{")
1257 SemaRef.getLocForEndOfToken(
1258 StructuredSubobjectInitList->getEndLoc()),
1259 "}");
1260 }
1261
1262 // Warn if this type won't be an aggregate in future versions of C++.
1263 auto *CXXRD = T->getAsCXXRecordDecl();
1264 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1265 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1266 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1267 << StructuredSubobjectInitList->getSourceRange() << T;
1268 }
1269 }
1270}
1271
1272/// Warn that \p Entity was of scalar type and was initialized by a
1273/// single-element braced initializer list.
1274static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1276 // Don't warn during template instantiation. If the initialization was
1277 // non-dependent, we warned during the initial parse; otherwise, the
1278 // type might not be scalar in some uses of the template.
1280 return;
1281
1282 unsigned DiagID = 0;
1283
1284 switch (Entity.getKind()) {
1294 // Extra braces here are suspicious.
1295 DiagID = diag::warn_braces_around_init;
1296 break;
1297
1299 // Warn on aggregate initialization but not on ctor init list or
1300 // default member initializer.
1301 if (Entity.getParent())
1302 DiagID = diag::warn_braces_around_init;
1303 break;
1304
1307 // No warning, might be direct-list-initialization.
1308 // FIXME: Should we warn for copy-list-initialization in these cases?
1309 break;
1310
1314 // No warning, braces are part of the syntax of the underlying construct.
1315 break;
1316
1318 // No warning, we already warned when initializing the result.
1319 break;
1320
1328 llvm_unreachable("unexpected braced scalar init");
1329 }
1330
1331 if (DiagID) {
1332 S.Diag(Braces.getBegin(), DiagID)
1333 << Entity.getType()->isSizelessBuiltinType() << Braces
1334 << FixItHint::CreateRemoval(Braces.getBegin())
1335 << FixItHint::CreateRemoval(Braces.getEnd());
1336 }
1337}
1338
1339/// Check whether the initializer \p IList (that was written with explicit
1340/// braces) can be used to initialize an object of type \p T.
1341///
1342/// This also fills in \p StructuredList with the fully-braced, desugared
1343/// form of the initialization.
1344void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1345 InitListExpr *IList, QualType &T,
1346 InitListExpr *StructuredList,
1347 bool TopLevelObject) {
1348 unsigned Index = 0, StructuredIndex = 0;
1349 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1350 Index, StructuredList, StructuredIndex, TopLevelObject);
1351 if (StructuredList) {
1352 QualType ExprTy = T;
1353 if (!ExprTy->isArrayType())
1354 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1355 if (!VerifyOnly)
1356 IList->setType(ExprTy);
1357 StructuredList->setType(ExprTy);
1358 }
1359 if (hadError)
1360 return;
1361
1362 // Don't complain for incomplete types, since we'll get an error elsewhere.
1363 if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) {
1364 // We have leftover initializers
1365 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1366 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1367 hadError = ExtraInitsIsError;
1368 if (VerifyOnly) {
1369 return;
1370 } else if (StructuredIndex == 1 &&
1371 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1372 SIF_None) {
1373 unsigned DK =
1374 ExtraInitsIsError
1375 ? diag::err_excess_initializers_in_char_array_initializer
1376 : diag::ext_excess_initializers_in_char_array_initializer;
1377 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1378 << IList->getInit(Index)->getSourceRange();
1379 } else if (T->isSizelessBuiltinType()) {
1380 unsigned DK = ExtraInitsIsError
1381 ? diag::err_excess_initializers_for_sizeless_type
1382 : diag::ext_excess_initializers_for_sizeless_type;
1383 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1384 << T << IList->getInit(Index)->getSourceRange();
1385 } else {
1386 int initKind = T->isArrayType() ? 0
1387 : T->isVectorType() ? 1
1388 : T->isMatrixType() ? 2
1389 : T->isScalarType() ? 3
1390 : T->isUnionType() ? 4
1391 : 5;
1392
1393 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1394 : diag::ext_excess_initializers;
1395 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1396 << initKind << IList->getInit(Index)->getSourceRange();
1397 }
1398 }
1399
1400 if (!VerifyOnly) {
1401 if (T->isScalarType() && IList->getNumInits() == 1 &&
1402 !isa<InitListExpr>(IList->getInit(0)))
1403 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1404
1405 // Warn if this is a class type that won't be an aggregate in future
1406 // versions of C++.
1407 auto *CXXRD = T->getAsCXXRecordDecl();
1408 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1409 // Don't warn if there's an equivalent default constructor that would be
1410 // used instead.
1411 bool HasEquivCtor = false;
1412 if (IList->getNumInits() == 0) {
1413 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1414 HasEquivCtor = CD && !CD->isDeleted();
1415 }
1416
1417 if (!HasEquivCtor) {
1418 SemaRef.Diag(IList->getBeginLoc(),
1419 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1420 << IList->getSourceRange() << T;
1421 }
1422 }
1423 }
1424}
1425
1426void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1427 InitListExpr *IList,
1428 QualType &DeclType,
1429 bool SubobjectIsDesignatorContext,
1430 unsigned &Index,
1431 InitListExpr *StructuredList,
1432 unsigned &StructuredIndex,
1433 bool TopLevelObject) {
1434 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1435 // Explicitly braced initializer for complex type can be real+imaginary
1436 // parts.
1437 CheckComplexType(Entity, IList, DeclType, Index,
1438 StructuredList, StructuredIndex);
1439 } else if (DeclType->isScalarType()) {
1440 CheckScalarType(Entity, IList, DeclType, Index,
1441 StructuredList, StructuredIndex);
1442 } else if (DeclType->isVectorType()) {
1443 CheckVectorType(Entity, IList, DeclType, Index,
1444 StructuredList, StructuredIndex);
1445 } else if (DeclType->isMatrixType()) {
1446 CheckMatrixType(Entity, IList, DeclType, Index, StructuredList,
1447 StructuredIndex);
1448 } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) {
1449 auto Bases =
1452 if (DeclType->isRecordType()) {
1453 assert(DeclType->isAggregateType() &&
1454 "non-aggregate records should be handed in CheckSubElementType");
1455 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1456 Bases = CXXRD->bases();
1457 } else {
1458 Bases = cast<CXXRecordDecl>(RD)->bases();
1459 }
1460 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1461 SubobjectIsDesignatorContext, Index, StructuredList,
1462 StructuredIndex, TopLevelObject);
1463 } else if (DeclType->isArrayType()) {
1464 llvm::APSInt Zero(
1465 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1466 false);
1467 CheckArrayType(Entity, IList, DeclType, Zero,
1468 SubobjectIsDesignatorContext, Index,
1469 StructuredList, StructuredIndex);
1470 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1471 // This type is invalid, issue a diagnostic.
1472 ++Index;
1473 if (!VerifyOnly)
1474 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1475 << DeclType;
1476 hadError = true;
1477 } else if (DeclType->isReferenceType()) {
1478 CheckReferenceType(Entity, IList, DeclType, Index,
1479 StructuredList, StructuredIndex);
1480 } else if (DeclType->isObjCObjectType()) {
1481 if (!VerifyOnly)
1482 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1483 hadError = true;
1484 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1485 DeclType->isSizelessBuiltinType()) {
1486 // Checks for scalar type are sufficient for these types too.
1487 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1488 StructuredIndex);
1489 } else if (DeclType->isDependentType()) {
1490 // C++ [over.match.class.deduct]p1.5:
1491 // brace elision is not considered for any aggregate element that has a
1492 // dependent non-array type or an array type with a value-dependent bound
1493 ++Index;
1494 assert(AggrDeductionCandidateParamTypes);
1495 AggrDeductionCandidateParamTypes->push_back(DeclType);
1496 } else {
1497 if (!VerifyOnly)
1498 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1499 << DeclType;
1500 hadError = true;
1501 }
1502}
1503
1504void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1505 InitListExpr *IList,
1506 QualType ElemType,
1507 unsigned &Index,
1508 InitListExpr *StructuredList,
1509 unsigned &StructuredIndex,
1510 bool DirectlyDesignated) {
1511 Expr *expr = IList->getInit(Index);
1512
1513 if (ElemType->isReferenceType())
1514 return CheckReferenceType(Entity, IList, ElemType, Index,
1515 StructuredList, StructuredIndex);
1516
1517 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1518 if (SubInitList->getNumInits() == 1 &&
1519 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1520 SIF_None) {
1521 // FIXME: It would be more faithful and no less correct to include an
1522 // InitListExpr in the semantic form of the initializer list in this case.
1523 expr = SubInitList->getInit(0);
1524 }
1525 // Nested aggregate initialization and C++ initialization are handled later.
1526 } else if (isa<ImplicitValueInitExpr>(expr)) {
1527 // This happens during template instantiation when we see an InitListExpr
1528 // that we've already checked once.
1529 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1530 "found implicit initialization for the wrong type");
1531 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1532 ++Index;
1533 return;
1534 }
1535
1536 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1537 // C++ [dcl.init.aggr]p2:
1538 // Each member is copy-initialized from the corresponding
1539 // initializer-clause.
1540
1541 // FIXME: Better EqualLoc?
1542 InitializationKind Kind =
1543 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1544
1545 // Vector elements can be initialized from other vectors in which case
1546 // we need initialization entity with a type of a vector (and not a vector
1547 // element!) initializing multiple vector elements.
1548 auto TmpEntity =
1549 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1551 : Entity;
1552
1553 if (TmpEntity.getType()->isDependentType()) {
1554 // C++ [over.match.class.deduct]p1.5:
1555 // brace elision is not considered for any aggregate element that has a
1556 // dependent non-array type or an array type with a value-dependent
1557 // bound
1558 assert(AggrDeductionCandidateParamTypes);
1559
1560 // In the presence of a braced-init-list within the initializer, we should
1561 // not perform brace-elision, even if brace elision would otherwise be
1562 // applicable. For example, given:
1563 //
1564 // template <class T> struct Foo {
1565 // T t[2];
1566 // };
1567 //
1568 // Foo t = {{1, 2}};
1569 //
1570 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1571 // {{1, 2}}.
1573 !isa_and_present<ConstantArrayType>(
1574 SemaRef.Context.getAsArrayType(ElemType))) {
1575 ++Index;
1576 AggrDeductionCandidateParamTypes->push_back(ElemType);
1577 return;
1578 }
1579 } else {
1580 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1581 /*TopLevelOfInitList*/ true);
1582 // C++14 [dcl.init.aggr]p13:
1583 // If the assignment-expression can initialize a member, the member is
1584 // initialized. Otherwise [...] brace elision is assumed
1585 //
1586 // Brace elision is never performed if the element is not an
1587 // assignment-expression.
1588 if (Seq || isa<InitListExpr>(expr)) {
1589 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1590 expr = HandleEmbed(Embed, Entity);
1591 }
1592 if (!VerifyOnly) {
1593 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1594 if (Result.isInvalid())
1595 hadError = true;
1596
1597 UpdateStructuredListElement(StructuredList, StructuredIndex,
1598 Result.getAs<Expr>());
1599 } else if (!Seq) {
1600 hadError = true;
1601 } else if (StructuredList) {
1602 UpdateStructuredListElement(StructuredList, StructuredIndex,
1603 getDummyInit());
1604 }
1605 if (!CurEmbed)
1606 ++Index;
1607 if (AggrDeductionCandidateParamTypes)
1608 AggrDeductionCandidateParamTypes->push_back(ElemType);
1609 return;
1610 }
1611 }
1612
1613 // Fall through for subaggregate initialization
1614 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1615 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1616 return CheckScalarType(Entity, IList, ElemType, Index,
1617 StructuredList, StructuredIndex);
1618 } else if (const ArrayType *arrayType =
1619 SemaRef.Context.getAsArrayType(ElemType)) {
1620 // arrayType can be incomplete if we're initializing a flexible
1621 // array member. There's nothing we can do with the completed
1622 // type here, though.
1623
1624 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1625 // FIXME: Should we do this checking in verify-only mode?
1626 if (!VerifyOnly)
1627 CheckStringInit(expr, ElemType, arrayType, SemaRef, Entity,
1628 SemaRef.getLangOpts().C23 &&
1630 if (StructuredList)
1631 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1632 ++Index;
1633 return;
1634 }
1635
1636 // Fall through for subaggregate initialization.
1637
1638 } else {
1639 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1640 ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1641 "Unexpected type");
1642
1643 // C99 6.7.8p13:
1644 //
1645 // The initializer for a structure or union object that has
1646 // automatic storage duration shall be either an initializer
1647 // list as described below, or a single expression that has
1648 // compatible structure or union type. In the latter case, the
1649 // initial value of the object, including unnamed members, is
1650 // that of the expression.
1651 ExprResult ExprRes = expr;
1652 if (SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
1653 !VerifyOnly) !=
1654 AssignConvertType::Incompatible) {
1655 if (ExprRes.isInvalid())
1656 hadError = true;
1657 else {
1658 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1659 if (ExprRes.isInvalid())
1660 hadError = true;
1661 }
1662 UpdateStructuredListElement(StructuredList, StructuredIndex,
1663 ExprRes.getAs<Expr>());
1664 ++Index;
1665 return;
1666 }
1667 ExprRes.get();
1668 // Fall through for subaggregate initialization
1669 }
1670
1671 // C++ [dcl.init.aggr]p12:
1672 //
1673 // [...] Otherwise, if the member is itself a non-empty
1674 // subaggregate, brace elision is assumed and the initializer is
1675 // considered for the initialization of the first member of
1676 // the subaggregate.
1677 // OpenCL vector initializer is handled elsewhere.
1678 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1679 ElemType->isAggregateType()) {
1680 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1681 StructuredIndex);
1682 ++StructuredIndex;
1683
1684 // In C++20, brace elision is not permitted for a designated initializer.
1685 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1686 if (InOverloadResolution)
1687 hadError = true;
1688 if (!VerifyOnly) {
1689 SemaRef.Diag(expr->getBeginLoc(),
1690 diag::ext_designated_init_brace_elision)
1691 << expr->getSourceRange()
1692 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1694 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1695 }
1696 }
1697 } else {
1698 if (!VerifyOnly) {
1699 // We cannot initialize this element, so let PerformCopyInitialization
1700 // produce the appropriate diagnostic. We already checked that this
1701 // initialization will fail.
1703 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1704 /*TopLevelOfInitList=*/true);
1705 (void)Copy;
1706 assert(Copy.isInvalid() &&
1707 "expected non-aggregate initialization to fail");
1708 }
1709 hadError = true;
1710 ++Index;
1711 ++StructuredIndex;
1712 }
1713}
1714
1715void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1716 InitListExpr *IList, QualType DeclType,
1717 unsigned &Index,
1718 InitListExpr *StructuredList,
1719 unsigned &StructuredIndex) {
1720 assert(Index == 0 && "Index in explicit init list must be zero");
1721
1722 // As an extension, clang supports complex initializers, which initialize
1723 // a complex number component-wise. When an explicit initializer list for
1724 // a complex number contains two initializers, this extension kicks in:
1725 // it expects the initializer list to contain two elements convertible to
1726 // the element type of the complex type. The first element initializes
1727 // the real part, and the second element intitializes the imaginary part.
1728
1729 if (IList->getNumInits() < 2)
1730 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1731 StructuredIndex);
1732
1733 // This is an extension in C. (The builtin _Complex type does not exist
1734 // in the C++ standard.)
1735 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1736 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1737 << IList->getSourceRange();
1738
1739 // Initialize the complex number.
1740 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1741 InitializedEntity ElementEntity =
1743
1744 for (unsigned i = 0; i < 2; ++i) {
1745 ElementEntity.setElementIndex(Index);
1746 CheckSubElementType(ElementEntity, IList, elementType, Index,
1747 StructuredList, StructuredIndex);
1748 }
1749}
1750
1751void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1752 InitListExpr *IList, QualType DeclType,
1753 unsigned &Index,
1754 InitListExpr *StructuredList,
1755 unsigned &StructuredIndex) {
1756 if (Index >= IList->getNumInits()) {
1757 if (!VerifyOnly) {
1758 if (SemaRef.getLangOpts().CPlusPlus) {
1759 if (DeclType->isSizelessBuiltinType())
1760 SemaRef.Diag(IList->getBeginLoc(),
1761 SemaRef.getLangOpts().CPlusPlus11
1762 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1763 : diag::err_empty_sizeless_initializer)
1764 << DeclType << IList->getSourceRange();
1765 else
1766 SemaRef.Diag(IList->getBeginLoc(),
1767 SemaRef.getLangOpts().CPlusPlus11
1768 ? diag::warn_cxx98_compat_empty_scalar_initializer
1769 : diag::err_empty_scalar_initializer)
1770 << IList->getSourceRange();
1771 }
1772 }
1773 hadError =
1774 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1775 ++Index;
1776 ++StructuredIndex;
1777 return;
1778 }
1779
1780 Expr *expr = IList->getInit(Index);
1781 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1782 // FIXME: This is invalid, and accepting it causes overload resolution
1783 // to pick the wrong overload in some corner cases.
1784 if (!VerifyOnly)
1785 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1786 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1787
1788 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1789 StructuredIndex);
1790 return;
1791 } else if (isa<DesignatedInitExpr>(expr)) {
1792 if (!VerifyOnly)
1793 SemaRef.Diag(expr->getBeginLoc(),
1794 diag::err_designator_for_scalar_or_sizeless_init)
1795 << DeclType->isSizelessBuiltinType() << DeclType
1796 << expr->getSourceRange();
1797 hadError = true;
1798 ++Index;
1799 ++StructuredIndex;
1800 return;
1801 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1802 expr = HandleEmbed(Embed, Entity);
1803 }
1804
1806 if (VerifyOnly) {
1807 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1808 Result = getDummyInit();
1809 else
1810 Result = ExprError();
1811 } else {
1812 Result =
1813 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1814 /*TopLevelOfInitList=*/true);
1815 }
1816
1817 Expr *ResultExpr = nullptr;
1818
1819 if (Result.isInvalid())
1820 hadError = true; // types weren't compatible.
1821 else {
1822 ResultExpr = Result.getAs<Expr>();
1823
1824 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1825 // The type was promoted, update initializer list.
1826 // FIXME: Why are we updating the syntactic init list?
1827 IList->setInit(Index, ResultExpr);
1828 }
1829 }
1830
1831 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1832 if (!CurEmbed)
1833 ++Index;
1834 if (AggrDeductionCandidateParamTypes)
1835 AggrDeductionCandidateParamTypes->push_back(DeclType);
1836}
1837
1838void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1839 InitListExpr *IList, QualType DeclType,
1840 unsigned &Index,
1841 InitListExpr *StructuredList,
1842 unsigned &StructuredIndex) {
1843 if (Index >= IList->getNumInits()) {
1844 // FIXME: It would be wonderful if we could point at the actual member. In
1845 // general, it would be useful to pass location information down the stack,
1846 // so that we know the location (or decl) of the "current object" being
1847 // initialized.
1848 if (!VerifyOnly)
1849 SemaRef.Diag(IList->getBeginLoc(),
1850 diag::err_init_reference_member_uninitialized)
1851 << DeclType << IList->getSourceRange();
1852 hadError = true;
1853 ++Index;
1854 ++StructuredIndex;
1855 return;
1856 }
1857
1858 Expr *expr = IList->getInit(Index);
1859 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1860 if (!VerifyOnly)
1861 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1862 << DeclType << IList->getSourceRange();
1863 hadError = true;
1864 ++Index;
1865 ++StructuredIndex;
1866 return;
1867 }
1868
1870 if (VerifyOnly) {
1871 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1872 Result = getDummyInit();
1873 else
1874 Result = ExprError();
1875 } else {
1876 Result =
1877 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1878 /*TopLevelOfInitList=*/true);
1879 }
1880
1881 if (Result.isInvalid())
1882 hadError = true;
1883
1884 expr = Result.getAs<Expr>();
1885 // FIXME: Why are we updating the syntactic init list?
1886 if (!VerifyOnly && expr)
1887 IList->setInit(Index, expr);
1888
1889 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1890 ++Index;
1891 if (AggrDeductionCandidateParamTypes)
1892 AggrDeductionCandidateParamTypes->push_back(DeclType);
1893}
1894
1895void InitListChecker::CheckMatrixType(const InitializedEntity &Entity,
1896 InitListExpr *IList, QualType DeclType,
1897 unsigned &Index,
1898 InitListExpr *StructuredList,
1899 unsigned &StructuredIndex) {
1900 if (!SemaRef.getLangOpts().HLSL)
1901 return;
1902
1903 const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>();
1904
1905 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1906 // initializer list diagnostics. That means the execution should require
1907 // getNumElementsFlattened to equal getNumInits. In other words the execution
1908 // should never reach this point if this condition is not true".
1909 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1910 "Inits must equal Matrix element count");
1911
1912 QualType ElemTy = MT->getElementType();
1913
1914 Index = 0;
1915 InitializedEntity Element =
1917
1918 while (Index < IList->getNumInits()) {
1919 // Not a sublist: just consume directly.
1920 // Note: In HLSL, elements of the InitListExpr are in row-major order, so no
1921 // change is needed to the Index.
1922 Element.setElementIndex(Index);
1923 CheckSubElementType(Element, IList, ElemTy, Index, StructuredList,
1924 StructuredIndex);
1925 }
1926}
1927
1928void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1929 InitListExpr *IList, QualType DeclType,
1930 unsigned &Index,
1931 InitListExpr *StructuredList,
1932 unsigned &StructuredIndex) {
1933 const VectorType *VT = DeclType->castAs<VectorType>();
1934 unsigned maxElements = VT->getNumElements();
1935 unsigned numEltsInit = 0;
1936 QualType elementType = VT->getElementType();
1937
1938 if (Index >= IList->getNumInits()) {
1939 // Make sure the element type can be value-initialized.
1940 CheckEmptyInitializable(
1942 IList->getEndLoc());
1943 return;
1944 }
1945
1946 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1947 // If the initializing element is a vector, try to copy-initialize
1948 // instead of breaking it apart (which is doomed to failure anyway).
1949 Expr *Init = IList->getInit(Index);
1950 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1952 if (VerifyOnly) {
1953 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1954 Result = getDummyInit();
1955 else
1956 Result = ExprError();
1957 } else {
1958 Result =
1959 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1960 /*TopLevelOfInitList=*/true);
1961 }
1962
1963 Expr *ResultExpr = nullptr;
1964 if (Result.isInvalid())
1965 hadError = true; // types weren't compatible.
1966 else {
1967 ResultExpr = Result.getAs<Expr>();
1968
1969 if (ResultExpr != Init && !VerifyOnly) {
1970 // The type was promoted, update initializer list.
1971 // FIXME: Why are we updating the syntactic init list?
1972 IList->setInit(Index, ResultExpr);
1973 }
1974 }
1975 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1976 ++Index;
1977 if (AggrDeductionCandidateParamTypes)
1978 AggrDeductionCandidateParamTypes->push_back(elementType);
1979 return;
1980 }
1981
1982 InitializedEntity ElementEntity =
1984
1985 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1986 // Don't attempt to go past the end of the init list
1987 if (Index >= IList->getNumInits()) {
1988 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1989 break;
1990 }
1991
1992 ElementEntity.setElementIndex(Index);
1993 CheckSubElementType(ElementEntity, IList, elementType, Index,
1994 StructuredList, StructuredIndex);
1995 }
1996
1997 if (VerifyOnly)
1998 return;
1999
2000 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
2001 const VectorType *T = Entity.getType()->castAs<VectorType>();
2002 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2003 T->getVectorKind() == VectorKind::NeonPoly)) {
2004 // The ability to use vector initializer lists is a GNU vector extension
2005 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2006 // endian machines it works fine, however on big endian machines it
2007 // exhibits surprising behaviour:
2008 //
2009 // uint32x2_t x = {42, 64};
2010 // return vget_lane_u32(x, 0); // Will return 64.
2011 //
2012 // Because of this, explicitly call out that it is non-portable.
2013 //
2014 SemaRef.Diag(IList->getBeginLoc(),
2015 diag::warn_neon_vector_initializer_non_portable);
2016
2017 const char *typeCode;
2018 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
2019
2020 if (elementType->isFloatingType())
2021 typeCode = "f";
2022 else if (elementType->isSignedIntegerType())
2023 typeCode = "s";
2024 else if (elementType->isUnsignedIntegerType())
2025 typeCode = "u";
2026 else if (elementType->isMFloat8Type())
2027 typeCode = "mf";
2028 else
2029 llvm_unreachable("Invalid element type!");
2030
2031 SemaRef.Diag(IList->getBeginLoc(),
2032 SemaRef.Context.getTypeSize(VT) > 64
2033 ? diag::note_neon_vector_initializer_non_portable_q
2034 : diag::note_neon_vector_initializer_non_portable)
2035 << typeCode << typeSize;
2036 }
2037
2038 return;
2039 }
2040
2041 InitializedEntity ElementEntity =
2043
2044 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2045 for (unsigned i = 0; i < maxElements; ++i) {
2046 // Don't attempt to go past the end of the init list
2047 if (Index >= IList->getNumInits())
2048 break;
2049
2050 ElementEntity.setElementIndex(Index);
2051
2052 QualType IType = IList->getInit(Index)->getType();
2053 if (!IType->isVectorType()) {
2054 CheckSubElementType(ElementEntity, IList, elementType, Index,
2055 StructuredList, StructuredIndex);
2056 ++numEltsInit;
2057 } else {
2058 QualType VecType;
2059 const VectorType *IVT = IType->castAs<VectorType>();
2060 unsigned numIElts = IVT->getNumElements();
2061
2062 if (IType->isExtVectorType())
2063 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2064 else
2065 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2066 IVT->getVectorKind());
2067 CheckSubElementType(ElementEntity, IList, VecType, Index,
2068 StructuredList, StructuredIndex);
2069 numEltsInit += numIElts;
2070 }
2071 }
2072
2073 // OpenCL and HLSL require all elements to be initialized.
2074 if (numEltsInit != maxElements) {
2075 if (!VerifyOnly)
2076 SemaRef.Diag(IList->getBeginLoc(),
2077 diag::err_vector_incorrect_num_elements)
2078 << (numEltsInit < maxElements) << maxElements << numEltsInit
2079 << /*initialization*/ 0;
2080 hadError = true;
2081 }
2082}
2083
2084/// Check if the type of a class element has an accessible destructor, and marks
2085/// it referenced. Returns true if we shouldn't form a reference to the
2086/// destructor.
2087///
2088/// Aggregate initialization requires a class element's destructor be
2089/// accessible per 11.6.1 [dcl.init.aggr]:
2090///
2091/// The destructor for each element of class type is potentially invoked
2092/// (15.4 [class.dtor]) from the context where the aggregate initialization
2093/// occurs.
2095 Sema &SemaRef) {
2096 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2097 // Bail out on incomplete record types: a forward-declared class has no
2098 // destructor to look up, and `LookupDestructor` (via `LookupSpecialMember`)
2099 // asserts that the record is fully defined. Error recovery for init lists
2100 // of incomplete element types reaches this point even after the parser has
2101 // already diagnosed the incompleteness.
2102 if (!CXXRD || !CXXRD->hasDefinition())
2103 return false;
2104
2106 if (!Destructor)
2107 return false;
2108
2109 SemaRef.CheckDestructorAccess(Loc, Destructor,
2110 SemaRef.PDiag(diag::err_access_dtor_temp)
2111 << ElementType);
2112 SemaRef.MarkFunctionReferenced(Loc, Destructor);
2113 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2114}
2115
2116static bool
2118 const InitializedEntity &Entity,
2119 ASTContext &Context) {
2120 QualType InitType = Entity.getType();
2121 const InitializedEntity *Parent = &Entity;
2122
2123 while (Parent) {
2124 InitType = Parent->getType();
2125 Parent = Parent->getParent();
2126 }
2127
2128 // Only one initializer, it's an embed and the types match;
2129 EmbedExpr *EE =
2130 ExprList.size() == 1
2131 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2132 : nullptr;
2133 if (!EE)
2134 return false;
2135
2136 if (InitType->isArrayType()) {
2137 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2139 return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2140 }
2141 return false;
2142}
2143
2144void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2145 InitListExpr *IList, QualType &DeclType,
2146 llvm::APSInt elementIndex,
2147 bool SubobjectIsDesignatorContext,
2148 unsigned &Index,
2149 InitListExpr *StructuredList,
2150 unsigned &StructuredIndex) {
2151 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2152
2153 if (!VerifyOnly) {
2154 if (checkDestructorReference(arrayType->getElementType(),
2155 IList->getEndLoc(), SemaRef)) {
2156 hadError = true;
2157 return;
2158 }
2159 }
2160
2161 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2162 SemaRef.Context)) {
2163 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2164 IList->setInit(0, Embed->getDataStringLiteral());
2165 }
2166
2167 // Check for the special-case of initializing an array with a string.
2168 if (Index < IList->getNumInits()) {
2169 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2170 SIF_None) {
2171 // We place the string literal directly into the resulting
2172 // initializer list. This is the only place where the structure
2173 // of the structured initializer list doesn't match exactly,
2174 // because doing so would involve allocating one character
2175 // constant for each string.
2176 // FIXME: Should we do these checks in verify-only mode too?
2177 if (!VerifyOnly)
2179 IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2180 SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2181 if (StructuredList) {
2182 UpdateStructuredListElement(StructuredList, StructuredIndex,
2183 IList->getInit(Index));
2184 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2185 }
2186 ++Index;
2187 if (AggrDeductionCandidateParamTypes)
2188 AggrDeductionCandidateParamTypes->push_back(DeclType);
2189 return;
2190 }
2191 }
2192 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2193 // Check for VLAs; in standard C it would be possible to check this
2194 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2195 // them in all sorts of strange places).
2196 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2197 if (!VerifyOnly) {
2198 // C23 6.7.10p4: An entity of variable length array type shall not be
2199 // initialized except by an empty initializer.
2200 //
2201 // The C extension warnings are issued from ParseBraceInitializer() and
2202 // do not need to be issued here. However, we continue to issue an error
2203 // in the case there are initializers or we are compiling C++. We allow
2204 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2205 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2206 // FIXME: should we allow this construct in C++ when it makes sense to do
2207 // so?
2208 if (HasErr)
2209 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2210 diag::err_variable_object_no_init)
2211 << VAT->getSizeExpr()->getSourceRange();
2212 }
2213 hadError = HasErr;
2214 ++Index;
2215 ++StructuredIndex;
2216 return;
2217 }
2218
2219 // We might know the maximum number of elements in advance.
2220 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2221 elementIndex.isUnsigned());
2222 bool maxElementsKnown = false;
2223 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2224 maxElements = CAT->getSize();
2225 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2226 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2227 maxElementsKnown = true;
2228 }
2229
2230 QualType elementType = arrayType->getElementType();
2231 while (Index < IList->getNumInits()) {
2232 Expr *Init = IList->getInit(Index);
2233 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2234 // If we're not the subobject that matches up with the '{' for
2235 // the designator, we shouldn't be handling the
2236 // designator. Return immediately.
2237 if (!SubobjectIsDesignatorContext)
2238 return;
2239
2240 // Handle this designated initializer. elementIndex will be
2241 // updated to be the next array element we'll initialize.
2242 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2243 DeclType, nullptr, &elementIndex, Index,
2244 StructuredList, StructuredIndex, true,
2245 false)) {
2246 hadError = true;
2247 continue;
2248 }
2249
2250 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2251 maxElements = maxElements.extend(elementIndex.getBitWidth());
2252 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2253 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2254 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2255
2256 // If the array is of incomplete type, keep track of the number of
2257 // elements in the initializer.
2258 if (!maxElementsKnown && elementIndex > maxElements)
2259 maxElements = elementIndex;
2260
2261 continue;
2262 }
2263
2264 // If we know the maximum number of elements, and we've already
2265 // hit it, stop consuming elements in the initializer list.
2266 if (maxElementsKnown && elementIndex == maxElements)
2267 break;
2268
2269 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2270 SemaRef.Context, StructuredIndex, Entity);
2271 ElementEntity.setElementIndex(elementIndex.getExtValue());
2272
2273 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2274 // Check this element.
2275 CheckSubElementType(ElementEntity, IList, elementType, Index,
2276 StructuredList, StructuredIndex);
2277 ++elementIndex;
2278 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2279 if (CurEmbed) {
2280 elementIndex =
2281 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2282 } else {
2283 auto Embed = cast<EmbedExpr>(Init);
2284 elementIndex = elementIndex + Embed->getDataElementCount() -
2285 EmbedElementIndexBeforeInit - 1;
2286 }
2287 }
2288
2289 // If the array is of incomplete type, keep track of the number of
2290 // elements in the initializer.
2291 if (!maxElementsKnown && elementIndex > maxElements)
2292 maxElements = elementIndex;
2293 }
2294 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2295 // If this is an incomplete array type, the actual type needs to
2296 // be calculated here.
2297 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2298 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2299 // Sizing an array implicitly to zero is not allowed by ISO C,
2300 // but is supported by GNU.
2301 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2302 }
2303
2304 DeclType = SemaRef.Context.getConstantArrayType(
2305 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2306 }
2307 if (!hadError) {
2308 // If there are any members of the array that get value-initialized, check
2309 // that is possible. That happens if we know the bound and don't have
2310 // enough elements, or if we're performing an array new with an unknown
2311 // bound.
2312 if ((maxElementsKnown && elementIndex < maxElements) ||
2313 Entity.isVariableLengthArrayNew())
2314 CheckEmptyInitializable(
2316 IList->getEndLoc());
2317 }
2318}
2319
2320bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2321 Expr *InitExpr,
2322 FieldDecl *Field,
2323 bool TopLevelObject) {
2324 // Handle GNU flexible array initializers.
2325 unsigned FlexArrayDiag;
2326 if (isa<InitListExpr>(InitExpr) &&
2327 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2328 // Empty flexible array init always allowed as an extension
2329 FlexArrayDiag = diag::ext_flexible_array_init;
2330 } else if (!TopLevelObject) {
2331 // Disallow flexible array init on non-top-level object
2332 FlexArrayDiag = diag::err_flexible_array_init;
2333 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2334 // Disallow flexible array init on anything which is not a variable.
2335 FlexArrayDiag = diag::err_flexible_array_init;
2336 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2337 // Disallow flexible array init on local variables.
2338 FlexArrayDiag = diag::err_flexible_array_init;
2339 } else {
2340 // Allow other cases.
2341 FlexArrayDiag = diag::ext_flexible_array_init;
2342 }
2343
2344 if (!VerifyOnly) {
2345 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2346 << InitExpr->getBeginLoc();
2347 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2348 << Field;
2349 }
2350
2351 return FlexArrayDiag != diag::ext_flexible_array_init;
2352}
2353
2354static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2355 return StructuredList && StructuredList->getNumInits() == 1U;
2356}
2357
2358void InitListChecker::CheckStructUnionTypes(
2359 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2361 bool SubobjectIsDesignatorContext, unsigned &Index,
2362 InitListExpr *StructuredList, unsigned &StructuredIndex,
2363 bool TopLevelObject) {
2364 const RecordDecl *RD = DeclType->getAsRecordDecl();
2365
2366 // If the record is invalid, some of it's members are invalid. To avoid
2367 // confusion, we forgo checking the initializer for the entire record.
2368 if (RD->isInvalidDecl()) {
2369 // Assume it was supposed to consume a single initializer.
2370 ++Index;
2371 hadError = true;
2372 return;
2373 }
2374
2375 if (RD->isUnion() && IList->getNumInits() == 0) {
2376 if (!VerifyOnly)
2377 for (FieldDecl *FD : RD->fields()) {
2378 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2379 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2380 hadError = true;
2381 return;
2382 }
2383 }
2384
2385 // If there's a default initializer, use it.
2386 if (isa<CXXRecordDecl>(RD) &&
2387 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2388 if (!StructuredList)
2389 return;
2390 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2391 Field != FieldEnd; ++Field) {
2392 if (Field->hasInClassInitializer() ||
2393 (Field->isAnonymousStructOrUnion() &&
2394 Field->getType()
2395 ->castAsCXXRecordDecl()
2396 ->hasInClassInitializer())) {
2397 StructuredList->setInitializedFieldInUnion(*Field);
2398 // FIXME: Actually build a CXXDefaultInitExpr?
2399 return;
2400 }
2401 }
2402 llvm_unreachable("Couldn't find in-class initializer");
2403 }
2404
2405 // Value-initialize the first member of the union that isn't an unnamed
2406 // bitfield.
2407 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2408 Field != FieldEnd; ++Field) {
2409 if (!Field->isUnnamedBitField()) {
2410 CheckEmptyInitializable(
2411 InitializedEntity::InitializeMember(*Field, &Entity),
2412 IList->getEndLoc());
2413 if (StructuredList)
2414 StructuredList->setInitializedFieldInUnion(*Field);
2415 break;
2416 }
2417 }
2418 return;
2419 }
2420
2421 bool InitializedSomething = false;
2422
2423 // If we have any base classes, they are initialized prior to the fields.
2424 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2425 auto &Base = *I;
2426 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2427
2428 // Designated inits always initialize fields, so if we see one, all
2429 // remaining base classes have no explicit initializer.
2430 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2431 Init = nullptr;
2432
2433 // C++ [over.match.class.deduct]p1.6:
2434 // each non-trailing aggregate element that is a pack expansion is assumed
2435 // to correspond to no elements of the initializer list, and (1.7) a
2436 // trailing aggregate element that is a pack expansion is assumed to
2437 // correspond to all remaining elements of the initializer list (if any).
2438
2439 // C++ [over.match.class.deduct]p1.9:
2440 // ... except that additional parameter packs of the form P_j... are
2441 // inserted into the parameter list in their original aggregate element
2442 // position corresponding to each non-trailing aggregate element of
2443 // type P_j that was skipped because it was a parameter pack, and the
2444 // trailing sequence of parameters corresponding to a trailing
2445 // aggregate element that is a pack expansion (if any) is replaced
2446 // by a single parameter of the form T_n....
2447 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2448 AggrDeductionCandidateParamTypes->push_back(
2449 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2450
2451 // Trailing pack expansion
2452 if (I + 1 == E && RD->field_empty()) {
2453 if (Index < IList->getNumInits())
2454 Index = IList->getNumInits();
2455 return;
2456 }
2457
2458 continue;
2459 }
2460
2461 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2462 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2463 SemaRef.Context, &Base, false, &Entity);
2464 if (Init) {
2465 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2466 StructuredList, StructuredIndex);
2467 InitializedSomething = true;
2468 } else {
2469 CheckEmptyInitializable(BaseEntity, InitLoc);
2470 }
2471
2472 if (!VerifyOnly)
2473 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2474 hadError = true;
2475 return;
2476 }
2477 }
2478
2479 // If structDecl is a forward declaration, this loop won't do
2480 // anything except look at designated initializers; That's okay,
2481 // because an error should get printed out elsewhere. It might be
2482 // worthwhile to skip over the rest of the initializer, though.
2483 RecordDecl::field_iterator FieldEnd = RD->field_end();
2484 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2485 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2486 });
2487 bool HasDesignatedInit = false;
2488
2489 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2490
2491 while (Index < IList->getNumInits()) {
2492 Expr *Init = IList->getInit(Index);
2493 SourceLocation InitLoc = Init->getBeginLoc();
2494
2495 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2496 // If we're not the subobject that matches up with the '{' for
2497 // the designator, we shouldn't be handling the
2498 // designator. Return immediately.
2499 if (!SubobjectIsDesignatorContext)
2500 return;
2501
2502 HasDesignatedInit = true;
2503
2504 // Handle this designated initializer. Field will be updated to
2505 // the next field that we'll be initializing.
2506 bool DesignatedInitFailed = CheckDesignatedInitializer(
2507 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2508 StructuredList, StructuredIndex, true, TopLevelObject);
2509 if (DesignatedInitFailed)
2510 hadError = true;
2511
2512 // Find the field named by the designated initializer.
2513 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2514 if (!VerifyOnly && D->isFieldDesignator()) {
2515 FieldDecl *F = D->getFieldDecl();
2516 InitializedFields.insert(F);
2517 if (!DesignatedInitFailed) {
2518 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2519 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2520 hadError = true;
2521 return;
2522 }
2523 }
2524 }
2525
2526 InitializedSomething = true;
2527 continue;
2528 }
2529
2530 // Check if this is an initializer of forms:
2531 //
2532 // struct foo f = {};
2533 // struct foo g = {0};
2534 //
2535 // These are okay for randomized structures. [C99 6.7.8p19]
2536 //
2537 // Also, if there is only one element in the structure, we allow something
2538 // like this, because it's really not randomized in the traditional sense.
2539 //
2540 // struct foo h = {bar};
2541 auto IsZeroInitializer = [&](const Expr *I) {
2542 if (IList->getNumInits() == 1) {
2543 if (NumRecordDecls == 1)
2544 return true;
2545 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2546 return IL->getValue().isZero();
2547 }
2548 return false;
2549 };
2550
2551 // Don't allow non-designated initializers on randomized structures.
2552 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2553 if (!VerifyOnly)
2554 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2555 hadError = true;
2556 break;
2557 }
2558
2559 if (Field == FieldEnd) {
2560 // We've run out of fields. We're done.
2561 break;
2562 }
2563
2564 // We've already initialized a member of a union. We can stop entirely.
2565 if (InitializedSomething && RD->isUnion())
2566 return;
2567
2568 // Stop if we've hit a flexible array member.
2569 if (Field->getType()->isIncompleteArrayType())
2570 break;
2571
2572 if (Field->isUnnamedBitField()) {
2573 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2574 ++Field;
2575 continue;
2576 }
2577
2578 // Make sure we can use this declaration.
2579 bool InvalidUse;
2580 if (VerifyOnly)
2581 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2582 else
2583 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2584 *Field, IList->getInit(Index)->getBeginLoc());
2585 if (InvalidUse) {
2586 ++Index;
2587 ++Field;
2588 hadError = true;
2589 continue;
2590 }
2591
2592 if (!VerifyOnly) {
2593 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2594 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2595 hadError = true;
2596 return;
2597 }
2598 }
2599
2600 InitializedEntity MemberEntity =
2601 InitializedEntity::InitializeMember(*Field, &Entity);
2602 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2603 StructuredList, StructuredIndex);
2604 InitializedSomething = true;
2605 InitializedFields.insert(*Field);
2606 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2607 // Initialize the first field within the union.
2608 StructuredList->setInitializedFieldInUnion(*Field);
2609 }
2610
2611 ++Field;
2612 }
2613
2614 // Emit warnings for missing struct field initializers.
2615 // This check is disabled for designated initializers in C.
2616 // This matches gcc behaviour.
2617 bool IsCDesignatedInitializer =
2618 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2619 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2620 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2621 !IsCDesignatedInitializer) {
2622 // It is possible we have one or more unnamed bitfields remaining.
2623 // Find first (if any) named field and emit warning.
2624 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2625 : Field,
2626 end = RD->field_end();
2627 it != end; ++it) {
2628 if (HasDesignatedInit && InitializedFields.count(*it))
2629 continue;
2630
2631 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2632 !it->getType()->isIncompleteArrayType()) {
2633 auto Diag = HasDesignatedInit
2634 ? diag::warn_missing_designated_field_initializers
2635 : diag::warn_missing_field_initializers;
2636 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2637 break;
2638 }
2639 }
2640 }
2641
2642 // Check that any remaining fields can be value-initialized if we're not
2643 // building a structured list. (If we are, we'll check this later.)
2644 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2645 !Field->getType()->isIncompleteArrayType()) {
2646 for (; Field != FieldEnd && !hadError; ++Field) {
2647 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2648 CheckEmptyInitializable(
2649 InitializedEntity::InitializeMember(*Field, &Entity),
2650 IList->getEndLoc());
2651 }
2652 }
2653
2654 // Check that the types of the remaining fields have accessible destructors.
2655 if (!VerifyOnly) {
2656 // If the initializer expression has a designated initializer, check the
2657 // elements for which a designated initializer is not provided too.
2658 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2659 : Field;
2660 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2661 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2662 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2663 hadError = true;
2664 return;
2665 }
2666 }
2667 }
2668
2669 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2670 Index >= IList->getNumInits())
2671 return;
2672
2673 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2674 TopLevelObject)) {
2675 hadError = true;
2676 ++Index;
2677 return;
2678 }
2679
2680 InitializedEntity MemberEntity =
2681 InitializedEntity::InitializeMember(*Field, &Entity);
2682
2683 if (isa<InitListExpr>(IList->getInit(Index)) ||
2684 AggrDeductionCandidateParamTypes)
2685 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2686 StructuredList, StructuredIndex);
2687 else
2688 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2689 StructuredList, StructuredIndex);
2690
2691 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2692 // Initialize the first field within the union.
2693 StructuredList->setInitializedFieldInUnion(*Field);
2694 }
2695}
2696
2697/// Expand a field designator that refers to a member of an
2698/// anonymous struct or union into a series of field designators that
2699/// refers to the field within the appropriate subobject.
2700///
2702 DesignatedInitExpr *DIE,
2703 unsigned DesigIdx,
2704 IndirectFieldDecl *IndirectField) {
2706
2707 // Build the replacement designators.
2708 SmallVector<Designator, 4> Replacements;
2709 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2710 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2711 if (PI + 1 == PE)
2712 Replacements.push_back(Designator::CreateFieldDesignator(
2713 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2714 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2715 else
2716 Replacements.push_back(Designator::CreateFieldDesignator(
2717 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2718 assert(isa<FieldDecl>(*PI));
2719 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2720 }
2721
2722 // Expand the current designator into the set of replacement
2723 // designators, so we have a full subobject path down to where the
2724 // member of the anonymous struct/union is actually stored.
2725 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2726 &Replacements[0] + Replacements.size());
2727}
2728
2730 DesignatedInitExpr *DIE) {
2731 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2732 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2733 for (unsigned I = 0; I < NumIndexExprs; ++I)
2734 IndexExprs[I] = DIE->getSubExpr(I + 1);
2735 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2736 IndexExprs,
2737 DIE->getEqualOrColonLoc(),
2738 DIE->usesGNUSyntax(), DIE->getInit());
2739}
2740
2741namespace {
2742
2743// Callback to only accept typo corrections that are for field members of
2744// the given struct or union.
2745class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2746 public:
2747 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2748 : Record(RD) {}
2749
2750 bool ValidateCandidate(const TypoCorrection &candidate) override {
2751 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2752 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2753 }
2754
2755 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2756 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2757 }
2758
2759 private:
2760 const RecordDecl *Record;
2761};
2762
2763} // end anonymous namespace
2764
2765/// Check the well-formedness of a C99 designated initializer.
2766///
2767/// Determines whether the designated initializer @p DIE, which
2768/// resides at the given @p Index within the initializer list @p
2769/// IList, is well-formed for a current object of type @p DeclType
2770/// (C99 6.7.8). The actual subobject that this designator refers to
2771/// within the current subobject is returned in either
2772/// @p NextField or @p NextElementIndex (whichever is appropriate).
2773///
2774/// @param IList The initializer list in which this designated
2775/// initializer occurs.
2776///
2777/// @param DIE The designated initializer expression.
2778///
2779/// @param DesigIdx The index of the current designator.
2780///
2781/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2782/// into which the designation in @p DIE should refer.
2783///
2784/// @param NextField If non-NULL and the first designator in @p DIE is
2785/// a field, this will be set to the field declaration corresponding
2786/// to the field named by the designator. On input, this is expected to be
2787/// the next field that would be initialized in the absence of designation,
2788/// if the complete object being initialized is a struct.
2789///
2790/// @param NextElementIndex If non-NULL and the first designator in @p
2791/// DIE is an array designator or GNU array-range designator, this
2792/// will be set to the last index initialized by this designator.
2793///
2794/// @param Index Index into @p IList where the designated initializer
2795/// @p DIE occurs.
2796///
2797/// @param StructuredList The initializer list expression that
2798/// describes all of the subobject initializers in the order they'll
2799/// actually be initialized.
2800///
2801/// @returns true if there was an error, false otherwise.
2802bool
2803InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2804 InitListExpr *IList,
2805 DesignatedInitExpr *DIE,
2806 unsigned DesigIdx,
2807 QualType &CurrentObjectType,
2808 RecordDecl::field_iterator *NextField,
2809 llvm::APSInt *NextElementIndex,
2810 unsigned &Index,
2811 InitListExpr *StructuredList,
2812 unsigned &StructuredIndex,
2813 bool FinishSubobjectInit,
2814 bool TopLevelObject) {
2815 if (DesigIdx == DIE->size()) {
2816 // C++20 designated initialization can result in direct-list-initialization
2817 // of the designated subobject. This is the only way that we can end up
2818 // performing direct initialization as part of aggregate initialization, so
2819 // it needs special handling.
2820 if (DIE->isDirectInit()) {
2821 Expr *Init = DIE->getInit();
2822 assert(isa<InitListExpr>(Init) &&
2823 "designator result in direct non-list initialization?");
2824 InitializationKind Kind = InitializationKind::CreateDirectList(
2825 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2826 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2827 /*TopLevelOfInitList*/ true);
2828 if (StructuredList) {
2829 ExprResult Result = VerifyOnly
2830 ? getDummyInit()
2831 : Seq.Perform(SemaRef, Entity, Kind, Init);
2832 UpdateStructuredListElement(StructuredList, StructuredIndex,
2833 Result.get());
2834 }
2835 ++Index;
2836 if (AggrDeductionCandidateParamTypes)
2837 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2838 return !Seq;
2839 }
2840
2841 // Check the actual initialization for the designated object type.
2842 bool prevHadError = hadError;
2843
2844 // Temporarily remove the designator expression from the
2845 // initializer list that the child calls see, so that we don't try
2846 // to re-process the designator.
2847 unsigned OldIndex = Index;
2848 auto *OldDIE =
2849 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2850 if (!OldDIE)
2851 OldDIE = DIE;
2852 IList->setInit(OldIndex, OldDIE->getInit());
2853
2854 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2855 StructuredIndex, /*DirectlyDesignated=*/true);
2856
2857 // Restore the designated initializer expression in the syntactic
2858 // form of the initializer list.
2859 if (IList->getInit(OldIndex) != OldDIE->getInit())
2860 OldDIE->setInit(IList->getInit(OldIndex));
2861 IList->setInit(OldIndex, OldDIE);
2862
2863 return hadError && !prevHadError;
2864 }
2865
2866 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2867 bool IsFirstDesignator = (DesigIdx == 0);
2868 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2869 // Determine the structural initializer list that corresponds to the
2870 // current subobject.
2871 if (IsFirstDesignator)
2872 StructuredList = FullyStructuredList;
2873 else {
2874 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2875 StructuredList->getInit(StructuredIndex) : nullptr;
2876 if (!ExistingInit && StructuredList->hasArrayFiller())
2877 ExistingInit = StructuredList->getArrayFiller();
2878
2879 if (!ExistingInit)
2880 StructuredList = getStructuredSubobjectInit(
2881 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2882 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2883 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2884 StructuredList = Result;
2885 else {
2886 // We are creating an initializer list that initializes the
2887 // subobjects of the current object, but there was already an
2888 // initialization that completely initialized the current
2889 // subobject, e.g., by a compound literal:
2890 //
2891 // struct X { int a, b; };
2892 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2893 //
2894 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2895 // designated initializer re-initializes only its current object
2896 // subobject [0].b.
2897 diagnoseInitOverride(ExistingInit,
2898 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2899 /*UnionOverride=*/false,
2900 /*FullyOverwritten=*/false);
2901
2902 if (!VerifyOnly) {
2903 if (DesignatedInitUpdateExpr *E =
2904 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2905 StructuredList = E->getUpdater();
2906 else {
2907 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2908 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2909 ExistingInit, DIE->getEndLoc());
2910 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2911 StructuredList = DIUE->getUpdater();
2912 }
2913 } else {
2914 // We don't need to track the structured representation of a
2915 // designated init update of an already-fully-initialized object in
2916 // verify-only mode. The only reason we would need the structure is
2917 // to determine where the uninitialized "holes" are, and in this
2918 // case, we know there aren't any and we can't introduce any.
2919 StructuredList = nullptr;
2920 }
2921 }
2922 }
2923 }
2924
2925 if (D->isFieldDesignator()) {
2926 // C99 6.7.8p7:
2927 //
2928 // If a designator has the form
2929 //
2930 // . identifier
2931 //
2932 // then the current object (defined below) shall have
2933 // structure or union type and the identifier shall be the
2934 // name of a member of that type.
2935 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2936 if (!RD) {
2937 SourceLocation Loc = D->getDotLoc();
2938 if (Loc.isInvalid())
2939 Loc = D->getFieldLoc();
2940 if (!VerifyOnly)
2941 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2942 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2943 ++Index;
2944 return true;
2945 }
2946
2947 FieldDecl *KnownField = D->getFieldDecl();
2948 if (!KnownField) {
2949 const IdentifierInfo *FieldName = D->getFieldName();
2950 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2951 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2952 KnownField = FD;
2953 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2954 // In verify mode, don't modify the original.
2955 if (VerifyOnly)
2956 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2957 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2958 D = DIE->getDesignator(DesigIdx);
2959 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2960 }
2961 if (!KnownField) {
2962 if (VerifyOnly) {
2963 ++Index;
2964 return true; // No typo correction when just trying this out.
2965 }
2966
2967 // We found a placeholder variable
2968 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2969 FieldName)) {
2970 ++Index;
2971 return true;
2972 }
2973 // Name lookup found something, but it wasn't a field.
2974 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2975 !Lookup.empty()) {
2976 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2977 << FieldName;
2978 SemaRef.Diag(Lookup.front()->getLocation(),
2979 diag::note_field_designator_found);
2980 ++Index;
2981 return true;
2982 }
2983
2984 // Name lookup didn't find anything.
2985 // Determine whether this was a typo for another field name.
2986 FieldInitializerValidatorCCC CCC(RD);
2987 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2988 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2989 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2990 CorrectTypoKind::ErrorRecovery, RD)) {
2991 SemaRef.diagnoseTypo(
2992 Corrected,
2993 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2994 << FieldName << CurrentObjectType);
2995 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2996 hadError = true;
2997 } else {
2998 // Typo correction didn't find anything.
2999 SourceLocation Loc = D->getFieldLoc();
3000
3001 // The loc can be invalid with a "null" designator (i.e. an anonymous
3002 // union/struct). Do our best to approximate the location.
3003 if (Loc.isInvalid())
3004 Loc = IList->getBeginLoc();
3005
3006 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
3007 << FieldName << CurrentObjectType << DIE->getSourceRange();
3008 ++Index;
3009 return true;
3010 }
3011 }
3012 }
3013
3014 unsigned NumBases = 0;
3015 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3016 NumBases = CXXRD->getNumBases();
3017
3018 unsigned FieldIndex = NumBases;
3019
3020 for (auto *FI : RD->fields()) {
3021 if (FI->isUnnamedBitField())
3022 continue;
3023 if (declaresSameEntity(KnownField, FI)) {
3024 KnownField = FI;
3025 break;
3026 }
3027 ++FieldIndex;
3028 }
3029
3031 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3032
3033 // All of the fields of a union are located at the same place in
3034 // the initializer list.
3035 if (RD->isUnion()) {
3036 FieldIndex = 0;
3037 if (StructuredList) {
3038 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3039 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3040 assert(StructuredList->getNumInits() == 1
3041 && "A union should never have more than one initializer!");
3042
3043 Expr *ExistingInit = StructuredList->getInit(0);
3044 if (ExistingInit) {
3045 // We're about to throw away an initializer, emit warning.
3046 diagnoseInitOverride(
3047 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3048 /*UnionOverride=*/true,
3049 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3050 : true);
3051 }
3052
3053 // remove existing initializer
3054 StructuredList->resizeInits(SemaRef.Context, 0);
3055 StructuredList->setInitializedFieldInUnion(nullptr);
3056 }
3057
3058 StructuredList->setInitializedFieldInUnion(*Field);
3059 }
3060 }
3061
3062 // Make sure we can use this declaration.
3063 bool InvalidUse;
3064 if (VerifyOnly)
3065 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3066 else
3067 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3068 if (InvalidUse) {
3069 ++Index;
3070 return true;
3071 }
3072
3073 // C++20 [dcl.init.list]p3:
3074 // The ordered identifiers in the designators of the designated-
3075 // initializer-list shall form a subsequence of the ordered identifiers
3076 // in the direct non-static data members of T.
3077 //
3078 // Note that this is not a condition on forming the aggregate
3079 // initialization, only on actually performing initialization,
3080 // so it is not checked in VerifyOnly mode.
3081 //
3082 // FIXME: This is the only reordering diagnostic we produce, and it only
3083 // catches cases where we have a top-level field designator that jumps
3084 // backwards. This is the only such case that is reachable in an
3085 // otherwise-valid C++20 program, so is the only case that's required for
3086 // conformance, but for consistency, we should diagnose all the other
3087 // cases where a designator takes us backwards too.
3088 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3089 NextField &&
3090 (*NextField == RD->field_end() ||
3091 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3092 // Find the field that we just initialized.
3093 FieldDecl *PrevField = nullptr;
3094 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3095 if (FI->isUnnamedBitField())
3096 continue;
3097 if (*NextField != RD->field_end() &&
3098 declaresSameEntity(*FI, **NextField))
3099 break;
3100 PrevField = *FI;
3101 }
3102
3103 const auto GenerateDesignatedInitReorderingFixit =
3104 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3105 struct ReorderInfo {
3106 int Pos{};
3107 const Expr *InitExpr{};
3108 };
3109
3110 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3111 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3112
3113 const auto *CxxRecord =
3115
3116 for (const FieldDecl *Field : CxxRecord->fields())
3117 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3118
3119 for (const Expr *Init : IList->inits()) {
3120 if (const auto *DI =
3121 dyn_cast_if_present<DesignatedInitExpr>(Init)) {
3122 // We expect only one Designator
3123 if (DI->size() != 1)
3124 return;
3125
3126 const IdentifierInfo *const FieldName =
3127 DI->getDesignator(0)->getFieldName();
3128 // In case we have an unknown initializer in the source, not in
3129 // the record
3130 if (MemberNameInx.contains(FieldName))
3131 ReorderedInitExprs.emplace_back(
3132 ReorderInfo{MemberNameInx.at(FieldName), Init});
3133 }
3134 }
3135
3136 llvm::sort(ReorderedInitExprs,
3137 [](const ReorderInfo &A, const ReorderInfo &B) {
3138 return A.Pos < B.Pos;
3139 });
3140
3141 llvm::SmallString<128> FixedInitList{};
3142 SourceManager &SM = SemaRef.getSourceManager();
3143 const LangOptions &LangOpts = SemaRef.getLangOpts();
3144
3145 // In a derived Record, first n base-classes are initialized first.
3146 // They do not use designated init, so skip them
3147 const ArrayRef<clang::Expr *> IListInits =
3148 IList->inits().drop_front(CxxRecord->getNumBases());
3149 // loop over each existing expressions and apply replacement
3150 for (const auto &[OrigExpr, Repl] :
3151 llvm::zip(IListInits, ReorderedInitExprs)) {
3152 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3153 Repl.InitExpr->getSourceRange());
3154 const StringRef InitText =
3155 Lexer::getSourceText(CharRange, SM, LangOpts);
3156
3157 Diag << FixItHint::CreateReplacement(OrigExpr->getSourceRange(),
3158 InitText.str());
3159 }
3160 };
3161
3162 if (PrevField &&
3163 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3164 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3165 diag::ext_designated_init_reordered)
3166 << KnownField << PrevField << DIE->getSourceRange();
3167
3168 unsigned OldIndex = StructuredIndex - 1;
3169 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3170 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3171 auto Diag = SemaRef.Diag(PrevInit->getBeginLoc(),
3172 diag::note_previous_field_init)
3173 << PrevField << PrevInit->getSourceRange();
3174 GenerateDesignatedInitReorderingFixit(Diag);
3175 }
3176 }
3177 }
3178 }
3179
3180
3181 // Update the designator with the field declaration.
3182 if (!VerifyOnly)
3183 D->setFieldDecl(*Field);
3184
3185 // Make sure that our non-designated initializer list has space
3186 // for a subobject corresponding to this field.
3187 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3188 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3189
3190 // This designator names a flexible array member.
3191 if (Field->getType()->isIncompleteArrayType()) {
3192 bool Invalid = false;
3193 if ((DesigIdx + 1) != DIE->size()) {
3194 // We can't designate an object within the flexible array
3195 // member (because GCC doesn't allow it).
3196 if (!VerifyOnly) {
3197 DesignatedInitExpr::Designator *NextD
3198 = DIE->getDesignator(DesigIdx + 1);
3199 SemaRef.Diag(NextD->getBeginLoc(),
3200 diag::err_designator_into_flexible_array_member)
3201 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3202 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3203 << *Field;
3204 }
3205 Invalid = true;
3206 }
3207
3208 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3209 !isa<StringLiteral>(DIE->getInit())) {
3210 // The initializer is not an initializer list.
3211 if (!VerifyOnly) {
3212 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3213 diag::err_flexible_array_init_needs_braces)
3214 << DIE->getInit()->getSourceRange();
3215 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3216 << *Field;
3217 }
3218 Invalid = true;
3219 }
3220
3221 // Check GNU flexible array initializer.
3222 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3223 TopLevelObject))
3224 Invalid = true;
3225
3226 if (Invalid) {
3227 ++Index;
3228 return true;
3229 }
3230
3231 // Initialize the array.
3232 bool prevHadError = hadError;
3233 unsigned newStructuredIndex = FieldIndex;
3234 unsigned OldIndex = Index;
3235 IList->setInit(Index, DIE->getInit());
3236
3237 InitializedEntity MemberEntity =
3238 InitializedEntity::InitializeMember(*Field, &Entity);
3239 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3240 StructuredList, newStructuredIndex);
3241
3242 IList->setInit(OldIndex, DIE);
3243 if (hadError && !prevHadError) {
3244 ++Field;
3245 ++FieldIndex;
3246 if (NextField)
3247 *NextField = Field;
3248 StructuredIndex = FieldIndex;
3249 return true;
3250 }
3251 } else {
3252 // Recurse to check later designated subobjects.
3253 QualType FieldType = Field->getType();
3254 unsigned newStructuredIndex = FieldIndex;
3255
3256 InitializedEntity MemberEntity =
3257 InitializedEntity::InitializeMember(*Field, &Entity);
3258 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3259 FieldType, nullptr, nullptr, Index,
3260 StructuredList, newStructuredIndex,
3261 FinishSubobjectInit, false))
3262 return true;
3263 }
3264
3265 // Find the position of the next field to be initialized in this
3266 // subobject.
3267 ++Field;
3268 ++FieldIndex;
3269
3270 // If this the first designator, our caller will continue checking
3271 // the rest of this struct/class/union subobject.
3272 if (IsFirstDesignator) {
3273 if (Field != RD->field_end() && Field->isUnnamedBitField())
3274 ++Field;
3275
3276 if (NextField)
3277 *NextField = Field;
3278
3279 StructuredIndex = FieldIndex;
3280 return false;
3281 }
3282
3283 if (!FinishSubobjectInit)
3284 return false;
3285
3286 // We've already initialized something in the union; we're done.
3287 if (RD->isUnion())
3288 return hadError;
3289
3290 // Check the remaining fields within this class/struct/union subobject.
3291 bool prevHadError = hadError;
3292
3293 auto NoBases =
3296 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3297 false, Index, StructuredList, FieldIndex);
3298 return hadError && !prevHadError;
3299 }
3300
3301 // C99 6.7.8p6:
3302 //
3303 // If a designator has the form
3304 //
3305 // [ constant-expression ]
3306 //
3307 // then the current object (defined below) shall have array
3308 // type and the expression shall be an integer constant
3309 // expression. If the array is of unknown size, any
3310 // nonnegative value is valid.
3311 //
3312 // Additionally, cope with the GNU extension that permits
3313 // designators of the form
3314 //
3315 // [ constant-expression ... constant-expression ]
3316 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3317 if (!AT) {
3318 if (!VerifyOnly)
3319 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3320 << CurrentObjectType;
3321 ++Index;
3322 return true;
3323 }
3324
3325 Expr *IndexExpr = nullptr;
3326 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3327 if (D->isArrayDesignator()) {
3328 IndexExpr = DIE->getArrayIndex(*D);
3329 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3330 DesignatedEndIndex = DesignatedStartIndex;
3331 } else {
3332 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3333
3334 DesignatedStartIndex =
3336 DesignatedEndIndex =
3338 IndexExpr = DIE->getArrayRangeEnd(*D);
3339
3340 // Codegen can't handle evaluating array range designators that have side
3341 // effects, because we replicate the AST value for each initialized element.
3342 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3343 // elements with something that has a side effect, so codegen can emit an
3344 // "error unsupported" error instead of miscompiling the app.
3345 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3346 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3347 FullyStructuredList->sawArrayRangeDesignator();
3348 }
3349
3350 if (isa<ConstantArrayType>(AT)) {
3351 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3352 DesignatedStartIndex
3353 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3354 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3355 DesignatedEndIndex
3356 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3357 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3358 if (DesignatedEndIndex >= MaxElements) {
3359 if (!VerifyOnly)
3360 SemaRef.Diag(IndexExpr->getBeginLoc(),
3361 diag::err_array_designator_too_large)
3362 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3363 << IndexExpr->getSourceRange();
3364 ++Index;
3365 return true;
3366 }
3367 } else {
3368 unsigned DesignatedIndexBitWidth =
3370 DesignatedStartIndex =
3371 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3372 DesignatedEndIndex =
3373 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3374 DesignatedStartIndex.setIsUnsigned(true);
3375 DesignatedEndIndex.setIsUnsigned(true);
3376 }
3377
3378 bool IsStringLiteralInitUpdate =
3379 StructuredList && StructuredList->isStringLiteralInit();
3380 if (IsStringLiteralInitUpdate && VerifyOnly) {
3381 // We're just verifying an update to a string literal init. We don't need
3382 // to split the string up into individual characters to do that.
3383 StructuredList = nullptr;
3384 } else if (IsStringLiteralInitUpdate) {
3385 // We're modifying a string literal init; we have to decompose the string
3386 // so we can modify the individual characters.
3387 ASTContext &Context = SemaRef.Context;
3388 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3389
3390 // Compute the character type
3391 QualType CharTy = AT->getElementType();
3392
3393 // Compute the type of the integer literals.
3394 QualType PromotedCharTy = CharTy;
3395 if (Context.isPromotableIntegerType(CharTy))
3396 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3397 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3398
3399 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3400 // Get the length of the string.
3401 uint64_t StrLen = SL->getLength();
3402 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3403 CAT && CAT->getSize().ult(StrLen))
3404 StrLen = CAT->getZExtSize();
3405 StructuredList->resizeInits(Context, StrLen);
3406
3407 // Build a literal for each character in the string, and put them into
3408 // the init list.
3409 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3410 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3411 Expr *Init = new (Context) IntegerLiteral(
3412 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3413 if (CharTy != PromotedCharTy)
3414 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3415 Init, nullptr, VK_PRValue,
3416 FPOptionsOverride());
3417 StructuredList->updateInit(Context, i, Init);
3418 }
3419 } else {
3420 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3421 std::string Str;
3422 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3423
3424 // Get the length of the string.
3425 uint64_t StrLen = Str.size();
3426 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3427 CAT && CAT->getSize().ult(StrLen))
3428 StrLen = CAT->getZExtSize();
3429 StructuredList->resizeInits(Context, StrLen);
3430
3431 // Build a literal for each character in the string, and put them into
3432 // the init list.
3433 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3434 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3435 Expr *Init = new (Context) IntegerLiteral(
3436 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3437 if (CharTy != PromotedCharTy)
3438 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3439 Init, nullptr, VK_PRValue,
3440 FPOptionsOverride());
3441 StructuredList->updateInit(Context, i, Init);
3442 }
3443 }
3444 }
3445
3446 // Make sure that our non-designated initializer list has space
3447 // for a subobject corresponding to this array element.
3448 if (StructuredList &&
3449 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3450 StructuredList->resizeInits(SemaRef.Context,
3451 DesignatedEndIndex.getZExtValue() + 1);
3452
3453 // Repeatedly perform subobject initializations in the range
3454 // [DesignatedStartIndex, DesignatedEndIndex].
3455
3456 // Move to the next designator
3457 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3458 unsigned OldIndex = Index;
3459
3460 InitializedEntity ElementEntity =
3462
3463 while (DesignatedStartIndex <= DesignatedEndIndex) {
3464 // Recurse to check later designated subobjects.
3465 QualType ElementType = AT->getElementType();
3466 Index = OldIndex;
3467
3468 ElementEntity.setElementIndex(ElementIndex);
3469 if (CheckDesignatedInitializer(
3470 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3471 nullptr, Index, StructuredList, ElementIndex,
3472 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3473 false))
3474 return true;
3475
3476 // Move to the next index in the array that we'll be initializing.
3477 ++DesignatedStartIndex;
3478 ElementIndex = DesignatedStartIndex.getZExtValue();
3479 }
3480
3481 // If this the first designator, our caller will continue checking
3482 // the rest of this array subobject.
3483 if (IsFirstDesignator) {
3484 if (NextElementIndex)
3485 *NextElementIndex = std::move(DesignatedStartIndex);
3486 StructuredIndex = ElementIndex;
3487 return false;
3488 }
3489
3490 if (!FinishSubobjectInit)
3491 return false;
3492
3493 // Check the remaining elements within this array subobject.
3494 bool prevHadError = hadError;
3495 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3496 /*SubobjectIsDesignatorContext=*/false, Index,
3497 StructuredList, ElementIndex);
3498 return hadError && !prevHadError;
3499}
3500
3501// Get the structured initializer list for a subobject of type
3502// @p CurrentObjectType.
3503InitListExpr *
3504InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3505 QualType CurrentObjectType,
3506 InitListExpr *StructuredList,
3507 unsigned StructuredIndex,
3508 SourceRange InitRange,
3509 bool IsFullyOverwritten) {
3510 if (!StructuredList)
3511 return nullptr;
3512
3513 Expr *ExistingInit = nullptr;
3514 if (StructuredIndex < StructuredList->getNumInits())
3515 ExistingInit = StructuredList->getInit(StructuredIndex);
3516
3517 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3518 // There might have already been initializers for subobjects of the current
3519 // object, but a subsequent initializer list will overwrite the entirety
3520 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3521 //
3522 // struct P { char x[6]; };
3523 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3524 //
3525 // The first designated initializer is ignored, and l.x is just "f".
3526 if (!IsFullyOverwritten)
3527 return Result;
3528
3529 if (ExistingInit) {
3530 // We are creating an initializer list that initializes the
3531 // subobjects of the current object, but there was already an
3532 // initialization that completely initialized the current
3533 // subobject:
3534 //
3535 // struct X { int a, b; };
3536 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3537 //
3538 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3539 // designated initializer overwrites the [0].b initializer
3540 // from the prior initialization.
3541 //
3542 // When the existing initializer is an expression rather than an
3543 // initializer list, we cannot decompose and update it in this way.
3544 // For example:
3545 //
3546 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3547 //
3548 // This case is handled by CheckDesignatedInitializer.
3549 diagnoseInitOverride(ExistingInit, InitRange);
3550 }
3551
3552 unsigned ExpectedNumInits = 0;
3553 if (Index < IList->getNumInits()) {
3554 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3555 ExpectedNumInits = Init->getNumInits();
3556 else
3557 ExpectedNumInits = IList->getNumInits() - Index;
3558 }
3559
3560 InitListExpr *Result = createInitListExpr(
3561 CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false);
3562
3563 // Link this new initializer list into the structured initializer
3564 // lists.
3565 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3566 return Result;
3567}
3568
3569InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType,
3570 SourceRange InitRange,
3571 unsigned ExpectedNumInits,
3572 bool IsExplicit) {
3573 InitListExpr *Result =
3574 new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(),
3575 {}, InitRange.getEnd(), IsExplicit);
3576
3577 QualType ResultType = CurrentObjectType;
3578 if (!ResultType->isArrayType())
3579 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3580 Result->setType(ResultType);
3581
3582 // Pre-allocate storage for the structured initializer list.
3583 unsigned NumElements = 0;
3584
3585 if (const ArrayType *AType
3586 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3587 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3588 NumElements = CAType->getZExtSize();
3589 // Simple heuristic so that we don't allocate a very large
3590 // initializer with many empty entries at the end.
3591 if (NumElements > ExpectedNumInits)
3592 NumElements = 0;
3593 }
3594 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3595 NumElements = VType->getNumElements();
3596 } else if (CurrentObjectType->isRecordType()) {
3597 NumElements = numStructUnionElements(CurrentObjectType);
3598 } else if (CurrentObjectType->isDependentType()) {
3599 NumElements = 1;
3600 }
3601
3602 Result->reserveInits(SemaRef.Context, NumElements);
3603
3604 return Result;
3605}
3606
3607/// Update the initializer at index @p StructuredIndex within the
3608/// structured initializer list to the value @p expr.
3609void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3610 unsigned &StructuredIndex,
3611 Expr *expr) {
3612 // No structured initializer list to update
3613 if (!StructuredList)
3614 return;
3615
3616 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3617 StructuredIndex, expr)) {
3618 // This initializer overwrites a previous initializer.
3619 // No need to diagnose when `expr` is nullptr because a more relevant
3620 // diagnostic has already been issued and this diagnostic is potentially
3621 // noise.
3622 if (expr)
3623 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3624 }
3625
3626 ++StructuredIndex;
3627}
3628
3630 const InitializedEntity &Entity, InitListExpr *From) {
3631 QualType Type = Entity.getType();
3632 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3633 /*TreatUnavailableAsInvalid=*/false,
3634 /*InOverloadResolution=*/true);
3635 return !Check.HadError();
3636}
3637
3638/// Check that the given Index expression is a valid array designator
3639/// value. This is essentially just a wrapper around
3640/// VerifyIntegerConstantExpression that also checks for negative values
3641/// and produces a reasonable diagnostic if there is a
3642/// failure. Returns the index expression, possibly with an implicit cast
3643/// added, on success. If everything went okay, Value will receive the
3644/// value of the constant expression.
3645static ExprResult
3646CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3647 SourceLocation Loc = Index->getBeginLoc();
3648
3649 // Make sure this is an integer constant expression.
3652 if (Result.isInvalid())
3653 return Result;
3654
3655 if (Value.isSigned() && Value.isNegative())
3656 return S.Diag(Loc, diag::err_array_designator_negative)
3657 << toString(Value, 10) << Index->getSourceRange();
3658
3659 Value.setIsUnsigned(true);
3660 return Result;
3661}
3662
3664 SourceLocation EqualOrColonLoc,
3665 bool GNUSyntax,
3666 ExprResult Init) {
3667 typedef DesignatedInitExpr::Designator ASTDesignator;
3668
3669 bool Invalid = false;
3671 SmallVector<Expr *, 32> InitExpressions;
3672
3673 // Build designators and check array designator expressions.
3674 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3675 const Designator &D = Desig.getDesignator(Idx);
3676
3677 if (D.isFieldDesignator()) {
3678 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3679 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3680 } else if (D.isArrayDesignator()) {
3681 Expr *Index = D.getArrayIndex();
3682 llvm::APSInt IndexValue;
3683 if (!Index->isTypeDependent() && !Index->isValueDependent())
3684 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3685 if (!Index)
3686 Invalid = true;
3687 else {
3688 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3689 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3690 InitExpressions.push_back(Index);
3691 }
3692 } else if (D.isArrayRangeDesignator()) {
3693 Expr *StartIndex = D.getArrayRangeStart();
3694 Expr *EndIndex = D.getArrayRangeEnd();
3695 llvm::APSInt StartValue;
3696 llvm::APSInt EndValue;
3697 bool StartDependent = StartIndex->isTypeDependent() ||
3698 StartIndex->isValueDependent();
3699 bool EndDependent = EndIndex->isTypeDependent() ||
3700 EndIndex->isValueDependent();
3701 if (!StartDependent)
3702 StartIndex =
3703 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3704 if (!EndDependent)
3705 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3706
3707 if (!StartIndex || !EndIndex)
3708 Invalid = true;
3709 else {
3710 // Make sure we're comparing values with the same bit width.
3711 if (StartDependent || EndDependent) {
3712 // Nothing to compute.
3713 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3714 EndValue = EndValue.extend(StartValue.getBitWidth());
3715 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3716 StartValue = StartValue.extend(EndValue.getBitWidth());
3717
3718 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3719 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3720 << toString(StartValue, 10) << toString(EndValue, 10)
3721 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3722 Invalid = true;
3723 } else {
3724 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3725 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3726 D.getRBracketLoc()));
3727 InitExpressions.push_back(StartIndex);
3728 InitExpressions.push_back(EndIndex);
3729 }
3730 }
3731 }
3732 }
3733
3734 if (Invalid || Init.isInvalid())
3735 return ExprError();
3736
3737 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3738 EqualOrColonLoc, GNUSyntax,
3739 Init.getAs<Expr>());
3740}
3741
3742//===----------------------------------------------------------------------===//
3743// Initialization entity
3744//===----------------------------------------------------------------------===//
3745
3746InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3747 const InitializedEntity &Parent)
3748 : Parent(&Parent), Index(Index)
3749{
3750 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3751 Kind = EK_ArrayElement;
3752 Type = AT->getElementType();
3753 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3754 Kind = EK_VectorElement;
3755 Type = VT->getElementType();
3756 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3757 Kind = EK_MatrixElement;
3758 Type = MT->getElementType();
3759 } else {
3760 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3761 assert(CT && "Unexpected type");
3762 Kind = EK_ComplexElement;
3763 Type = CT->getElementType();
3764 }
3765}
3766
3769 const CXXBaseSpecifier *Base,
3770 bool IsInheritedVirtualBase,
3771 const InitializedEntity *Parent) {
3772 InitializedEntity Result;
3773 Result.Kind = EK_Base;
3774 Result.Parent = Parent;
3775 Result.Base = {Base, IsInheritedVirtualBase};
3776 Result.Type = Base->getType();
3777 return Result;
3778}
3779
3781 switch (getKind()) {
3782 case EK_Parameter:
3784 ParmVarDecl *D = Parameter.getPointer();
3785 return (D ? D->getDeclName() : DeclarationName());
3786 }
3787
3788 case EK_Variable:
3789 case EK_Member:
3791 case EK_Binding:
3793 return Variable.VariableOrMember->getDeclName();
3794
3795 case EK_LambdaCapture:
3796 return DeclarationName(Capture.VarID);
3797
3798 case EK_Result:
3799 case EK_StmtExprResult:
3800 case EK_Exception:
3801 case EK_New:
3802 case EK_Temporary:
3803 case EK_Base:
3804 case EK_Delegating:
3805 case EK_ArrayElement:
3806 case EK_VectorElement:
3807 case EK_MatrixElement:
3808 case EK_ComplexElement:
3809 case EK_BlockElement:
3812 case EK_RelatedResult:
3813 return DeclarationName();
3814 }
3815
3816 llvm_unreachable("Invalid EntityKind!");
3817}
3818
3820 switch (getKind()) {
3821 case EK_Variable:
3822 case EK_Member:
3824 case EK_Binding:
3826 return cast<ValueDecl>(Variable.VariableOrMember);
3827
3828 case EK_Parameter:
3830 return Parameter.getPointer();
3831
3832 case EK_Result:
3833 case EK_StmtExprResult:
3834 case EK_Exception:
3835 case EK_New:
3836 case EK_Temporary:
3837 case EK_Base:
3838 case EK_Delegating:
3839 case EK_ArrayElement:
3840 case EK_VectorElement:
3841 case EK_MatrixElement:
3842 case EK_ComplexElement:
3843 case EK_BlockElement:
3845 case EK_LambdaCapture:
3847 case EK_RelatedResult:
3848 return nullptr;
3849 }
3850
3851 llvm_unreachable("Invalid EntityKind!");
3852}
3853
3855 switch (getKind()) {
3856 case EK_Result:
3857 case EK_Exception:
3858 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3859
3860 case EK_StmtExprResult:
3861 case EK_Variable:
3862 case EK_Parameter:
3865 case EK_Member:
3867 case EK_Binding:
3868 case EK_New:
3869 case EK_Temporary:
3871 case EK_Base:
3872 case EK_Delegating:
3873 case EK_ArrayElement:
3874 case EK_VectorElement:
3875 case EK_MatrixElement:
3876 case EK_ComplexElement:
3877 case EK_BlockElement:
3879 case EK_LambdaCapture:
3880 case EK_RelatedResult:
3881 break;
3882 }
3883
3884 return false;
3885}
3886
3887unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3888 assert(getParent() != this);
3889 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3890 for (unsigned I = 0; I != Depth; ++I)
3891 OS << "`-";
3892
3893 switch (getKind()) {
3894 case EK_Variable: OS << "Variable"; break;
3895 case EK_Parameter: OS << "Parameter"; break;
3896 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3897 break;
3898 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3899 case EK_Result: OS << "Result"; break;
3900 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3901 case EK_Exception: OS << "Exception"; break;
3902 case EK_Member:
3904 OS << "Member";
3905 break;
3906 case EK_Binding: OS << "Binding"; break;
3907 case EK_New: OS << "New"; break;
3908 case EK_Temporary: OS << "Temporary"; break;
3909 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3910 case EK_RelatedResult: OS << "RelatedResult"; break;
3911 case EK_Base: OS << "Base"; break;
3912 case EK_Delegating: OS << "Delegating"; break;
3913 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3914 case EK_VectorElement: OS << "VectorElement " << Index; break;
3915 case EK_MatrixElement:
3916 OS << "MatrixElement " << Index;
3917 break;
3918 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3919 case EK_BlockElement: OS << "Block"; break;
3921 OS << "Block (lambda)";
3922 break;
3923 case EK_LambdaCapture:
3924 OS << "LambdaCapture ";
3925 OS << DeclarationName(Capture.VarID);
3926 break;
3927 }
3928
3929 if (auto *D = getDecl()) {
3930 OS << " ";
3931 D->printQualifiedName(OS);
3932 }
3933
3934 OS << " '" << getType() << "'\n";
3935
3936 return Depth + 1;
3937}
3938
3939LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3940 dumpImpl(llvm::errs());
3941}
3942
3943//===----------------------------------------------------------------------===//
3944// Initialization sequence
3945//===----------------------------------------------------------------------===//
3946
3993
3995 // There can be some lvalue adjustments after the SK_BindReference step.
3996 for (const Step &S : llvm::reverse(Steps)) {
3997 if (S.Kind == SK_BindReference)
3998 return true;
3999 if (S.Kind == SK_BindReferenceToTemporary)
4000 return false;
4001 }
4002 return false;
4003}
4004
4006 if (!Failed())
4007 return false;
4008
4009 switch (getFailureKind()) {
4020 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4037 case FK_Incomplete:
4042 case FK_PlaceholderType:
4048 return false;
4049
4054 return FailedOverloadResult == OR_Ambiguous;
4055 }
4056
4057 llvm_unreachable("Invalid EntityKind!");
4058}
4059
4061 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4062}
4063
4064void
4065InitializationSequence
4066::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4068 bool HadMultipleCandidates) {
4069 Step S;
4071 S.Type = Function->getType();
4072 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4075 Steps.push_back(S);
4076}
4077
4079 ExprValueKind VK) {
4080 Step S;
4081 switch (VK) {
4082 case VK_PRValue:
4084 break;
4085 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4086 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4087 }
4088 S.Type = BaseType;
4089 Steps.push_back(S);
4090}
4091
4093 bool BindingTemporary) {
4094 Step S;
4095 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4096 S.Type = T;
4097 Steps.push_back(S);
4098}
4099
4101 Step S;
4102 S.Kind = SK_FinalCopy;
4103 S.Type = T;
4104 Steps.push_back(S);
4105}
4106
4108 Step S;
4110 S.Type = T;
4111 Steps.push_back(S);
4112}
4113
4114void
4116 DeclAccessPair FoundDecl,
4117 QualType T,
4118 bool HadMultipleCandidates) {
4119 Step S;
4121 S.Type = T;
4122 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4124 S.Function.FoundDecl = FoundDecl;
4125 Steps.push_back(S);
4126}
4127
4129 ExprValueKind VK) {
4130 Step S;
4131 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4132 switch (VK) {
4133 case VK_PRValue:
4135 break;
4136 case VK_XValue:
4138 break;
4139 case VK_LValue:
4141 break;
4142 }
4143 S.Type = Ty;
4144 Steps.push_back(S);
4145}
4146
4148 Step S;
4150 S.Type = Ty;
4151 Steps.push_back(S);
4152}
4153
4155 Step S;
4157 S.Type = Ty;
4158 Steps.push_back(S);
4159}
4160
4163 bool TopLevelOfInitList) {
4164 Step S;
4165 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4167 S.Type = T;
4168 S.ICS = new ImplicitConversionSequence(ICS);
4169 Steps.push_back(S);
4170}
4171
4173 Step S;
4175 S.Type = T;
4176 Steps.push_back(S);
4177}
4178
4181 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4182 Step S;
4183 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4186 S.Type = T;
4187 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4189 S.Function.FoundDecl = FoundDecl;
4190 Steps.push_back(S);
4191}
4192
4194 Step S;
4196 S.Type = T;
4197 Steps.push_back(S);
4198}
4199
4201 Step S;
4202 S.Kind = SK_CAssignment;
4203 S.Type = T;
4204 Steps.push_back(S);
4205}
4206
4208 Step S;
4209 S.Kind = SK_StringInit;
4210 S.Type = T;
4211 Steps.push_back(S);
4212}
4213
4215 Step S;
4217 S.Type = T;
4218 Steps.push_back(S);
4219}
4220
4222 Step S;
4223 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4224 S.Type = T;
4225 Steps.push_back(S);
4226}
4227
4229 Step S;
4231 S.Type = EltT;
4232 Steps.insert(Steps.begin(), S);
4233
4235 S.Type = T;
4236 Steps.push_back(S);
4237}
4238
4240 Step S;
4242 S.Type = T;
4243 Steps.push_back(S);
4244}
4245
4247 bool shouldCopy) {
4248 Step s;
4249 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4251 s.Type = type;
4252 Steps.push_back(s);
4253}
4254
4256 Step S;
4258 S.Type = T;
4259 Steps.push_back(S);
4260}
4261
4263 Step S;
4265 S.Type = T;
4266 Steps.push_back(S);
4267}
4268
4270 Step S;
4272 S.Type = T;
4273 Steps.push_back(S);
4274}
4275
4277 Step S;
4279 S.Type = T;
4280 Steps.push_back(S);
4281}
4282
4284 Step S;
4286 S.Type = T;
4287 Steps.push_back(S);
4288}
4289
4291 InitListExpr *Syntactic) {
4292 assert(Syntactic->getNumInits() == 1 &&
4293 "Can only unwrap trivial init lists.");
4294 Step S;
4296 S.Type = Syntactic->getInit(0)->getType();
4297 Steps.insert(Steps.begin(), S);
4298}
4299
4301 InitListExpr *Syntactic) {
4302 assert(Syntactic->getNumInits() == 1 &&
4303 "Can only rewrap trivial init lists.");
4304 Step S;
4306 S.Type = Syntactic->getInit(0)->getType();
4307 Steps.insert(Steps.begin(), S);
4308
4310 S.Type = T;
4311 S.WrappingSyntacticList = Syntactic;
4312 Steps.push_back(S);
4313}
4314
4316 Step S;
4318 S.Type = T;
4319 Steps.push_back(S);
4320}
4321
4325 this->Failure = Failure;
4326 this->FailedOverloadResult = Result;
4327}
4328
4329//===----------------------------------------------------------------------===//
4330// Attempt initialization
4331//===----------------------------------------------------------------------===//
4332
4333/// Tries to add a zero initializer. Returns true if that worked.
4334static bool
4336 const InitializedEntity &Entity) {
4338 return false;
4339
4340 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4341 if (VD->getInit() || VD->getEndLoc().isMacroID())
4342 return false;
4343
4344 QualType VariableTy = VD->getType().getCanonicalType();
4346 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4347 if (!Init.empty()) {
4348 Sequence.AddZeroInitializationStep(Entity.getType());
4349 Sequence.SetZeroInitializationFixit(Init, Loc);
4350 return true;
4351 }
4352 return false;
4353}
4354
4356 InitializationSequence &Sequence,
4357 const InitializedEntity &Entity) {
4358 if (!S.getLangOpts().ObjCAutoRefCount) return;
4359
4360 /// When initializing a parameter, produce the value if it's marked
4361 /// __attribute__((ns_consumed)).
4362 if (Entity.isParameterKind()) {
4363 if (!Entity.isParameterConsumed())
4364 return;
4365
4366 assert(Entity.getType()->isObjCRetainableType() &&
4367 "consuming an object of unretainable type?");
4368 Sequence.AddProduceObjCObjectStep(Entity.getType());
4369
4370 /// When initializing a return value, if the return type is a
4371 /// retainable type, then returns need to immediately retain the
4372 /// object. If an autorelease is required, it will be done at the
4373 /// last instant.
4374 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4376 if (!Entity.getType()->isObjCRetainableType())
4377 return;
4378
4379 Sequence.AddProduceObjCObjectStep(Entity.getType());
4380 }
4381}
4382
4383/// Initialize an array from another array
4384static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4385 const InitializedEntity &Entity, Expr *Initializer,
4386 QualType DestType, InitializationSequence &Sequence,
4387 bool TreatUnavailableAsInvalid) {
4388 // If source is a prvalue, use it directly.
4389 if (Initializer->isPRValue()) {
4390 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4391 return;
4392 }
4393
4394 // Emit element-at-a-time copy loop.
4395 InitializedEntity Element =
4397 QualType InitEltT =
4399
4400 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4401 // allocator at the moment
4403 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4404 Initializer->getObjectKind());
4405 Expr *OVEAsExpr = OVE;
4406 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4407 /*TopLevelOfInitList*/ false,
4408 TreatUnavailableAsInvalid);
4409 if (Sequence)
4410 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4411}
4412
4413static void TryListInitialization(Sema &S,
4414 const InitializedEntity &Entity,
4415 const InitializationKind &Kind,
4416 InitListExpr *InitList,
4417 InitializationSequence &Sequence,
4418 bool TreatUnavailableAsInvalid);
4419
4420/// When initializing from init list via constructor, handle
4421/// initialization of an object of type std::initializer_list<T>.
4422///
4423/// \return true if we have handled initialization of an object of type
4424/// std::initializer_list<T>, false otherwise.
4426 InitListExpr *List,
4427 QualType DestType,
4428 InitializationSequence &Sequence,
4429 bool TreatUnavailableAsInvalid) {
4430 QualType E;
4431 if (!S.isStdInitializerList(DestType, &E))
4432 return false;
4433
4434 if (!S.isCompleteType(List->getExprLoc(), E)) {
4435 Sequence.setIncompleteTypeFailure(E);
4436 return true;
4437 }
4438
4439 // Try initializing a temporary array from the init list.
4441 E.withConst(),
4442 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4445 InitializedEntity HiddenArray =
4448 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4449 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4450 TreatUnavailableAsInvalid);
4451 if (Sequence)
4452 Sequence.AddStdInitializerListConstructionStep(DestType);
4453 return true;
4454}
4455
4456/// Determine if the constructor has the signature of a copy or move
4457/// constructor for the type T of the class in which it was found. That is,
4458/// determine if its first parameter is of type T or reference to (possibly
4459/// cv-qualified) T.
4461 const ConstructorInfo &Info) {
4462 if (Info.Constructor->getNumParams() == 0)
4463 return false;
4464
4465 QualType ParmT =
4467 CanQualType ClassT = Ctx.getCanonicalTagType(
4469
4470 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4471}
4472
4474 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4475 OverloadCandidateSet &CandidateSet, QualType DestType,
4477 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4478 bool IsListInit, bool RequireActualConstructor,
4479 bool SecondStepOfCopyInit = false) {
4481 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4482
4483 for (NamedDecl *D : Ctors) {
4484 auto Info = getConstructorInfo(D);
4485 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4486 continue;
4487
4488 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4489 continue;
4490
4491 // C++11 [over.best.ics]p4:
4492 // ... and the constructor or user-defined conversion function is a
4493 // candidate by
4494 // - 13.3.1.3, when the argument is the temporary in the second step
4495 // of a class copy-initialization, or
4496 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4497 // - the second phase of 13.3.1.7 when the initializer list has exactly
4498 // one element that is itself an initializer list, and the target is
4499 // the first parameter of a constructor of class X, and the conversion
4500 // is to X or reference to (possibly cv-qualified X),
4501 // user-defined conversion sequences are not considered.
4502 bool SuppressUserConversions =
4503 SecondStepOfCopyInit ||
4504 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4506
4507 if (Info.ConstructorTmpl)
4509 Info.ConstructorTmpl, Info.FoundDecl,
4510 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4511 /*PartialOverloading=*/false, AllowExplicit);
4512 else {
4513 // C++ [over.match.copy]p1:
4514 // - When initializing a temporary to be bound to the first parameter
4515 // of a constructor [for type T] that takes a reference to possibly
4516 // cv-qualified T as its first argument, called with a single
4517 // argument in the context of direct-initialization, explicit
4518 // conversion functions are also considered.
4519 // FIXME: What if a constructor template instantiates to such a signature?
4520 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4521 Args.size() == 1 &&
4523 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4524 CandidateSet, SuppressUserConversions,
4525 /*PartialOverloading=*/false, AllowExplicit,
4526 AllowExplicitConv);
4527 }
4528 }
4529
4530 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4531 //
4532 // When initializing an object of class type T by constructor
4533 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4534 // from a single expression of class type U, conversion functions of
4535 // U that convert to the non-reference type cv T are candidates.
4536 // Explicit conversion functions are only candidates during
4537 // direct-initialization.
4538 //
4539 // Note: SecondStepOfCopyInit is only ever true in this case when
4540 // evaluating whether to produce a C++98 compatibility warning.
4541 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4542 !RequireActualConstructor && !SecondStepOfCopyInit) {
4543 Expr *Initializer = Args[0];
4544 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4545 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4546 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4547 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4548 NamedDecl *D = *I;
4550 D = D->getUnderlyingDecl();
4551
4552 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4553 CXXConversionDecl *Conv;
4554 if (ConvTemplate)
4555 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4556 else
4557 Conv = cast<CXXConversionDecl>(D);
4558
4559 if (ConvTemplate)
4561 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4562 CandidateSet, AllowExplicit, AllowExplicit,
4563 /*AllowResultConversion*/ false);
4564 else
4565 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4566 DestType, CandidateSet, AllowExplicit,
4567 AllowExplicit,
4568 /*AllowResultConversion*/ false);
4569 }
4570 }
4571 }
4572
4573 // Perform overload resolution and return the result.
4574 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4575}
4576
4577/// Attempt initialization by constructor (C++ [dcl.init]), which
4578/// enumerates the constructors of the initialized entity and performs overload
4579/// resolution to select the best.
4580/// \param DestType The destination class type.
4581/// \param DestArrayType The destination type, which is either DestType or
4582/// a (possibly multidimensional) array of DestType.
4583/// \param IsListInit Is this list-initialization?
4584/// \param IsInitListCopy Is this non-list-initialization resulting from a
4585/// list-initialization from {x} where x is the same
4586/// aggregate type as the entity?
4588 const InitializedEntity &Entity,
4589 const InitializationKind &Kind,
4590 MultiExprArg Args, QualType DestType,
4591 QualType DestArrayType,
4592 InitializationSequence &Sequence,
4593 bool IsListInit = false,
4594 bool IsInitListCopy = false) {
4595 assert(((!IsListInit && !IsInitListCopy) ||
4596 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4597 "IsListInit/IsInitListCopy must come with a single initializer list "
4598 "argument.");
4599 InitListExpr *ILE =
4600 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4601 MultiExprArg UnwrappedArgs =
4602 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4603
4604 // The type we're constructing needs to be complete.
4605 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4606 Sequence.setIncompleteTypeFailure(DestType);
4607 return;
4608 }
4609
4610 bool RequireActualConstructor =
4611 !(Entity.getKind() != InitializedEntity::EK_Base &&
4613 Entity.getKind() !=
4615
4616 bool CopyElisionPossible = false;
4617 auto ElideConstructor = [&] {
4618 // Convert qualifications if necessary.
4619 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4620 if (ILE)
4621 Sequence.RewrapReferenceInitList(DestType, ILE);
4622 };
4623
4624 // C++17 [dcl.init]p17:
4625 // - If the initializer expression is a prvalue and the cv-unqualified
4626 // version of the source type is the same class as the class of the
4627 // destination, the initializer expression is used to initialize the
4628 // destination object.
4629 // Per DR (no number yet), this does not apply when initializing a base
4630 // class or delegating to another constructor from a mem-initializer.
4631 // ObjC++: Lambda captured by the block in the lambda to block conversion
4632 // should avoid copy elision.
4633 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4634 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4635 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4636 if (ILE && !DestType->isAggregateType()) {
4637 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4638 // Make this an elision if this won't call an initializer-list
4639 // constructor. (Always on an aggregate type or check constructors first.)
4640
4641 // This effectively makes our resolution as follows. The parts in angle
4642 // brackets are additions.
4643 // C++17 [over.match.list]p(1.2):
4644 // - If no viable initializer-list constructor is found <and the
4645 // initializer list does not consist of exactly a single element with
4646 // the same cv-unqualified class type as T>, [...]
4647 // C++17 [dcl.init.list]p(3.6):
4648 // - Otherwise, if T is a class type, constructors are considered. The
4649 // applicable constructors are enumerated and the best one is chosen
4650 // through overload resolution. <If no constructor is found and the
4651 // initializer list consists of exactly a single element with the same
4652 // cv-unqualified class type as T, the object is initialized from that
4653 // element (by copy-initialization for copy-list-initialization, or by
4654 // direct-initialization for direct-list-initialization). Otherwise, >
4655 // if a narrowing conversion [...]
4656 assert(!IsInitListCopy &&
4657 "IsInitListCopy only possible with aggregate types");
4658 CopyElisionPossible = true;
4659 } else {
4660 ElideConstructor();
4661 return;
4662 }
4663 }
4664
4665 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4666 // Build the candidate set directly in the initialization sequence
4667 // structure, so that it will persist if we fail.
4668 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4669
4670 // Determine whether we are allowed to call explicit constructors or
4671 // explicit conversion operators.
4672 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4673 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4674
4675 // - Otherwise, if T is a class type, constructors are considered. The
4676 // applicable constructors are enumerated, and the best one is chosen
4677 // through overload resolution.
4678 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4679
4682 bool AsInitializerList = false;
4683
4684 // C++11 [over.match.list]p1, per DR1467:
4685 // When objects of non-aggregate type T are list-initialized, such that
4686 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4687 // according to the rules in this section, overload resolution selects
4688 // the constructor in two phases:
4689 //
4690 // - Initially, the candidate functions are the initializer-list
4691 // constructors of the class T and the argument list consists of the
4692 // initializer list as a single argument.
4693 if (IsListInit) {
4694 AsInitializerList = true;
4695
4696 // If the initializer list has no elements and T has a default constructor,
4697 // the first phase is omitted.
4698 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4700 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4701 CopyInitialization, AllowExplicit,
4702 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4703
4704 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4705 // No initializer list candidate
4706 ElideConstructor();
4707 return;
4708 }
4709 }
4710
4711 // if the initialization is direct-initialization, or if it is
4712 // copy-initialization where the cv-unqualified version of the source type is
4713 // the same as or is derived from the class of the destination type,
4714 // constructors are considered.
4715 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4716 Kind.getKind() == InitializationKind::IK_Copy) &&
4717 Args.size() == 1 &&
4719 Args[0]->getType().getNonReferenceType(),
4720 DestType.getNonReferenceType()))
4721 RequireActualConstructor = true;
4722
4723 // C++11 [over.match.list]p1:
4724 // - If no viable initializer-list constructor is found, overload resolution
4725 // is performed again, where the candidate functions are all the
4726 // constructors of the class T and the argument list consists of the
4727 // elements of the initializer list.
4729 AsInitializerList = false;
4731 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4732 Best, CopyInitialization, AllowExplicit,
4733 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4734 }
4735 if (Result) {
4736 Sequence.SetOverloadFailure(
4739 Result);
4740
4741 if (Result != OR_Deleted)
4742 return;
4743 }
4744
4745 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4746
4747 // In C++17, ResolveConstructorOverload can select a conversion function
4748 // instead of a constructor.
4749 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4750 // Add the user-defined conversion step that calls the conversion function.
4751 QualType ConvType = CD->getConversionType();
4752 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4753 "should not have selected this conversion function");
4754 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4755 HadMultipleCandidates);
4756 if (!S.Context.hasSameType(ConvType, DestType))
4757 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4758 if (IsListInit)
4759 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4760 return;
4761 }
4762
4763 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4764 if (Result != OR_Deleted) {
4765 if (!IsListInit &&
4766 (Kind.getKind() == InitializationKind::IK_Default ||
4767 Kind.getKind() == InitializationKind::IK_Direct) &&
4768 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4769 DestRecordDecl->isAggregate() &&
4770 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4771 !S.isUnevaluatedContext()) {
4772 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4773 << /* Var-in-Record */ 1 << DestRecordDecl;
4774 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4775 }
4776
4777 // C++11 [dcl.init]p6:
4778 // If a program calls for the default initialization of an object
4779 // of a const-qualified type T, T shall be a class type with a
4780 // user-provided default constructor.
4781 // C++ core issue 253 proposal:
4782 // If the implicit default constructor initializes all subobjects, no
4783 // initializer should be required.
4784 // The 253 proposal is for example needed to process libstdc++ headers
4785 // in 5.x.
4786 if (Kind.getKind() == InitializationKind::IK_Default &&
4787 Entity.getType().isConstQualified()) {
4788 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4789 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4791 return;
4792 }
4793 }
4794
4795 // C++11 [over.match.list]p1:
4796 // In copy-list-initialization, if an explicit constructor is chosen, the
4797 // initializer is ill-formed.
4798 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4800 return;
4801 }
4802 }
4803
4804 // [class.copy.elision]p3:
4805 // In some copy-initialization contexts, a two-stage overload resolution
4806 // is performed.
4807 // If the first overload resolution selects a deleted function, we also
4808 // need the initialization sequence to decide whether to perform the second
4809 // overload resolution.
4810 // For deleted functions in other contexts, there is no need to get the
4811 // initialization sequence.
4812 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4813 return;
4814
4815 // Add the constructor initialization step. Any cv-qualification conversion is
4816 // subsumed by the initialization.
4818 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4819 IsListInit | IsInitListCopy, AsInitializerList);
4820}
4821
4823 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4824 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4825 ExprResult *Result = nullptr);
4826
4827/// Attempt to initialize an object of a class type either by
4828/// direct-initialization, or by copy-initialization from an
4829/// expression of the same or derived class type. This corresponds
4830/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4831///
4832/// \param IsAggrListInit Is this non-list-initialization being done as
4833/// part of a list-initialization of an aggregate
4834/// from a single expression of the same or
4835/// derived class type (C++2c [dcl.init.list] p3.2)?
4837 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4838 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4839 bool IsAggrListInit) {
4840 // C++2c [dcl.init.general] p16.6:
4841 // * Otherwise, if the destination type is a class type:
4842 // * If the initializer expression is a prvalue and
4843 // the cv-unqualified version of the source type is the same
4844 // as the destination type, the initializer expression is used
4845 // to initialize the destination object.
4846 // * Otherwise, if the initialization is direct-initialization,
4847 // or if it is copy-initialization where the cv-unqualified
4848 // version of the source type is the same as or is derived from
4849 // the class of the destination type, constructors are considered.
4850 // The applicable constructors are enumerated, and the best one
4851 // is chosen through overload resolution. Then:
4852 // * If overload resolution is successful, the selected
4853 // constructor is called to initialize the object, with
4854 // the initializer expression or expression-list as its
4855 // argument(s).
4856 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4857 Sequence, /*IsListInit=*/false, IsAggrListInit);
4858
4859 // * Otherwise, if no constructor is viable, the destination type
4860 // is an aggregate class, and the initializer is a parenthesized
4861 // expression-list, the object is initialized as follows. [...]
4862 // Parenthesized initialization of aggregates is a C++20 feature.
4863 if (S.getLangOpts().CPlusPlus20 &&
4864 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4865 Sequence.getFailureKind() ==
4868 (IsAggrListInit || DestType->isAggregateType()))
4869 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4870 /*VerifyOnly=*/true);
4871
4872 // * Otherwise, the initialization is ill-formed.
4873}
4874
4875static bool
4878 QualType &SourceType,
4879 QualType &UnqualifiedSourceType,
4880 QualType UnqualifiedTargetType,
4881 InitializationSequence &Sequence) {
4882 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4883 S.Context.OverloadTy) {
4885 bool HadMultipleCandidates = false;
4886 if (FunctionDecl *Fn
4888 UnqualifiedTargetType,
4889 false, Found,
4890 &HadMultipleCandidates)) {
4892 HadMultipleCandidates);
4893 SourceType = Fn->getType();
4894 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4895 } else if (!UnqualifiedTargetType->isRecordType()) {
4897 return true;
4898 }
4899 }
4900 return false;
4901}
4902
4903static void TryReferenceInitializationCore(Sema &S,
4904 const InitializedEntity &Entity,
4905 const InitializationKind &Kind,
4906 Expr *Initializer,
4907 QualType cv1T1, QualType T1,
4908 Qualifiers T1Quals,
4909 QualType cv2T2, QualType T2,
4910 Qualifiers T2Quals,
4911 InitializationSequence &Sequence,
4912 bool TopLevelOfInitList);
4913
4914static void TryValueInitialization(Sema &S,
4915 const InitializedEntity &Entity,
4916 const InitializationKind &Kind,
4917 InitializationSequence &Sequence,
4918 InitListExpr *InitList = nullptr);
4919
4920/// Attempt list initialization of a reference.
4922 const InitializedEntity &Entity,
4923 const InitializationKind &Kind,
4924 InitListExpr *InitList,
4925 InitializationSequence &Sequence,
4926 bool TreatUnavailableAsInvalid) {
4927 // First, catch C++03 where this isn't possible.
4928 if (!S.getLangOpts().CPlusPlus11) {
4930 return;
4931 }
4932 // Can't reference initialize a compound literal.
4935 return;
4936 }
4937
4938 QualType DestType = Entity.getType();
4939 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4940 Qualifiers T1Quals;
4941 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4942
4943 // Reference initialization via an initializer list works thus:
4944 // If the initializer list consists of a single element that is
4945 // reference-related to the referenced type, bind directly to that element
4946 // (possibly creating temporaries).
4947 // Otherwise, initialize a temporary with the initializer list and
4948 // bind to that.
4949 if (InitList->getNumInits() == 1) {
4950 Expr *Initializer = InitList->getInit(0);
4952 Qualifiers T2Quals;
4953 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4954
4955 // If this fails, creating a temporary wouldn't work either.
4957 T1, Sequence))
4958 return;
4959
4960 SourceLocation DeclLoc = Initializer->getBeginLoc();
4961 Sema::ReferenceCompareResult RefRelationship
4962 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4963 if (RefRelationship >= Sema::Ref_Related) {
4964 // Try to bind the reference here.
4965 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4966 T1Quals, cv2T2, T2, T2Quals, Sequence,
4967 /*TopLevelOfInitList=*/true);
4968 if (Sequence)
4969 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4970 return;
4971 }
4972
4973 // Update the initializer if we've resolved an overloaded function.
4974 if (!Sequence.steps().empty())
4975 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4976 }
4977 // Perform address space compatibility check.
4978 QualType cv1T1IgnoreAS = cv1T1;
4979 if (T1Quals.hasAddressSpace()) {
4980 Qualifiers T2Quals;
4981 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4982 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4983 Sequence.SetFailed(
4985 return;
4986 }
4987 // Ignore address space of reference type at this point and perform address
4988 // space conversion after the reference binding step.
4989 cv1T1IgnoreAS =
4991 }
4992 // Not reference-related. Create a temporary and bind to that.
4993 InitializedEntity TempEntity =
4995
4996 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4997 TreatUnavailableAsInvalid);
4998 if (Sequence) {
4999 if (DestType->isRValueReferenceType() ||
5000 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
5001 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
5002 /*BindingTemporary=*/true);
5003 if (S.getLangOpts().CPlusPlus20 &&
5005 DestType->isRValueReferenceType()) {
5006 // C++20 [dcl.init.list]p3.10:
5007 // List-initialization of an object or reference of type T is defined as
5008 // follows:
5009 // ..., unless T is “reference to array of unknown bound of U”, in which
5010 // case the type of the prvalue is the type of x in the declaration U
5011 // x[] H, where H is the initializer list.
5012
5013 // The call to AddReferenceBindingStep above converts the rvalue to an
5014 // xvalue. Convert that xvalue to the incomplete array type.
5016 }
5017 if (T1Quals.hasAddressSpace())
5019 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5020 } else
5021 Sequence.SetFailed(
5023 }
5024}
5025
5026/// Attempt list initialization (C++0x [dcl.init.list])
5028 const InitializedEntity &Entity,
5029 const InitializationKind &Kind,
5030 InitListExpr *InitList,
5031 InitializationSequence &Sequence,
5032 bool TreatUnavailableAsInvalid) {
5033 QualType DestType = Entity.getType();
5034
5035 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
5037 return;
5038 }
5039
5040 // C++ doesn't allow scalar initialization with more than one argument.
5041 // But C99 complex numbers are scalars and it makes sense there.
5042 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5043 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5045 return;
5046 }
5047 if (DestType->isReferenceType()) {
5048 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5049 TreatUnavailableAsInvalid);
5050 return;
5051 }
5052
5053 if (DestType->isRecordType() &&
5054 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
5055 Sequence.setIncompleteTypeFailure(DestType);
5056 return;
5057 }
5058
5059 // C++20 [dcl.init.list]p3:
5060 // - If the braced-init-list contains a designated-initializer-list, T shall
5061 // be an aggregate class. [...] Aggregate initialization is performed.
5062 //
5063 // We allow arrays here too in order to support array designators.
5064 //
5065 // FIXME: This check should precede the handling of reference initialization.
5066 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5067 // as a tentative DR resolution.
5068 bool IsDesignatedInit = InitList->hasDesignatedInit();
5069 if (!DestType->isAggregateType() && IsDesignatedInit) {
5070 Sequence.SetFailed(
5072 return;
5073 }
5074
5075 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5076 // - If T is an aggregate class and the initializer list has a single element
5077 // of type cv U, where U is T or a class derived from T, the object is
5078 // initialized from that element (by copy-initialization for
5079 // copy-list-initialization, or by direct-initialization for
5080 // direct-list-initialization).
5081 // - Otherwise, if T is a character array and the initializer list has a
5082 // single element that is an appropriately-typed string literal
5083 // (8.5.2 [dcl.init.string]), initialization is performed as described
5084 // in that section.
5085 // - Otherwise, if T is an aggregate, [...] (continue below).
5086 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5087 !IsDesignatedInit) {
5088 if (DestType->isRecordType() && DestType->isAggregateType()) {
5089 QualType InitType = InitList->getInit(0)->getType();
5090 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
5091 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
5092 InitializationKind SubKind =
5094 ? InitializationKind::CreateDirect(Kind.getLocation(),
5095 InitList->getLBraceLoc(),
5096 InitList->getRBraceLoc())
5097 : Kind;
5098 Expr *InitListAsExpr = InitList;
5100 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5101 /*IsAggrListInit=*/true);
5102 return;
5103 }
5104 }
5105 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5106 Expr *SubInit[1] = {InitList->getInit(0)};
5107
5108 // C++17 [dcl.struct.bind]p1:
5109 // ... If the assignment-expression in the initializer has array type A
5110 // and no ref-qualifier is present, e has type cv A and each element is
5111 // copy-initialized or direct-initialized from the corresponding element
5112 // of the assignment-expression as specified by the form of the
5113 // initializer. ...
5114 //
5115 // This is a special case not following list-initialization.
5116 if (isa<ConstantArrayType>(DestAT) &&
5118 isa<DecompositionDecl>(Entity.getDecl())) {
5119 assert(
5120 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5121 "Deduced to other type?");
5122 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5123 "List-initialize structured bindings but not "
5124 "direct-list-initialization?");
5125 TryArrayCopy(S,
5126 InitializationKind::CreateDirect(Kind.getLocation(),
5127 InitList->getLBraceLoc(),
5128 InitList->getRBraceLoc()),
5129 Entity, SubInit[0], DestType, Sequence,
5130 TreatUnavailableAsInvalid);
5131 if (Sequence)
5132 Sequence.AddUnwrapInitListInitStep(InitList);
5133 return;
5134 }
5135
5136 if (!isa<VariableArrayType>(DestAT) &&
5137 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5138 InitializationKind SubKind =
5140 ? InitializationKind::CreateDirect(Kind.getLocation(),
5141 InitList->getLBraceLoc(),
5142 InitList->getRBraceLoc())
5143 : Kind;
5144 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5145 /*TopLevelOfInitList*/ true,
5146 TreatUnavailableAsInvalid);
5147
5148 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5149 // the element is not an appropriately-typed string literal, in which
5150 // case we should proceed as in C++11 (below).
5151 if (Sequence) {
5152 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5153 return;
5154 }
5155 }
5156 }
5157 }
5158
5159 // C++11 [dcl.init.list]p3:
5160 // - If T is an aggregate, aggregate initialization is performed.
5161 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5162 (S.getLangOpts().CPlusPlus11 &&
5163 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5164 if (S.getLangOpts().CPlusPlus11) {
5165 // - Otherwise, if the initializer list has no elements and T is a
5166 // class type with a default constructor, the object is
5167 // value-initialized.
5168 if (InitList->getNumInits() == 0) {
5169 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5170 if (S.LookupDefaultConstructor(RD)) {
5171 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5172 return;
5173 }
5174 }
5175
5176 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5177 // an initializer_list object constructed [...]
5178 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5179 TreatUnavailableAsInvalid))
5180 return;
5181
5182 // - Otherwise, if T is a class type, constructors are considered.
5183 Expr *InitListAsExpr = InitList;
5184 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5185 DestType, Sequence, /*InitListSyntax*/true);
5186 } else
5188 return;
5189 }
5190
5191 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5192 InitList->getNumInits() == 1) {
5193 Expr *E = InitList->getInit(0);
5194
5195 // - Otherwise, if T is an enumeration with a fixed underlying type,
5196 // the initializer-list has a single element v, and the initialization
5197 // is direct-list-initialization, the object is initialized with the
5198 // value T(v); if a narrowing conversion is required to convert v to
5199 // the underlying type of T, the program is ill-formed.
5200 if (S.getLangOpts().CPlusPlus17 &&
5201 Kind.getKind() == InitializationKind::IK_DirectList &&
5202 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5203 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5205 E->getType()->isFloatingType())) {
5206 // There are two ways that T(v) can work when T is an enumeration type.
5207 // If there is either an implicit conversion sequence from v to T or
5208 // a conversion function that can convert from v to T, then we use that.
5209 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5210 // type, it is converted to the enumeration type via its underlying type.
5211 // There is no overlap possible between these two cases (except when the
5212 // source value is already of the destination type), and the first
5213 // case is handled by the general case for single-element lists below.
5215 ICS.setStandard();
5217 if (!E->isPRValue())
5219 // If E is of a floating-point type, then the conversion is ill-formed
5220 // due to narrowing, but go through the motions in order to produce the
5221 // right diagnostic.
5225 ICS.Standard.setFromType(E->getType());
5226 ICS.Standard.setToType(0, E->getType());
5227 ICS.Standard.setToType(1, DestType);
5228 ICS.Standard.setToType(2, DestType);
5229 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5230 /*TopLevelOfInitList*/true);
5231 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5232 return;
5233 }
5234
5235 // - Otherwise, if the initializer list has a single element of type E
5236 // [...references are handled above...], the object or reference is
5237 // initialized from that element (by copy-initialization for
5238 // copy-list-initialization, or by direct-initialization for
5239 // direct-list-initialization); if a narrowing conversion is required
5240 // to convert the element to T, the program is ill-formed.
5241 //
5242 // Per core-24034, this is direct-initialization if we were performing
5243 // direct-list-initialization and copy-initialization otherwise.
5244 // We can't use InitListChecker for this, because it always performs
5245 // copy-initialization. This only matters if we might use an 'explicit'
5246 // conversion operator, or for the special case conversion of nullptr_t to
5247 // bool, so we only need to handle those cases.
5248 //
5249 // FIXME: Why not do this in all cases?
5250 Expr *Init = InitList->getInit(0);
5251 if (Init->getType()->isRecordType() ||
5252 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5253 InitializationKind SubKind =
5255 ? InitializationKind::CreateDirect(Kind.getLocation(),
5256 InitList->getLBraceLoc(),
5257 InitList->getRBraceLoc())
5258 : Kind;
5259 Expr *SubInit[1] = { Init };
5260 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5261 /*TopLevelOfInitList*/true,
5262 TreatUnavailableAsInvalid);
5263 if (Sequence)
5264 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5265 return;
5266 }
5267 }
5268
5269 InitListChecker CheckInitList(S, Entity, InitList,
5270 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5271 if (CheckInitList.HadError()) {
5273 return;
5274 }
5275
5276 // Add the list initialization step with the built init list.
5277 Sequence.AddListInitializationStep(DestType);
5278}
5279
5280/// Try a reference initialization that involves calling a conversion
5281/// function.
5283 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5284 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5285 InitializationSequence &Sequence) {
5286 QualType DestType = Entity.getType();
5287 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5288 QualType T1 = cv1T1.getUnqualifiedType();
5289 QualType cv2T2 = Initializer->getType();
5290 QualType T2 = cv2T2.getUnqualifiedType();
5291
5292 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5293 "Must have incompatible references when binding via conversion");
5294
5295 // Build the candidate set directly in the initialization sequence
5296 // structure, so that it will persist if we fail.
5297 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5299
5300 // Determine whether we are allowed to call explicit conversion operators.
5301 // Note that none of [over.match.copy], [over.match.conv], nor
5302 // [over.match.ref] permit an explicit constructor to be chosen when
5303 // initializing a reference, not even for direct-initialization.
5304 bool AllowExplicitCtors = false;
5305 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5306
5307 if (AllowRValues && T1->isRecordType() &&
5308 S.isCompleteType(Kind.getLocation(), T1)) {
5309 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5310 if (T1RecordDecl->isInvalidDecl())
5311 return OR_No_Viable_Function;
5312 // The type we're converting to is a class type. Enumerate its constructors
5313 // to see if there is a suitable conversion.
5314 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5315 auto Info = getConstructorInfo(D);
5316 if (!Info.Constructor)
5317 continue;
5318
5319 if (!Info.Constructor->isInvalidDecl() &&
5320 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5321 if (Info.ConstructorTmpl)
5323 Info.ConstructorTmpl, Info.FoundDecl,
5324 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5325 /*SuppressUserConversions=*/true,
5326 /*PartialOverloading*/ false, AllowExplicitCtors);
5327 else
5329 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5330 /*SuppressUserConversions=*/true,
5331 /*PartialOverloading*/ false, AllowExplicitCtors);
5332 }
5333 }
5334 }
5335
5336 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5337 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5338 if (T2RecordDecl->isInvalidDecl())
5339 return OR_No_Viable_Function;
5340 // The type we're converting from is a class type, enumerate its conversion
5341 // functions.
5342 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5343 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5344 NamedDecl *D = *I;
5346 if (isa<UsingShadowDecl>(D))
5347 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5348
5349 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5350 CXXConversionDecl *Conv;
5351 if (ConvTemplate)
5352 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5353 else
5354 Conv = cast<CXXConversionDecl>(D);
5355
5356 // If the conversion function doesn't return a reference type,
5357 // it can't be considered for this conversion unless we're allowed to
5358 // consider rvalues.
5359 // FIXME: Do we need to make sure that we only consider conversion
5360 // candidates with reference-compatible results? That might be needed to
5361 // break recursion.
5362 if ((AllowRValues ||
5364 if (ConvTemplate)
5366 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5367 CandidateSet,
5368 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5369 else
5371 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5372 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5373 }
5374 }
5375 }
5376
5377 SourceLocation DeclLoc = Initializer->getBeginLoc();
5378
5379 // Perform overload resolution. If it fails, return the failed result.
5382 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5383 return Result;
5384
5385 FunctionDecl *Function = Best->Function;
5386 // This is the overload that will be used for this initialization step if we
5387 // use this initialization. Mark it as referenced.
5388 Function->setReferenced();
5389
5390 // Compute the returned type and value kind of the conversion.
5391 QualType cv3T3;
5392 if (isa<CXXConversionDecl>(Function))
5393 cv3T3 = Function->getReturnType();
5394 else
5395 cv3T3 = T1;
5396
5398 if (cv3T3->isLValueReferenceType())
5399 VK = VK_LValue;
5400 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5401 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5402 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5403
5404 // Add the user-defined conversion step.
5405 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5406 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5407 HadMultipleCandidates);
5408
5409 // Determine whether we'll need to perform derived-to-base adjustments or
5410 // other conversions.
5412 Sema::ReferenceCompareResult NewRefRelationship =
5413 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5414
5415 // Add the final conversion sequence, if necessary.
5416 if (NewRefRelationship == Sema::Ref_Incompatible) {
5417 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5418 "should not have conversion after constructor");
5419
5421 ICS.setStandard();
5422 ICS.Standard = Best->FinalConversion;
5423 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5424
5425 // Every implicit conversion results in a prvalue, except for a glvalue
5426 // derived-to-base conversion, which we handle below.
5427 cv3T3 = ICS.Standard.getToType(2);
5428 VK = VK_PRValue;
5429 }
5430
5431 // If the converted initializer is a prvalue, its type T4 is adjusted to
5432 // type "cv1 T4" and the temporary materialization conversion is applied.
5433 //
5434 // We adjust the cv-qualifications to match the reference regardless of
5435 // whether we have a prvalue so that the AST records the change. In this
5436 // case, T4 is "cv3 T3".
5437 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5438 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5439 Sequence.AddQualificationConversionStep(cv1T4, VK);
5440 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5441 VK = IsLValueRef ? VK_LValue : VK_XValue;
5442
5443 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5444 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5445 else if (RefConv & Sema::ReferenceConversions::ObjC)
5446 Sequence.AddObjCObjectConversionStep(cv1T1);
5447 else if (RefConv & Sema::ReferenceConversions::Function)
5448 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5449 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5450 if (!S.Context.hasSameType(cv1T4, cv1T1))
5451 Sequence.AddQualificationConversionStep(cv1T1, VK);
5452 }
5453
5454 return OR_Success;
5455}
5456
5457static void CheckCXX98CompatAccessibleCopy(Sema &S,
5458 const InitializedEntity &Entity,
5459 Expr *CurInitExpr);
5460
5461/// Attempt reference initialization (C++0x [dcl.init.ref])
5463 const InitializationKind &Kind,
5465 InitializationSequence &Sequence,
5466 bool TopLevelOfInitList) {
5467 QualType DestType = Entity.getType();
5468 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5469 Qualifiers T1Quals;
5470 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5472 Qualifiers T2Quals;
5473 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5474
5475 // If the initializer is the address of an overloaded function, try
5476 // to resolve the overloaded function. If all goes well, T2 is the
5477 // type of the resulting function.
5479 T1, Sequence))
5480 return;
5481
5482 // Delegate everything else to a subfunction.
5483 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5484 T1Quals, cv2T2, T2, T2Quals, Sequence,
5485 TopLevelOfInitList);
5486}
5487
5488/// Determine whether an expression is a non-referenceable glvalue (one to
5489/// which a reference can never bind). Attempting to bind a reference to
5490/// such a glvalue will always create a temporary.
5492 return E->refersToBitField() || E->refersToVectorElement() ||
5494}
5495
5496/// Reference initialization without resolving overloaded functions.
5497///
5498/// We also can get here in C if we call a builtin which is declared as
5499/// a function with a parameter of reference type (such as __builtin_va_end()).
5501 const InitializedEntity &Entity,
5502 const InitializationKind &Kind,
5504 QualType cv1T1, QualType T1,
5505 Qualifiers T1Quals,
5506 QualType cv2T2, QualType T2,
5507 Qualifiers T2Quals,
5508 InitializationSequence &Sequence,
5509 bool TopLevelOfInitList) {
5510 QualType DestType = Entity.getType();
5511 SourceLocation DeclLoc = Initializer->getBeginLoc();
5512
5513 // Compute some basic properties of the types and the initializer.
5514 bool isLValueRef = DestType->isLValueReferenceType();
5515 bool isRValueRef = !isLValueRef;
5516 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5517
5519 Sema::ReferenceCompareResult RefRelationship =
5520 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5521
5522 // C++0x [dcl.init.ref]p5:
5523 // A reference to type "cv1 T1" is initialized by an expression of type
5524 // "cv2 T2" as follows:
5525 //
5526 // - If the reference is an lvalue reference and the initializer
5527 // expression
5528 // Note the analogous bullet points for rvalue refs to functions. Because
5529 // there are no function rvalues in C++, rvalue refs to functions are treated
5530 // like lvalue refs.
5531 OverloadingResult ConvOvlResult = OR_Success;
5532 bool T1Function = T1->isFunctionType();
5533 if (isLValueRef || T1Function) {
5534 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5535 (RefRelationship == Sema::Ref_Compatible ||
5536 (Kind.isCStyleOrFunctionalCast() &&
5537 RefRelationship == Sema::Ref_Related))) {
5538 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5539 // reference-compatible with "cv2 T2," or
5540 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5541 Sema::ReferenceConversions::ObjC)) {
5542 // If we're converting the pointee, add any qualifiers first;
5543 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5544 if (RefConv & (Sema::ReferenceConversions::Qualification))
5546 S.Context.getQualifiedType(T2, T1Quals),
5547 Initializer->getValueKind());
5548 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5549 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5550 else
5551 Sequence.AddObjCObjectConversionStep(cv1T1);
5552 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5553 // Perform a (possibly multi-level) qualification conversion.
5554 Sequence.AddQualificationConversionStep(cv1T1,
5555 Initializer->getValueKind());
5556 } else if (RefConv & Sema::ReferenceConversions::Function) {
5557 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5558 }
5559
5560 // We only create a temporary here when binding a reference to a
5561 // bit-field or vector element. Those cases are't supposed to be
5562 // handled by this bullet, but the outcome is the same either way.
5563 Sequence.AddReferenceBindingStep(cv1T1, false);
5564 return;
5565 }
5566
5567 // - has a class type (i.e., T2 is a class type), where T1 is not
5568 // reference-related to T2, and can be implicitly converted to an
5569 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5570 // with "cv3 T3" (this conversion is selected by enumerating the
5571 // applicable conversion functions (13.3.1.6) and choosing the best
5572 // one through overload resolution (13.3)),
5573 // If we have an rvalue ref to function type here, the rhs must be
5574 // an rvalue. DR1287 removed the "implicitly" here.
5575 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5576 (isLValueRef || InitCategory.isRValue())) {
5577 if (S.getLangOpts().CPlusPlus) {
5578 // Try conversion functions only for C++.
5579 ConvOvlResult = TryRefInitWithConversionFunction(
5580 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5581 /*IsLValueRef*/ isLValueRef, Sequence);
5582 if (ConvOvlResult == OR_Success)
5583 return;
5584 if (ConvOvlResult != OR_No_Viable_Function)
5585 Sequence.SetOverloadFailure(
5587 ConvOvlResult);
5588 } else {
5589 ConvOvlResult = OR_No_Viable_Function;
5590 }
5591 }
5592 }
5593
5594 // - Otherwise, the reference shall be an lvalue reference to a
5595 // non-volatile const type (i.e., cv1 shall be const), or the reference
5596 // shall be an rvalue reference.
5597 // For address spaces, we interpret this to mean that an addr space
5598 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5599 if (isLValueRef &&
5600 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5601 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5604 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5605 Sequence.SetOverloadFailure(
5607 ConvOvlResult);
5608 else if (!InitCategory.isLValue())
5609 Sequence.SetFailed(
5610 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5614 else {
5616 switch (RefRelationship) {
5618 if (Initializer->refersToBitField())
5619 FK = InitializationSequence::
5620 FK_NonConstLValueReferenceBindingToBitfield;
5621 else if (Initializer->refersToVectorElement())
5622 FK = InitializationSequence::
5623 FK_NonConstLValueReferenceBindingToVectorElement;
5624 else if (Initializer->refersToMatrixElement())
5625 FK = InitializationSequence::
5626 FK_NonConstLValueReferenceBindingToMatrixElement;
5627 else
5628 llvm_unreachable("unexpected kind of compatible initializer");
5629 break;
5630 case Sema::Ref_Related:
5632 break;
5634 FK = InitializationSequence::
5635 FK_NonConstLValueReferenceBindingToUnrelated;
5636 break;
5637 }
5638 Sequence.SetFailed(FK);
5639 }
5640 return;
5641 }
5642
5643 // - If the initializer expression
5644 // - is an
5645 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5646 // [1z] rvalue (but not a bit-field) or
5647 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5648 //
5649 // Note: functions are handled above and below rather than here...
5650 if (!T1Function &&
5651 (RefRelationship == Sema::Ref_Compatible ||
5652 (Kind.isCStyleOrFunctionalCast() &&
5653 RefRelationship == Sema::Ref_Related)) &&
5654 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5655 (InitCategory.isPRValue() &&
5656 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5657 T2->isArrayType())))) {
5658 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5659 if (InitCategory.isPRValue() && T2->isRecordType()) {
5660 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5661 // compiler the freedom to perform a copy here or bind to the
5662 // object, while C++0x requires that we bind directly to the
5663 // object. Hence, we always bind to the object without making an
5664 // extra copy. However, in C++03 requires that we check for the
5665 // presence of a suitable copy constructor:
5666 //
5667 // The constructor that would be used to make the copy shall
5668 // be callable whether or not the copy is actually done.
5669 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5670 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5671 else if (S.getLangOpts().CPlusPlus11)
5673 }
5674
5675 // C++1z [dcl.init.ref]/5.2.1.2:
5676 // If the converted initializer is a prvalue, its type T4 is adjusted
5677 // to type "cv1 T4" and the temporary materialization conversion is
5678 // applied.
5679 // Postpone address space conversions to after the temporary materialization
5680 // conversion to allow creating temporaries in the alloca address space.
5681 auto T1QualsIgnoreAS = T1Quals;
5682 auto T2QualsIgnoreAS = T2Quals;
5683 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5684 T1QualsIgnoreAS.removeAddressSpace();
5685 T2QualsIgnoreAS.removeAddressSpace();
5686 }
5687 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5688 // with T1's qualifiers.
5689 QualType T2ForQualConv = cv2T2;
5690 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5691 Qualifiers T2BaseQuals =
5692 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5693 T2ForQualConv = S.Context.getQualifiedType(
5694 T2ForQualConv.getUnqualifiedType(), T2BaseQuals);
5695 }
5696 QualType cv1T4 = S.Context.getQualifiedType(T2ForQualConv, T1QualsIgnoreAS);
5697 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5698 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5699 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5700 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5701 // Add addr space conversion if required.
5702 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5703 auto T4Quals = cv1T4.getQualifiers();
5704 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5705 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5706 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5707 cv1T4 = cv1T4WithAS;
5708 }
5709
5710 // In any case, the reference is bound to the resulting glvalue (or to
5711 // an appropriate base class subobject).
5712 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5713 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5714 else if (RefConv & Sema::ReferenceConversions::ObjC)
5715 Sequence.AddObjCObjectConversionStep(cv1T1);
5716 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5717 if (!S.Context.hasSameType(cv1T4, cv1T1))
5718 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5719 }
5720 return;
5721 }
5722
5723 // - has a class type (i.e., T2 is a class type), where T1 is not
5724 // reference-related to T2, and can be implicitly converted to an
5725 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5726 // where "cv1 T1" is reference-compatible with "cv3 T3",
5727 //
5728 // DR1287 removes the "implicitly" here.
5729 if (T2->isRecordType()) {
5730 if (RefRelationship == Sema::Ref_Incompatible) {
5731 ConvOvlResult = TryRefInitWithConversionFunction(
5732 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5733 /*IsLValueRef*/ isLValueRef, Sequence);
5734 if (ConvOvlResult)
5735 Sequence.SetOverloadFailure(
5737 ConvOvlResult);
5738
5739 return;
5740 }
5741
5742 if (RefRelationship == Sema::Ref_Compatible &&
5743 isRValueRef && InitCategory.isLValue()) {
5744 Sequence.SetFailed(
5746 return;
5747 }
5748
5750 return;
5751 }
5752
5753 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5754 // from the initializer expression using the rules for a non-reference
5755 // copy-initialization (8.5). The reference is then bound to the
5756 // temporary. [...]
5757
5758 // Ignore address space of reference type at this point and perform address
5759 // space conversion after the reference binding step.
5760 QualType cv1T1IgnoreAS =
5761 T1Quals.hasAddressSpace()
5763 : cv1T1;
5764
5765 InitializedEntity TempEntity =
5767
5768 // FIXME: Why do we use an implicit conversion here rather than trying
5769 // copy-initialization?
5771 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5772 /*SuppressUserConversions=*/false,
5773 Sema::AllowedExplicit::None,
5774 /*FIXME:InOverloadResolution=*/false,
5775 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5776 /*AllowObjCWritebackConversion=*/false);
5777
5778 if (ICS.isBad()) {
5779 // FIXME: Use the conversion function set stored in ICS to turn
5780 // this into an overloading ambiguity diagnostic. However, we need
5781 // to keep that set as an OverloadCandidateSet rather than as some
5782 // other kind of set.
5783 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5784 Sequence.SetOverloadFailure(
5786 ConvOvlResult);
5787 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5789 else
5791 return;
5792 } else {
5793 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5794 TopLevelOfInitList);
5795 }
5796
5797 // [...] If T1 is reference-related to T2, cv1 must be the
5798 // same cv-qualification as, or greater cv-qualification
5799 // than, cv2; otherwise, the program is ill-formed.
5800 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5801 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5802 if (RefRelationship == Sema::Ref_Related &&
5803 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5804 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5806 return;
5807 }
5808
5809 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5810 // reference, the initializer expression shall not be an lvalue.
5811 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5812 InitCategory.isLValue()) {
5813 Sequence.SetFailed(
5815 return;
5816 }
5817
5818 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5819
5820 if (T1Quals.hasAddressSpace()) {
5823 Sequence.SetFailed(
5825 return;
5826 }
5827 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5828 : VK_XValue);
5829 }
5830}
5831
5832/// Attempt character array initialization from a string literal
5833/// (C++ [dcl.init.string], C99 6.7.8).
5835 const InitializedEntity &Entity,
5836 const InitializationKind &Kind,
5838 InitializationSequence &Sequence) {
5839 Sequence.AddStringInitStep(Entity.getType());
5840}
5841
5842/// Attempt value initialization (C++ [dcl.init]p7).
5844 const InitializedEntity &Entity,
5845 const InitializationKind &Kind,
5846 InitializationSequence &Sequence,
5847 InitListExpr *InitList) {
5848 assert((!InitList || InitList->getNumInits() == 0) &&
5849 "Shouldn't use value-init for non-empty init lists");
5850
5851 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5852 //
5853 // To value-initialize an object of type T means:
5854 QualType T = Entity.getType();
5855 assert(!T->isVoidType() && "Cannot value-init void");
5856
5857 // -- if T is an array type, then each element is value-initialized;
5858 T = S.Context.getBaseElementType(T);
5859
5860 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5861 bool NeedZeroInitialization = true;
5862 // C++98:
5863 // -- if T is a class type (clause 9) with a user-declared constructor
5864 // (12.1), then the default constructor for T is called (and the
5865 // initialization is ill-formed if T has no accessible default
5866 // constructor);
5867 // C++11:
5868 // -- if T is a class type (clause 9) with either no default constructor
5869 // (12.1 [class.ctor]) or a default constructor that is user-provided
5870 // or deleted, then the object is default-initialized;
5871 //
5872 // Note that the C++11 rule is the same as the C++98 rule if there are no
5873 // defaulted or deleted constructors, so we just use it unconditionally.
5875 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5876 NeedZeroInitialization = false;
5877
5878 // -- if T is a (possibly cv-qualified) non-union class type without a
5879 // user-provided or deleted default constructor, then the object is
5880 // zero-initialized and, if T has a non-trivial default constructor,
5881 // default-initialized;
5882 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5883 // constructor' part was removed by DR1507.
5884 if (NeedZeroInitialization)
5885 Sequence.AddZeroInitializationStep(Entity.getType());
5886
5887 // C++03:
5888 // -- if T is a non-union class type without a user-declared constructor,
5889 // then every non-static data member and base class component of T is
5890 // value-initialized;
5891 // [...] A program that calls for [...] value-initialization of an
5892 // entity of reference type is ill-formed.
5893 //
5894 // C++11 doesn't need this handling, because value-initialization does not
5895 // occur recursively there, and the implicit default constructor is
5896 // defined as deleted in the problematic cases.
5897 if (!S.getLangOpts().CPlusPlus11 &&
5898 ClassDecl->hasUninitializedReferenceMember()) {
5900 return;
5901 }
5902
5903 // If this is list-value-initialization, pass the empty init list on when
5904 // building the constructor call. This affects the semantics of a few
5905 // things (such as whether an explicit default constructor can be called).
5906 Expr *InitListAsExpr = InitList;
5907 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5908 bool InitListSyntax = InitList;
5909
5910 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5911 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5913 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5914 }
5915
5916 Sequence.AddZeroInitializationStep(Entity.getType());
5917}
5918
5919/// Attempt default initialization (C++ [dcl.init]p6).
5921 const InitializedEntity &Entity,
5922 const InitializationKind &Kind,
5923 InitializationSequence &Sequence) {
5924 assert(Kind.getKind() == InitializationKind::IK_Default);
5925
5926 // C++ [dcl.init]p6:
5927 // To default-initialize an object of type T means:
5928 // - if T is an array type, each element is default-initialized;
5929 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5930
5931 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5932 // constructor for T is called (and the initialization is ill-formed if
5933 // T has no accessible default constructor);
5934 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5935 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5936 Entity.getType(), Sequence);
5937 return;
5938 }
5939
5940 // - otherwise, no initialization is performed.
5941
5942 // If a program calls for the default initialization of an object of
5943 // a const-qualified type T, T shall be a class type with a user-provided
5944 // default constructor.
5945 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5946 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5948 return;
5949 }
5950
5951 // If the destination type has a lifetime property, zero-initialize it.
5952 if (DestType.getQualifiers().hasObjCLifetime()) {
5953 Sequence.AddZeroInitializationStep(Entity.getType());
5954 return;
5955 }
5956}
5957
5959 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5960 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5961 ExprResult *Result) {
5962 unsigned EntityIndexToProcess = 0;
5963 SmallVector<Expr *, 4> InitExprs;
5964 QualType ResultType;
5965 Expr *ArrayFiller = nullptr;
5966 FieldDecl *InitializedFieldInUnion = nullptr;
5967
5968 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5969 const InitializationKind &SubKind,
5970 Expr *Arg, Expr **InitExpr = nullptr) {
5972 S, SubEntity, SubKind,
5973 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5974
5975 if (IS.Failed()) {
5976 if (!VerifyOnly) {
5977 IS.Diagnose(S, SubEntity, SubKind,
5978 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5979 } else {
5980 Sequence.SetFailed(
5982 }
5983
5984 return false;
5985 }
5986 if (!VerifyOnly) {
5987 ExprResult ER;
5988 ER = IS.Perform(S, SubEntity, SubKind,
5989 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5990
5991 if (ER.isInvalid())
5992 return false;
5993
5994 if (InitExpr)
5995 *InitExpr = ER.get();
5996 else
5997 InitExprs.push_back(ER.get());
5998 }
5999 return true;
6000 };
6001
6002 if (const ArrayType *AT =
6003 S.getASTContext().getAsArrayType(Entity.getType())) {
6004 uint64_t ArrayLength;
6005 // C++ [dcl.init]p16.5
6006 // if the destination type is an array, the object is initialized as
6007 // follows. Let x1, . . . , xk be the elements of the expression-list. If
6008 // the destination type is an array of unknown bound, it is defined as
6009 // having k elements.
6010 if (const ConstantArrayType *CAT =
6012 ArrayLength = CAT->getZExtSize();
6013 ResultType = Entity.getType();
6014 } else if (const VariableArrayType *VAT =
6016 // Braced-initialization of variable array types is not allowed, even if
6017 // the size is greater than or equal to the number of args, so we don't
6018 // allow them to be initialized via parenthesized aggregate initialization
6019 // either.
6020 const Expr *SE = VAT->getSizeExpr();
6021 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
6022 << SE->getSourceRange();
6023 return;
6024 } else {
6025 assert(Entity.getType()->isIncompleteArrayType());
6026 ArrayLength = Args.size();
6027 }
6028 EntityIndexToProcess = ArrayLength;
6029
6030 // ...the ith array element is copy-initialized with xi for each
6031 // 1 <= i <= k
6032 for (Expr *E : Args) {
6034 S.getASTContext(), EntityIndexToProcess, Entity);
6036 E->getExprLoc(), /*isDirectInit=*/false, E);
6037 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6038 return;
6039 }
6040 // ...and value-initialized for each k < i <= n;
6041 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6043 S.getASTContext(), Args.size(), Entity);
6045 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6046 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6047 return;
6048 }
6049
6050 if (ResultType.isNull()) {
6051 ResultType = S.Context.getConstantArrayType(
6052 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
6053 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
6054 }
6055 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6056 bool IsUnion = RD->isUnion();
6057 if (RD->isInvalidDecl()) {
6058 // Exit early to avoid confusion when processing members.
6059 // We do the same for braced list initialization in
6060 // `CheckStructUnionTypes`.
6061 Sequence.SetFailed(
6063 return;
6064 }
6065
6066 if (!IsUnion) {
6067 for (const CXXBaseSpecifier &Base : RD->bases()) {
6069 S.getASTContext(), &Base, false, &Entity);
6070 if (EntityIndexToProcess < Args.size()) {
6071 // C++ [dcl.init]p16.6.2.2.
6072 // ...the object is initialized is follows. Let e1, ..., en be the
6073 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6074 // the elements of the expression-list...The element ei is
6075 // copy-initialized with xi for 1 <= i <= k.
6076 Expr *E = Args[EntityIndexToProcess];
6078 E->getExprLoc(), /*isDirectInit=*/false, E);
6079 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6080 return;
6081 } else {
6082 // We've processed all of the args, but there are still base classes
6083 // that have to be initialized.
6084 // C++ [dcl.init]p17.6.2.2
6085 // The remaining elements...otherwise are value initialzed
6087 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
6088 /*IsImplicit=*/true);
6089 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6090 return;
6091 }
6092 EntityIndexToProcess++;
6093 }
6094 }
6095
6096 for (FieldDecl *FD : RD->fields()) {
6097 // Unnamed bitfields should not be initialized at all, either with an arg
6098 // or by default.
6099 if (FD->isUnnamedBitField())
6100 continue;
6101
6102 InitializedEntity SubEntity =
6104
6105 if (EntityIndexToProcess < Args.size()) {
6106 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6107 Expr *E = Args[EntityIndexToProcess];
6108
6109 // Incomplete array types indicate flexible array members. Do not allow
6110 // paren list initializations of structs with these members, as GCC
6111 // doesn't either.
6112 if (FD->getType()->isIncompleteArrayType()) {
6113 if (!VerifyOnly) {
6114 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6115 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6116 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6117 }
6118 Sequence.SetFailed(
6120 return;
6121 }
6122
6124 E->getExprLoc(), /*isDirectInit=*/false, E);
6125 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6126 return;
6127
6128 // Unions should have only one initializer expression, so we bail out
6129 // after processing the first field. If there are more initializers then
6130 // it will be caught when we later check whether EntityIndexToProcess is
6131 // less than Args.size();
6132 if (IsUnion) {
6133 InitializedFieldInUnion = FD;
6134 EntityIndexToProcess = 1;
6135 break;
6136 }
6137 } else {
6138 // We've processed all of the args, but there are still members that
6139 // have to be initialized.
6140 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6141 !S.isUnevaluatedContext()) {
6142 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6143 << /* Var-in-Record */ 0 << FD;
6144 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6145 }
6146
6147 if (FD->hasInClassInitializer()) {
6148 if (!VerifyOnly) {
6149 // C++ [dcl.init]p16.6.2.2
6150 // The remaining elements are initialized with their default
6151 // member initializers, if any
6153 Kind.getParenOrBraceRange().getEnd(), FD);
6154 if (DIE.isInvalid())
6155 return;
6156 S.checkInitializerLifetime(SubEntity, DIE.get());
6157 InitExprs.push_back(DIE.get());
6158 }
6159 } else {
6160 // C++ [dcl.init]p17.6.2.2
6161 // The remaining elements...otherwise are value initialzed
6162 if (FD->getType()->isReferenceType()) {
6163 Sequence.SetFailed(
6165 if (!VerifyOnly) {
6166 SourceRange SR = Kind.getParenOrBraceRange();
6167 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6168 << FD->getType() << SR;
6169 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6170 }
6171 return;
6172 }
6174 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6175 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6176 return;
6177 }
6178 }
6179 EntityIndexToProcess++;
6180 }
6181 ResultType = Entity.getType();
6182 }
6183
6184 // Not all of the args have been processed, so there must've been more args
6185 // than were required to initialize the element.
6186 if (EntityIndexToProcess < Args.size()) {
6188 if (!VerifyOnly) {
6189 QualType T = Entity.getType();
6190 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6191 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6192 Args.back()->getEndLoc());
6193 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6194 << InitKind << ExcessInitSR;
6195 }
6196 return;
6197 }
6198
6199 if (VerifyOnly) {
6201 Sequence.AddParenthesizedListInitStep(Entity.getType());
6202 } else if (Result) {
6203 SourceRange SR = Kind.getParenOrBraceRange();
6204 auto *CPLIE = CXXParenListInitExpr::Create(
6205 S.getASTContext(), InitExprs, ResultType, Args.size(),
6206 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6207 if (ArrayFiller)
6208 CPLIE->setArrayFiller(ArrayFiller);
6209 if (InitializedFieldInUnion)
6210 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6211 *Result = CPLIE;
6212 S.Diag(Kind.getLocation(),
6213 diag::warn_cxx17_compat_aggregate_init_paren_list)
6214 << Kind.getLocation() << SR << ResultType;
6215 }
6216}
6217
6218/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6219/// which enumerates all conversion functions and performs overload resolution
6220/// to select the best.
6222 QualType DestType,
6223 const InitializationKind &Kind,
6225 InitializationSequence &Sequence,
6226 bool TopLevelOfInitList) {
6227 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6228 QualType SourceType = Initializer->getType();
6229 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6230 "Must have a class type to perform a user-defined conversion");
6231
6232 // Build the candidate set directly in the initialization sequence
6233 // structure, so that it will persist if we fail.
6234 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6236 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6237
6238 // Determine whether we are allowed to call explicit constructors or
6239 // explicit conversion operators.
6240 bool AllowExplicit = Kind.AllowExplicit();
6241
6242 if (DestType->isRecordType()) {
6243 // The type we're converting to is a class type. Enumerate its constructors
6244 // to see if there is a suitable conversion.
6245 // Try to complete the type we're converting to.
6246 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6247 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6248 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6249 auto Info = getConstructorInfo(D);
6250 if (!Info.Constructor)
6251 continue;
6252
6253 if (!Info.Constructor->isInvalidDecl() &&
6254 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6255 if (Info.ConstructorTmpl)
6257 Info.ConstructorTmpl, Info.FoundDecl,
6258 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6259 /*SuppressUserConversions=*/true,
6260 /*PartialOverloading*/ false, AllowExplicit);
6261 else
6262 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6263 Initializer, CandidateSet,
6264 /*SuppressUserConversions=*/true,
6265 /*PartialOverloading*/ false, AllowExplicit);
6266 }
6267 }
6268 }
6269 }
6270
6271 SourceLocation DeclLoc = Initializer->getBeginLoc();
6272
6273 if (SourceType->isRecordType()) {
6274 // The type we're converting from is a class type, enumerate its conversion
6275 // functions.
6276
6277 // We can only enumerate the conversion functions for a complete type; if
6278 // the type isn't complete, simply skip this step.
6279 if (S.isCompleteType(DeclLoc, SourceType)) {
6280 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6281 const auto &Conversions =
6282 SourceRecordDecl->getVisibleConversionFunctions();
6283 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6284 NamedDecl *D = *I;
6286 if (isa<UsingShadowDecl>(D))
6287 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6288
6289 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6290 CXXConversionDecl *Conv;
6291 if (ConvTemplate)
6292 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6293 else
6294 Conv = cast<CXXConversionDecl>(D);
6295
6296 if (ConvTemplate)
6298 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6299 CandidateSet, AllowExplicit, AllowExplicit);
6300 else
6301 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6302 DestType, CandidateSet, AllowExplicit,
6303 AllowExplicit);
6304 }
6305 }
6306 }
6307
6308 // Perform overload resolution. If it fails, return the failed result.
6311 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6312 Sequence.SetOverloadFailure(
6314
6315 // [class.copy.elision]p3:
6316 // In some copy-initialization contexts, a two-stage overload resolution
6317 // is performed.
6318 // If the first overload resolution selects a deleted function, we also
6319 // need the initialization sequence to decide whether to perform the second
6320 // overload resolution.
6321 if (!(Result == OR_Deleted &&
6322 Kind.getKind() == InitializationKind::IK_Copy))
6323 return;
6324 }
6325
6326 FunctionDecl *Function = Best->Function;
6327 Function->setReferenced();
6328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6329
6330 if (isa<CXXConstructorDecl>(Function)) {
6331 // Add the user-defined conversion step. Any cv-qualification conversion is
6332 // subsumed by the initialization. Per DR5, the created temporary is of the
6333 // cv-unqualified type of the destination.
6334 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6335 DestType.getUnqualifiedType(),
6336 HadMultipleCandidates);
6337
6338 // C++14 and before:
6339 // - if the function is a constructor, the call initializes a temporary
6340 // of the cv-unqualified version of the destination type. The [...]
6341 // temporary [...] is then used to direct-initialize, according to the
6342 // rules above, the object that is the destination of the
6343 // copy-initialization.
6344 // Note that this just performs a simple object copy from the temporary.
6345 //
6346 // C++17:
6347 // - if the function is a constructor, the call is a prvalue of the
6348 // cv-unqualified version of the destination type whose return object
6349 // is initialized by the constructor. The call is used to
6350 // direct-initialize, according to the rules above, the object that
6351 // is the destination of the copy-initialization.
6352 // Therefore we need to do nothing further.
6353 //
6354 // FIXME: Mark this copy as extraneous.
6355 if (!S.getLangOpts().CPlusPlus17)
6356 Sequence.AddFinalCopy(DestType);
6357 else if (DestType.hasQualifiers())
6358 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6359 return;
6360 }
6361
6362 // Add the user-defined conversion step that calls the conversion function.
6363 QualType ConvType = Function->getCallResultType();
6364 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6365 HadMultipleCandidates);
6366
6367 if (ConvType->isRecordType()) {
6368 if (S.getLangOpts().HLSL &&
6369 ConvType.getAddressSpace() == LangAS::hlsl_constant &&
6370 S.Context.hasSameUnqualifiedType(ConvType, DestType)) {
6371 Sequence.AddHLSLBufferConversionStep(ConvType);
6372 return;
6373 }
6374
6375 // The call is used to direct-initialize [...] the object that is the
6376 // destination of the copy-initialization.
6377 //
6378 // In C++17, this does not call a constructor if we enter /17.6.1:
6379 // - If the initializer expression is a prvalue and the cv-unqualified
6380 // version of the source type is the same as the class of the
6381 // destination [... do not make an extra copy]
6382 //
6383 // FIXME: Mark this copy as extraneous.
6384 if (!S.getLangOpts().CPlusPlus17 ||
6385 Function->getReturnType()->isReferenceType() ||
6386 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6387 Sequence.AddFinalCopy(DestType);
6388 else if (!S.Context.hasSameType(ConvType, DestType))
6389 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6390 return;
6391 }
6392
6393 // If the conversion following the call to the conversion function
6394 // is interesting, add it as a separate step.
6395 assert(Best->HasFinalConversion);
6396 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6397 Best->FinalConversion.Third) {
6399 ICS.setStandard();
6400 ICS.Standard = Best->FinalConversion;
6401 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6402 }
6403}
6404
6405/// The non-zero enum values here are indexes into diagnostic alternatives.
6407
6408/// Determines whether this expression is an acceptable ICR source.
6410 bool isAddressOf, bool &isWeakAccess) {
6411 // Skip parens.
6412 e = e->IgnoreParens();
6413
6414 // Skip address-of nodes.
6415 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6416 if (op->getOpcode() == UO_AddrOf)
6417 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6418 isWeakAccess);
6419
6420 // Skip certain casts.
6421 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6422 switch (ce->getCastKind()) {
6423 case CK_Dependent:
6424 case CK_BitCast:
6425 case CK_LValueBitCast:
6426 case CK_NoOp:
6427 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6428
6429 case CK_ArrayToPointerDecay:
6430 return IIK_nonscalar;
6431
6432 case CK_NullToPointer:
6433 return IIK_okay;
6434
6435 default:
6436 break;
6437 }
6438
6439 // If we have a declaration reference, it had better be a local variable.
6440 } else if (isa<DeclRefExpr>(e)) {
6441 // set isWeakAccess to true, to mean that there will be an implicit
6442 // load which requires a cleanup.
6444 isWeakAccess = true;
6445
6446 if (!isAddressOf) return IIK_nonlocal;
6447
6448 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6449 if (!var) return IIK_nonlocal;
6450
6451 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6452
6453 // If we have a conditional operator, check both sides.
6454 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6455 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6456 isWeakAccess))
6457 return iik;
6458
6459 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6460
6461 // These are never scalar.
6462 } else if (isa<ArraySubscriptExpr>(e)) {
6463 return IIK_nonscalar;
6464
6465 // Otherwise, it needs to be a null pointer constant.
6466 } else {
6469 }
6470
6471 return IIK_nonlocal;
6472}
6473
6474/// Check whether the given expression is a valid operand for an
6475/// indirect copy/restore.
6477 assert(src->isPRValue());
6478 bool isWeakAccess = false;
6479 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6480 // If isWeakAccess to true, there will be an implicit
6481 // load which requires a cleanup.
6482 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6484
6485 if (iik == IIK_okay) return;
6486
6487 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6488 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6489 << src->getSourceRange();
6490}
6491
6492/// Determine whether we have compatible array types for the
6493/// purposes of GNU by-copy array initialization.
6494static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6495 const ArrayType *Source) {
6496 // If the source and destination array types are equivalent, we're
6497 // done.
6498 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6499 return true;
6500
6501 // Make sure that the element types are the same.
6502 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6503 return false;
6504
6505 // The only mismatch we allow is when the destination is an
6506 // incomplete array type and the source is a constant array type.
6507 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6508}
6509
6511 InitializationSequence &Sequence,
6512 const InitializedEntity &Entity,
6513 Expr *Initializer) {
6514 bool ArrayDecay = false;
6515 QualType ArgType = Initializer->getType();
6516 QualType ArgPointee;
6517 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6518 ArrayDecay = true;
6519 ArgPointee = ArgArrayType->getElementType();
6520 ArgType = S.Context.getPointerType(ArgPointee);
6521 }
6522
6523 // Handle write-back conversion.
6524 QualType ConvertedArgType;
6525 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6526 ConvertedArgType))
6527 return false;
6528
6529 // We should copy unless we're passing to an argument explicitly
6530 // marked 'out'.
6531 bool ShouldCopy = true;
6532 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6533 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6534
6535 // Do we need an lvalue conversion?
6536 if (ArrayDecay || Initializer->isGLValue()) {
6538 ICS.setStandard();
6540
6541 QualType ResultType;
6542 if (ArrayDecay) {
6544 ResultType = S.Context.getPointerType(ArgPointee);
6545 } else {
6547 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6548 }
6549
6550 Sequence.AddConversionSequenceStep(ICS, ResultType);
6551 }
6552
6553 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6554 return true;
6555}
6556
6558 InitializationSequence &Sequence,
6559 QualType DestType,
6560 Expr *Initializer) {
6561 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6562 (!Initializer->isIntegerConstantExpr(S.Context) &&
6563 !Initializer->getType()->isSamplerT()))
6564 return false;
6565
6566 Sequence.AddOCLSamplerInitStep(DestType);
6567 return true;
6568}
6569
6570static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6571 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6572 return Value && Value->isZero();
6573}
6574
6576 InitializationSequence &Sequence,
6577 QualType DestType,
6578 Expr *Initializer) {
6579 if (!S.getLangOpts().OpenCL)
6580 return false;
6581
6582 //
6583 // OpenCL 1.2 spec, s6.12.10
6584 //
6585 // The event argument can also be used to associate the
6586 // async_work_group_copy with a previous async copy allowing
6587 // an event to be shared by multiple async copies; otherwise
6588 // event should be zero.
6589 //
6590 if (DestType->isEventT() || DestType->isQueueT()) {
6592 return false;
6593
6594 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6595 return true;
6596 }
6597
6598 // We should allow zero initialization for all types defined in the
6599 // cl_intel_device_side_avc_motion_estimation extension, except
6600 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6602 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6603 DestType->isOCLIntelSubgroupAVCType()) {
6604 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6605 DestType->isOCLIntelSubgroupAVCMceResultType())
6606 return false;
6608 return false;
6609
6610 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6611 return true;
6612 }
6613
6614 return false;
6615}
6616
6618 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6619 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6620 : FailedOverloadResult(OR_Success),
6621 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6622 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6623 TreatUnavailableAsInvalid);
6624}
6625
6626/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6627/// address of that function, this returns true. Otherwise, it returns false.
6628static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6629 auto *DRE = dyn_cast<DeclRefExpr>(E);
6630 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6631 return false;
6632
6634 cast<FunctionDecl>(DRE->getDecl()));
6635}
6636
6637/// Determine whether we can perform an elementwise array copy for this kind
6638/// of entity.
6639static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6640 switch (Entity.getKind()) {
6642 // C++ [expr.prim.lambda]p24:
6643 // For array members, the array elements are direct-initialized in
6644 // increasing subscript order.
6645 return true;
6646
6648 // C++ [dcl.decomp]p1:
6649 // [...] each element is copy-initialized or direct-initialized from the
6650 // corresponding element of the assignment-expression [...]
6651 return isa<DecompositionDecl>(Entity.getDecl());
6652
6654 // C++ [class.copy.ctor]p14:
6655 // - if the member is an array, each element is direct-initialized with
6656 // the corresponding subobject of x
6657 return Entity.isImplicitMemberInitializer();
6658
6660 // All the above cases are intended to apply recursively, even though none
6661 // of them actually say that.
6662 if (auto *E = Entity.getParent())
6663 return canPerformArrayCopy(*E);
6664 break;
6665
6666 default:
6667 break;
6668 }
6669
6670 return false;
6671}
6672
6673static const FieldDecl *getConstField(const RecordDecl *RD) {
6674 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6675 for (const FieldDecl *FD : RD->fields()) {
6676 // If the field is a flexible array member, we don't want to consider it
6677 // as a const field because there's no way to initialize the FAM anyway.
6678 const ASTContext &Ctx = FD->getASTContext();
6680 Ctx, FD, FD->getType(),
6681 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6682 /*IgnoreTemplateOrMacroSubstitution=*/true))
6683 continue;
6684
6685 QualType QT = FD->getType();
6686 if (QT.isConstQualified())
6687 return FD;
6688 if (const auto *RD = QT->getAsRecordDecl()) {
6689 if (const FieldDecl *FD = getConstField(RD))
6690 return FD;
6691 }
6692 }
6693 return nullptr;
6694}
6695
6697 const InitializedEntity &Entity,
6698 const InitializationKind &Kind,
6699 MultiExprArg Args,
6700 bool TopLevelOfInitList,
6701 bool TreatUnavailableAsInvalid) {
6702 ASTContext &Context = S.Context;
6703
6704 // Eliminate non-overload placeholder types in the arguments. We
6705 // need to do this before checking whether types are dependent
6706 // because lowering a pseudo-object expression might well give us
6707 // something of dependent type.
6708 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6709 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6710 // FIXME: should we be doing this here?
6711 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6712 if (result.isInvalid()) {
6714 return;
6715 }
6716 Args[I] = result.get();
6717 }
6718
6719 // C++0x [dcl.init]p16:
6720 // The semantics of initializers are as follows. The destination type is
6721 // the type of the object or reference being initialized and the source
6722 // type is the type of the initializer expression. The source type is not
6723 // defined when the initializer is a braced-init-list or when it is a
6724 // parenthesized list of expressions.
6725 QualType DestType = Entity.getType();
6726
6727 if (DestType->isDependentType() ||
6730 return;
6731 }
6732
6733 // Almost everything is a normal sequence.
6735
6736 QualType SourceType;
6737 Expr *Initializer = nullptr;
6738 if (Args.size() == 1) {
6739 Initializer = Args[0];
6740 if (S.getLangOpts().ObjC) {
6742 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6743 Initializer) ||
6745 Args[0] = Initializer;
6746 }
6748 SourceType = Initializer->getType();
6749 }
6750
6751 // - If the initializer is a (non-parenthesized) braced-init-list, the
6752 // object is list-initialized (8.5.4).
6753 if (Kind.getKind() != InitializationKind::IK_Direct) {
6754 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6755 TryListInitialization(S, Entity, Kind, InitList, *this,
6756 TreatUnavailableAsInvalid);
6757 return;
6758 }
6759 }
6760
6761 if (!S.getLangOpts().CPlusPlus &&
6762 Kind.getKind() == InitializationKind::IK_Default) {
6763 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6764 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6765 if (Rec->hasUninitializedExplicitInitFields()) {
6766 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6767 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6768 << /* Var-in-Record */ 1 << Rec;
6770 }
6771 }
6772 // If the record has any members which are const (recursively checked),
6773 // then we want to diagnose those as being uninitialized if there is no
6774 // initializer present. However, we only do this for structure types, not
6775 // union types, because an unitialized field in a union is generally
6776 // reasonable, especially in C where unions can be used for type punning.
6777 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6778 if (const FieldDecl *FD = getConstField(Rec)) {
6779 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6780 if (Var->getStorageDuration() == SD_Static ||
6781 Var->getStorageDuration() == SD_Thread)
6782 DiagID = diag::warn_default_init_const_field;
6783
6784 bool EmitCppCompat = !S.Diags.isIgnored(
6785 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6786 Var->getLocation());
6787
6788 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6789 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6790 }
6791 }
6792 }
6793 }
6794
6795 // - If the destination type is a reference type, see 8.5.3.
6796 if (DestType->isReferenceType()) {
6797 // C++0x [dcl.init.ref]p1:
6798 // A variable declared to be a T& or T&&, that is, "reference to type T"
6799 // (8.3.2), shall be initialized by an object, or function, of type T or
6800 // by an object that can be converted into a T.
6801 // (Therefore, multiple arguments are not permitted.)
6802 if (Args.size() != 1)
6804 // C++17 [dcl.init.ref]p5:
6805 // A reference [...] is initialized by an expression [...] as follows:
6806 // If the initializer is not an expression, presumably we should reject,
6807 // but the standard fails to actually say so.
6808 else if (isa<InitListExpr>(Args[0]))
6810 else
6811 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6812 TopLevelOfInitList);
6813 return;
6814 }
6815
6816 // - If the initializer is (), the object is value-initialized.
6817 if (Kind.getKind() == InitializationKind::IK_Value ||
6818 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6819 TryValueInitialization(S, Entity, Kind, *this);
6820 return;
6821 }
6822
6823 // Handle default initialization.
6824 if (Kind.getKind() == InitializationKind::IK_Default) {
6825 TryDefaultInitialization(S, Entity, Kind, *this);
6826 return;
6827 }
6828
6829 // - If the destination type is an array of characters, an array of
6830 // char16_t, an array of char32_t, or an array of wchar_t, and the
6831 // initializer is a string literal, see 8.5.2.
6832 // - Otherwise, if the destination type is an array, the program is
6833 // ill-formed.
6834 // - Except in HLSL, where non-decaying array parameters behave like
6835 // non-array types for initialization.
6836 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6837 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6838 if (Initializer && isa<VariableArrayType>(DestAT)) {
6840 return;
6841 }
6842
6843 if (Initializer) {
6844 switch (IsStringInit(Initializer, DestAT, Context)) {
6845 case SIF_None:
6846 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6847 return;
6850 return;
6853 return;
6856 return;
6859 return;
6862 return;
6863 case SIF_Other:
6864 break;
6865 }
6866 }
6867
6868 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6869 QualType SrcType = Entity.getType();
6870 if (SrcType->isArrayParameterType())
6871 SrcType =
6872 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6873 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6874 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6875 TreatUnavailableAsInvalid);
6876 return;
6877 }
6878 }
6879
6880 // Some kinds of initialization permit an array to be initialized from
6881 // another array of the same type, and perform elementwise initialization.
6882 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6884 Entity.getType()) &&
6885 canPerformArrayCopy(Entity)) {
6886 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6887 TreatUnavailableAsInvalid);
6888 return;
6889 }
6890
6891 // Note: as an GNU C extension, we allow initialization of an
6892 // array from a compound literal that creates an array of the same
6893 // type, so long as the initializer has no side effects.
6894 if (!S.getLangOpts().CPlusPlus && Initializer &&
6895 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6896 Initializer->getType()->isArrayType()) {
6897 const ArrayType *SourceAT
6898 = Context.getAsArrayType(Initializer->getType());
6899 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6901 else if (Initializer->HasSideEffects(S.Context))
6903 else {
6904 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6905 }
6906 }
6907 // Note: as a GNU C++ extension, we allow list-initialization of a
6908 // class member of array type from a parenthesized initializer list.
6909 else if (S.getLangOpts().CPlusPlus &&
6911 isa_and_nonnull<InitListExpr>(Initializer)) {
6913 *this, TreatUnavailableAsInvalid);
6915 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6916 Kind.getKind() == InitializationKind::IK_Direct)
6917 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6918 /*VerifyOnly=*/true);
6919 else if (DestAT->getElementType()->isCharType())
6921 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6923 else
6925
6926 return;
6927 }
6928
6929 // Determine whether we should consider writeback conversions for
6930 // Objective-C ARC.
6931 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6932 Entity.isParameterKind();
6933
6934 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6935 return;
6936
6937 // We're at the end of the line for C: it's either a write-back conversion
6938 // or it's a C assignment. There's no need to check anything else.
6939 if (!S.getLangOpts().CPlusPlus) {
6940 assert(Initializer && "Initializer must be non-null");
6941 // If allowed, check whether this is an Objective-C writeback conversion.
6942 if (allowObjCWritebackConversion &&
6943 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6944 return;
6945 }
6946
6947 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6948 return;
6949
6950 // Handle initialization in C
6951 AddCAssignmentStep(DestType);
6952 MaybeProduceObjCObject(S, *this, Entity);
6953 return;
6954 }
6955
6956 assert(S.getLangOpts().CPlusPlus);
6957
6958 // - If the destination type is a (possibly cv-qualified) class type:
6959 // (except for HLSL, where user-defined record types do not have
6960 // constructors or conversion functions)
6961 if (DestType->isRecordType() &&
6962 (!S.getLangOpts().HLSL ||
6963 DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
6964 // - If the initialization is direct-initialization, or if it is
6965 // copy-initialization where the cv-unqualified version of the
6966 // source type is the same class as, or a derived class of, the
6967 // class of the destination, constructors are considered. [...]
6968 if (Kind.getKind() == InitializationKind::IK_Direct ||
6969 (Kind.getKind() == InitializationKind::IK_Copy &&
6970 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6971 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6972 SourceType, DestType))))) {
6973 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6974 *this, /*IsAggrListInit=*/false);
6975 } else {
6976 // - Otherwise (i.e., for the remaining copy-initialization cases),
6977 // user-defined conversion sequences that can convert from the
6978 // source type to the destination type or (when a conversion
6979 // function is used) to a derived class thereof are enumerated as
6980 // described in 13.3.1.4, and the best one is chosen through
6981 // overload resolution (13.3).
6982 assert(Initializer && "Initializer must be non-null");
6983 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6984 TopLevelOfInitList);
6985 }
6986 return;
6987 }
6988
6989 assert(Args.size() >= 1 && "Zero-argument case handled above");
6990
6991 // For HLSL ext vector types we allow list initialization behavior for C++
6992 // functional cast expressions which look like constructor syntax. This is
6993 // accomplished by converting initialization arguments to InitListExpr.
6994 auto ShouldTryListInitialization = [&]() -> bool {
6995 // Only try list initialization for HLSL.
6996 if (!S.getLangOpts().HLSL)
6997 return false;
6998
6999 bool DestIsVec = DestType->isExtVectorType();
7000 bool DestIsMat = DestType->isConstantMatrixType();
7001
7002 // If the destination type is neither a vector nor a matrix, then don't try
7003 // list initialization.
7004 if (!DestIsVec && !DestIsMat)
7005 return false;
7006
7007 // If there is only a single source argument, then only try list
7008 // initialization if initializing a matrix with a vector or vice versa.
7009 if (Args.size() == 1) {
7010 assert(!SourceType.isNull() &&
7011 "Source QualType should not be null when arg size is exactly 1");
7012 bool SourceIsVec = SourceType->isExtVectorType();
7013 bool SourceIsMat = SourceType->isConstantMatrixType();
7014
7015 if (DestIsMat && !SourceIsVec)
7016 return false;
7017 if (DestIsVec && !SourceIsMat)
7018 return false;
7019 }
7020
7021 // Try list initialization if the source type is null or if the
7022 // destination and source types differ.
7023 return SourceType.isNull() ||
7024 !Context.hasSameUnqualifiedType(SourceType, DestType);
7025 };
7026 if (ShouldTryListInitialization()) {
7027 InitListExpr *ILE = new (Context)
7028 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
7029 Args.back()->getEndLoc(), /*isExplicit=*/false);
7030 ILE->setType(DestType);
7031 Args[0] = ILE;
7032 TryListInitialization(S, Entity, Kind, ILE, *this,
7033 TreatUnavailableAsInvalid);
7034 return;
7035 }
7036
7037 // The remaining cases all need a source type.
7038 if (Args.size() > 1) {
7040 return;
7041 } else if (isa<InitListExpr>(Args[0])) {
7043 return;
7044 }
7045
7046 // - Otherwise, if the source type is a (possibly cv-qualified) class
7047 // type, conversion functions are considered.
7048 // (except for HLSL, where user-defined record types do not have
7049 // constructors or conversion functions).
7050 if (!SourceType.isNull() && SourceType->isRecordType() &&
7051 (!S.getLangOpts().HLSL ||
7052 SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
7053 assert(Initializer && "Initializer must be non-null");
7054 // For a conversion to _Atomic(T) from either T or a class type derived
7055 // from T, initialize the T object then convert to _Atomic type.
7056 bool NeedAtomicConversion = false;
7057 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7058 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
7059 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
7060 Atomic->getValueType())) {
7061 DestType = Atomic->getValueType();
7062 NeedAtomicConversion = true;
7063 }
7064 }
7065
7066 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7067 TopLevelOfInitList);
7068 MaybeProduceObjCObject(S, *this, Entity);
7069 if (!Failed() && NeedAtomicConversion)
7071 return;
7072 }
7073
7074 // - Otherwise, if the initialization is direct-initialization, the source
7075 // type is std::nullptr_t, and the destination type is bool, the initial
7076 // value of the object being initialized is false.
7077 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7078 DestType->isBooleanType() &&
7079 Kind.getKind() == InitializationKind::IK_Direct) {
7082 Initializer->isGLValue()),
7083 DestType);
7084 return;
7085 }
7086
7087 // - Otherwise, the initial value of the object being initialized is the
7088 // (possibly converted) value of the initializer expression. Standard
7089 // conversions (Clause 4) will be used, if necessary, to convert the
7090 // initializer expression to the cv-unqualified version of the
7091 // destination type; no user-defined conversions are considered.
7092
7094 = S.TryImplicitConversion(Initializer, DestType,
7095 /*SuppressUserConversions*/true,
7096 Sema::AllowedExplicit::None,
7097 /*InOverloadResolution*/ false,
7098 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7099 allowObjCWritebackConversion);
7100
7101 if (ICS.isStandard() &&
7103 // Objective-C ARC writeback conversion.
7104
7105 // We should copy unless we're passing to an argument explicitly
7106 // marked 'out'.
7107 bool ShouldCopy = true;
7108 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
7109 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7110
7111 // If there was an lvalue adjustment, add it as a separate conversion.
7112 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7115 LvalueICS.setStandard();
7117 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
7118 LvalueICS.Standard.First = ICS.Standard.First;
7119 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
7120 }
7121
7122 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
7123 } else if (ICS.isBad()) {
7125 Initializer->getType() == Context.OverloadTy &&
7127 /*Complain=*/false, Found))
7129 else if (Initializer->getType()->isFunctionType() &&
7132 else
7134 } else {
7135 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
7136
7137 MaybeProduceObjCObject(S, *this, Entity);
7138 }
7139}
7140
7142 for (auto &S : Steps)
7143 S.Destroy();
7144}
7145
7146//===----------------------------------------------------------------------===//
7147// Perform initialization
7148//===----------------------------------------------------------------------===//
7150 bool Diagnose = false) {
7151 switch(Entity.getKind()) {
7158
7160 if (Entity.getDecl() &&
7163
7165
7167 if (Entity.getDecl() &&
7170
7171 return !Diagnose ? AssignmentAction::Passing
7173
7175 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7177
7180 // FIXME: Can we tell apart casting vs. converting?
7182
7184 // This is really initialization, but refer to it as conversion for
7185 // consistency with CheckConvertedConstantExpression.
7187
7200 }
7201
7202 llvm_unreachable("Invalid EntityKind!");
7203}
7204
7205/// Whether we should bind a created object as a temporary when
7206/// initializing the given entity.
7239
7240/// Whether the given entity, when initialized with an object
7241/// created for that initialization, requires destruction.
7274
7275/// Get the location at which initialization diagnostics should appear.
7314
7315/// Make a (potentially elidable) temporary copy of the object
7316/// provided by the given initializer by calling the appropriate copy
7317/// constructor.
7318///
7319/// \param S The Sema object used for type-checking.
7320///
7321/// \param T The type of the temporary object, which must either be
7322/// the type of the initializer expression or a superclass thereof.
7323///
7324/// \param Entity The entity being initialized.
7325///
7326/// \param CurInit The initializer expression.
7327///
7328/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7329/// is permitted in C++03 (but not C++0x) when binding a reference to
7330/// an rvalue.
7331///
7332/// \returns An expression that copies the initializer expression into
7333/// a temporary object, or an error expression if a copy could not be
7334/// created.
7336 QualType T,
7337 const InitializedEntity &Entity,
7338 ExprResult CurInit,
7339 bool IsExtraneousCopy) {
7340 if (CurInit.isInvalid())
7341 return CurInit;
7342 // Determine which class type we're copying to.
7343 Expr *CurInitExpr = (Expr *)CurInit.get();
7344 auto *Class = T->getAsCXXRecordDecl();
7345 if (!Class)
7346 return CurInit;
7347
7348 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7349
7350 // Make sure that the type we are copying is complete.
7351 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7352 return CurInit;
7353
7354 // Perform overload resolution using the class's constructors. Per
7355 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7356 // is direct-initialization.
7359
7362 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7363 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7364 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7365 /*RequireActualConstructor=*/false,
7366 /*SecondStepOfCopyInit=*/true)) {
7367 case OR_Success:
7368 break;
7369
7371 CandidateSet.NoteCandidates(
7373 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7374 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7375 : diag::err_temp_copy_no_viable)
7376 << (int)Entity.getKind() << CurInitExpr->getType()
7377 << CurInitExpr->getSourceRange()),
7378 S, OCD_AllCandidates, CurInitExpr);
7379 if (!IsExtraneousCopy || S.isSFINAEContext())
7380 return ExprError();
7381 return CurInit;
7382
7383 case OR_Ambiguous:
7384 CandidateSet.NoteCandidates(
7385 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7386 << (int)Entity.getKind()
7387 << CurInitExpr->getType()
7388 << CurInitExpr->getSourceRange()),
7389 S, OCD_AmbiguousCandidates, CurInitExpr);
7390 return ExprError();
7391
7392 case OR_Deleted:
7393 S.Diag(Loc, diag::err_temp_copy_deleted)
7394 << (int)Entity.getKind() << CurInitExpr->getType()
7395 << CurInitExpr->getSourceRange();
7396 S.NoteDeletedFunction(Best->Function);
7397 return ExprError();
7398 }
7399
7400 bool HadMultipleCandidates = CandidateSet.size() > 1;
7401
7403 SmallVector<Expr*, 8> ConstructorArgs;
7404 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7405
7406 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7407 IsExtraneousCopy);
7408
7409 if (IsExtraneousCopy) {
7410 // If this is a totally extraneous copy for C++03 reference
7411 // binding purposes, just return the original initialization
7412 // expression. We don't generate an (elided) copy operation here
7413 // because doing so would require us to pass down a flag to avoid
7414 // infinite recursion, where each step adds another extraneous,
7415 // elidable copy.
7416
7417 // Instantiate the default arguments of any extra parameters in
7418 // the selected copy constructor, as if we were going to create a
7419 // proper call to the copy constructor.
7420 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7421 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7422 if (S.RequireCompleteType(Loc, Parm->getType(),
7423 diag::err_call_incomplete_argument))
7424 break;
7425
7426 // Build the default argument expression; we don't actually care
7427 // if this succeeds or not, because this routine will complain
7428 // if there was a problem.
7429 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7430 }
7431
7432 return CurInitExpr;
7433 }
7434
7435 // Determine the arguments required to actually perform the
7436 // constructor call (we might have derived-to-base conversions, or
7437 // the copy constructor may have default arguments).
7438 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7439 ConstructorArgs))
7440 return ExprError();
7441
7442 // C++0x [class.copy]p32:
7443 // When certain criteria are met, an implementation is allowed to
7444 // omit the copy/move construction of a class object, even if the
7445 // copy/move constructor and/or destructor for the object have
7446 // side effects. [...]
7447 // - when a temporary class object that has not been bound to a
7448 // reference (12.2) would be copied/moved to a class object
7449 // with the same cv-unqualified type, the copy/move operation
7450 // can be omitted by constructing the temporary object
7451 // directly into the target of the omitted copy/move
7452 //
7453 // Note that the other three bullets are handled elsewhere. Copy
7454 // elision for return statements and throw expressions are handled as part
7455 // of constructor initialization, while copy elision for exception handlers
7456 // is handled by the run-time.
7457 //
7458 // FIXME: If the function parameter is not the same type as the temporary, we
7459 // should still be able to elide the copy, but we don't have a way to
7460 // represent in the AST how much should be elided in this case.
7461 bool Elidable =
7462 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7464 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7465 CurInitExpr->getType());
7466
7467 // Actually perform the constructor call.
7468 CurInit = S.BuildCXXConstructExpr(
7469 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7470 HadMultipleCandidates,
7471 /*ListInit*/ false,
7472 /*StdInitListInit*/ false,
7473 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7474
7475 // If we're supposed to bind temporaries, do so.
7476 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7477 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7478 return CurInit;
7479}
7480
7481/// Check whether elidable copy construction for binding a reference to
7482/// a temporary would have succeeded if we were building in C++98 mode, for
7483/// -Wc++98-compat.
7485 const InitializedEntity &Entity,
7486 Expr *CurInitExpr) {
7487 assert(S.getLangOpts().CPlusPlus11);
7488
7489 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7490 if (!Record)
7491 return;
7492
7493 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7494 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7495 return;
7496
7497 // Find constructors which would have been considered.
7500
7501 // Perform overload resolution.
7504 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7505 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7506 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7507 /*RequireActualConstructor=*/false,
7508 /*SecondStepOfCopyInit=*/true);
7509
7510 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7511 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7512 << CurInitExpr->getSourceRange();
7513
7514 switch (OR) {
7515 case OR_Success:
7516 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7517 Best->FoundDecl, Entity, Diag);
7518 // FIXME: Check default arguments as far as that's possible.
7519 break;
7520
7522 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7523 OCD_AllCandidates, CurInitExpr);
7524 break;
7525
7526 case OR_Ambiguous:
7527 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7528 OCD_AmbiguousCandidates, CurInitExpr);
7529 break;
7530
7531 case OR_Deleted:
7532 S.Diag(Loc, Diag);
7533 S.NoteDeletedFunction(Best->Function);
7534 break;
7535 }
7536}
7537
7538void InitializationSequence::PrintInitLocationNote(Sema &S,
7539 const InitializedEntity &Entity) {
7540 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7541 if (Entity.getDecl()->getLocation().isInvalid())
7542 return;
7543
7544 if (Entity.getDecl()->getDeclName())
7545 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7546 << Entity.getDecl()->getDeclName();
7547 else
7548 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7549 }
7550 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7551 Entity.getMethodDecl())
7552 S.Diag(Entity.getMethodDecl()->getLocation(),
7553 diag::note_method_return_type_change)
7554 << Entity.getMethodDecl()->getDeclName();
7555}
7556
7557/// Returns true if the parameters describe a constructor initialization of
7558/// an explicit temporary object, e.g. "Point(x, y)".
7559static bool isExplicitTemporary(const InitializedEntity &Entity,
7560 const InitializationKind &Kind,
7561 unsigned NumArgs) {
7562 switch (Entity.getKind()) {
7566 break;
7567 default:
7568 return false;
7569 }
7570
7571 switch (Kind.getKind()) {
7573 return true;
7574 // FIXME: Hack to work around cast weirdness.
7577 return NumArgs != 1;
7578 default:
7579 return false;
7580 }
7581}
7582
7583static ExprResult
7585 const InitializedEntity &Entity,
7586 const InitializationKind &Kind,
7587 MultiExprArg Args,
7588 const InitializationSequence::Step& Step,
7589 bool &ConstructorInitRequiresZeroInit,
7590 bool IsListInitialization,
7591 bool IsStdInitListInitialization,
7592 SourceLocation LBraceLoc,
7593 SourceLocation RBraceLoc) {
7594 unsigned NumArgs = Args.size();
7597 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7598
7599 // Build a call to the selected constructor.
7600 SmallVector<Expr*, 8> ConstructorArgs;
7601 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7602 ? Kind.getEqualLoc()
7603 : Kind.getLocation();
7604
7605 if (Kind.getKind() == InitializationKind::IK_Default) {
7606 // Force even a trivial, implicit default constructor to be
7607 // semantically checked. We do this explicitly because we don't build
7608 // the definition for completely trivial constructors.
7609 assert(Constructor->getParent() && "No parent class for constructor.");
7610 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7611 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7612 S.runWithSufficientStackSpace(Loc, [&] {
7614 });
7615 }
7616 }
7617
7618 ExprResult CurInit((Expr *)nullptr);
7619
7620 // C++ [over.match.copy]p1:
7621 // - When initializing a temporary to be bound to the first parameter
7622 // of a constructor that takes a reference to possibly cv-qualified
7623 // T as its first argument, called with a single argument in the
7624 // context of direct-initialization, explicit conversion functions
7625 // are also considered.
7626 bool AllowExplicitConv =
7627 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7630
7631 // A smart pointer constructed from a nullable pointer is nullable.
7632 if (NumArgs == 1 && !Kind.isExplicitCast())
7634 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7635
7636 // Determine the arguments required to actually perform the constructor
7637 // call.
7638 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7639 ConstructorArgs, AllowExplicitConv,
7640 IsListInitialization))
7641 return ExprError();
7642
7643 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7644 // An explicitly-constructed temporary, e.g., X(1, 2).
7645 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7646 return ExprError();
7647
7648 if (Kind.getKind() == InitializationKind::IK_Value &&
7649 Constructor->isImplicit()) {
7650 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7651 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7652 unsigned I = 0;
7653 for (const FieldDecl *FD : RD->fields()) {
7654 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7655 !S.isUnevaluatedContext()) {
7656 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7657 << /* Var-in-Record */ 0 << FD;
7658 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7659 }
7660 ++I;
7661 }
7662 }
7663 }
7664
7665 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7666 if (!TSInfo)
7667 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7668 SourceRange ParenOrBraceRange =
7669 (Kind.getKind() == InitializationKind::IK_DirectList)
7670 ? SourceRange(LBraceLoc, RBraceLoc)
7671 : Kind.getParenOrBraceRange();
7672
7673 CXXConstructorDecl *CalleeDecl = Constructor;
7674 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7675 Step.Function.FoundDecl.getDecl())) {
7676 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7677 }
7678 S.MarkFunctionReferenced(Loc, CalleeDecl);
7679
7680 CurInit = S.CheckForImmediateInvocation(
7682 S.Context, CalleeDecl,
7683 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7684 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7685 IsListInitialization, IsStdInitListInitialization,
7686 ConstructorInitRequiresZeroInit),
7687 CalleeDecl);
7688 } else {
7690
7691 if (Entity.getKind() == InitializedEntity::EK_Base) {
7692 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7695 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7696 ConstructKind = CXXConstructionKind::Delegating;
7697 }
7698
7699 // Only get the parenthesis or brace range if it is a list initialization or
7700 // direct construction.
7701 SourceRange ParenOrBraceRange;
7702 if (IsListInitialization)
7703 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7704 else if (Kind.getKind() == InitializationKind::IK_Direct)
7705 ParenOrBraceRange = Kind.getParenOrBraceRange();
7706
7707 // If the entity allows NRVO, mark the construction as elidable
7708 // unconditionally.
7709 if (Entity.allowsNRVO())
7710 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7711 Step.Function.FoundDecl,
7712 Constructor, /*Elidable=*/true,
7713 ConstructorArgs,
7714 HadMultipleCandidates,
7715 IsListInitialization,
7716 IsStdInitListInitialization,
7717 ConstructorInitRequiresZeroInit,
7718 ConstructKind,
7719 ParenOrBraceRange);
7720 else
7721 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7722 Step.Function.FoundDecl,
7724 ConstructorArgs,
7725 HadMultipleCandidates,
7726 IsListInitialization,
7727 IsStdInitListInitialization,
7728 ConstructorInitRequiresZeroInit,
7729 ConstructKind,
7730 ParenOrBraceRange);
7731 }
7732 if (CurInit.isInvalid())
7733 return ExprError();
7734
7735 // Only check access if all of that succeeded.
7738 return ExprError();
7739
7740 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7742 return ExprError();
7743
7744 if (shouldBindAsTemporary(Entity))
7745 CurInit = S.MaybeBindToTemporary(CurInit.get());
7746
7747 return CurInit;
7748}
7749
7751 Expr *Init) {
7752 return sema::checkInitLifetime(*this, Entity, Init);
7753}
7754
7755static void DiagnoseNarrowingInInitList(Sema &S,
7756 const ImplicitConversionSequence &ICS,
7757 QualType PreNarrowingType,
7758 QualType EntityType,
7759 const Expr *PostInit);
7760
7761static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7762 QualType ToType, Expr *Init);
7763
7764/// Provide warnings when std::move is used on construction.
7765static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7766 bool IsReturnStmt) {
7767 if (!InitExpr)
7768 return;
7769
7771 return;
7772
7773 QualType DestType = InitExpr->getType();
7774 if (!DestType->isRecordType())
7775 return;
7776
7777 unsigned DiagID = 0;
7778 if (IsReturnStmt) {
7779 const CXXConstructExpr *CCE =
7780 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7781 if (!CCE || CCE->getNumArgs() != 1)
7782 return;
7783
7785 return;
7786
7787 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7788 }
7789
7790 // Find the std::move call and get the argument.
7791 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7792 if (!CE || !CE->isCallToStdMove())
7793 return;
7794
7795 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7796
7797 if (IsReturnStmt) {
7798 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7799 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7800 return;
7801
7802 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7803 if (!VD || !VD->hasLocalStorage())
7804 return;
7805
7806 // __block variables are not moved implicitly.
7807 if (VD->hasAttr<BlocksAttr>())
7808 return;
7809
7810 QualType SourceType = VD->getType();
7811 if (!SourceType->isRecordType())
7812 return;
7813
7814 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7815 return;
7816 }
7817
7818 // If we're returning a function parameter, copy elision
7819 // is not possible.
7820 if (isa<ParmVarDecl>(VD))
7821 DiagID = diag::warn_redundant_move_on_return;
7822 else
7823 DiagID = diag::warn_pessimizing_move_on_return;
7824 } else {
7825 DiagID = diag::warn_pessimizing_move_on_initialization;
7826 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7827 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7828 return;
7829 }
7830
7831 S.Diag(CE->getBeginLoc(), DiagID);
7832
7833 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7834 // is within a macro.
7835 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7836 if (CallBegin.isMacroID())
7837 return;
7838 SourceLocation RParen = CE->getRParenLoc();
7839 if (RParen.isMacroID())
7840 return;
7841 SourceLocation LParen;
7842 SourceLocation ArgLoc = Arg->getBeginLoc();
7843
7844 // Special testing for the argument location. Since the fix-it needs the
7845 // location right before the argument, the argument location can be in a
7846 // macro only if it is at the beginning of the macro.
7847 while (ArgLoc.isMacroID() &&
7850 }
7851
7852 if (LParen.isMacroID())
7853 return;
7854
7855 LParen = ArgLoc.getLocWithOffset(-1);
7856
7857 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7858 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7859 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7860}
7861
7862static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7863 // Check to see if we are dereferencing a null pointer. If so, this is
7864 // undefined behavior, so warn about it. This only handles the pattern
7865 // "*null", which is a very syntactic check.
7866 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7867 if (UO->getOpcode() == UO_Deref &&
7868 UO->getSubExpr()->IgnoreParenCasts()->
7869 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7870 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7871 S.PDiag(diag::warn_binding_null_to_reference)
7872 << UO->getSubExpr()->getSourceRange());
7873 }
7874}
7875
7878 bool BoundToLvalueReference) {
7879 auto MTE = new (Context)
7880 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7881
7882 // Order an ExprWithCleanups for lifetime marks.
7883 //
7884 // TODO: It'll be good to have a single place to check the access of the
7885 // destructor and generate ExprWithCleanups for various uses. Currently these
7886 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7887 // but there may be a chance to merge them.
7888 Cleanup.setExprNeedsCleanups(false);
7891 return MTE;
7892}
7893
7895 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7896 // same rule, but C99 is broken without this behavior and so we treat the
7897 // change as applying to all C language modes.
7898 // FIXME: This means that AST consumers need to deal with "prvalues" that
7899 // denote materialized temporaries. Maybe we should add another ValueKind
7900 // for "xvalue pretending to be a prvalue" for C++98 support.
7901 if (!E->isPRValue() ||
7903 return E;
7904
7905 // C++1z [conv.rval]/1: T shall be a complete type.
7906 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7907 // If so, we should check for a non-abstract class type here too.
7908 QualType T = E->getType();
7909 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7910 return ExprError();
7911
7912 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7913}
7914
7918
7919 CastKind CK = CK_NoOp;
7920
7921 if (VK == VK_PRValue) {
7922 auto PointeeTy = Ty->getPointeeType();
7923 auto ExprPointeeTy = E->getType()->getPointeeType();
7924 if (!PointeeTy.isNull() &&
7925 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7926 CK = CK_AddressSpaceConversion;
7927 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7928 CK = CK_AddressSpaceConversion;
7929 }
7930
7931 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7932}
7933
7935 const InitializedEntity &Entity,
7936 const InitializationKind &Kind,
7937 MultiExprArg Args,
7938 QualType *ResultType) {
7939 if (Failed()) {
7940 Diagnose(S, Entity, Kind, Args);
7941 return ExprError();
7942 }
7943 if (!ZeroInitializationFixit.empty()) {
7944 const Decl *D = Entity.getDecl();
7945 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7946 QualType DestType = Entity.getType();
7947
7948 // The initialization would have succeeded with this fixit. Since the fixit
7949 // is on the error, we need to build a valid AST in this case, so this isn't
7950 // handled in the Failed() branch above.
7951 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7952 // Use a more useful diagnostic for constexpr variables.
7953 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7954 << VD
7955 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7956 ZeroInitializationFixit);
7957 } else {
7958 unsigned DiagID = diag::err_default_init_const;
7959 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7960 DiagID = diag::ext_default_init_const;
7961
7962 S.Diag(Kind.getLocation(), DiagID)
7963 << DestType << DestType->isRecordType()
7964 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7965 ZeroInitializationFixit);
7966 }
7967 }
7968
7969 if (getKind() == DependentSequence) {
7970 // If the declaration is a non-dependent, incomplete array type
7971 // that has an initializer, then its type will be completed once
7972 // the initializer is instantiated.
7973 if (ResultType && !Entity.getType()->isDependentType() &&
7974 Args.size() == 1) {
7975 QualType DeclType = Entity.getType();
7976 if (const IncompleteArrayType *ArrayT
7977 = S.Context.getAsIncompleteArrayType(DeclType)) {
7978 // FIXME: We don't currently have the ability to accurately
7979 // compute the length of an initializer list without
7980 // performing full type-checking of the initializer list
7981 // (since we have to determine where braces are implicitly
7982 // introduced and such). So, we fall back to making the array
7983 // type a dependently-sized array type with no specified
7984 // bound.
7985 if (isa<InitListExpr>((Expr *)Args[0]))
7986 *ResultType = S.Context.getDependentSizedArrayType(
7987 ArrayT->getElementType(),
7988 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7989 ArrayT->getIndexTypeCVRQualifiers());
7990 }
7991 }
7992 if (Kind.getKind() == InitializationKind::IK_Direct &&
7993 !Kind.isExplicitCast()) {
7994 // Rebuild the ParenListExpr.
7995 SourceRange ParenRange = Kind.getParenOrBraceRange();
7996 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7997 Args);
7998 }
7999 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8000 Kind.isExplicitCast() ||
8001 Kind.getKind() == InitializationKind::IK_DirectList);
8002 return ExprResult(Args[0]);
8003 }
8004
8005 // No steps means no initialization.
8006 if (Steps.empty())
8007 return ExprResult((Expr *)nullptr);
8008
8009 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8010 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8011 !Entity.isParamOrTemplateParamKind()) {
8012 // Produce a C++98 compatibility warning if we are initializing a reference
8013 // from an initializer list. For parameters, we produce a better warning
8014 // elsewhere.
8015 Expr *Init = Args[0];
8016 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8017 << Init->getSourceRange();
8018 }
8019
8020 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8021 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8022 // Produce a Microsoft compatibility warning when initializing from a
8023 // predefined expression since MSVC treats predefined expressions as string
8024 // literals.
8025 Expr *Init = Args[0];
8026 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8027 }
8028
8029 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8030 QualType ETy = Entity.getType();
8031 bool HasGlobalAS = ETy.hasAddressSpace() &&
8033
8034 if (S.getLangOpts().OpenCLVersion >= 200 &&
8035 ETy->isAtomicType() && !HasGlobalAS &&
8036 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8037 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8038 << 1
8039 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8040 return ExprError();
8041 }
8042
8043 QualType DestType = Entity.getType().getNonReferenceType();
8044 // FIXME: Ugly hack around the fact that Entity.getType() is not
8045 // the same as Entity.getDecl()->getType() in cases involving type merging,
8046 // and we want latter when it makes sense.
8047 if (ResultType)
8048 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8049 Entity.getType();
8050
8051 ExprResult CurInit((Expr *)nullptr);
8052 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8053
8054 // HLSL allows vector/matrix initialization to function like list
8055 // initialization, but use the syntax of a C++-like constructor.
8056 bool IsHLSLVectorOrMatrixInit =
8057 S.getLangOpts().HLSL &&
8058 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8059 isa<InitListExpr>(Args[0]);
8060 (void)IsHLSLVectorOrMatrixInit;
8061
8062 // For initialization steps that start with a single initializer,
8063 // grab the only argument out the Args and place it into the "current"
8064 // initializer.
8065 switch (Steps.front().Kind) {
8070 case SK_BindReference:
8072 case SK_FinalCopy:
8074 case SK_UserConversion:
8083 case SK_UnwrapInitList:
8084 case SK_RewrapInitList:
8085 case SK_CAssignment:
8086 case SK_StringInit:
8088 case SK_ArrayLoopIndex:
8089 case SK_ArrayLoopInit:
8090 case SK_ArrayInit:
8091 case SK_GNUArrayInit:
8097 case SK_OCLSamplerInit:
8100 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8101 CurInit = Args[0];
8102 if (!CurInit.get()) return ExprError();
8103 break;
8104 }
8105
8111 break;
8112 }
8113
8114 // Promote from an unevaluated context to an unevaluated list context in
8115 // C++11 list-initialization; we need to instantiate entities usable in
8116 // constant expressions here in order to perform narrowing checks =(
8119 isa_and_nonnull<InitListExpr>(CurInit.get()));
8120
8121 // C++ [class.abstract]p2:
8122 // no objects of an abstract class can be created except as subobjects
8123 // of a class derived from it
8124 auto checkAbstractType = [&](QualType T) -> bool {
8125 if (Entity.getKind() == InitializedEntity::EK_Base ||
8127 return false;
8128 return S.RequireNonAbstractType(Kind.getLocation(), T,
8129 diag::err_allocation_of_abstract_type);
8130 };
8131
8132 // Walk through the computed steps for the initialization sequence,
8133 // performing the specified conversions along the way.
8134 bool ConstructorInitRequiresZeroInit = false;
8135 for (step_iterator Step = step_begin(), StepEnd = step_end();
8136 Step != StepEnd; ++Step) {
8137 if (CurInit.isInvalid())
8138 return ExprError();
8139
8140 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8141
8142 switch (Step->Kind) {
8144 // Overload resolution determined which function invoke; update the
8145 // initializer to reflect that choice.
8147 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8148 return ExprError();
8149 CurInit = S.FixOverloadedFunctionReference(CurInit,
8152 // We might get back another placeholder expression if we resolved to a
8153 // builtin.
8154 if (!CurInit.isInvalid())
8155 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8156 break;
8157
8161 // We have a derived-to-base cast that produces either an rvalue or an
8162 // lvalue. Perform that cast.
8163
8164 CXXCastPath BasePath;
8165
8166 // Casts to inaccessible base classes are allowed with C-style casts.
8167 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8169 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8170 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8171 return ExprError();
8172
8175 ? VK_LValue
8177 : VK_PRValue);
8179 CK_DerivedToBase, CurInit.get(),
8180 &BasePath, VK, FPOptionsOverride());
8181 break;
8182 }
8183
8184 case SK_BindReference:
8185 // Reference binding does not have any corresponding ASTs.
8186
8187 // Check exception specifications
8188 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8189 return ExprError();
8190
8191 // We don't check for e.g. function pointers here, since address
8192 // availability checks should only occur when the function first decays
8193 // into a pointer or reference.
8194 if (CurInit.get()->getType()->isFunctionProtoType()) {
8195 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8196 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8197 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8198 DRE->getBeginLoc()))
8199 return ExprError();
8200 }
8201 }
8202 }
8203
8204 CheckForNullPointerDereference(S, CurInit.get());
8205 break;
8206
8208 // Make sure the "temporary" is actually an rvalue.
8209 assert(CurInit.get()->isPRValue() && "not a temporary");
8210
8211 // Check exception specifications
8212 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8213 return ExprError();
8214
8215 QualType MTETy = Step->Type;
8216
8217 // When this is an incomplete array type (such as when this is
8218 // initializing an array of unknown bounds from an init list), use THAT
8219 // type instead so that we propagate the array bounds.
8220 if (MTETy->isIncompleteArrayType() &&
8221 !CurInit.get()->getType()->isIncompleteArrayType() &&
8224 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8225 MTETy = CurInit.get()->getType();
8226
8227 // Materialize the temporary into memory.
8229 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8230 CurInit = MTE;
8231
8232 // If we're extending this temporary to automatic storage duration -- we
8233 // need to register its cleanup during the full-expression's cleanups.
8234 if (MTE->getStorageDuration() == SD_Automatic &&
8235 MTE->getType().isDestructedType())
8237 break;
8238 }
8239
8240 case SK_FinalCopy:
8241 if (checkAbstractType(Step->Type))
8242 return ExprError();
8243
8244 // If the overall initialization is initializing a temporary, we already
8245 // bound our argument if it was necessary to do so. If not (if we're
8246 // ultimately initializing a non-temporary), our argument needs to be
8247 // bound since it's initializing a function parameter.
8248 // FIXME: This is a mess. Rationalize temporary destruction.
8249 if (!shouldBindAsTemporary(Entity))
8250 CurInit = S.MaybeBindToTemporary(CurInit.get());
8251 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8252 /*IsExtraneousCopy=*/false);
8253 break;
8254
8256 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8257 /*IsExtraneousCopy=*/true);
8258 break;
8259
8260 case SK_UserConversion: {
8261 // We have a user-defined conversion that invokes either a constructor
8262 // or a conversion function.
8266 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8267 bool CreatedObject = false;
8268 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8269 // Build a call to the selected constructor.
8270 SmallVector<Expr*, 8> ConstructorArgs;
8271 SourceLocation Loc = CurInit.get()->getBeginLoc();
8272
8273 // Determine the arguments required to actually perform the constructor
8274 // call.
8275 Expr *Arg = CurInit.get();
8277 MultiExprArg(&Arg, 1), Loc,
8278 ConstructorArgs))
8279 return ExprError();
8280
8281 // Build an expression that constructs a temporary.
8282 CurInit = S.BuildCXXConstructExpr(
8283 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8284 HadMultipleCandidates,
8285 /*ListInit*/ false,
8286 /*StdInitListInit*/ false,
8287 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8288 if (CurInit.isInvalid())
8289 return ExprError();
8290
8291 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8292 Entity);
8293 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8294 return ExprError();
8295
8296 CastKind = CK_ConstructorConversion;
8297 CreatedObject = true;
8298 } else {
8299 // Build a call to the conversion function.
8301 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8302 FoundFn);
8303 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8304 return ExprError();
8305
8306 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8307 HadMultipleCandidates);
8308 if (CurInit.isInvalid())
8309 return ExprError();
8310
8311 CastKind = CK_UserDefinedConversion;
8312 CreatedObject = Conversion->getReturnType()->isRecordType();
8313 }
8314
8315 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8316 return ExprError();
8317
8318 CurInit = ImplicitCastExpr::Create(
8319 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8320 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8321
8322 if (shouldBindAsTemporary(Entity))
8323 // The overall entity is temporary, so this expression should be
8324 // destroyed at the end of its full-expression.
8325 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8326 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8327 // The object outlasts the full-expression, but we need to prepare for
8328 // a destructor being run on it.
8329 // FIXME: It makes no sense to do this here. This should happen
8330 // regardless of how we initialized the entity.
8331 QualType T = CurInit.get()->getType();
8332 if (auto *Record = T->castAsCXXRecordDecl()) {
8335 S.PDiag(diag::err_access_dtor_temp) << T);
8337 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8338 return ExprError();
8339 }
8340 }
8341 break;
8342 }
8343
8347 // Perform a qualification conversion; these can never go wrong.
8350 ? VK_LValue
8352 : VK_PRValue);
8353 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8354 break;
8355 }
8356
8358 assert(CurInit.get()->isLValue() &&
8359 "function reference should be lvalue");
8360 CurInit =
8361 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8362 break;
8363
8364 case SK_AtomicConversion: {
8365 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8366 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8367 CK_NonAtomicToAtomic, VK_PRValue);
8368 break;
8369 }
8370
8373 if (const auto *FromPtrType =
8374 CurInit.get()->getType()->getAs<PointerType>()) {
8375 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8376 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8377 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8378 // Do not check static casts here because they are checked earlier
8379 // in Sema::ActOnCXXNamedCast()
8380 if (!Kind.isStaticCast()) {
8381 S.Diag(CurInit.get()->getExprLoc(),
8382 diag::warn_noderef_to_dereferenceable_pointer)
8383 << CurInit.get()->getSourceRange();
8384 }
8385 }
8386 }
8387 }
8388 Expr *Init = CurInit.get();
8390 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8391 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8392 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8394 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8395 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8396 if (CurInitExprRes.isInvalid())
8397 return ExprError();
8398
8400
8401 CurInit = CurInitExprRes;
8402
8404 S.getLangOpts().CPlusPlus)
8405 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8406 CurInit.get());
8407
8408 break;
8409 }
8410
8411 case SK_ListInitialization: {
8412 if (checkAbstractType(Step->Type))
8413 return ExprError();
8414
8415 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8416 // If we're not initializing the top-level entity, we need to create an
8417 // InitializeTemporary entity for our target type.
8418 QualType Ty = Step->Type;
8419 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8420 InitializedEntity InitEntity =
8421 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8422 InitListChecker PerformInitList(S, InitEntity,
8423 InitList, Ty, /*VerifyOnly=*/false,
8424 /*TreatUnavailableAsInvalid=*/false);
8425 if (PerformInitList.HadError())
8426 return ExprError();
8427
8428 // Hack: We must update *ResultType if available in order to set the
8429 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8430 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8431 if (ResultType &&
8432 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8433 if ((*ResultType)->isRValueReferenceType())
8435 else if ((*ResultType)->isLValueReferenceType())
8437 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8438 *ResultType = Ty;
8439 }
8440
8441 InitListExpr *StructuredInitList =
8442 PerformInitList.getFullyStructuredList();
8443 CurInit = shouldBindAsTemporary(InitEntity)
8444 ? S.MaybeBindToTemporary(StructuredInitList)
8445 : StructuredInitList;
8446 break;
8447 }
8448
8450 if (checkAbstractType(Step->Type))
8451 return ExprError();
8452
8453 // When an initializer list is passed for a parameter of type "reference
8454 // to object", we don't get an EK_Temporary entity, but instead an
8455 // EK_Parameter entity with reference type.
8456 // FIXME: This is a hack. What we really should do is create a user
8457 // conversion step for this case, but this makes it considerably more
8458 // complicated. For now, this will do.
8460 Entity.getType().getNonReferenceType());
8461 bool UseTemporary = Entity.getType()->isReferenceType();
8462 assert(Args.size() == 1 && "expected a single argument for list init");
8463 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8464 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8465 << InitList->getSourceRange();
8466 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8467 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8468 Entity,
8469 Kind, Arg, *Step,
8470 ConstructorInitRequiresZeroInit,
8471 /*IsListInitialization*/true,
8472 /*IsStdInitListInit*/false,
8473 InitList->getLBraceLoc(),
8474 InitList->getRBraceLoc());
8475 break;
8476 }
8477
8478 case SK_UnwrapInitList:
8479 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8480 break;
8481
8482 case SK_RewrapInitList: {
8483 Expr *E = CurInit.get();
8485 InitListExpr *ILE = new (S.Context)
8486 InitListExpr(S.Context, Syntactic->getLBraceLoc(), E,
8487 Syntactic->getRBraceLoc(), Syntactic->isExplicit());
8488 ILE->setSyntacticForm(Syntactic);
8489 ILE->setType(E->getType());
8490 ILE->setValueKind(E->getValueKind());
8491 CurInit = ILE;
8492 break;
8493 }
8494
8497 if (checkAbstractType(Step->Type))
8498 return ExprError();
8499
8500 // When an initializer list is passed for a parameter of type "reference
8501 // to object", we don't get an EK_Temporary entity, but instead an
8502 // EK_Parameter entity with reference type.
8503 // FIXME: This is a hack. What we really should do is create a user
8504 // conversion step for this case, but this makes it considerably more
8505 // complicated. For now, this will do.
8507 Entity.getType().getNonReferenceType());
8508 bool UseTemporary = Entity.getType()->isReferenceType();
8509 bool IsStdInitListInit =
8511 Expr *Source = CurInit.get();
8512 SourceRange Range = Kind.hasParenOrBraceRange()
8513 ? Kind.getParenOrBraceRange()
8514 : SourceRange();
8516 S, UseTemporary ? TempEntity : Entity, Kind,
8517 Source ? MultiExprArg(Source) : Args, *Step,
8518 ConstructorInitRequiresZeroInit,
8519 /*IsListInitialization*/ IsStdInitListInit,
8520 /*IsStdInitListInitialization*/ IsStdInitListInit,
8521 /*LBraceLoc*/ Range.getBegin(),
8522 /*RBraceLoc*/ Range.getEnd());
8523 break;
8524 }
8525
8526 case SK_ZeroInitialization: {
8527 step_iterator NextStep = Step;
8528 ++NextStep;
8529 if (NextStep != StepEnd &&
8530 (NextStep->Kind == SK_ConstructorInitialization ||
8531 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8532 // The need for zero-initialization is recorded directly into
8533 // the call to the object's constructor within the next step.
8534 ConstructorInitRequiresZeroInit = true;
8535 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8536 S.getLangOpts().CPlusPlus &&
8537 !Kind.isImplicitValueInit()) {
8538 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8539 if (!TSInfo)
8541 Kind.getRange().getBegin());
8542
8543 CurInit = new (S.Context) CXXScalarValueInitExpr(
8544 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8545 Kind.getRange().getEnd());
8546 } else {
8547 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8548 // Note the return value isn't used to return a ExprError() when
8549 // initialization fails . For struct initialization allows all field
8550 // assignments to be checked rather than bailing on the first error.
8551 S.BoundsSafetyCheckInitialization(Entity, Kind,
8553 Step->Type, CurInit.get());
8554 }
8555 break;
8556 }
8557
8558 case SK_CAssignment: {
8559 QualType SourceType = CurInit.get()->getType();
8560 Expr *Init = CurInit.get();
8561
8562 // Save off the initial CurInit in case we need to emit a diagnostic
8563 ExprResult InitialCurInit = Init;
8566 Step->Type, Result, true,
8568 if (Result.isInvalid())
8569 return ExprError();
8570 CurInit = Result;
8571
8572 // If this is a call, allow conversion to a transparent union.
8573 ExprResult CurInitExprRes = CurInit;
8574 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8576 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8578 if (CurInitExprRes.isInvalid())
8579 return ExprError();
8580 CurInit = CurInitExprRes;
8581
8582 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8583 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8584 CurInit.get());
8585
8586 // C23 6.7.1p6: If an object or subobject declared with storage-class
8587 // specifier constexpr has pointer, integer, or arithmetic type, any
8588 // explicit initializer value for it shall be null, an integer
8589 // constant expression, or an arithmetic constant expression,
8590 // respectively.
8592 if (Entity.getType()->getAs<PointerType>() &&
8593 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8594 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8595 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8596 return ExprError();
8597 }
8598 }
8599
8600 // Note the return value isn't used to return a ExprError() when
8601 // initialization fails. For struct initialization this allows all field
8602 // assignments to be checked rather than bailing on the first error.
8603 S.BoundsSafetyCheckInitialization(Entity, Kind,
8604 getAssignmentAction(Entity, true),
8605 Step->Type, InitialCurInit.get());
8606
8607 bool Complained;
8608 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8609 Step->Type, SourceType,
8610 InitialCurInit.get(),
8611 getAssignmentAction(Entity, true),
8612 &Complained)) {
8613 PrintInitLocationNote(S, Entity);
8614 return ExprError();
8615 } else if (Complained)
8616 PrintInitLocationNote(S, Entity);
8617 break;
8618 }
8619
8620 case SK_StringInit: {
8621 QualType Ty = Step->Type;
8622 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8623 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8624 S.Context.getAsArrayType(Ty), S, Entity,
8625 S.getLangOpts().C23 &&
8627 break;
8628 }
8629
8631 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8632 CK_ObjCObjectLValueCast,
8633 CurInit.get()->getValueKind());
8634 break;
8635
8636 case SK_ArrayLoopIndex: {
8637 Expr *Cur = CurInit.get();
8638 Expr *BaseExpr = new (S.Context)
8639 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8640 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8641 Expr *IndexExpr =
8644 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8645 ArrayLoopCommonExprs.push_back(BaseExpr);
8646 break;
8647 }
8648
8649 case SK_ArrayLoopInit: {
8650 assert(!ArrayLoopCommonExprs.empty() &&
8651 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8652 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8653 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8654 CurInit.get());
8655 break;
8656 }
8657
8658 case SK_GNUArrayInit:
8659 // Okay: we checked everything before creating this step. Note that
8660 // this is a GNU extension.
8661 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8662 << Step->Type << CurInit.get()->getType()
8663 << CurInit.get()->getSourceRange();
8665 [[fallthrough]];
8666 case SK_ArrayInit:
8667 // If the destination type is an incomplete array type, update the
8668 // type accordingly.
8669 if (ResultType) {
8670 if (const IncompleteArrayType *IncompleteDest
8672 if (const ConstantArrayType *ConstantSource
8673 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8674 *ResultType = S.Context.getConstantArrayType(
8675 IncompleteDest->getElementType(), ConstantSource->getSize(),
8676 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8677 }
8678 }
8679 }
8680 break;
8681
8683 // Okay: we checked everything before creating this step. Note that
8684 // this is a GNU extension.
8685 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8686 << CurInit.get()->getSourceRange();
8687 break;
8688
8691 checkIndirectCopyRestoreSource(S, CurInit.get());
8692 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8693 CurInit.get(), Step->Type,
8695 break;
8696
8698 CurInit = ImplicitCastExpr::Create(
8699 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8701 break;
8702
8703 case SK_StdInitializerList: {
8704 S.Diag(CurInit.get()->getExprLoc(),
8705 diag::warn_cxx98_compat_initializer_list_init)
8706 << CurInit.get()->getSourceRange();
8707
8708 // Materialize the temporary into memory.
8710 CurInit.get()->getType(), CurInit.get(),
8711 /*BoundToLvalueReference=*/false);
8712
8713 // Wrap it in a construction of a std::initializer_list<T>.
8714 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8715
8716 if (!Step->Type->isDependentType()) {
8717 QualType ElementType;
8718 [[maybe_unused]] bool IsStdInitializerList =
8719 S.isStdInitializerList(Step->Type, &ElementType);
8720 assert(IsStdInitializerList &&
8721 "StdInitializerList step to non-std::initializer_list");
8722 const auto *Record = Step->Type->castAsCXXRecordDecl();
8723 assert(Record->isCompleteDefinition() &&
8724 "std::initializer_list should have already be "
8725 "complete/instantiated by this point");
8726
8727 auto InvalidType = [&] {
8728 S.Diag(Record->getLocation(),
8729 diag::err_std_initializer_list_malformed)
8731 return ExprError();
8732 };
8733
8734 if (Record->isUnion() || Record->getNumBases() != 0 ||
8735 Record->isPolymorphic())
8736 return InvalidType();
8737
8738 RecordDecl::field_iterator Field = Record->field_begin();
8739 if (Field == Record->field_end())
8740 return InvalidType();
8741
8742 // Start pointer
8743 if (!Field->getType()->isPointerType() ||
8744 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8745 ElementType.withConst()))
8746 return InvalidType();
8747
8748 if (++Field == Record->field_end())
8749 return InvalidType();
8750
8751 // Size or end pointer
8752 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8753 if (!S.Context.hasSameType(PT->getPointeeType(),
8754 ElementType.withConst()))
8755 return InvalidType();
8756 } else {
8757 if (Field->isBitField() ||
8758 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8759 return InvalidType();
8760 }
8761
8762 if (++Field != Record->field_end())
8763 return InvalidType();
8764 }
8765
8766 // Bind the result, in case the library has given initializer_list a
8767 // non-trivial destructor.
8768 if (shouldBindAsTemporary(Entity))
8769 CurInit = S.MaybeBindToTemporary(CurInit.get());
8770 break;
8771 }
8772
8773 case SK_OCLSamplerInit: {
8774 // Sampler initialization have 5 cases:
8775 // 1. function argument passing
8776 // 1a. argument is a file-scope variable
8777 // 1b. argument is a function-scope variable
8778 // 1c. argument is one of caller function's parameters
8779 // 2. variable initialization
8780 // 2a. initializing a file-scope variable
8781 // 2b. initializing a function-scope variable
8782 //
8783 // For file-scope variables, since they cannot be initialized by function
8784 // call of __translate_sampler_initializer in LLVM IR, their references
8785 // need to be replaced by a cast from their literal initializers to
8786 // sampler type. Since sampler variables can only be used in function
8787 // calls as arguments, we only need to replace them when handling the
8788 // argument passing.
8789 assert(Step->Type->isSamplerT() &&
8790 "Sampler initialization on non-sampler type.");
8791 Expr *Init = CurInit.get()->IgnoreParens();
8792 QualType SourceType = Init->getType();
8793 // Case 1
8794 if (Entity.isParameterKind()) {
8795 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8796 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8797 << SourceType;
8798 break;
8799 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8800 auto Var = cast<VarDecl>(DRE->getDecl());
8801 // Case 1b and 1c
8802 // No cast from integer to sampler is needed.
8803 if (!Var->hasGlobalStorage()) {
8804 CurInit = ImplicitCastExpr::Create(
8805 S.Context, Step->Type, CK_LValueToRValue, Init,
8806 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8807 break;
8808 }
8809 // Case 1a
8810 // For function call with a file-scope sampler variable as argument,
8811 // get the integer literal.
8812 // Do not diagnose if the file-scope variable does not have initializer
8813 // since this has already been diagnosed when parsing the variable
8814 // declaration.
8815 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8816 break;
8817 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8818 Var->getInit()))->getSubExpr();
8819 SourceType = Init->getType();
8820 }
8821 } else {
8822 // Case 2
8823 // Check initializer is 32 bit integer constant.
8824 // If the initializer is taken from global variable, do not diagnose since
8825 // this has already been done when parsing the variable declaration.
8826 if (!Init->isConstantInitializer(S.Context))
8827 break;
8828
8829 if (!SourceType->isIntegerType() ||
8830 32 != S.Context.getIntWidth(SourceType)) {
8831 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8832 << SourceType;
8833 break;
8834 }
8835
8836 Expr::EvalResult EVResult;
8837 Init->EvaluateAsInt(EVResult, S.Context);
8838 llvm::APSInt Result = EVResult.Val.getInt();
8839 const uint64_t SamplerValue = Result.getLimitedValue();
8840 // 32-bit value of sampler's initializer is interpreted as
8841 // bit-field with the following structure:
8842 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8843 // |31 6|5 4|3 1| 0|
8844 // This structure corresponds to enum values of sampler properties
8845 // defined in SPIR spec v1.2 and also opencl-c.h
8846 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8847 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8848 if (FilterMode != 1 && FilterMode != 2 &&
8850 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8851 S.Diag(Kind.getLocation(),
8852 diag::warn_sampler_initializer_invalid_bits)
8853 << "Filter Mode";
8854 if (AddressingMode > 4)
8855 S.Diag(Kind.getLocation(),
8856 diag::warn_sampler_initializer_invalid_bits)
8857 << "Addressing Mode";
8858 }
8859
8860 // Cases 1a, 2a and 2b
8861 // Insert cast from integer to sampler.
8863 CK_IntToOCLSampler);
8864 break;
8865 }
8866 case SK_OCLZeroOpaqueType: {
8867 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8869 "Wrong type for initialization of OpenCL opaque type.");
8870
8871 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8872 CK_ZeroToOCLOpaqueType,
8873 CurInit.get()->getValueKind());
8874 break;
8875 }
8877 CurInit = nullptr;
8878 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8879 /*VerifyOnly=*/false, &CurInit);
8880 if (CurInit.get() && ResultType)
8881 *ResultType = CurInit.get()->getType();
8882 if (shouldBindAsTemporary(Entity))
8883 CurInit = S.MaybeBindToTemporary(CurInit.get());
8884 break;
8885 }
8887 CurInit = ImplicitCastExpr::Create(
8888 S.Context, Step->Type.getLocalUnqualifiedType(), CK_LValueToRValue,
8889 CurInit.get(),
8890 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8891 break;
8892 }
8893 }
8894 }
8895
8896 Expr *Init = CurInit.get();
8897 if (!Init)
8898 return ExprError();
8899
8900 // Check whether the initializer has a shorter lifetime than the initialized
8901 // entity, and if not, either lifetime-extend or warn as appropriate.
8902 S.checkInitializerLifetime(Entity, Init);
8903
8904 // Diagnose non-fatal problems with the completed initialization.
8905 if (InitializedEntity::EntityKind EK = Entity.getKind();
8908 cast<FieldDecl>(Entity.getDecl())->isBitField())
8909 S.CheckBitFieldInitialization(Kind.getLocation(),
8910 cast<FieldDecl>(Entity.getDecl()), Init);
8911
8912 // Check for std::move on construction.
8915
8916 return Init;
8917}
8918
8919/// Somewhere within T there is an uninitialized reference subobject.
8920/// Dig it out and diagnose it.
8922 QualType T) {
8923 if (T->isReferenceType()) {
8924 S.Diag(Loc, diag::err_reference_without_init)
8925 << T.getNonReferenceType();
8926 return true;
8927 }
8928
8929 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8930 if (!RD || !RD->hasUninitializedReferenceMember())
8931 return false;
8932
8933 for (const auto *FI : RD->fields()) {
8934 if (FI->isUnnamedBitField())
8935 continue;
8936
8937 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8938 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8939 return true;
8940 }
8941 }
8942
8943 for (const auto &BI : RD->bases()) {
8944 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8945 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8946 return true;
8947 }
8948 }
8949
8950 return false;
8951}
8952
8953
8954//===----------------------------------------------------------------------===//
8955// Diagnose initialization failures
8956//===----------------------------------------------------------------------===//
8957
8958/// Emit notes associated with an initialization that failed due to a
8959/// "simple" conversion failure.
8960static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8961 Expr *op) {
8962 QualType destType = entity.getType();
8963 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8965
8966 // Emit a possible note about the conversion failing because the
8967 // operand is a message send with a related result type.
8969
8970 // Emit a possible note about a return failing because we're
8971 // expecting a related result type.
8972 if (entity.getKind() == InitializedEntity::EK_Result)
8974 }
8975 QualType fromType = op->getType();
8976 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8977 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8978 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8979 auto *destDecl = destType->getPointeeCXXRecordDecl();
8980 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8981 destDecl->getDeclKind() == Decl::CXXRecord &&
8982 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8983 !fromDecl->hasDefinition() &&
8984 destPointeeType.getQualifiers().compatiblyIncludes(
8985 fromPointeeType.getQualifiers(), S.getASTContext()))
8986 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8987 << S.getASTContext().getCanonicalTagType(fromDecl)
8988 << S.getASTContext().getCanonicalTagType(destDecl);
8989}
8990
8991static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8992 InitListExpr *InitList) {
8993 QualType DestType = Entity.getType();
8994
8995 QualType E;
8996 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8998 E.withConst(),
8999 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9000 InitList->getNumInits()),
9002 InitializedEntity HiddenArray =
9004 return diagnoseListInit(S, HiddenArray, InitList);
9005 }
9006
9007 if (DestType->isReferenceType()) {
9008 // A list-initialization failure for a reference means that we tried to
9009 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9010 // inner initialization failed.
9011 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9013 SourceLocation Loc = InitList->getBeginLoc();
9014 if (auto *D = Entity.getDecl())
9015 Loc = D->getLocation();
9016 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9017 return;
9018 }
9019
9020 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9021 /*VerifyOnly=*/false,
9022 /*TreatUnavailableAsInvalid=*/false);
9023 assert(DiagnoseInitList.HadError() &&
9024 "Inconsistent init list check result.");
9025}
9026
9028 const InitializedEntity &Entity,
9029 const InitializationKind &Kind,
9030 ArrayRef<Expr *> Args) {
9031 if (!Failed())
9032 return false;
9033
9034 QualType DestType = Entity.getType();
9035
9036 // When we want to diagnose only one element of a braced-init-list,
9037 // we need to factor it out.
9038 Expr *OnlyArg;
9039 if (Args.size() == 1) {
9040 auto *List = dyn_cast<InitListExpr>(Args[0]);
9041 if (List && List->getNumInits() == 1)
9042 OnlyArg = List->getInit(0);
9043 else
9044 OnlyArg = Args[0];
9045
9046 if (OnlyArg->getType() == S.Context.OverloadTy) {
9049 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9050 Found)) {
9051 if (Expr *Resolved =
9052 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9053 OnlyArg = Resolved;
9054 }
9055 }
9056 }
9057 else
9058 OnlyArg = nullptr;
9059
9060 switch (Failure) {
9062 // FIXME: Customize for the initialized entity?
9063 if (Args.empty()) {
9064 // Dig out the reference subobject which is uninitialized and diagnose it.
9065 // If this is value-initialization, this could be nested some way within
9066 // the target type.
9067 assert(Kind.getKind() == InitializationKind::IK_Value ||
9068 DestType->isReferenceType());
9069 bool Diagnosed =
9070 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9071 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9072 (void)Diagnosed;
9073 } else // FIXME: diagnostic below could be better!
9074 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9075 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9076 break;
9078 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9079 << 1 << Entity.getType() << Args[0]->getSourceRange();
9080 break;
9081
9083 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9084 break;
9086 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9087 break;
9089 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9090 break;
9092 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9093 break;
9095 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9096 break;
9098 S.Diag(Kind.getLocation(),
9099 diag::err_array_init_incompat_wide_string_into_wchar);
9100 break;
9102 S.Diag(Kind.getLocation(),
9103 diag::err_array_init_plain_string_into_char8_t);
9104 S.Diag(Args.front()->getBeginLoc(),
9105 diag::note_array_init_plain_string_into_char8_t)
9106 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9107 break;
9109 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9110 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9111 break;
9114 S.Diag(Kind.getLocation(),
9115 (Failure == FK_ArrayTypeMismatch
9116 ? diag::err_array_init_different_type
9117 : diag::err_array_init_non_constant_array))
9118 << DestType.getNonReferenceType()
9119 << OnlyArg->getType()
9120 << Args[0]->getSourceRange();
9121 break;
9122
9124 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9125 << Args[0]->getSourceRange();
9126 break;
9127
9131 DestType.getNonReferenceType(),
9132 true,
9133 Found);
9134 break;
9135 }
9136
9138 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9139 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9140 OnlyArg->getBeginLoc());
9141 break;
9142 }
9143
9146 switch (FailedOverloadResult) {
9147 case OR_Ambiguous:
9148
9149 FailedCandidateSet.NoteCandidates(
9151 Kind.getLocation(),
9153 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9154 << OnlyArg->getType() << DestType
9155 << Args[0]->getSourceRange())
9156 : (S.PDiag(diag::err_ref_init_ambiguous)
9157 << DestType << OnlyArg->getType()
9158 << Args[0]->getSourceRange())),
9159 S, OCD_AmbiguousCandidates, Args);
9160 break;
9161
9162 case OR_No_Viable_Function: {
9163 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9164 if (!S.RequireCompleteType(Kind.getLocation(),
9165 DestType.getNonReferenceType(),
9166 diag::err_typecheck_nonviable_condition_incomplete,
9167 OnlyArg->getType(), Args[0]->getSourceRange()))
9168 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9169 << (Entity.getKind() == InitializedEntity::EK_Result)
9170 << OnlyArg->getType() << Args[0]->getSourceRange()
9171 << DestType.getNonReferenceType();
9172
9173 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9174 break;
9175 }
9176 case OR_Deleted: {
9179 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9180
9181 StringLiteral *Msg = Best->Function->getDeletedMessage();
9182 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9183 << OnlyArg->getType() << DestType.getNonReferenceType()
9184 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9185 << Args[0]->getSourceRange();
9186 if (Ovl == OR_Deleted) {
9187 S.NoteDeletedFunction(Best->Function);
9188 } else {
9189 llvm_unreachable("Inconsistent overload resolution?");
9190 }
9191 break;
9192 }
9193
9194 case OR_Success:
9195 llvm_unreachable("Conversion did not fail!");
9196 }
9197 break;
9198
9200 if (isa<InitListExpr>(Args[0])) {
9201 S.Diag(Kind.getLocation(),
9202 diag::err_lvalue_reference_bind_to_initlist)
9204 << DestType.getNonReferenceType()
9205 << Args[0]->getSourceRange();
9206 break;
9207 }
9208 [[fallthrough]];
9209
9211 S.Diag(Kind.getLocation(),
9213 ? diag::err_lvalue_reference_bind_to_temporary
9214 : diag::err_lvalue_reference_bind_to_unrelated)
9216 << DestType.getNonReferenceType()
9217 << OnlyArg->getType()
9218 << Args[0]->getSourceRange();
9219 break;
9220
9222 // We don't necessarily have an unambiguous source bit-field.
9223 FieldDecl *BitField = Args[0]->getSourceBitField();
9224 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9225 << DestType.isVolatileQualified()
9226 << (BitField ? BitField->getDeclName() : DeclarationName())
9227 << (BitField != nullptr)
9228 << Args[0]->getSourceRange();
9229 if (BitField)
9230 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9231 break;
9232 }
9233
9235 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9236 << DestType.isVolatileQualified()
9237 << Args[0]->getSourceRange();
9238 break;
9239
9241 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9242 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9243 break;
9244
9246 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9247 << DestType.getNonReferenceType() << OnlyArg->getType()
9248 << Args[0]->getSourceRange();
9249 break;
9250
9252 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9253 << DestType << Args[0]->getSourceRange();
9254 break;
9255
9257 QualType SourceType = OnlyArg->getType();
9258 QualType NonRefType = DestType.getNonReferenceType();
9259 Qualifiers DroppedQualifiers =
9260 SourceType.getQualifiers() - NonRefType.getQualifiers();
9261
9262 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9263 SourceType.getQualifiers(), S.getASTContext()))
9264 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9265 << NonRefType << SourceType << 1 /*addr space*/
9266 << Args[0]->getSourceRange();
9267 else if (DroppedQualifiers.hasQualifiers())
9268 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9269 << NonRefType << SourceType << 0 /*cv quals*/
9270 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9271 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9272 else
9273 // FIXME: Consider decomposing the type and explaining which qualifiers
9274 // were dropped where, or on which level a 'const' is missing, etc.
9275 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9276 << NonRefType << SourceType << 2 /*incompatible quals*/
9277 << Args[0]->getSourceRange();
9278 break;
9279 }
9280
9282 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9283 << DestType.getNonReferenceType()
9284 << DestType.getNonReferenceType()->isIncompleteType()
9285 << OnlyArg->isLValue()
9286 << OnlyArg->getType()
9287 << Args[0]->getSourceRange();
9288 emitBadConversionNotes(S, Entity, Args[0]);
9289 break;
9290
9291 case FK_ConversionFailed: {
9292 QualType FromType = OnlyArg->getType();
9293 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9294 // type, although this is almost always an error and we advise against it.
9295 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9296 DestType == S.Context.getLogicalOperationType()) {
9297 S.Diag(OnlyArg->getExprLoc(),
9298 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9299 << OnlyArg << DestType;
9300 break;
9301 }
9302 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9303 << (int)Entity.getKind()
9304 << DestType
9305 << OnlyArg->isLValue()
9306 << FromType
9307 << Args[0]->getSourceRange();
9308 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9309 S.Diag(Kind.getLocation(), PDiag);
9310 emitBadConversionNotes(S, Entity, Args[0]);
9311 break;
9312 }
9313
9315 // No-op. This error has already been reported.
9316 break;
9317
9319 SourceRange R;
9320
9321 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9322 if (InitList && InitList->getNumInits() >= 1) {
9323 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9324 } else {
9325 assert(Args.size() > 1 && "Expected multiple initializers!");
9326 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9327 }
9328
9329 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9330 if (Kind.isCStyleOrFunctionalCast())
9331 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9332 << R;
9333 else
9334 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9335 << /*scalar=*/3 << R;
9336 break;
9337 }
9338
9340 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9341 << 0 << Entity.getType() << Args[0]->getSourceRange();
9342 break;
9343
9345 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9346 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9347 break;
9348
9350 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9351 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9352 break;
9353
9356 SourceRange ArgsRange;
9357 if (Args.size())
9358 ArgsRange =
9359 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9360
9361 if (Failure == FK_ListConstructorOverloadFailed) {
9362 assert(Args.size() == 1 &&
9363 "List construction from other than 1 argument.");
9364 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9365 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9366 }
9367
9368 // FIXME: Using "DestType" for the entity we're printing is probably
9369 // bad.
9370 switch (FailedOverloadResult) {
9371 case OR_Ambiguous:
9372 FailedCandidateSet.NoteCandidates(
9373 PartialDiagnosticAt(Kind.getLocation(),
9374 S.PDiag(diag::err_ovl_ambiguous_init)
9375 << DestType << ArgsRange),
9376 S, OCD_AmbiguousCandidates, Args);
9377 break;
9378
9380 if (Kind.getKind() == InitializationKind::IK_Default &&
9381 (Entity.getKind() == InitializedEntity::EK_Base ||
9385 // This is implicit default initialization of a member or
9386 // base within a constructor. If no viable function was
9387 // found, notify the user that they need to explicitly
9388 // initialize this base/member.
9391 const CXXRecordDecl *InheritedFrom = nullptr;
9392 if (auto Inherited = Constructor->getInheritedConstructor())
9393 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9394 if (Entity.getKind() == InitializedEntity::EK_Base) {
9395 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9396 << (InheritedFrom ? 2
9397 : Constructor->isImplicit() ? 1
9398 : 0)
9399 << S.Context.getCanonicalTagType(Constructor->getParent())
9400 << /*base=*/0 << Entity.getType() << InheritedFrom;
9401
9402 auto *BaseDecl =
9404 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9405 << S.Context.getCanonicalTagType(BaseDecl);
9406 } else {
9407 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9408 << (InheritedFrom ? 2
9409 : Constructor->isImplicit() ? 1
9410 : 0)
9411 << S.Context.getCanonicalTagType(Constructor->getParent())
9412 << /*member=*/1 << Entity.getName() << InheritedFrom;
9413 S.Diag(Entity.getDecl()->getLocation(),
9414 diag::note_member_declared_at);
9415
9416 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9417 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9418 << S.Context.getCanonicalTagType(Record->getDecl());
9419 }
9420 break;
9421 }
9422
9423 FailedCandidateSet.NoteCandidates(
9425 Kind.getLocation(),
9426 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9427 << DestType << ArgsRange),
9428 S, OCD_AllCandidates, Args);
9429 break;
9430
9431 case OR_Deleted: {
9434 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9435 if (Ovl != OR_Deleted) {
9436 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9437 << DestType << ArgsRange;
9438 llvm_unreachable("Inconsistent overload resolution?");
9439 break;
9440 }
9441
9442 // If this is a defaulted or implicitly-declared function, then
9443 // it was implicitly deleted. Make it clear that the deletion was
9444 // implicit.
9445 if (S.isImplicitlyDeleted(Best->Function))
9446 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9447 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9448 << DestType << ArgsRange;
9449 else {
9450 StringLiteral *Msg = Best->Function->getDeletedMessage();
9451 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9452 << DestType << (Msg != nullptr)
9453 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9454 }
9455
9456 // If it's a default constructed member, but it's not in the
9457 // constructor's initializer list, explicitly note where the member is
9458 // declared so the user can see which member is erroneously initialized
9459 // with a deleted default constructor.
9460 if (Kind.getKind() == InitializationKind::IK_Default &&
9463 S.Diag(Entity.getDecl()->getLocation(),
9464 diag::note_default_constructed_field)
9465 << Entity.getDecl();
9466 }
9467 S.NoteDeletedFunction(Best->Function);
9468 break;
9469 }
9470
9471 case OR_Success:
9472 llvm_unreachable("Conversion did not fail!");
9473 }
9474 }
9475 break;
9476
9478 if (Entity.getKind() == InitializedEntity::EK_Member &&
9480 // This is implicit default-initialization of a const member in
9481 // a constructor. Complain that it needs to be explicitly
9482 // initialized.
9484 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9485 << (Constructor->getInheritedConstructor() ? 2
9486 : Constructor->isImplicit() ? 1
9487 : 0)
9488 << S.Context.getCanonicalTagType(Constructor->getParent())
9489 << /*const=*/1 << Entity.getName();
9490 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9491 << Entity.getName();
9492 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9493 VD && VD->isConstexpr()) {
9494 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9495 << VD;
9496 } else {
9497 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9498 << DestType << DestType->isRecordType();
9499 }
9500 break;
9501
9502 case FK_Incomplete:
9503 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9504 diag::err_init_incomplete_type);
9505 break;
9506
9508 // Run the init list checker again to emit diagnostics.
9509 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9510 diagnoseListInit(S, Entity, InitList);
9511 break;
9512 }
9513
9514 case FK_PlaceholderType: {
9515 // FIXME: Already diagnosed!
9516 break;
9517 }
9518
9520 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9521 // allows us to diagnose the failure when it happens in the
9522 // TryListInitialization call instead of delaying the diagnosis, which is
9523 // beneficial because the flattening is also expensive.
9524 break;
9525 }
9526
9528 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9529 << Args[0]->getSourceRange();
9532 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9533 (void)Ovl;
9534 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9535 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9536 S.Diag(CtorDecl->getLocation(),
9537 diag::note_explicit_ctor_deduction_guide_here) << false;
9538 break;
9539 }
9540
9542 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9543 /*VerifyOnly=*/false);
9544 break;
9545
9547 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9548 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9549 << Entity.getType() << InitList->getSourceRange();
9550 break;
9551 }
9552
9553 PrintInitLocationNote(S, Entity);
9554 return true;
9555}
9556
9557void InitializationSequence::dump(raw_ostream &OS) const {
9558 switch (SequenceKind) {
9559 case FailedSequence: {
9560 OS << "Failed sequence: ";
9561 switch (Failure) {
9563 OS << "too many initializers for reference";
9564 break;
9565
9567 OS << "parenthesized list init for reference";
9568 break;
9569
9571 OS << "array requires initializer list";
9572 break;
9573
9575 OS << "address of unaddressable function was taken";
9576 break;
9577
9579 OS << "array requires initializer list or string literal";
9580 break;
9581
9583 OS << "array requires initializer list or wide string literal";
9584 break;
9585
9587 OS << "narrow string into wide char array";
9588 break;
9589
9591 OS << "wide string into char array";
9592 break;
9593
9595 OS << "incompatible wide string into wide char array";
9596 break;
9597
9599 OS << "plain string literal into char8_t array";
9600 break;
9601
9603 OS << "u8 string literal into char array";
9604 break;
9605
9607 OS << "array type mismatch";
9608 break;
9609
9611 OS << "non-constant array initializer";
9612 break;
9613
9615 OS << "address of overloaded function failed";
9616 break;
9617
9619 OS << "overload resolution for reference initialization failed";
9620 break;
9621
9623 OS << "non-const lvalue reference bound to temporary";
9624 break;
9625
9627 OS << "non-const lvalue reference bound to bit-field";
9628 break;
9629
9631 OS << "non-const lvalue reference bound to vector element";
9632 break;
9633
9635 OS << "non-const lvalue reference bound to matrix element";
9636 break;
9637
9639 OS << "non-const lvalue reference bound to unrelated type";
9640 break;
9641
9643 OS << "rvalue reference bound to an lvalue";
9644 break;
9645
9647 OS << "reference initialization drops qualifiers";
9648 break;
9649
9651 OS << "reference with mismatching address space bound to temporary";
9652 break;
9653
9655 OS << "reference initialization failed";
9656 break;
9657
9659 OS << "conversion failed";
9660 break;
9661
9663 OS << "conversion from property failed";
9664 break;
9665
9667 OS << "too many initializers for scalar";
9668 break;
9669
9671 OS << "parenthesized list init for reference";
9672 break;
9673
9675 OS << "referencing binding to initializer list";
9676 break;
9677
9679 OS << "initializer list for non-aggregate, non-scalar type";
9680 break;
9681
9683 OS << "overloading failed for user-defined conversion";
9684 break;
9685
9687 OS << "constructor overloading failed";
9688 break;
9689
9691 OS << "default initialization of a const variable";
9692 break;
9693
9694 case FK_Incomplete:
9695 OS << "initialization of incomplete type";
9696 break;
9697
9699 OS << "list initialization checker failure";
9700 break;
9701
9703 OS << "variable length array has an initializer";
9704 break;
9705
9706 case FK_PlaceholderType:
9707 OS << "initializer expression isn't contextually valid";
9708 break;
9709
9711 OS << "list constructor overloading failed";
9712 break;
9713
9715 OS << "list copy initialization chose explicit constructor";
9716 break;
9717
9719 OS << "parenthesized list initialization failed";
9720 break;
9721
9723 OS << "designated initializer for non-aggregate type";
9724 break;
9725
9727 OS << "HLSL initialization list flattening failed";
9728 break;
9729 }
9730 OS << '\n';
9731 return;
9732 }
9733
9734 case DependentSequence:
9735 OS << "Dependent sequence\n";
9736 return;
9737
9738 case NormalSequence:
9739 OS << "Normal sequence: ";
9740 break;
9741 }
9742
9743 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9744 if (S != step_begin()) {
9745 OS << " -> ";
9746 }
9747
9748 switch (S->Kind) {
9750 OS << "resolve address of overloaded function";
9751 break;
9752
9754 OS << "derived-to-base (prvalue)";
9755 break;
9756
9758 OS << "derived-to-base (xvalue)";
9759 break;
9760
9762 OS << "derived-to-base (lvalue)";
9763 break;
9764
9765 case SK_BindReference:
9766 OS << "bind reference to lvalue";
9767 break;
9768
9770 OS << "bind reference to a temporary";
9771 break;
9772
9773 case SK_FinalCopy:
9774 OS << "final copy in class direct-initialization";
9775 break;
9776
9778 OS << "extraneous C++03 copy to temporary";
9779 break;
9780
9781 case SK_UserConversion:
9782 OS << "user-defined conversion via " << *S->Function.Function;
9783 break;
9784
9786 OS << "qualification conversion (prvalue)";
9787 break;
9788
9790 OS << "qualification conversion (xvalue)";
9791 break;
9792
9794 OS << "qualification conversion (lvalue)";
9795 break;
9796
9798 OS << "function reference conversion";
9799 break;
9800
9802 OS << "non-atomic-to-atomic conversion";
9803 break;
9804
9806 OS << "implicit conversion sequence (";
9807 S->ICS->dump(); // FIXME: use OS
9808 OS << ")";
9809 break;
9810
9812 OS << "implicit conversion sequence with narrowing prohibited (";
9813 S->ICS->dump(); // FIXME: use OS
9814 OS << ")";
9815 break;
9816
9818 OS << "list aggregate initialization";
9819 break;
9820
9821 case SK_UnwrapInitList:
9822 OS << "unwrap reference initializer list";
9823 break;
9824
9825 case SK_RewrapInitList:
9826 OS << "rewrap reference initializer list";
9827 break;
9828
9830 OS << "constructor initialization";
9831 break;
9832
9834 OS << "list initialization via constructor";
9835 break;
9836
9838 OS << "zero initialization";
9839 break;
9840
9841 case SK_CAssignment:
9842 OS << "C assignment";
9843 break;
9844
9845 case SK_StringInit:
9846 OS << "string initialization";
9847 break;
9848
9850 OS << "Objective-C object conversion";
9851 break;
9852
9853 case SK_ArrayLoopIndex:
9854 OS << "indexing for array initialization loop";
9855 break;
9856
9857 case SK_ArrayLoopInit:
9858 OS << "array initialization loop";
9859 break;
9860
9861 case SK_ArrayInit:
9862 OS << "array initialization";
9863 break;
9864
9865 case SK_GNUArrayInit:
9866 OS << "array initialization (GNU extension)";
9867 break;
9868
9870 OS << "parenthesized array initialization";
9871 break;
9872
9874 OS << "pass by indirect copy and restore";
9875 break;
9876
9878 OS << "pass by indirect restore";
9879 break;
9880
9882 OS << "Objective-C object retension";
9883 break;
9884
9886 OS << "std::initializer_list from initializer list";
9887 break;
9888
9890 OS << "list initialization from std::initializer_list";
9891 break;
9892
9893 case SK_OCLSamplerInit:
9894 OS << "OpenCL sampler_t from integer constant";
9895 break;
9896
9898 OS << "OpenCL opaque type from zero";
9899 break;
9900
9902 OS << "initialization from a parenthesized list of values";
9903 break;
9904
9906 OS << "HLSL buffer conversion";
9907 break;
9908 }
9909
9910 OS << " [" << S->Type << ']';
9911 }
9912
9913 OS << '\n';
9914}
9915
9917 dump(llvm::errs());
9918}
9919
9921 const ImplicitConversionSequence &ICS,
9922 QualType PreNarrowingType,
9923 QualType EntityType,
9924 const Expr *PostInit) {
9925 const StandardConversionSequence *SCS = nullptr;
9926 switch (ICS.getKind()) {
9928 SCS = &ICS.Standard;
9929 break;
9931 SCS = &ICS.UserDefined.After;
9932 break;
9937 return;
9938 }
9939
9940 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9941 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9942 unsigned DiagID;
9943 auto &L = S.getLangOpts();
9944 if (L.CPlusPlus11 && !L.HLSL &&
9945 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9946 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9947 else
9948 DiagID = WarnDiagID;
9949 return S.Diag(PostInit->getBeginLoc(), DiagID)
9950 << PostInit->getSourceRange();
9951 };
9952
9953 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9954 APValue ConstantValue;
9955 QualType ConstantType;
9956 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9957 ConstantType)) {
9958 case NK_Not_Narrowing:
9960 // No narrowing occurred.
9961 return;
9962
9963 case NK_Type_Narrowing: {
9964 // This was a floating-to-integer conversion, which is always considered a
9965 // narrowing conversion even if the value is a constant and can be
9966 // represented exactly as an integer.
9967 QualType T = EntityType.getNonReferenceType();
9968 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9969 diag::ext_init_list_type_narrowing_const_reference,
9970 diag::warn_init_list_type_narrowing)
9971 << PreNarrowingType.getLocalUnqualifiedType()
9973 break;
9974 }
9975
9976 case NK_Constant_Narrowing: {
9977 // A constant value was narrowed.
9978 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9979 diag::ext_init_list_constant_narrowing,
9980 diag::ext_init_list_constant_narrowing_const_reference,
9981 diag::warn_init_list_constant_narrowing)
9982 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9984 break;
9985 }
9986
9987 case NK_Variable_Narrowing: {
9988 // A variable's value may have been narrowed.
9989 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9990 diag::ext_init_list_variable_narrowing,
9991 diag::ext_init_list_variable_narrowing_const_reference,
9992 diag::warn_init_list_variable_narrowing)
9993 << PreNarrowingType.getLocalUnqualifiedType()
9995 break;
9996 }
9997 }
9998
9999 SmallString<128> StaticCast;
10000 llvm::raw_svector_ostream OS(StaticCast);
10001 OS << "static_cast<";
10002 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10003 // It's important to use the typedef's name if there is one so that the
10004 // fixit doesn't break code using types like int64_t.
10005 //
10006 // FIXME: This will break if the typedef requires qualification. But
10007 // getQualifiedNameAsString() includes non-machine-parsable components.
10008 OS << *TT->getDecl();
10009 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10010 OS << BT->getName(S.getLangOpts());
10011 else {
10012 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10013 // with a broken cast.
10014 return;
10015 }
10016 OS << ">(";
10017 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10018 << PostInit->getSourceRange()
10019 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10021 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10022}
10023
10025 QualType ToType, Expr *Init) {
10026 assert(S.getLangOpts().C23);
10028 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10029 Sema::AllowedExplicit::None,
10030 /*InOverloadResolution*/ false,
10031 /*CStyle*/ false,
10032 /*AllowObjCWritebackConversion=*/false);
10033
10034 if (!ICS.isStandard())
10035 return;
10036
10037 APValue Value;
10038 QualType PreNarrowingType;
10039 // Reuse C++ narrowing check.
10040 switch (ICS.Standard.getNarrowingKind(
10041 S.Context, Init, Value, PreNarrowingType,
10042 /*IgnoreFloatToIntegralConversion*/ false)) {
10043 // The value doesn't fit.
10045 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10046 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10047 return;
10048
10049 // Conversion to a narrower type.
10050 case NK_Type_Narrowing:
10051 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10052 << ToType << FromType;
10053 return;
10054
10055 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10056 // not really interested in these cases.
10059 case NK_Not_Narrowing:
10060 return;
10061 }
10062 llvm_unreachable("unhandled case in switch");
10063}
10064
10066 Sema &SemaRef, QualType &TT) {
10067 assert(SemaRef.getLangOpts().C23);
10068 // character that string literal contains fits into TT - target type.
10069 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10070 QualType CharType = AT->getElementType();
10071 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10072 bool isUnsigned = CharType->isUnsignedIntegerType();
10073 llvm::APSInt Value(BitWidth, isUnsigned);
10074 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10075 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10076 Value = C;
10077 if (Value != C) {
10078 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10079 diag::err_c23_constexpr_init_not_representable)
10080 << C << CharType;
10081 return;
10082 }
10083 }
10084}
10085
10086//===----------------------------------------------------------------------===//
10087// Initialization helper functions
10088//===----------------------------------------------------------------------===//
10089bool
10091 ExprResult Init) {
10092 if (Init.isInvalid())
10093 return false;
10094
10095 Expr *InitE = Init.get();
10096 assert(InitE && "No initialization expression");
10097
10098 InitializationKind Kind =
10100 InitializationSequence Seq(*this, Entity, Kind, InitE);
10101 return !Seq.Failed();
10102}
10103
10106 SourceLocation EqualLoc,
10108 bool TopLevelOfInitList,
10109 bool AllowExplicit) {
10110 if (Init.isInvalid())
10111 return ExprError();
10112
10113 Expr *InitE = Init.get();
10114 assert(InitE && "No initialization expression?");
10115
10116 if (EqualLoc.isInvalid())
10117 EqualLoc = InitE->getBeginLoc();
10118
10119 if (Entity.getType().getDesugaredType(Context) ==
10120 Context.AMDGPUFeaturePredicateTy &&
10121 Entity.getDecl()) {
10122 Diag(EqualLoc, diag::err_amdgcn_predicate_type_is_not_constructible)
10123 << Entity.getDecl();
10124 return ExprError();
10125 }
10126
10128 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10129 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10130
10131 // Prevent infinite recursion when performing parameter copy-initialization.
10132 const bool ShouldTrackCopy =
10133 Entity.isParameterKind() && Seq.isConstructorInitialization();
10134 if (ShouldTrackCopy) {
10135 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10136 Seq.SetOverloadFailure(
10139
10140 // Try to give a meaningful diagnostic note for the problematic
10141 // constructor.
10142 const auto LastStep = Seq.step_end() - 1;
10143 assert(LastStep->Kind ==
10145 const FunctionDecl *Function = LastStep->Function.Function;
10146 auto Candidate =
10147 llvm::find_if(Seq.getFailedCandidateSet(),
10148 [Function](const OverloadCandidate &Candidate) -> bool {
10149 return Candidate.Viable &&
10150 Candidate.Function == Function &&
10151 Candidate.Conversions.size() > 0;
10152 });
10153 if (Candidate != Seq.getFailedCandidateSet().end() &&
10154 Function->getNumParams() > 0) {
10155 Candidate->Viable = false;
10158 InitE,
10159 Function->getParamDecl(0)->getType());
10160 }
10161 }
10162 CurrentParameterCopyTypes.push_back(Entity.getType());
10163 }
10164
10165 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10166
10167 if (ShouldTrackCopy)
10168 CurrentParameterCopyTypes.pop_back();
10169
10170 return Result;
10171}
10172
10173/// Determine whether RD is, or is derived from, a specialization of CTD.
10175 ClassTemplateDecl *CTD) {
10176 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10177 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10178 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10179 };
10180 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10181}
10182
10184 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10185 const InitializationKind &Kind, MultiExprArg Inits) {
10186 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10187 TSInfo->getType()->getContainedDeducedType());
10188 assert(DeducedTST && "not a deduced template specialization type");
10189
10190 auto TemplateName = DeducedTST->getTemplateName();
10192 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10193
10194 // We can only perform deduction for class templates or alias templates.
10195 auto *Template =
10196 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10197 TemplateDecl *LookupTemplateDecl = Template;
10198 if (!Template) {
10199 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10201 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10202 LookupTemplateDecl = AliasTemplate;
10203 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10204 ->getUnderlyingType()
10205 .getCanonicalType();
10206 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10207 // of the form
10208 // [typename] [nested-name-specifier] [template] simple-template-id
10209 if (const auto *TST =
10210 UnderlyingType->getAs<TemplateSpecializationType>()) {
10211 Template = dyn_cast_or_null<ClassTemplateDecl>(
10212 TST->getTemplateName().getAsTemplateDecl());
10213 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10214 // Cases where template arguments in the RHS of the alias are not
10215 // dependent. e.g.
10216 // using AliasFoo = Foo<bool>;
10217 if (const auto *CTSD =
10218 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10219 Template = CTSD->getSpecializedTemplate();
10220 }
10221 }
10222 }
10223 if (!Template) {
10224 Diag(Kind.getLocation(),
10225 diag::err_deduced_non_class_or_alias_template_specialization_type)
10227 if (auto *TD = TemplateName.getAsTemplateDecl())
10229 return QualType();
10230 }
10231
10232 // Can't deduce from dependent arguments.
10234 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10235 diag::warn_cxx14_compat_class_template_argument_deduction)
10236 << TSInfo->getTypeLoc().getSourceRange() << 0;
10237 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10238 }
10239
10240 // FIXME: Perform "exact type" matching first, per CWG discussion?
10241 // Or implement this via an implied 'T(T) -> T' deduction guide?
10242
10243 // Look up deduction guides, including those synthesized from constructors.
10244 //
10245 // C++1z [over.match.class.deduct]p1:
10246 // A set of functions and function templates is formed comprising:
10247 // - For each constructor of the class template designated by the
10248 // template-name, a function template [...]
10249 // - For each deduction-guide, a function or function template [...]
10250 DeclarationNameInfo NameInfo(
10251 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10252 TSInfo->getTypeLoc().getEndLoc());
10253 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10254 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10255
10256 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10257 // clear on this, but they're not found by name so access does not apply.
10258 Guides.suppressDiagnostics();
10259
10260 // Figure out if this is list-initialization.
10262 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10263 ? dyn_cast<InitListExpr>(Inits[0])
10264 : nullptr;
10265
10266 // C++1z [over.match.class.deduct]p1:
10267 // Initialization and overload resolution are performed as described in
10268 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10269 // (as appropriate for the type of initialization performed) for an object
10270 // of a hypothetical class type, where the selected functions and function
10271 // templates are considered to be the constructors of that class type
10272 //
10273 // Since we know we're initializing a class type of a type unrelated to that
10274 // of the initializer, this reduces to something fairly reasonable.
10275 OverloadCandidateSet Candidates(Kind.getLocation(),
10278
10279 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10280
10281 // Return true if the candidate is added successfully, false otherwise.
10282 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10284 DeclAccessPair FoundDecl,
10285 bool OnlyListConstructors,
10286 bool AllowAggregateDeductionCandidate) {
10287 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10288 // For copy-initialization, the candidate functions are all the
10289 // converting constructors (12.3.1) of that class.
10290 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10291 // The converting constructors of T are candidate functions.
10292 if (!AllowExplicit) {
10293 // Overload resolution checks whether the deduction guide is declared
10294 // explicit for us.
10295
10296 // When looking for a converting constructor, deduction guides that
10297 // could never be called with one argument are not interesting to
10298 // check or note.
10299 if (GD->getMinRequiredArguments() > 1 ||
10300 (GD->getNumParams() == 0 && !GD->isVariadic()))
10301 return;
10302 }
10303
10304 // C++ [over.match.list]p1.1: (first phase list initialization)
10305 // Initially, the candidate functions are the initializer-list
10306 // constructors of the class T
10307 if (OnlyListConstructors && !isInitListConstructor(GD))
10308 return;
10309
10310 if (!AllowAggregateDeductionCandidate &&
10311 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10312 return;
10313
10314 // C++ [over.match.list]p1.2: (second phase list initialization)
10315 // the candidate functions are all the constructors of the class T
10316 // C++ [over.match.ctor]p1: (all other cases)
10317 // the candidate functions are all the constructors of the class of
10318 // the object being initialized
10319
10320 // C++ [over.best.ics]p4:
10321 // When [...] the constructor [...] is a candidate by
10322 // - [over.match.copy] (in all cases)
10323 if (TD) {
10324
10325 // As template candidates are not deduced immediately,
10326 // persist the array in the overload set.
10327 MutableArrayRef<Expr *> TmpInits =
10328 Candidates.getPersistentArgsArray(Inits.size());
10329
10330 for (auto [I, E] : llvm::enumerate(Inits)) {
10331 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10332 TmpInits[I] = DI->getInit();
10333 else
10334 TmpInits[I] = E;
10335 }
10336
10338 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10339 /*SuppressUserConversions=*/false,
10340 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10341 /*PO=*/{}, AllowAggregateDeductionCandidate);
10342 } else {
10343 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10344 /*SuppressUserConversions=*/false,
10345 /*PartialOverloading=*/false, AllowExplicit);
10346 }
10347 };
10348
10349 bool FoundDeductionGuide = false;
10350
10351 auto TryToResolveOverload =
10352 [&](bool OnlyListConstructors) -> OverloadingResult {
10354 bool HasAnyDeductionGuide = false;
10355
10356 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10357 auto *Pattern = Template;
10358 while (Pattern->getInstantiatedFromMemberTemplate()) {
10359 if (Pattern->isMemberSpecialization())
10360 break;
10361 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10362 }
10363
10364 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10365 if (!(RD->getDefinition() && RD->isAggregate()))
10366 return;
10367 QualType Ty = Context.getCanonicalTagType(RD);
10368 SmallVector<QualType, 8> ElementTypes;
10369
10370 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10371 if (!CheckInitList.HadError()) {
10372 // C++ [over.match.class.deduct]p1.8:
10373 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10374 // rvalue reference to the declared type of e_i and
10375 // C++ [over.match.class.deduct]p1.9:
10376 // if e_i is of array type and x_i is a string-literal, T_i is an
10377 // lvalue reference to the const-qualified declared type of e_i and
10378 // C++ [over.match.class.deduct]p1.10:
10379 // otherwise, T_i is the declared type of e_i
10380 for (int I = 0, E = ListInit->getNumInits();
10381 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10382 if (ElementTypes[I]->isArrayType()) {
10384 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10385 else if (isa<StringLiteral>(
10386 ListInit->getInit(I)->IgnoreParenImpCasts()))
10387 ElementTypes[I] =
10388 Context.getLValueReferenceType(ElementTypes[I].withConst());
10389 }
10390
10391 if (CXXDeductionGuideDecl *GD =
10393 LookupTemplateDecl, ElementTypes,
10394 TSInfo->getTypeLoc().getEndLoc())) {
10395 auto *TD = GD->getDescribedFunctionTemplate();
10396 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10397 OnlyListConstructors,
10398 /*AllowAggregateDeductionCandidate=*/true);
10399 HasAnyDeductionGuide = true;
10400 }
10401 }
10402 };
10403
10404 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10405 NamedDecl *D = (*I)->getUnderlyingDecl();
10406 if (D->isInvalidDecl())
10407 continue;
10408
10409 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10410 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10411 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10412 if (!GD)
10413 continue;
10414
10415 if (!GD->isImplicit())
10416 HasAnyDeductionGuide = true;
10417
10418 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10419 /*AllowAggregateDeductionCandidate=*/false);
10420 }
10421
10422 // C++ [over.match.class.deduct]p1.4:
10423 // if C is defined and its definition satisfies the conditions for an
10424 // aggregate class ([dcl.init.aggr]) with the assumption that any
10425 // dependent base class has no virtual functions and no virtual base
10426 // classes, and the initializer is a non-empty braced-init-list or
10427 // parenthesized expression-list, and there are no deduction-guides for
10428 // C, the set contains an additional function template, called the
10429 // aggregate deduction candidate, defined as follows.
10430 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10431 if (ListInit && ListInit->getNumInits()) {
10432 SynthesizeAggrGuide(ListInit);
10433 } else if (Inits.size()) { // parenthesized expression-list
10434 // Inits are expressions inside the parentheses. We don't have
10435 // the parentheses source locations, use the begin/end of Inits as the
10436 // best heuristic.
10437 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10438 Inits, Inits.back()->getEndLoc(),
10439 /*isExplicit=*/false);
10440 SynthesizeAggrGuide(&TempListInit);
10441 }
10442 }
10443
10444 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10445
10446 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10447 };
10448
10450
10451 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10452 // try initializer-list constructors.
10453 if (ListInit) {
10454 bool TryListConstructors = true;
10455
10456 // Try list constructors unless the list is empty and the class has one or
10457 // more default constructors, in which case those constructors win.
10458 if (!ListInit->getNumInits()) {
10459 for (NamedDecl *D : Guides) {
10460 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10461 if (FD && FD->getMinRequiredArguments() == 0) {
10462 TryListConstructors = false;
10463 break;
10464 }
10465 }
10466 } else if (ListInit->getNumInits() == 1) {
10467 // C++ [over.match.class.deduct]:
10468 // As an exception, the first phase in [over.match.list] (considering
10469 // initializer-list constructors) is omitted if the initializer list
10470 // consists of a single expression of type cv U, where U is a
10471 // specialization of C or a class derived from a specialization of C.
10472 Expr *E = ListInit->getInit(0);
10473 auto *RD = E->getType()->getAsCXXRecordDecl();
10474 if (!isa<InitListExpr>(E) && RD &&
10475 isCompleteType(Kind.getLocation(), E->getType()) &&
10477 TryListConstructors = false;
10478 }
10479
10480 if (TryListConstructors)
10481 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10482 // Then unwrap the initializer list and try again considering all
10483 // constructors.
10484 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10485 }
10486
10487 // If list-initialization fails, or if we're doing any other kind of
10488 // initialization, we (eventually) consider constructors.
10490 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10491
10492 switch (Result) {
10493 case OR_Ambiguous:
10494 // FIXME: For list-initialization candidates, it'd usually be better to
10495 // list why they were not viable when given the initializer list itself as
10496 // an argument.
10497 Candidates.NoteCandidates(
10499 Kind.getLocation(),
10500 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10501 << TemplateName),
10503 return QualType();
10504
10505 case OR_No_Viable_Function: {
10506 CXXRecordDecl *Primary =
10507 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10508 bool Complete = isCompleteType(Kind.getLocation(),
10509 Context.getCanonicalTagType(Primary));
10510 Candidates.NoteCandidates(
10512 Kind.getLocation(),
10513 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10514 : diag::err_deduced_class_template_incomplete)
10515 << TemplateName << !Guides.empty()),
10516 *this, OCD_AllCandidates, Inits);
10517 return QualType();
10518 }
10519
10520 case OR_Deleted: {
10521 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10522 // like we ever get here; attempts to trigger this seem to yield a
10523 // generic c'all to deleted function' diagnostic instead.
10524 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10525 << TemplateName;
10526 NoteDeletedFunction(Best->Function);
10527 return QualType();
10528 }
10529
10530 case OR_Success:
10531 // C++ [over.match.list]p1:
10532 // In copy-list-initialization, if an explicit constructor is chosen, the
10533 // initialization is ill-formed.
10534 if (Kind.isCopyInit() && ListInit &&
10535 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10536 bool IsDeductionGuide = !Best->Function->isImplicit();
10537 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10538 << TemplateName << IsDeductionGuide;
10539 Diag(Best->Function->getLocation(),
10540 diag::note_explicit_ctor_deduction_guide_here)
10541 << IsDeductionGuide;
10542 return QualType();
10543 }
10544
10545 // Make sure we didn't select an unusable deduction guide, and mark it
10546 // as referenced.
10547 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10548 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10549 break;
10550 }
10551
10552 // C++ [dcl.type.class.deduct]p1:
10553 // The placeholder is replaced by the return type of the function selected
10554 // by overload resolution for class template deduction.
10555 QualType DeducedType =
10556 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10557 ->getType();
10558 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10559 diag::warn_cxx14_compat_class_template_argument_deduction)
10560 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10561
10562 // Warn if CTAD was used on a type that does not have any user-defined
10563 // deduction guides.
10564 if (!FoundDeductionGuide) {
10565 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10566 diag::warn_ctad_maybe_unsupported)
10567 << TemplateName;
10568 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10569 }
10570
10571 return DeducedType;
10572}
Defines the clang::ASTContext interface.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
static bool isRValueRef(QualType ParamType)
Definition Consumed.cpp:178
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
#define SM(sm)
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:563
This file declares semantic analysis for HLSL constructs.
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
static void updateStringLiteralType(Expr *E, QualType Ty)
Update the type of a string literal, including any surrounding parentheses, to match the type of the ...
Definition SemaInit.cpp:176
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition SemaInit.cpp:188
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition SemaInit.cpp:197
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, SourceRange Braces)
Warn that Entity was of scalar type and was initialized by a single-element braced initializer list.
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
static bool hasAnyDesignatedInits(const InitListExpr *IL)
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
static ExprResult CopyObject(Sema &S, QualType T, const InitializedEntity &Entity, ExprResult CurInit, bool IsExtraneousCopy)
Make a (potentially elidable) temporary copy of the object provided by the given initializer by calli...
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, const InitializedEntity &Entity, bool CheckC23ConstexprInit=false)
Definition SemaInit.cpp:215
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
static void CheckCXX98CompatAccessibleCopy(Sema &S, const InitializedEntity &Entity, Expr *CurInitExpr)
Check whether elidable copy construction for binding a reference to a temporary would have succeeded ...
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
static bool canInitializeArrayWithEmbedDataString(ArrayRef< Expr * > ExprList, const InitializedEntity &Entity, ASTContext &Context)
static bool TryInitializerListConstruction(Sema &S, InitListExpr *List, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
When initializing from init list via constructor, handle initialization of an object of type std::ini...
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, ASTContext &Context)
Check whether the array of type AT can be initialized by the Init expression by means of string initi...
Definition SemaInit.cpp:75
static void TryArrayCopy(Sema &S, const InitializationKind &Kind, const InitializedEntity &Entity, Expr *Initializer, QualType DestType, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Initialize an array from another array.
static bool isInitializedStructuredList(const InitListExpr *StructuredList)
StringInitFailureKind
Definition SemaInit.cpp:61
@ SIF_None
Definition SemaInit.cpp:62
@ SIF_PlainStringIntoUTF8Char
Definition SemaInit.cpp:67
@ SIF_IncompatWideStringIntoWideChar
Definition SemaInit.cpp:65
@ SIF_UTF8StringIntoPlainChar
Definition SemaInit.cpp:66
@ SIF_NarrowStringIntoWideChar
Definition SemaInit.cpp:63
@ SIF_Other
Definition SemaInit.cpp:68
@ SIF_WideStringIntoChar
Definition SemaInit.cpp:64
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
static ExprResult CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value)
Check that the given Index expression is a valid array designator value.
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
static void TryReferenceInitializationCore(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, QualType cv1T1, QualType T1, Qualifiers T1Quals, QualType cv2T2, QualType T2, Qualifiers T2Quals, InitializationSequence &Sequence, bool TopLevelOfInitList)
Reference initialization without resolving overloaded functions.
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
static void ExpandAnonymousFieldDesignator(Sema &SemaRef, DesignatedInitExpr *DIE, unsigned DesigIdx, IndirectFieldDecl *IndirectField)
Expand a field designator that refers to a member of an anonymous struct or union into a series of fi...
static void TryValueInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence, InitListExpr *InitList=nullptr)
Attempt value initialization (C++ [dcl.init]p7).
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
static OverloadingResult ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, MultiExprArg Args, OverloadCandidateSet &CandidateSet, QualType DestType, DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, bool IsListInit, bool RequireActualConstructor, bool SecondStepOfCopyInit=false)
static AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
static void TryListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization (C++0x [dcl.init.list])
static void TryStringLiteralInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence)
Attempt character array initialization from a string literal (C++ [dcl.init.string],...
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, Sema &SemaRef)
Check if the type of a class element has an accessible destructor, and marks it referenced.
static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt reference initialization (C++0x [dcl.init.ref])
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, const ArrayType *Source)
Determine whether we have compatible array types for the purposes of GNU by-copy array initialization...
static bool isExplicitTemporary(const InitializedEntity &Entity, const InitializationKind &Kind, unsigned NumArgs)
Returns true if the parameters describe a constructor initialization of an explicit temporary object,...
static bool isNonReferenceableGLValue(Expr *E)
Determine whether an expression is a non-referenceable glvalue (one to which a reference can never bi...
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
static bool IsWideCharCompatible(QualType T, ASTContext &Context)
Check whether T is compatible with a wide character type (wchar_t, char16_t or char32_t).
Definition SemaInit.cpp:51
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
static OverloadingResult TryRefInitWithConversionFunction(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, Expr *Initializer, bool AllowRValues, bool IsLValueRef, InitializationSequence &Sequence)
Try a reference initialization that involves calling a conversion function.
void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R)
Definition SemaInit.cpp:311
static void TryConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, QualType DestArrayType, InitializationSequence &Sequence, bool IsListInit=false, bool IsInitListCopy=false)
Attempt initialization by constructor (C++ [dcl.init]), which enumerates the constructors of the init...
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, Expr *op)
Emit notes associated with an initialization that failed due to a "simple" conversion failure.
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity)
Determine whether Entity is an entity for which it is idiomatic to elide the braces in aggregate init...
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
static void TryConstructorOrParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType DestType, InitializationSequence &Sequence, bool IsAggrListInit)
Attempt to initialize an object of a class type either by direct-initialization, or by copy-initializ...
static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx)
static const FieldDecl * getConstField(const RecordDecl *RD)
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
@ IIK_okay
@ IIK_nonlocal
@ IIK_nonscalar
static ExprResult PerformConstructorInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, const InitializationSequence::Step &Step, bool &ConstructorInitRequiresZeroInit, bool IsListInitialization, bool IsStdInitListInitialization, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
static void TryReferenceListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitListExpr *InitList, InitializationSequence &Sequence, bool TreatUnavailableAsInvalid)
Attempt list initialization of a reference.
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, const ConstructorInfo &Info)
Determine if the constructor has the signature of a copy or move constructor for the type T of the cl...
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
This file declares semantic analysis for Objective-C.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool isLValue() const
Definition APValue.h:490
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:974
bool isNullPointer() const
Definition APValue.cpp:1037
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:962
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType OverloadTy
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType OCLSamplerTy
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:924
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6024
Represents a loop initializing the elements of an array.
Definition Expr.h:5971
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
Represents a base class of a C++ class.
Definition DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2873
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2710
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3067
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3004
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:1996
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1998
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasUninitializedReferenceMember() const
Whether this class or any of its subobjects has any members of reference type which would make value-...
Definition DeclCXX.h:1163
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition DeclCXX.h:1402
CXXBaseSpecifier * base_class_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:517
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition DeclCXX.h:605
base_class_range bases()
Definition DeclCXX.h:608
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1564
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
llvm::iterator_range< base_class_iterator > base_class_range
Definition DeclCXX.h:604
bool forallBases(ForallBasesCallback BaseMatches) const
Determines if the given callback holds for all the direct or indirect base classes of this type.
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
static CXXTemporaryObjectExpr * Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef< Expr * > Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization)
Definition ExprCXX.cpp:1153
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
SourceLocation getRParenLoc() const
Definition Expr.h:3280
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
Declaration of a class template.
void setExprNeedsCleanups(bool SideEffects)
Definition CleanupInfo.h:28
ConditionalOperator - The ?
Definition Expr.h:4397
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4473
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2255
DeclContextLookupResult lookup_result
Definition DeclBase.h:2594
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2390
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
ValueDecl * getDecl()
Definition Expr.h:1344
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:460
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
Represents a single C99 designator.
Definition Expr.h:5597
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:5759
void setFieldDecl(FieldDecl *FD)
Definition Expr.h:5695
FieldDecl * getFieldDecl() const
Definition Expr.h:5688
SourceLocation getFieldLoc() const
Definition Expr.h:5705
const IdentifierInfo * getFieldName() const
Definition Expr.cpp:4795
SourceLocation getDotLoc() const
Definition Expr.h:5700
SourceLocation getLBracketLoc() const
Definition Expr.h:5741
Represents a C99 designated initializer expression.
Definition Expr.h:5554
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition Expr.h:5814
Expr * getArrayRangeEnd(const Designator &D) const
Definition Expr.cpp:4904
Expr * getSubExpr(unsigned Idx) const
Definition Expr.h:5836
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition Expr.h:5818
Expr * getArrayRangeStart(const Designator &D) const
Definition Expr.cpp:4899
void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last)
Replaces the designator at index Idx with the series of designators in [First, Last).
Definition Expr.cpp:4911
MutableArrayRef< Designator > designators()
Definition Expr.h:5787
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4894
Designator * getDesignator(unsigned Idx)
Definition Expr.h:5795
Expr * getInit() const
Retrieve the initializer value.
Definition Expr.h:5822
unsigned size() const
Returns the number of designators in this initializer.
Definition Expr.h:5784
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4873
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4890
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition Expr.h:5809
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition Expr.h:5834
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition Expr.cpp:4836
InitListExpr * getUpdater() const
Definition Expr.h:5939
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
const Designator & getDesignator(unsigned Idx) const
Definition Designator.h:232
unsigned getNumDesignators() const
Definition Designator.h:231
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
SourceLocation getFieldLoc() const
Definition Designator.h:133
SourceLocation getDotLoc() const
Definition Designator.h:128
Expr * getArrayRangeStart() const
Definition Designator.h:194
bool isArrayDesignator() const
Definition Designator.h:108
SourceLocation getLBracketLoc() const
Definition Designator.h:167
bool isArrayRangeDesignator() const
Definition Designator.h:109
bool isFieldDesignator() const
Definition Designator.h:107
SourceLocation getRBracketLoc() const
Definition Designator.h:174
SourceLocation getEllipsisLoc() const
Definition Designator.h:204
Expr * getArrayRangeEnd() const
Definition Designator.h:199
const IdentifierInfo * getFieldDecl() const
Definition Designator.h:123
Expr * getArrayIndex() const
Definition Designator.h:162
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
Definition Designator.h:115
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:961
Represents a reference to emded data.
Definition Expr.h:5132
StringLiteral * getDataStringLiteral() const
Definition Expr.h:5149
EmbedDataStorage * getData() const
Definition Expr.h:5151
SourceLocation getLocation() const
Definition Expr.h:5145
size_t getDataElementCount() const
Definition Expr.h:5154
RAII object that enters a new expression evaluation context.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4257
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4292
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3348
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3262
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4077
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToMatrixElement() const
Returns whether this expression refers to a matrix element.
Definition Expr.h:517
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3179
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3359
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4850
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3264
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3285
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
Represents a function declaration or definition.
Definition Decl.h:2027
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2802
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3825
QualType getReturnType() const
Definition Decl.h:2850
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2541
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2386
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3804
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
One of these records is kept for each identifier that is lexed.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:827
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a C array with an unspecified size.
Definition TypeBase.h:3973
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3486
chain_iterator chain_end() const
Definition Decl.h:3509
chain_iterator chain_begin() const
Definition Decl.h:3508
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition Decl.h:3505
Describes an C or C++ initializer list.
Definition Expr.h:5305
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition Expr.h:5418
void setSyntacticForm(InitListExpr *Init)
Definition Expr.h:5479
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition Expr.h:5380
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5421
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2471
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2431
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5432
unsigned getNumInits() const
Definition Expr.h:5338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2505
void setInit(unsigned Init, Expr *expr)
Definition Expr.h:5370
SourceLocation getLBraceLoc() const
Definition Expr.h:5463
Expr * updateInit(const ASTContext &C, unsigned Init, Expr *expr)
Updates the initializer at index Init with the new expression expr, and returns the old expression at...
Definition Expr.cpp:2435
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2447
InitListExpr * getSyntacticForm() const
Definition Expr.h:5475
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5408
bool isExplicit() const
Definition Expr.h:5448
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5342
SourceLocation getRBraceLoc() const
Definition Expr.h:5465
InitListExpr * getSemanticForm() const
Definition Expr.h:5469
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition Expr.cpp:2494
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2523
void setInitializedFieldInUnion(FieldDecl *FD)
Definition Expr.h:5438
bool isSyntacticForm() const
Definition Expr.h:5472
void setRBraceLoc(SourceLocation Loc)
Definition Expr.h:5466
ArrayRef< Expr * > inits() const
Definition Expr.h:5358
void sawArrayRangeDesignator(bool ARD=true)
Definition Expr.h:5489
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5351
Describes the kind of initialization being performed, along with location information for tokens rela...
@ IK_DirectList
Direct list-initialization.
@ IK_Value
Value initialization.
@ IK_Direct
Direct initialization.
@ IK_Copy
Copy initialization.
@ IK_Default
Default initialization.
InitKind getKind() const
Determine the initialization kind.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
A single step in the initialization sequence.
StepKind Kind
The kind of conversion or initialization step we are taking.
InitListExpr * WrappingSyntacticList
When Kind = SK_RewrapInitList, the syntactic form of the wrapping list.
ImplicitConversionSequence * ICS
When Kind = SK_ConversionSequence, the implicit conversion sequence.
struct F Function
When Kind == SK_ResolvedOverloadedFunction or Kind == SK_UserConversion, the function that the expres...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
void AddListInitializationStep(QualType T)
Add a list-initialization step.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
void AddStringInitStep(QualType T)
Add a string init step.
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
@ SK_StdInitializerListConstructorCall
Perform initialization via a constructor taking a single std::initializer_list argument.
@ SK_AtomicConversion
Perform a conversion adding _Atomic to a type.
@ SK_ObjCObjectConversion
An initialization that "converts" an Objective-C object (not a point to an object) to another Objecti...
@ SK_GNUArrayInit
Array initialization (from an array rvalue) as a GNU extension.
@ SK_CastDerivedToBaseLValue
Perform a derived-to-base cast, producing an lvalue.
@ SK_ProduceObjCObject
Produce an Objective-C object pointer.
@ SK_FunctionReferenceConversion
Perform a function reference conversion, see [dcl.init.ref]p4.
@ SK_BindReference
Reference binding to an lvalue.
@ SK_ArrayLoopInit
Array initialization by elementwise copy.
@ SK_ConstructorInitialization
Perform initialization via a constructor.
@ SK_OCLSamplerInit
Initialize an OpenCL sampler from an integer.
@ SK_StringInit
Initialization by string.
@ SK_ZeroInitialization
Zero-initialize the object.
@ SK_CastDerivedToBaseXValue
Perform a derived-to-base cast, producing an xvalue.
@ SK_QualificationConversionXValue
Perform a qualification conversion, producing an xvalue.
@ SK_UserConversion
Perform a user-defined conversion, either via a conversion function or via a constructor.
@ SK_CastDerivedToBasePRValue
Perform a derived-to-base cast, producing an rvalue.
@ SK_BindReferenceToTemporary
Reference binding to a temporary.
@ SK_PassByIndirectRestore
Pass an object by indirect restore.
@ SK_ParenthesizedArrayInit
Array initialization from a parenthesized initializer list.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
@ SK_ArrayInit
Array initialization (from an array rvalue).
@ SK_ExtraneousCopyToTemporary
An optional copy of a temporary object to another temporary object, which is permitted (but not requi...
@ SK_ArrayLoopIndex
Array indexing for initialization by elementwise copy.
@ SK_ConversionSequenceNoNarrowing
Perform an implicit conversion sequence without narrowing.
@ SK_RewrapInitList
Rewrap the single-element initializer list for a reference.
@ SK_ConstructorInitializationFromList
Perform initialization via a constructor, taking arguments from a single InitListExpr.
@ SK_PassByIndirectCopyRestore
Pass an object by indirect copy-and-restore.
@ SK_ResolveAddressOfOverloadedFunction
Resolve the address of an overloaded function to a specific function declaration.
@ SK_UnwrapInitList
Unwrap the single-element initializer list for a reference.
@ SK_FinalCopy
Direct-initialization from a reference-related object in the final stage of class copy-initialization...
@ SK_QualificationConversionLValue
Perform a qualification conversion, producing an lvalue.
@ SK_StdInitializerList
Construct a std::initializer_list from an initializer list.
@ SK_QualificationConversionPRValue
Perform a qualification conversion, producing a prvalue.
@ SK_ConversionSequence
Perform an implicit conversion sequence.
@ SK_ListInitialization
Perform list-initialization without a constructor.
@ SK_OCLZeroOpaqueType
Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero.
void AddUserConversionStep(FunctionDecl *Function, DeclAccessPair FoundDecl, QualType T, bool HadMultipleCandidates)
Add a new step invoking a conversion function, which is either a constructor or a conversion function...
void AddHLSLBufferConversionStep(QualType T)
void SetZeroInitializationFixit(const std::string &Fixit, SourceLocation L)
Call for initializations are invalid but that would be valid zero initialzations if Fixit was applied...
InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList=false, bool TreatUnavailableAsInvalid=true)
Try to perform initialization of the given entity, creating a record of the steps required to perform...
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
FailureKind getFailureKind() const
Determine why initialization failed.
void InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
void AddParenthesizedListInitStep(QualType T)
void SetFailed(FailureKind Failure)
Note that this initialization sequence failed.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
void AddUnwrapInitListInitStep(InitListExpr *Syntactic)
Only used when initializing structured bindings from an array with direct-list-initialization.
void AddOCLZeroOpaqueTypeStep(QualType T)
Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.) from a zero constant.
void AddFinalCopy(QualType T)
Add a new step that makes a copy of the input to an object of the given type, as the final step in cl...
OverloadingResult getFailedOverloadResult() const
Get the overloading result, for when the initialization sequence failed due to a bad overload.
void setSequenceKind(enum SequenceKind SK)
Set the kind of sequence computed.
void AddObjCObjectConversionStep(QualType T)
Add an Objective-C object conversion step, which is always a no-op.
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
void AddExtraneousCopyToTemporary(QualType T)
Add a new step that makes an extraneous copy of the input to a temporary of the same class type.
void setIncompleteTypeFailure(QualType IncompleteType)
Note that this initialization sequence failed due to an incomplete type.
void AddOCLSamplerInitStep(QualType T)
Add a step to initialize an OpenCL sampler from an integer constant.
void AddCAssignmentStep(QualType T)
Add a C assignment step.
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic)
Add steps to unwrap a initializer list for a reference around a single element and rewrap it at the e...
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
bool Failed() const
Determine whether the initialization sequence is invalid.
void AddAtomicConversionStep(QualType Ty)
Add a new step that performs conversion from non-atomic to atomic type.
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
enum SequenceKind getKind() const
Determine the kind of initialization sequence computed.
SequenceKind
Describes the kind of initialization sequence computed.
@ NormalSequence
A normal sequence.
@ FailedSequence
A failed initialization sequence.
@ DependentSequence
A dependent initialization, which could not be type-checked due to the presence of dependent types or...
void AddReferenceBindingStep(QualType T, bool BindingTemporary)
Add a new step binding a reference to an object.
FailureKind
Describes why initialization failed.
@ FK_UserConversionOverloadFailed
Overloading for a user-defined conversion failed.
@ FK_NarrowStringIntoWideCharArray
Initializing a wide char array with narrow string literal.
@ FK_ArrayTypeMismatch
Array type mismatch.
@ FK_ParenthesizedListInitForReference
Reference initialized from a parenthesized initializer list.
@ FK_NonConstLValueReferenceBindingToVectorElement
Non-const lvalue reference binding to a vector element.
@ FK_ReferenceInitDropsQualifiers
Reference binding drops qualifiers.
@ FK_InitListBadDestinationType
Initialization of some unused destination type with an initializer list.
@ FK_ConversionFromPropertyFailed
Implicit conversion failed.
@ FK_NonConstLValueReferenceBindingToUnrelated
Non-const lvalue reference binding to an lvalue of unrelated type.
@ FK_ListConstructorOverloadFailed
Overloading for list-initialization by constructor failed.
@ FK_ReferenceInitFailed
Reference binding failed.
@ FK_ArrayNeedsInitList
Array must be initialized with an initializer list.
@ FK_PlainStringIntoUTF8Char
Initializing char8_t array with plain string literal.
@ FK_NonConstantArrayInit
Non-constant array initializer.
@ FK_NonConstLValueReferenceBindingToTemporary
Non-const lvalue reference binding to a temporary.
@ FK_ConversionFailed
Implicit conversion failed.
@ FK_ArrayNeedsInitListOrStringLiteral
Array must be initialized with an initializer list or a string literal.
@ FK_ParenthesizedListInitForScalar
Scalar initialized from a parenthesized initializer list.
@ FK_HLSLInitListFlatteningFailed
HLSL initialization list flattening failed.
@ FK_PlaceholderType
Initializer has a placeholder type which cannot be resolved by initialization.
@ FK_IncompatWideStringIntoWideChar
Initializing wide char array with incompatible wide string literal.
@ FK_NonConstLValueReferenceBindingToMatrixElement
Non-const lvalue reference binding to a matrix element.
@ FK_TooManyInitsForReference
Too many initializers provided for a reference.
@ FK_NonConstLValueReferenceBindingToBitfield
Non-const lvalue reference binding to a bit-field.
@ FK_ReferenceAddrspaceMismatchTemporary
Reference with mismatching address space binding to temporary.
@ FK_ListInitializationFailed
List initialization failed at some point.
@ FK_TooManyInitsForScalar
Too many initializers for scalar.
@ FK_AddressOfOverloadFailed
Cannot resolve the address of an overloaded function.
@ FK_VariableLengthArrayHasInitializer
Variable-length array must not have an initializer.
@ FK_ArrayNeedsInitListOrWideStringLiteral
Array must be initialized with an initializer list or a wide string literal.
@ FK_RValueReferenceBindingToLValue
Rvalue reference binding to an lvalue.
@ FK_Incomplete
Initialization of an incomplete type.
@ FK_WideStringIntoCharArray
Initializing char array with wide string literal.
@ FK_ExplicitConstructor
List-copy-initialization chose an explicit constructor.
@ FK_ReferenceInitOverloadFailed
Overloading due to reference initialization failed.
@ FK_ConstructorOverloadFailed
Overloading for initialization by constructor failed.
@ FK_ReferenceBindingToInitList
Reference initialization from an initializer list.
@ FK_DefaultInitOfConst
Default-initialization of a 'const' object.
@ FK_ParenthesizedListInitFailed
Parenthesized list initialization failed at some point.
@ FK_AddressOfUnaddressableFunction
Trying to take the address of a function that doesn't support having its address taken.
@ FK_UTF8StringIntoPlainChar
Initializing char array with UTF-8 string literal.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
void AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates)
Add a new step in the initialization that resolves the address of an overloaded function to a specifi...
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
SmallVectorImpl< Step >::const_iterator step_iterator
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
VD Variable
When Kind == EK_Variable, EK_Member, EK_Binding, or EK_TemplateParameter, the variable,...
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
EntityKind getKind() const
Determine the kind of initialization.
DeclarationName getName() const
Retrieve the name of the entity being initialized.
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
bool isImplicitMemberInitializer() const
Is this the implicit initialization of a member of a class from a defaulted constructor?
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index.
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda.
bool isParamOrTemplateParamKind() const
llvm::PointerIntPair< const CXXBaseSpecifier *, 1 > Base
When Kind == EK_Base, the base specifier that provides the base class.
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
EntityKind
Specifies the kind of entity being initialized.
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_MatrixElement
The entity being initialized is an element of a matrix.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
static InitializedEntity InitializeMemberFromParenAggInit(FieldDecl *Member)
Create the initialization entity for a member subobject initialized via parenthesized aggregate init.
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, EK_MatrixElement, or EK_ComplexElement,...
bool isVariableLengthArrayNew() const
Determine whether this is an array new with an unknown bound.
llvm::PointerIntPair< ParmVarDecl *, 1 > Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the integer indicating whether the parameter is "con...
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call.
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1074
Represents the results of name lookup.
Definition Lookup.h:147
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4401
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represent a C++ namespace.
Definition Decl.h:592
Represents a place-holder for an object not to be initialized by anything.
Definition Expr.h:5880
QualType getEncodedType() const
Definition ExprObjC.h:460
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition ExprObjC.h:1613
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition Overload.h:1486
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CandidateSetKind getKind() const
Definition Overload.h:1349
Represents a parameter to a function.
Definition Decl.h:1817
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3686
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
QualType withConst() const
Definition TypeBase.h:1174
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1240
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
bool hasConst() const
Definition TypeBase.h:457
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition TypeBase.h:646
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasAddressSpace() const
Definition TypeBase.h:570
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
Qualifiers withoutAddressSpace() const
Definition TypeBase.h:538
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:435
bool hasVolatile() const
Definition TypeBase.h:467
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4344
field_iterator field_end() const
Definition Decl.h:4550
field_range fields() const
Definition Decl.h:4547
bool isRandomized() const
Definition Decl.h:4502
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4528
bool hasUninitializedExplicitInitFields() const
Definition Decl.h:4470
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4544
bool field_empty() const
Definition Decl.h:4555
field_iterator field_begin() const
Definition Decl.cpp:5299
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
bool isSpelledAsLValue() const
Definition TypeBase.h:3650
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6394
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10487
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10490
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10496
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10494
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
Definition Sema.h:939
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7017
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2078
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7029
ASTContext & Context
Definition Sema.h:1309
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:686
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition Sema.h:1519
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:761
ASTContext & getASTContext() const
Definition Sema.h:940
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:9097
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition Sema.h:933
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
SemaHLSL & HLSL()
Definition Sema.h:1484
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:78
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7053
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10515
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8266
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8133
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7065
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8258
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13985
SourceManager & getSourceManager() const
Definition Sema.h:938
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity, const InitializationKind &Kind, AssignmentAction Action, QualType LHSType, Expr *RHSExpr)
Perform Bounds Safety Semantic checks for initializing a Bounds Safety pointer.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13718
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15504
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6828
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
SourceManager & SourceMgr
Definition Sema.h:1312
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
DiagnosticsEngine & Diags
Definition Sema.h:1311
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:934
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1589
CXXDeductionGuideDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
QualType getToType(unsigned Idx) const
Definition Overload.h:411
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
unsigned getLength() const
Definition Expr.h:1915
StringLiteralKind getKind() const
Definition Expr.h:1918
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition Expr.h:1902
StringRef getString() const
Definition Expr.h:1873
bool isUnion() const
Definition Decl.h:3947
bool isBigEndian() const
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isDependent() const
Determines whether this is a dependent template name.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isMFloat8Type() const
Definition TypeBase.h:9075
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
bool isRValueReferenceType() const
Definition TypeBase.h:8716
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2197
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isArrayParameterType() const
Definition TypeBase.h:8799
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1958
bool isChar8Type() const
Definition Type.cpp:2213
bool isSizelessBuiltinType() const
Definition Type.cpp:2627
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8827
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:8969
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isOpenCLSpecificType() const
Definition TypeBase.h:8984
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2507
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8819
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2113
bool isQueueT() const
Definition TypeBase.h:8940
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isAtomicType() const
Definition TypeBase.h:8876
bool isFunctionProtoType() const
Definition TypeBase.h:2661
bool isMatrixType() const
Definition TypeBase.h:8847
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isObjCObjectType() const
Definition TypeBase.h:8867
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isEventT() const
Definition TypeBase.h:8932
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isVectorType() const
Definition TypeBase.h:8823
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isFloatingType() const
Definition Type.cpp:2393
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2336
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isObjCRetainableType() const
Definition Type.cpp:5435
bool isUnionType() const
Definition Type.cpp:755
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
const Expr * getInit() const
Definition Decl.h:1389
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1250
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
VectorKind getVectorKind() const
Definition TypeBase.h:4259
QualType getElementType() const
Definition TypeBase.h:4253
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1544
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:346
@ SD_Static
Static storage duration.
Definition Specifiers.h:347
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:345
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ Template
We are parsing a template declaration.
Definition Parser.h:81
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
ExprResult ExprError()
Definition Ownership.h:265
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
Expr * IgnoreParensSingleStep(Expr *E)
Definition IgnoreExpr.h:157
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2252
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:438
@ Implicit
An implicit conversion.
Definition Sema.h:440
@ CStyleCast
A C-style cast.
Definition Sema.h:442
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:446
@ FunctionalCast
A functional-style cast.
Definition Sema.h:444
unsigned long uint64_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
CXXConstructorDecl * Constructor
Definition Overload.h:1511
DeclAccessPair FoundDecl
Definition Overload.h:1510
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6939
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6907
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6945
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6962
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506