clang 24.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 Expr *ExtraInit =
1366 Index < IList->getNumInits() ? IList->getInit(Index) : CurEmbed;
1367 SourceLocation ExtraInitLoc =
1368 ExtraInit ? ExtraInit->getBeginLoc() : IList->getEndLoc();
1369 SourceRange ExtraInitRange =
1370 ExtraInit ? ExtraInit->getSourceRange() : IList->getSourceRange();
1371 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1372 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1373 hadError = ExtraInitsIsError;
1374 if (VerifyOnly) {
1375 return;
1376 } else if (StructuredIndex == 1 && StructuredList->getNumInits() != 0 &&
1377 StructuredList->getInit(0) &&
1378 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1379 SIF_None) {
1380 unsigned DK =
1381 ExtraInitsIsError
1382 ? diag::err_excess_initializers_in_char_array_initializer
1383 : diag::ext_excess_initializers_in_char_array_initializer;
1384 SemaRef.Diag(ExtraInitLoc, DK) << ExtraInitRange;
1385 } else if (T->isSizelessBuiltinType()) {
1386 unsigned DK = ExtraInitsIsError
1387 ? diag::err_excess_initializers_for_sizeless_type
1388 : diag::ext_excess_initializers_for_sizeless_type;
1389 SemaRef.Diag(ExtraInitLoc, DK) << T << ExtraInitRange;
1390 } else {
1391 int initKind = T->isArrayType() ? 0
1392 : T->isVectorType() ? 1
1393 : T->isMatrixType() ? 2
1394 : T->isScalarType() ? 3
1395 : T->isUnionType() ? 4
1396 : 5;
1397
1398 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1399 : diag::ext_excess_initializers;
1400 SemaRef.Diag(ExtraInitLoc, DK) << initKind << ExtraInitRange;
1401 }
1402 }
1403
1404 if (!VerifyOnly) {
1405 if (T->isScalarType() && IList->getNumInits() == 1 &&
1406 !isa<InitListExpr>(IList->getInit(0)))
1407 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1408
1409 // Warn if this is a class type that won't be an aggregate in future
1410 // versions of C++.
1411 auto *CXXRD = T->getAsCXXRecordDecl();
1412 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1413 // Don't warn if there's an equivalent default constructor that would be
1414 // used instead.
1415 bool HasEquivCtor = false;
1416 if (IList->getNumInits() == 0) {
1417 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1418 HasEquivCtor = CD && !CD->isDeleted();
1419 }
1420
1421 if (!HasEquivCtor) {
1422 SemaRef.Diag(IList->getBeginLoc(),
1423 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1424 << IList->getSourceRange() << T;
1425 }
1426 }
1427 }
1428}
1429
1430void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1431 InitListExpr *IList,
1432 QualType &DeclType,
1433 bool SubobjectIsDesignatorContext,
1434 unsigned &Index,
1435 InitListExpr *StructuredList,
1436 unsigned &StructuredIndex,
1437 bool TopLevelObject) {
1438 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1439 // Explicitly braced initializer for complex type can be real+imaginary
1440 // parts.
1441 CheckComplexType(Entity, IList, DeclType, Index,
1442 StructuredList, StructuredIndex);
1443 } else if (DeclType->isScalarType()) {
1444 CheckScalarType(Entity, IList, DeclType, Index,
1445 StructuredList, StructuredIndex);
1446 } else if (DeclType->isVectorType()) {
1447 CheckVectorType(Entity, IList, DeclType, Index,
1448 StructuredList, StructuredIndex);
1449 } else if (DeclType->isMatrixType()) {
1450 CheckMatrixType(Entity, IList, DeclType, Index, StructuredList,
1451 StructuredIndex);
1452 } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) {
1453 auto Bases =
1456 if (DeclType->isRecordType()) {
1457 assert(DeclType->isAggregateType() &&
1458 "non-aggregate records should be handed in CheckSubElementType");
1459 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1460 Bases = CXXRD->bases();
1461 } else {
1462 Bases = cast<CXXRecordDecl>(RD)->bases();
1463 }
1464 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1465 SubobjectIsDesignatorContext, Index, StructuredList,
1466 StructuredIndex, TopLevelObject);
1467 } else if (DeclType->isArrayType()) {
1468 llvm::APSInt Zero(
1469 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1470 false);
1471 CheckArrayType(Entity, IList, DeclType, Zero,
1472 SubobjectIsDesignatorContext, Index,
1473 StructuredList, StructuredIndex);
1474 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1475 // This type is invalid, issue a diagnostic.
1476 ++Index;
1477 if (!VerifyOnly)
1478 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1479 << DeclType;
1480 hadError = true;
1481 } else if (DeclType->isReferenceType()) {
1482 CheckReferenceType(Entity, IList, DeclType, Index,
1483 StructuredList, StructuredIndex);
1484 } else if (DeclType->isObjCObjectType()) {
1485 if (!VerifyOnly)
1486 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1487 hadError = true;
1488 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1489 DeclType->isSizelessBuiltinType()) {
1490 // Checks for scalar type are sufficient for these types too.
1491 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1492 StructuredIndex);
1493 } else if (DeclType->isDependentType()) {
1494 // C++ [over.match.class.deduct]p1.5:
1495 // brace elision is not considered for any aggregate element that has a
1496 // dependent non-array type or an array type with a value-dependent bound
1497 ++Index;
1498 assert(AggrDeductionCandidateParamTypes);
1499 AggrDeductionCandidateParamTypes->push_back(DeclType);
1500 } else {
1501 if (!VerifyOnly)
1502 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1503 << DeclType;
1504 hadError = true;
1505 }
1506}
1507
1508void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1509 InitListExpr *IList,
1510 QualType ElemType,
1511 unsigned &Index,
1512 InitListExpr *StructuredList,
1513 unsigned &StructuredIndex,
1514 bool DirectlyDesignated) {
1515 Expr *expr = IList->getInit(Index);
1516
1517 if (ElemType->isReferenceType())
1518 return CheckReferenceType(Entity, IList, ElemType, Index,
1519 StructuredList, StructuredIndex);
1520
1521 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1522 if (SubInitList->getNumInits() == 1 &&
1523 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1524 SIF_None) {
1525 // FIXME: It would be more faithful and no less correct to include an
1526 // InitListExpr in the semantic form of the initializer list in this case.
1527 expr = SubInitList->getInit(0);
1528 }
1529 // Nested aggregate initialization and C++ initialization are handled later.
1530 } else if (isa<ImplicitValueInitExpr>(expr)) {
1531 // This happens during template instantiation when we see an InitListExpr
1532 // that we've already checked once.
1533 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1534 "found implicit initialization for the wrong type");
1535 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1536 ++Index;
1537 return;
1538 }
1539
1540 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1541 // C++ [dcl.init.aggr]p2:
1542 // Each member is copy-initialized from the corresponding
1543 // initializer-clause.
1544
1545 // FIXME: Better EqualLoc?
1546 InitializationKind Kind =
1547 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1548
1549 // Vector elements can be initialized from other vectors in which case
1550 // we need initialization entity with a type of a vector (and not a vector
1551 // element!) initializing multiple vector elements.
1552 auto TmpEntity =
1553 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1555 : Entity;
1556
1557 if (TmpEntity.getType()->isDependentType()) {
1558 // C++ [over.match.class.deduct]p1.5:
1559 // brace elision is not considered for any aggregate element that has a
1560 // dependent non-array type or an array type with a value-dependent
1561 // bound
1562 assert(AggrDeductionCandidateParamTypes);
1563
1564 // In the presence of a braced-init-list within the initializer, we should
1565 // not perform brace-elision, even if brace elision would otherwise be
1566 // applicable. For example, given:
1567 //
1568 // template <class T> struct Foo {
1569 // T t[2];
1570 // };
1571 //
1572 // Foo t = {{1, 2}};
1573 //
1574 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1575 // {{1, 2}}.
1577 !isa_and_present<ConstantArrayType>(
1578 SemaRef.Context.getAsArrayType(ElemType))) {
1579 ++Index;
1580 AggrDeductionCandidateParamTypes->push_back(ElemType);
1581 return;
1582 }
1583 } else {
1584 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1585 /*TopLevelOfInitList*/ true);
1586 // C++14 [dcl.init.aggr]p13:
1587 // If the assignment-expression can initialize a member, the member is
1588 // initialized. Otherwise [...] brace elision is assumed
1589 //
1590 // Brace elision is never performed if the element is not an
1591 // assignment-expression.
1592 if (Seq || isa<InitListExpr>(expr)) {
1593 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1594 expr = HandleEmbed(Embed, Entity);
1595 }
1596 if (!VerifyOnly) {
1597 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1598 if (Result.isInvalid())
1599 hadError = true;
1600
1601 UpdateStructuredListElement(StructuredList, StructuredIndex,
1602 Result.getAs<Expr>());
1603 } else if (!Seq) {
1604 hadError = true;
1605 } else if (StructuredList) {
1606 UpdateStructuredListElement(StructuredList, StructuredIndex,
1607 getDummyInit());
1608 }
1609 if (!CurEmbed)
1610 ++Index;
1611 if (AggrDeductionCandidateParamTypes)
1612 AggrDeductionCandidateParamTypes->push_back(ElemType);
1613 return;
1614 }
1615 }
1616
1617 // Fall through for subaggregate initialization
1618 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1619 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1620 return CheckScalarType(Entity, IList, ElemType, Index,
1621 StructuredList, StructuredIndex);
1622 } else if (const ArrayType *arrayType =
1623 SemaRef.Context.getAsArrayType(ElemType)) {
1624 // arrayType can be incomplete if we're initializing a flexible
1625 // array member. There's nothing we can do with the completed
1626 // type here, though.
1627
1628 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1629 // FIXME: Should we do this checking in verify-only mode?
1630 if (!VerifyOnly)
1631 CheckStringInit(expr, ElemType, arrayType, SemaRef, Entity,
1632 SemaRef.getLangOpts().C23 &&
1634 if (StructuredList)
1635 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1636 ++Index;
1637 return;
1638 }
1639
1640 // Fall through for subaggregate initialization.
1641
1642 } else {
1643 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1644 ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1645 "Unexpected type");
1646
1647 // C99 6.7.8p13:
1648 //
1649 // The initializer for a structure or union object that has
1650 // automatic storage duration shall be either an initializer
1651 // list as described below, or a single expression that has
1652 // compatible structure or union type. In the latter case, the
1653 // initial value of the object, including unnamed members, is
1654 // that of the expression.
1655 ExprResult ExprRes = expr;
1656 if (SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
1657 !VerifyOnly) !=
1658 AssignConvertType::Incompatible) {
1659 if (ExprRes.isInvalid())
1660 hadError = true;
1661 else {
1662 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1663 if (ExprRes.isInvalid())
1664 hadError = true;
1665 }
1666 UpdateStructuredListElement(StructuredList, StructuredIndex,
1667 ExprRes.getAs<Expr>());
1668 ++Index;
1669 return;
1670 }
1671 ExprRes.get();
1672 // Fall through for subaggregate initialization
1673 }
1674
1675 // C++ [dcl.init.aggr]p12:
1676 //
1677 // [...] Otherwise, if the member is itself a non-empty
1678 // subaggregate, brace elision is assumed and the initializer is
1679 // considered for the initialization of the first member of
1680 // the subaggregate.
1681 // OpenCL vector initializer is handled elsewhere.
1682 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1683 ElemType->isAggregateType()) {
1684 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1685 StructuredIndex);
1686 ++StructuredIndex;
1687
1688 // In C++20, brace elision is not permitted for a designated initializer.
1689 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1690 if (InOverloadResolution)
1691 hadError = true;
1692 if (!VerifyOnly) {
1693 SemaRef.Diag(expr->getBeginLoc(),
1694 diag::ext_designated_init_brace_elision)
1695 << expr->getSourceRange()
1696 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1698 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1699 }
1700 }
1701 } else {
1702 if (!VerifyOnly) {
1703 // We cannot initialize this element, so let PerformCopyInitialization
1704 // produce the appropriate diagnostic. We already checked that this
1705 // initialization will fail.
1707 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1708 /*TopLevelOfInitList=*/true);
1709 (void)Copy;
1710 assert(Copy.isInvalid() &&
1711 "expected non-aggregate initialization to fail");
1712 }
1713 hadError = true;
1714 ++Index;
1715 ++StructuredIndex;
1716 }
1717}
1718
1719void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1720 InitListExpr *IList, QualType DeclType,
1721 unsigned &Index,
1722 InitListExpr *StructuredList,
1723 unsigned &StructuredIndex) {
1724 assert(Index == 0 && "Index in explicit init list must be zero");
1725
1726 // As an extension, clang supports complex initializers, which initialize
1727 // a complex number component-wise. When an explicit initializer list for
1728 // a complex number contains two initializers, this extension kicks in:
1729 // it expects the initializer list to contain two elements convertible to
1730 // the element type of the complex type. The first element initializes
1731 // the real part, and the second element intitializes the imaginary part.
1732
1733 if (IList->getNumInits() < 2)
1734 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1735 StructuredIndex);
1736
1737 // This is an extension in C. (The builtin _Complex type does not exist
1738 // in the C++ standard.)
1739 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1740 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1741 << IList->getSourceRange();
1742
1743 // Initialize the complex number.
1744 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1745 InitializedEntity ElementEntity =
1747
1748 for (unsigned i = 0; i < 2; ++i) {
1749 ElementEntity.setElementIndex(Index);
1750 CheckSubElementType(ElementEntity, IList, elementType, Index,
1751 StructuredList, StructuredIndex);
1752 }
1753}
1754
1755void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1756 InitListExpr *IList, QualType DeclType,
1757 unsigned &Index,
1758 InitListExpr *StructuredList,
1759 unsigned &StructuredIndex) {
1760 if (Index >= IList->getNumInits()) {
1761 if (!VerifyOnly) {
1762 if (SemaRef.getLangOpts().CPlusPlus) {
1763 if (DeclType->isSizelessBuiltinType())
1764 SemaRef.Diag(IList->getBeginLoc(),
1765 SemaRef.getLangOpts().CPlusPlus11
1766 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1767 : diag::err_empty_sizeless_initializer)
1768 << DeclType << IList->getSourceRange();
1769 else
1770 SemaRef.Diag(IList->getBeginLoc(),
1771 SemaRef.getLangOpts().CPlusPlus11
1772 ? diag::warn_cxx98_compat_empty_scalar_initializer
1773 : diag::err_empty_scalar_initializer)
1774 << IList->getSourceRange();
1775 }
1776 }
1777 hadError =
1778 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1779 ++Index;
1780 ++StructuredIndex;
1781 return;
1782 }
1783
1784 Expr *expr = IList->getInit(Index);
1785 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1786 // FIXME: This is invalid, and accepting it causes overload resolution
1787 // to pick the wrong overload in some corner cases.
1788 if (!VerifyOnly)
1789 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1790 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1791
1792 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1793 StructuredIndex);
1794 return;
1795 } else if (isa<DesignatedInitExpr>(expr)) {
1796 if (!VerifyOnly)
1797 SemaRef.Diag(expr->getBeginLoc(),
1798 diag::err_designator_for_scalar_or_sizeless_init)
1799 << DeclType->isSizelessBuiltinType() << DeclType
1800 << expr->getSourceRange();
1801 hadError = true;
1802 ++Index;
1803 ++StructuredIndex;
1804 return;
1805 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1806 expr = HandleEmbed(Embed, Entity);
1807 }
1808
1810 if (VerifyOnly) {
1811 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1812 Result = getDummyInit();
1813 else
1814 Result = ExprError();
1815 } else {
1816 Result =
1817 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1818 /*TopLevelOfInitList=*/true);
1819 }
1820
1821 Expr *ResultExpr = nullptr;
1822
1823 if (Result.isInvalid())
1824 hadError = true; // types weren't compatible.
1825 else {
1826 ResultExpr = Result.getAs<Expr>();
1827
1828 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1829 // The type was promoted, update initializer list.
1830 // FIXME: Why are we updating the syntactic init list?
1831 IList->setInit(Index, ResultExpr);
1832 }
1833 }
1834
1835 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1836 if (!CurEmbed)
1837 ++Index;
1838 if (AggrDeductionCandidateParamTypes)
1839 AggrDeductionCandidateParamTypes->push_back(DeclType);
1840}
1841
1842void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1843 InitListExpr *IList, QualType DeclType,
1844 unsigned &Index,
1845 InitListExpr *StructuredList,
1846 unsigned &StructuredIndex) {
1847 if (Index >= IList->getNumInits()) {
1848 // FIXME: It would be wonderful if we could point at the actual member. In
1849 // general, it would be useful to pass location information down the stack,
1850 // so that we know the location (or decl) of the "current object" being
1851 // initialized.
1852 if (!VerifyOnly)
1853 SemaRef.Diag(IList->getBeginLoc(),
1854 diag::err_init_reference_member_uninitialized)
1855 << DeclType << IList->getSourceRange();
1856 hadError = true;
1857 ++Index;
1858 ++StructuredIndex;
1859 return;
1860 }
1861
1862 Expr *expr = IList->getInit(Index);
1863 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1864 if (!VerifyOnly)
1865 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1866 << DeclType << IList->getSourceRange();
1867 hadError = true;
1868 ++Index;
1869 ++StructuredIndex;
1870 return;
1871 }
1872
1874 if (VerifyOnly) {
1875 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1876 Result = getDummyInit();
1877 else
1878 Result = ExprError();
1879 } else {
1880 Result =
1881 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1882 /*TopLevelOfInitList=*/true);
1883 }
1884
1885 if (Result.isInvalid())
1886 hadError = true;
1887
1888 expr = Result.getAs<Expr>();
1889 // FIXME: Why are we updating the syntactic init list?
1890 if (!VerifyOnly && expr)
1891 IList->setInit(Index, expr);
1892
1893 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1894 ++Index;
1895 if (AggrDeductionCandidateParamTypes)
1896 AggrDeductionCandidateParamTypes->push_back(DeclType);
1897}
1898
1899void InitListChecker::CheckMatrixType(const InitializedEntity &Entity,
1900 InitListExpr *IList, QualType DeclType,
1901 unsigned &Index,
1902 InitListExpr *StructuredList,
1903 unsigned &StructuredIndex) {
1904 if (!SemaRef.getLangOpts().HLSL)
1905 return;
1906
1907 const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>();
1908
1909 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1910 // initializer list diagnostics. That means the execution should require
1911 // getNumElementsFlattened to equal getNumInits. In other words the execution
1912 // should never reach this point if this condition is not true".
1913 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1914 "Inits must equal Matrix element count");
1915
1916 QualType ElemTy = MT->getElementType();
1917
1918 Index = 0;
1919 InitializedEntity Element =
1921
1922 while (Index < IList->getNumInits()) {
1923 // Not a sublist: just consume directly.
1924 // Note: In HLSL, elements of the InitListExpr are in row-major order, so no
1925 // change is needed to the Index.
1926 Element.setElementIndex(Index);
1927 CheckSubElementType(Element, IList, ElemTy, Index, StructuredList,
1928 StructuredIndex);
1929 }
1930}
1931
1932void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1933 InitListExpr *IList, QualType DeclType,
1934 unsigned &Index,
1935 InitListExpr *StructuredList,
1936 unsigned &StructuredIndex) {
1937 const VectorType *VT = DeclType->castAs<VectorType>();
1938 unsigned maxElements = VT->getNumElements();
1939 unsigned numEltsInit = 0;
1940 QualType elementType = VT->getElementType();
1941
1942 if (Index >= IList->getNumInits()) {
1943 // Make sure the element type can be value-initialized.
1944 CheckEmptyInitializable(
1946 IList->getEndLoc());
1947 return;
1948 }
1949
1950 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1951 // If the initializing element is a vector, try to copy-initialize
1952 // instead of breaking it apart (which is doomed to failure anyway).
1953 Expr *Init = IList->getInit(Index);
1954 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1956 if (VerifyOnly) {
1957 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1958 Result = getDummyInit();
1959 else
1960 Result = ExprError();
1961 } else {
1962 Result =
1963 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1964 /*TopLevelOfInitList=*/true);
1965 }
1966
1967 Expr *ResultExpr = nullptr;
1968 if (Result.isInvalid())
1969 hadError = true; // types weren't compatible.
1970 else {
1971 ResultExpr = Result.getAs<Expr>();
1972
1973 if (ResultExpr != Init && !VerifyOnly) {
1974 // The type was promoted, update initializer list.
1975 // FIXME: Why are we updating the syntactic init list?
1976 IList->setInit(Index, ResultExpr);
1977 }
1978 }
1979 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1980 ++Index;
1981 if (AggrDeductionCandidateParamTypes)
1982 AggrDeductionCandidateParamTypes->push_back(elementType);
1983 return;
1984 }
1985
1986 InitializedEntity ElementEntity =
1988
1989 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1990 // Don't attempt to go past the end of the init list
1991 if (Index >= IList->getNumInits()) {
1992 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1993 break;
1994 }
1995
1996 ElementEntity.setElementIndex(Index);
1997 CheckSubElementType(ElementEntity, IList, elementType, Index,
1998 StructuredList, StructuredIndex);
1999 }
2000
2001 if (VerifyOnly)
2002 return;
2003
2004 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
2005 const VectorType *T = Entity.getType()->castAs<VectorType>();
2006 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2007 T->getVectorKind() == VectorKind::NeonPoly)) {
2008 // The ability to use vector initializer lists is a GNU vector extension
2009 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2010 // endian machines it works fine, however on big endian machines it
2011 // exhibits surprising behaviour:
2012 //
2013 // uint32x2_t x = {42, 64};
2014 // return vget_lane_u32(x, 0); // Will return 64.
2015 //
2016 // Because of this, explicitly call out that it is non-portable.
2017 //
2018 SemaRef.Diag(IList->getBeginLoc(),
2019 diag::warn_neon_vector_initializer_non_portable);
2020
2021 const char *typeCode;
2022 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
2023
2024 if (elementType->isFloatingType())
2025 typeCode = "f";
2026 else if (elementType->isSignedIntegerType())
2027 typeCode = "s";
2028 else if (elementType->isUnsignedIntegerType())
2029 typeCode = "u";
2030 else if (elementType->isMFloat8Type())
2031 typeCode = "mf";
2032 else
2033 llvm_unreachable("Invalid element type!");
2034
2035 SemaRef.Diag(IList->getBeginLoc(),
2036 SemaRef.Context.getTypeSize(VT) > 64
2037 ? diag::note_neon_vector_initializer_non_portable_q
2038 : diag::note_neon_vector_initializer_non_portable)
2039 << typeCode << typeSize;
2040 }
2041
2042 return;
2043 }
2044
2045 InitializedEntity ElementEntity =
2047
2048 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2049 for (unsigned i = 0; i < maxElements; ++i) {
2050 // Don't attempt to go past the end of the init list
2051 if (Index >= IList->getNumInits())
2052 break;
2053
2054 ElementEntity.setElementIndex(Index);
2055
2056 QualType IType = IList->getInit(Index)->getType();
2057 if (!IType->isVectorType()) {
2058 CheckSubElementType(ElementEntity, IList, elementType, Index,
2059 StructuredList, StructuredIndex);
2060 ++numEltsInit;
2061 } else {
2062 QualType VecType;
2063 const VectorType *IVT = IType->castAs<VectorType>();
2064 unsigned numIElts = IVT->getNumElements();
2065
2066 if (IType->isExtVectorType())
2067 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2068 else
2069 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2070 IVT->getVectorKind());
2071 CheckSubElementType(ElementEntity, IList, VecType, Index,
2072 StructuredList, StructuredIndex);
2073 numEltsInit += numIElts;
2074 }
2075 }
2076
2077 // OpenCL and HLSL require all elements to be initialized.
2078 if (numEltsInit != maxElements) {
2079 if (!VerifyOnly)
2080 SemaRef.Diag(IList->getBeginLoc(),
2081 diag::err_vector_incorrect_num_elements)
2082 << (numEltsInit < maxElements) << maxElements << numEltsInit
2083 << /*initialization*/ 0;
2084 hadError = true;
2085 }
2086}
2087
2088/// Check if the type of a class element has an accessible destructor, and marks
2089/// it referenced. Returns true if we shouldn't form a reference to the
2090/// destructor.
2091///
2092/// Aggregate initialization requires a class element's destructor be
2093/// accessible per 11.6.1 [dcl.init.aggr]:
2094///
2095/// The destructor for each element of class type is potentially invoked
2096/// (15.4 [class.dtor]) from the context where the aggregate initialization
2097/// occurs.
2099 Sema &SemaRef) {
2100 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2101 // Bail out on incomplete record types: a forward-declared class has no
2102 // destructor to look up, and `LookupDestructor` (via `LookupSpecialMember`)
2103 // asserts that the record is fully defined. Error recovery for init lists
2104 // of incomplete element types reaches this point even after the parser has
2105 // already diagnosed the incompleteness.
2106 if (!CXXRD || !CXXRD->hasDefinition())
2107 return false;
2108
2110 if (!Destructor)
2111 return false;
2112
2113 SemaRef.CheckDestructorAccess(Loc, Destructor,
2114 SemaRef.PDiag(diag::err_access_dtor_temp)
2115 << ElementType);
2116 SemaRef.MarkFunctionReferenced(Loc, Destructor);
2117 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2118}
2119
2120static bool
2122 const InitializedEntity &Entity,
2123 ASTContext &Context) {
2124 QualType InitType = Entity.getType();
2125 const InitializedEntity *Parent = &Entity;
2126
2127 while (Parent) {
2128 InitType = Parent->getType();
2129 Parent = Parent->getParent();
2130 }
2131
2132 // Only one initializer, it's an embed and the types match;
2133 EmbedExpr *EE =
2134 ExprList.size() == 1
2135 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2136 : nullptr;
2137 if (!EE)
2138 return false;
2139
2140 if (InitType->isArrayType()) {
2141 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2143 return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2144 }
2145 return false;
2146}
2147
2148void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2149 InitListExpr *IList, QualType &DeclType,
2150 llvm::APSInt elementIndex,
2151 bool SubobjectIsDesignatorContext,
2152 unsigned &Index,
2153 InitListExpr *StructuredList,
2154 unsigned &StructuredIndex) {
2155 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2156
2157 if (!VerifyOnly) {
2158 if (checkDestructorReference(arrayType->getElementType(),
2159 IList->getEndLoc(), SemaRef)) {
2160 hadError = true;
2161 return;
2162 }
2163 }
2164
2165 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2166 SemaRef.Context)) {
2167 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2168 IList->setInit(0, Embed->getDataStringLiteral());
2169 }
2170
2171 // Check for the special-case of initializing an array with a string.
2172 if (Index < IList->getNumInits()) {
2173 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2174 SIF_None) {
2175 // We place the string literal directly into the resulting
2176 // initializer list. This is the only place where the structure
2177 // of the structured initializer list doesn't match exactly,
2178 // because doing so would involve allocating one character
2179 // constant for each string.
2180 // FIXME: Should we do these checks in verify-only mode too?
2181 if (!VerifyOnly)
2183 IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2184 SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2185 if (StructuredList) {
2186 UpdateStructuredListElement(StructuredList, StructuredIndex,
2187 IList->getInit(Index));
2188 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2189 }
2190 ++Index;
2191 if (AggrDeductionCandidateParamTypes)
2192 AggrDeductionCandidateParamTypes->push_back(DeclType);
2193 return;
2194 }
2195 }
2196 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2197 // Check for VLAs; in standard C it would be possible to check this
2198 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2199 // them in all sorts of strange places).
2200 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2201 if (!VerifyOnly) {
2202 // C23 6.7.10p4: An entity of variable length array type shall not be
2203 // initialized except by an empty initializer.
2204 //
2205 // The C extension warnings are issued from ParseBraceInitializer() and
2206 // do not need to be issued here. However, we continue to issue an error
2207 // in the case there are initializers or we are compiling C++. We allow
2208 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2209 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2210 // FIXME: should we allow this construct in C++ when it makes sense to do
2211 // so?
2212 if (HasErr)
2213 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2214 diag::err_variable_object_no_init)
2215 << VAT->getSizeExpr()->getSourceRange();
2216 }
2217 hadError = HasErr;
2218 ++Index;
2219 ++StructuredIndex;
2220 return;
2221 }
2222
2223 // We might know the maximum number of elements in advance.
2224 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2225 elementIndex.isUnsigned());
2226 bool maxElementsKnown = false;
2227 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2228 maxElements = CAT->getSize();
2229 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2230 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2231 maxElementsKnown = true;
2232 }
2233
2234 QualType elementType = arrayType->getElementType();
2235 while (Index < IList->getNumInits()) {
2236 Expr *Init = IList->getInit(Index);
2237 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2238 // If we're not the subobject that matches up with the '{' for
2239 // the designator, we shouldn't be handling the
2240 // designator. Return immediately.
2241 if (!SubobjectIsDesignatorContext)
2242 return;
2243
2244 // Handle this designated initializer. elementIndex will be
2245 // updated to be the next array element we'll initialize.
2246 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2247 DeclType, nullptr, &elementIndex, Index,
2248 StructuredList, StructuredIndex, true,
2249 false)) {
2250 hadError = true;
2251 continue;
2252 }
2253
2254 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2255 maxElements = maxElements.extend(elementIndex.getBitWidth());
2256 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2257 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2258 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2259
2260 // If the array is of incomplete type, keep track of the number of
2261 // elements in the initializer.
2262 if (!maxElementsKnown && elementIndex > maxElements)
2263 maxElements = elementIndex;
2264
2265 continue;
2266 }
2267
2268 // If we know the maximum number of elements, and we've already
2269 // hit it, stop consuming elements in the initializer list.
2270 if (maxElementsKnown && elementIndex == maxElements)
2271 break;
2272
2273 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2274 SemaRef.Context, StructuredIndex, Entity);
2275 ElementEntity.setElementIndex(elementIndex.getExtValue());
2276
2277 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2278 // Check this element.
2279 CheckSubElementType(ElementEntity, IList, elementType, Index,
2280 StructuredList, StructuredIndex);
2281 ++elementIndex;
2282 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2283 if (CurEmbed) {
2284 elementIndex =
2285 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2286 } else {
2287 auto Embed = cast<EmbedExpr>(Init);
2288 elementIndex = elementIndex + Embed->getDataElementCount() -
2289 EmbedElementIndexBeforeInit - 1;
2290 }
2291 }
2292
2293 // If the array is of incomplete type, keep track of the number of
2294 // elements in the initializer.
2295 if (!maxElementsKnown && elementIndex > maxElements)
2296 maxElements = elementIndex;
2297 }
2298 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2299 // If this is an incomplete array type, the actual type needs to
2300 // be calculated here.
2301 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2302 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2303 // Sizing an array implicitly to zero is not allowed by ISO C,
2304 // but is supported by GNU.
2305 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2306 }
2307
2308 DeclType = SemaRef.Context.getConstantArrayType(
2309 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2310 }
2311 if (!hadError) {
2312 // If there are any members of the array that get value-initialized, check
2313 // that is possible. That happens if we know the bound and don't have
2314 // enough elements, or if we're performing an array new with an unknown
2315 // bound.
2316 if ((maxElementsKnown && elementIndex < maxElements) ||
2317 Entity.isVariableLengthArrayNew())
2318 CheckEmptyInitializable(
2320 IList->getEndLoc());
2321 }
2322}
2323
2324bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2325 Expr *InitExpr,
2326 FieldDecl *Field,
2327 bool TopLevelObject) {
2328 // Handle GNU flexible array initializers.
2329 unsigned FlexArrayDiag;
2330 if (isa<InitListExpr>(InitExpr) &&
2331 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2332 // Empty flexible array init always allowed as an extension
2333 FlexArrayDiag = diag::ext_flexible_array_init;
2334 } else if (!TopLevelObject) {
2335 // Disallow flexible array init on non-top-level object
2336 FlexArrayDiag = diag::err_flexible_array_init;
2337 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2338 // Disallow flexible array init on anything which is not a variable.
2339 FlexArrayDiag = diag::err_flexible_array_init;
2340 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2341 // Disallow flexible array init on local variables.
2342 FlexArrayDiag = diag::err_flexible_array_init;
2343 } else {
2344 // Allow other cases.
2345 FlexArrayDiag = diag::ext_flexible_array_init;
2346 }
2347
2348 if (!VerifyOnly) {
2349 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2350 << InitExpr->getBeginLoc();
2351 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2352 << Field;
2353 }
2354
2355 return FlexArrayDiag != diag::ext_flexible_array_init;
2356}
2357
2358static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2359 return StructuredList && StructuredList->getNumInits() == 1U;
2360}
2361
2362void InitListChecker::CheckStructUnionTypes(
2363 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2365 bool SubobjectIsDesignatorContext, unsigned &Index,
2366 InitListExpr *StructuredList, unsigned &StructuredIndex,
2367 bool TopLevelObject) {
2368 const RecordDecl *RD = DeclType->getAsRecordDecl();
2369
2370 // If the record is invalid, some of it's members are invalid. To avoid
2371 // confusion, we forgo checking the initializer for the entire record.
2372 if (RD->isInvalidDecl()) {
2373 // Assume it was supposed to consume a single initializer.
2374 ++Index;
2375 hadError = true;
2376 return;
2377 }
2378
2379 if (RD->isUnion() && IList->getNumInits() == 0) {
2380 if (!VerifyOnly)
2381 for (FieldDecl *FD : RD->fields()) {
2382 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2383 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2384 hadError = true;
2385 return;
2386 }
2387 }
2388
2389 // If there's a default initializer, use it.
2390 if (isa<CXXRecordDecl>(RD) &&
2391 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2392 if (!StructuredList)
2393 return;
2394 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2395 Field != FieldEnd; ++Field) {
2396 if (Field->hasInClassInitializer() ||
2397 (Field->isAnonymousStructOrUnion() &&
2398 Field->getType()
2399 ->castAsCXXRecordDecl()
2400 ->hasInClassInitializer())) {
2401 StructuredList->setInitializedFieldInUnion(*Field);
2402 // FIXME: Actually build a CXXDefaultInitExpr?
2403 return;
2404 }
2405 }
2406 llvm_unreachable("Couldn't find in-class initializer");
2407 }
2408
2409 // Value-initialize the first member of the union that isn't an unnamed
2410 // bitfield.
2411 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2412 Field != FieldEnd; ++Field) {
2413 if (!Field->isUnnamedBitField()) {
2414 CheckEmptyInitializable(
2415 InitializedEntity::InitializeMember(*Field, &Entity),
2416 IList->getEndLoc());
2417 if (StructuredList)
2418 StructuredList->setInitializedFieldInUnion(*Field);
2419 break;
2420 }
2421 }
2422 return;
2423 }
2424
2425 bool InitializedSomething = false;
2426
2427 // If we have any base classes, they are initialized prior to the fields.
2428 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2429 auto &Base = *I;
2430 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2431
2432 // Designated inits always initialize fields, so if we see one, all
2433 // remaining base classes have no explicit initializer.
2434 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2435 Init = nullptr;
2436
2437 // C++ [over.match.class.deduct]p1.6:
2438 // each non-trailing aggregate element that is a pack expansion is assumed
2439 // to correspond to no elements of the initializer list, and (1.7) a
2440 // trailing aggregate element that is a pack expansion is assumed to
2441 // correspond to all remaining elements of the initializer list (if any).
2442
2443 // C++ [over.match.class.deduct]p1.9:
2444 // ... except that additional parameter packs of the form P_j... are
2445 // inserted into the parameter list in their original aggregate element
2446 // position corresponding to each non-trailing aggregate element of
2447 // type P_j that was skipped because it was a parameter pack, and the
2448 // trailing sequence of parameters corresponding to a trailing
2449 // aggregate element that is a pack expansion (if any) is replaced
2450 // by a single parameter of the form T_n....
2451 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2452 AggrDeductionCandidateParamTypes->push_back(
2453 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2454
2455 // Trailing pack expansion
2456 if (I + 1 == E && RD->field_empty()) {
2457 if (Index < IList->getNumInits())
2458 Index = IList->getNumInits();
2459 return;
2460 }
2461
2462 continue;
2463 }
2464
2465 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2466 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2467 SemaRef.Context, &Base, false, &Entity);
2468 if (Init) {
2469 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2470 StructuredList, StructuredIndex);
2471 InitializedSomething = true;
2472 } else {
2473 CheckEmptyInitializable(BaseEntity, InitLoc);
2474 }
2475
2476 if (!VerifyOnly)
2477 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2478 hadError = true;
2479 return;
2480 }
2481 }
2482
2483 // If structDecl is a forward declaration, this loop won't do
2484 // anything except look at designated initializers; That's okay,
2485 // because an error should get printed out elsewhere. It might be
2486 // worthwhile to skip over the rest of the initializer, though.
2487 RecordDecl::field_iterator FieldEnd = RD->field_end();
2488 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2489 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2490 });
2491 bool HasDesignatedInit = false;
2492
2493 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2494
2495 while (Index < IList->getNumInits()) {
2496 Expr *Init = IList->getInit(Index);
2497 SourceLocation InitLoc = Init->getBeginLoc();
2498
2499 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2500 // If we're not the subobject that matches up with the '{' for
2501 // the designator, we shouldn't be handling the
2502 // designator. Return immediately.
2503 if (!SubobjectIsDesignatorContext)
2504 return;
2505
2506 HasDesignatedInit = true;
2507
2508 // Handle this designated initializer. Field will be updated to
2509 // the next field that we'll be initializing.
2510 bool DesignatedInitFailed = CheckDesignatedInitializer(
2511 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2512 StructuredList, StructuredIndex, true, TopLevelObject);
2513 if (DesignatedInitFailed)
2514 hadError = true;
2515
2516 // Find the field named by the designated initializer.
2517 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2518 if (!VerifyOnly && D->isFieldDesignator()) {
2519 FieldDecl *F = D->getFieldDecl();
2520 InitializedFields.insert(F);
2521 if (!DesignatedInitFailed) {
2522 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2523 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2524 hadError = true;
2525 return;
2526 }
2527 }
2528 }
2529
2530 InitializedSomething = true;
2531 continue;
2532 }
2533
2534 // Check if this is an initializer of forms:
2535 //
2536 // struct foo f = {};
2537 // struct foo g = {0};
2538 //
2539 // These are okay for randomized structures. [C99 6.7.8p19]
2540 //
2541 // Also, if there is only one element in the structure, we allow something
2542 // like this, because it's really not randomized in the traditional sense.
2543 //
2544 // struct foo h = {bar};
2545 auto IsZeroInitializer = [&](const Expr *I) {
2546 if (IList->getNumInits() == 1) {
2547 if (NumRecordDecls == 1)
2548 return true;
2549 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2550 return IL->getValue().isZero();
2551 }
2552 return false;
2553 };
2554
2555 // Don't allow non-designated initializers on randomized structures.
2556 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2557 if (!VerifyOnly)
2558 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2559 hadError = true;
2560 break;
2561 }
2562
2563 if (Field == FieldEnd) {
2564 // We've run out of fields. We're done.
2565 break;
2566 }
2567
2568 // We've already initialized a member of a union. We can stop entirely.
2569 if (InitializedSomething && RD->isUnion())
2570 return;
2571
2572 // Stop if we've hit a flexible array member.
2573 if (Field->getType()->isIncompleteArrayType())
2574 break;
2575
2576 if (Field->isUnnamedBitField()) {
2577 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2578 ++Field;
2579 continue;
2580 }
2581
2582 // Make sure we can use this declaration.
2583 bool InvalidUse;
2584 if (VerifyOnly)
2585 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2586 else
2587 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2588 *Field, IList->getInit(Index)->getBeginLoc());
2589 if (InvalidUse) {
2590 ++Index;
2591 ++Field;
2592 hadError = true;
2593 continue;
2594 }
2595
2596 if (!VerifyOnly) {
2597 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2598 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2599 hadError = true;
2600 return;
2601 }
2602 }
2603
2604 InitializedEntity MemberEntity =
2605 InitializedEntity::InitializeMember(*Field, &Entity);
2606 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2607 StructuredList, StructuredIndex);
2608 InitializedSomething = true;
2609 InitializedFields.insert(*Field);
2610 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2611 // Initialize the first field within the union.
2612 StructuredList->setInitializedFieldInUnion(*Field);
2613 }
2614
2615 ++Field;
2616 }
2617
2618 // Emit warnings for missing struct field initializers.
2619 // This check is disabled for designated initializers in C.
2620 // This matches gcc behaviour.
2621 bool IsCDesignatedInitializer =
2622 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2623 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2624 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2625 !IsCDesignatedInitializer) {
2626 // It is possible we have one or more unnamed bitfields remaining.
2627 // Find first (if any) named field and emit warning.
2628 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2629 : Field,
2630 end = RD->field_end();
2631 it != end; ++it) {
2632 if (HasDesignatedInit && InitializedFields.count(*it))
2633 continue;
2634
2635 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2636 !it->getType()->isIncompleteArrayType()) {
2637 auto Diag = HasDesignatedInit
2638 ? diag::warn_missing_designated_field_initializers
2639 : diag::warn_missing_field_initializers;
2640 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2641 break;
2642 }
2643 }
2644 }
2645
2646 // Check that any remaining fields can be value-initialized if we're not
2647 // building a structured list. (If we are, we'll check this later.)
2648 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2649 !Field->getType()->isIncompleteArrayType()) {
2650 for (; Field != FieldEnd && !hadError; ++Field) {
2651 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2652 CheckEmptyInitializable(
2653 InitializedEntity::InitializeMember(*Field, &Entity),
2654 IList->getEndLoc());
2655 }
2656 }
2657
2658 // Check that the types of the remaining fields have accessible destructors.
2659 if (!VerifyOnly) {
2660 // If the initializer expression has a designated initializer, check the
2661 // elements for which a designated initializer is not provided too.
2662 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2663 : Field;
2664 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2665 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2666 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2667 hadError = true;
2668 return;
2669 }
2670 }
2671 }
2672
2673 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2674 Index >= IList->getNumInits())
2675 return;
2676
2677 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2678 TopLevelObject)) {
2679 hadError = true;
2680 ++Index;
2681 return;
2682 }
2683
2684 InitializedEntity MemberEntity =
2685 InitializedEntity::InitializeMember(*Field, &Entity);
2686
2687 if (isa<InitListExpr>(IList->getInit(Index)) ||
2688 AggrDeductionCandidateParamTypes)
2689 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2690 StructuredList, StructuredIndex);
2691 else
2692 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2693 StructuredList, StructuredIndex);
2694
2695 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2696 // Initialize the first field within the union.
2697 StructuredList->setInitializedFieldInUnion(*Field);
2698 }
2699}
2700
2701/// Expand a field designator that refers to a member of an
2702/// anonymous struct or union into a series of field designators that
2703/// refers to the field within the appropriate subobject.
2704///
2706 DesignatedInitExpr *DIE,
2707 unsigned DesigIdx,
2708 IndirectFieldDecl *IndirectField) {
2710
2711 // Build the replacement designators.
2712 SmallVector<Designator, 4> Replacements;
2713 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2714 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2715 if (PI + 1 == PE)
2716 Replacements.push_back(Designator::CreateFieldDesignator(
2717 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2718 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2719 else
2720 Replacements.push_back(Designator::CreateFieldDesignator(
2721 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2722 assert(isa<FieldDecl>(*PI));
2723 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2724 }
2725
2726 // Expand the current designator into the set of replacement
2727 // designators, so we have a full subobject path down to where the
2728 // member of the anonymous struct/union is actually stored.
2729 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2730 &Replacements[0] + Replacements.size());
2731}
2732
2734 DesignatedInitExpr *DIE) {
2735 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2736 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2737 for (unsigned I = 0; I < NumIndexExprs; ++I)
2738 IndexExprs[I] = DIE->getSubExpr(I + 1);
2739 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2740 IndexExprs,
2741 DIE->getEqualOrColonLoc(),
2742 DIE->usesGNUSyntax(), DIE->getInit());
2743}
2744
2745namespace {
2746
2747// Callback to only accept typo corrections that are for field members of
2748// the given struct or union.
2749class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2750 public:
2751 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2752 : Record(RD) {}
2753
2754 bool ValidateCandidate(const TypoCorrection &candidate) override {
2755 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2756 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2757 }
2758
2759 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2760 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2761 }
2762
2763 private:
2764 const RecordDecl *Record;
2765};
2766
2767} // end anonymous namespace
2768
2769/// Check the well-formedness of a C99 designated initializer.
2770///
2771/// Determines whether the designated initializer @p DIE, which
2772/// resides at the given @p Index within the initializer list @p
2773/// IList, is well-formed for a current object of type @p DeclType
2774/// (C99 6.7.8). The actual subobject that this designator refers to
2775/// within the current subobject is returned in either
2776/// @p NextField or @p NextElementIndex (whichever is appropriate).
2777///
2778/// @param IList The initializer list in which this designated
2779/// initializer occurs.
2780///
2781/// @param DIE The designated initializer expression.
2782///
2783/// @param DesigIdx The index of the current designator.
2784///
2785/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2786/// into which the designation in @p DIE should refer.
2787///
2788/// @param NextField If non-NULL and the first designator in @p DIE is
2789/// a field, this will be set to the field declaration corresponding
2790/// to the field named by the designator. On input, this is expected to be
2791/// the next field that would be initialized in the absence of designation,
2792/// if the complete object being initialized is a struct.
2793///
2794/// @param NextElementIndex If non-NULL and the first designator in @p
2795/// DIE is an array designator or GNU array-range designator, this
2796/// will be set to the last index initialized by this designator.
2797///
2798/// @param Index Index into @p IList where the designated initializer
2799/// @p DIE occurs.
2800///
2801/// @param StructuredList The initializer list expression that
2802/// describes all of the subobject initializers in the order they'll
2803/// actually be initialized.
2804///
2805/// @returns true if there was an error, false otherwise.
2806bool
2807InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2808 InitListExpr *IList,
2809 DesignatedInitExpr *DIE,
2810 unsigned DesigIdx,
2811 QualType &CurrentObjectType,
2812 RecordDecl::field_iterator *NextField,
2813 llvm::APSInt *NextElementIndex,
2814 unsigned &Index,
2815 InitListExpr *StructuredList,
2816 unsigned &StructuredIndex,
2817 bool FinishSubobjectInit,
2818 bool TopLevelObject) {
2819 if (DesigIdx == DIE->size()) {
2820 // C++20 designated initialization can result in direct-list-initialization
2821 // of the designated subobject. This is the only way that we can end up
2822 // performing direct initialization as part of aggregate initialization, so
2823 // it needs special handling.
2824 if (DIE->isDirectInit()) {
2825 Expr *Init = DIE->getInit();
2826 assert(isa<InitListExpr>(Init) &&
2827 "designator result in direct non-list initialization?");
2828 InitializationKind Kind = InitializationKind::CreateDirectList(
2829 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2830 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2831 /*TopLevelOfInitList*/ true);
2832 if (StructuredList) {
2833 ExprResult Result = VerifyOnly
2834 ? getDummyInit()
2835 : Seq.Perform(SemaRef, Entity, Kind, Init);
2836 UpdateStructuredListElement(StructuredList, StructuredIndex,
2837 Result.get());
2838 }
2839 ++Index;
2840 if (AggrDeductionCandidateParamTypes)
2841 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2842 return !Seq;
2843 }
2844
2845 // Check the actual initialization for the designated object type.
2846 bool prevHadError = hadError;
2847
2848 // Temporarily remove the designator expression from the
2849 // initializer list that the child calls see, so that we don't try
2850 // to re-process the designator.
2851 unsigned OldIndex = Index;
2852 auto *OldDIE =
2853 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2854 if (!OldDIE)
2855 OldDIE = DIE;
2856 IList->setInit(OldIndex, OldDIE->getInit());
2857
2858 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2859 StructuredIndex, /*DirectlyDesignated=*/true);
2860
2861 // Restore the designated initializer expression in the syntactic
2862 // form of the initializer list.
2863 if (IList->getInit(OldIndex) != OldDIE->getInit())
2864 OldDIE->setInit(IList->getInit(OldIndex));
2865 IList->setInit(OldIndex, OldDIE);
2866
2867 return hadError && !prevHadError;
2868 }
2869
2870 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2871 bool IsFirstDesignator = (DesigIdx == 0);
2872 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2873 // Determine the structural initializer list that corresponds to the
2874 // current subobject.
2875 if (IsFirstDesignator)
2876 StructuredList = FullyStructuredList;
2877 else {
2878 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2879 StructuredList->getInit(StructuredIndex) : nullptr;
2880 if (!ExistingInit && StructuredList->hasArrayFiller())
2881 ExistingInit = StructuredList->getArrayFiller();
2882
2883 if (!ExistingInit)
2884 StructuredList = getStructuredSubobjectInit(
2885 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2886 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2887 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2888 StructuredList = Result;
2889 else {
2890 // We are creating an initializer list that initializes the
2891 // subobjects of the current object, but there was already an
2892 // initialization that completely initialized the current
2893 // subobject, e.g., by a compound literal:
2894 //
2895 // struct X { int a, b; };
2896 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2897 //
2898 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2899 // designated initializer re-initializes only its current object
2900 // subobject [0].b.
2901 diagnoseInitOverride(ExistingInit,
2902 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2903 /*UnionOverride=*/false,
2904 /*FullyOverwritten=*/false);
2905
2906 if (!VerifyOnly) {
2907 if (DesignatedInitUpdateExpr *E =
2908 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2909 StructuredList = E->getUpdater();
2910 else {
2911 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2912 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2913 ExistingInit, DIE->getEndLoc());
2914 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2915 StructuredList = DIUE->getUpdater();
2916 }
2917 } else {
2918 // We don't need to track the structured representation of a
2919 // designated init update of an already-fully-initialized object in
2920 // verify-only mode. The only reason we would need the structure is
2921 // to determine where the uninitialized "holes" are, and in this
2922 // case, we know there aren't any and we can't introduce any.
2923 StructuredList = nullptr;
2924 }
2925 }
2926 }
2927 }
2928
2929 if (D->isFieldDesignator()) {
2930 // C99 6.7.8p7:
2931 //
2932 // If a designator has the form
2933 //
2934 // . identifier
2935 //
2936 // then the current object (defined below) shall have
2937 // structure or union type and the identifier shall be the
2938 // name of a member of that type.
2939 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2940 if (!RD) {
2941 SourceLocation Loc = D->getDotLoc();
2942 if (Loc.isInvalid())
2943 Loc = D->getFieldLoc();
2944 if (!VerifyOnly)
2945 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2946 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2947 ++Index;
2948 return true;
2949 }
2950
2951 FieldDecl *KnownField = D->getFieldDecl();
2952 if (!KnownField) {
2953 const IdentifierInfo *FieldName = D->getFieldName();
2954 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2955 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2956 KnownField = FD;
2957 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2958 // In verify mode, don't modify the original.
2959 if (VerifyOnly)
2960 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2961 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2962 D = DIE->getDesignator(DesigIdx);
2963 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2964 }
2965 if (!KnownField) {
2966 if (VerifyOnly) {
2967 ++Index;
2968 return true; // No typo correction when just trying this out.
2969 }
2970
2971 // We found a placeholder variable
2972 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2973 FieldName)) {
2974 ++Index;
2975 return true;
2976 }
2977 // Name lookup found something, but it wasn't a field.
2978 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2979 !Lookup.empty()) {
2980 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2981 << FieldName;
2982 SemaRef.Diag(Lookup.front()->getLocation(),
2983 diag::note_field_designator_found);
2984 ++Index;
2985 return true;
2986 }
2987
2988 // Name lookup didn't find anything.
2989 // Determine whether this was a typo for another field name.
2990 FieldInitializerValidatorCCC CCC(RD);
2991 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2992 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2993 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2994 CorrectTypoKind::ErrorRecovery, RD)) {
2995 SemaRef.diagnoseTypo(
2996 Corrected,
2997 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2998 << FieldName << CurrentObjectType);
2999 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
3000 hadError = true;
3001 } else {
3002 // Typo correction didn't find anything.
3003 SourceLocation Loc = D->getFieldLoc();
3004
3005 // The loc can be invalid with a "null" designator (i.e. an anonymous
3006 // union/struct). Do our best to approximate the location.
3007 if (Loc.isInvalid())
3008 Loc = IList->getBeginLoc();
3009
3010 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
3011 << FieldName << CurrentObjectType << DIE->getSourceRange();
3012 ++Index;
3013 return true;
3014 }
3015 }
3016 }
3017
3018 unsigned NumBases = 0;
3019 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3020 NumBases = CXXRD->getNumBases();
3021
3022 unsigned FieldIndex = NumBases;
3023
3024 for (auto *FI : RD->fields()) {
3025 if (FI->isUnnamedBitField())
3026 continue;
3027 if (declaresSameEntity(KnownField, FI)) {
3028 KnownField = FI;
3029 break;
3030 }
3031 ++FieldIndex;
3032 }
3033
3035 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3036
3037 // All of the fields of a union are located at the same place in
3038 // the initializer list.
3039 if (RD->isUnion()) {
3040 FieldIndex = 0;
3041 if (StructuredList) {
3042 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3043 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3044 assert(StructuredList->getNumInits() == 1
3045 && "A union should never have more than one initializer!");
3046
3047 Expr *ExistingInit = StructuredList->getInit(0);
3048 if (ExistingInit) {
3049 // We're about to throw away an initializer, emit warning.
3050 diagnoseInitOverride(
3051 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3052 /*UnionOverride=*/true,
3053 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3054 : true);
3055 }
3056
3057 // remove existing initializer
3058 StructuredList->resizeInits(SemaRef.Context, 0);
3059 StructuredList->setInitializedFieldInUnion(nullptr);
3060 }
3061
3062 StructuredList->setInitializedFieldInUnion(*Field);
3063 }
3064 }
3065
3066 // Make sure we can use this declaration.
3067 bool InvalidUse;
3068 if (VerifyOnly)
3069 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3070 else
3071 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3072 if (InvalidUse) {
3073 ++Index;
3074 return true;
3075 }
3076
3077 // C++20 [dcl.init.list]p3:
3078 // The ordered identifiers in the designators of the designated-
3079 // initializer-list shall form a subsequence of the ordered identifiers
3080 // in the direct non-static data members of T.
3081 //
3082 // Note that this is not a condition on forming the aggregate
3083 // initialization, only on actually performing initialization,
3084 // so it is not checked in VerifyOnly mode.
3085 //
3086 // FIXME: This is the only reordering diagnostic we produce, and it only
3087 // catches cases where we have a top-level field designator that jumps
3088 // backwards. This is the only such case that is reachable in an
3089 // otherwise-valid C++20 program, so is the only case that's required for
3090 // conformance, but for consistency, we should diagnose all the other
3091 // cases where a designator takes us backwards too.
3092 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3093 NextField &&
3094 (*NextField == RD->field_end() ||
3095 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3096 // Find the field that we just initialized.
3097 FieldDecl *PrevField = nullptr;
3098 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3099 if (FI->isUnnamedBitField())
3100 continue;
3101 if (*NextField != RD->field_end() &&
3102 declaresSameEntity(*FI, **NextField))
3103 break;
3104 PrevField = *FI;
3105 }
3106
3107 const auto GenerateDesignatedInitReorderingFixit =
3108 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3109 struct ReorderInfo {
3110 int Pos{};
3111 const Expr *InitExpr{};
3112 };
3113
3114 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3115 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3116
3117 const auto *CxxRecord =
3119
3120 for (const FieldDecl *Field : CxxRecord->fields())
3121 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3122
3123 for (const Expr *Init : IList->inits()) {
3124 if (const auto *DI =
3125 dyn_cast_if_present<DesignatedInitExpr>(Init)) {
3126 // We expect only one Designator
3127 if (DI->size() != 1)
3128 return;
3129
3130 const IdentifierInfo *const FieldName =
3131 DI->getDesignator(0)->getFieldName();
3132 // In case we have an unknown initializer in the source, not in
3133 // the record
3134 if (MemberNameInx.contains(FieldName))
3135 ReorderedInitExprs.emplace_back(
3136 ReorderInfo{MemberNameInx.at(FieldName), Init});
3137 }
3138 }
3139
3140 llvm::sort(ReorderedInitExprs,
3141 [](const ReorderInfo &A, const ReorderInfo &B) {
3142 return A.Pos < B.Pos;
3143 });
3144
3145 llvm::SmallString<128> FixedInitList{};
3146 SourceManager &SM = SemaRef.getSourceManager();
3147 const LangOptions &LangOpts = SemaRef.getLangOpts();
3148
3149 // In a derived Record, first n base-classes are initialized first.
3150 // They do not use designated init, so skip them
3151 const ArrayRef<clang::Expr *> IListInits =
3152 IList->inits().drop_front(CxxRecord->getNumBases());
3153 // loop over each existing expressions and apply replacement
3154 for (const auto &[OrigExpr, Repl] :
3155 llvm::zip(IListInits, ReorderedInitExprs)) {
3156 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3157 Repl.InitExpr->getSourceRange());
3158 const StringRef InitText =
3159 Lexer::getSourceText(CharRange, SM, LangOpts);
3160
3161 Diag << FixItHint::CreateReplacement(OrigExpr->getSourceRange(),
3162 InitText.str());
3163 }
3164 };
3165
3166 if (PrevField &&
3167 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3168 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3169 diag::ext_designated_init_reordered)
3170 << KnownField << PrevField << DIE->getSourceRange();
3171
3172 unsigned OldIndex = StructuredIndex - 1;
3173 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3174 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3175 auto Diag = SemaRef.Diag(PrevInit->getBeginLoc(),
3176 diag::note_previous_field_init)
3177 << PrevField << PrevInit->getSourceRange();
3178 GenerateDesignatedInitReorderingFixit(Diag);
3179 }
3180 }
3181 }
3182 }
3183
3184
3185 // Update the designator with the field declaration.
3186 if (!VerifyOnly)
3187 D->setFieldDecl(*Field);
3188
3189 // Make sure that our non-designated initializer list has space
3190 // for a subobject corresponding to this field.
3191 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3192 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3193
3194 // This designator names a flexible array member.
3195 if (Field->getType()->isIncompleteArrayType()) {
3196 bool Invalid = false;
3197 if ((DesigIdx + 1) != DIE->size()) {
3198 // We can't designate an object within the flexible array
3199 // member (because GCC doesn't allow it).
3200 if (!VerifyOnly) {
3201 DesignatedInitExpr::Designator *NextD
3202 = DIE->getDesignator(DesigIdx + 1);
3203 SemaRef.Diag(NextD->getBeginLoc(),
3204 diag::err_designator_into_flexible_array_member)
3205 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3206 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3207 << *Field;
3208 }
3209 Invalid = true;
3210 }
3211
3212 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3213 !isa<StringLiteral>(DIE->getInit())) {
3214 // The initializer is not an initializer list.
3215 if (!VerifyOnly) {
3216 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3217 diag::err_flexible_array_init_needs_braces)
3218 << DIE->getInit()->getSourceRange();
3219 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3220 << *Field;
3221 }
3222 Invalid = true;
3223 }
3224
3225 // Check GNU flexible array initializer.
3226 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3227 TopLevelObject))
3228 Invalid = true;
3229
3230 if (Invalid) {
3231 ++Index;
3232 return true;
3233 }
3234
3235 // Initialize the array.
3236 bool prevHadError = hadError;
3237 unsigned newStructuredIndex = FieldIndex;
3238 unsigned OldIndex = Index;
3239 IList->setInit(Index, DIE->getInit());
3240
3241 InitializedEntity MemberEntity =
3242 InitializedEntity::InitializeMember(*Field, &Entity);
3243 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3244 StructuredList, newStructuredIndex);
3245
3246 IList->setInit(OldIndex, DIE);
3247 if (hadError && !prevHadError) {
3248 ++Field;
3249 ++FieldIndex;
3250 if (NextField)
3251 *NextField = Field;
3252 StructuredIndex = FieldIndex;
3253 return true;
3254 }
3255 } else {
3256 // Recurse to check later designated subobjects.
3257 QualType FieldType = Field->getType();
3258 unsigned newStructuredIndex = FieldIndex;
3259
3260 InitializedEntity MemberEntity =
3261 InitializedEntity::InitializeMember(*Field, &Entity);
3262 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3263 FieldType, nullptr, nullptr, Index,
3264 StructuredList, newStructuredIndex,
3265 FinishSubobjectInit, false))
3266 return true;
3267 }
3268
3269 // Find the position of the next field to be initialized in this
3270 // subobject.
3271 ++Field;
3272 ++FieldIndex;
3273
3274 // If this the first designator, our caller will continue checking
3275 // the rest of this struct/class/union subobject.
3276 if (IsFirstDesignator) {
3277 if (Field != RD->field_end() && Field->isUnnamedBitField())
3278 ++Field;
3279
3280 if (NextField)
3281 *NextField = Field;
3282
3283 StructuredIndex = FieldIndex;
3284 return false;
3285 }
3286
3287 if (!FinishSubobjectInit)
3288 return false;
3289
3290 // We've already initialized something in the union; we're done.
3291 if (RD->isUnion())
3292 return hadError;
3293
3294 // Check the remaining fields within this class/struct/union subobject.
3295 bool prevHadError = hadError;
3296
3297 auto NoBases =
3300 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3301 false, Index, StructuredList, FieldIndex);
3302 return hadError && !prevHadError;
3303 }
3304
3305 // C99 6.7.8p6:
3306 //
3307 // If a designator has the form
3308 //
3309 // [ constant-expression ]
3310 //
3311 // then the current object (defined below) shall have array
3312 // type and the expression shall be an integer constant
3313 // expression. If the array is of unknown size, any
3314 // nonnegative value is valid.
3315 //
3316 // Additionally, cope with the GNU extension that permits
3317 // designators of the form
3318 //
3319 // [ constant-expression ... constant-expression ]
3320 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3321 if (!AT) {
3322 if (!VerifyOnly)
3323 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3324 << CurrentObjectType;
3325 ++Index;
3326 return true;
3327 }
3328
3329 Expr *IndexExpr = nullptr;
3330 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3331 if (D->isArrayDesignator()) {
3332 IndexExpr = DIE->getArrayIndex(*D);
3333 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3334 DesignatedEndIndex = DesignatedStartIndex;
3335 } else {
3336 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3337
3338 DesignatedStartIndex =
3340 DesignatedEndIndex =
3342 IndexExpr = DIE->getArrayRangeEnd(*D);
3343
3344 // Codegen can't handle evaluating array range designators that have side
3345 // effects, because we replicate the AST value for each initialized element.
3346 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3347 // elements with something that has a side effect, so codegen can emit an
3348 // "error unsupported" error instead of miscompiling the app.
3349 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3350 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3351 FullyStructuredList->sawArrayRangeDesignator();
3352 }
3353
3354 if (isa<ConstantArrayType>(AT)) {
3355 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3356 DesignatedStartIndex
3357 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3358 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3359 DesignatedEndIndex
3360 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3361 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3362 if (DesignatedEndIndex >= MaxElements) {
3363 if (!VerifyOnly)
3364 SemaRef.Diag(IndexExpr->getBeginLoc(),
3365 diag::err_array_designator_too_large)
3366 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3367 << IndexExpr->getSourceRange();
3368 ++Index;
3369 return true;
3370 }
3371 } else {
3372 unsigned DesignatedIndexBitWidth =
3374 DesignatedStartIndex =
3375 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3376 DesignatedEndIndex =
3377 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3378 DesignatedStartIndex.setIsUnsigned(true);
3379 DesignatedEndIndex.setIsUnsigned(true);
3380 }
3381
3382 bool IsStringLiteralInitUpdate =
3383 StructuredList && StructuredList->isStringLiteralInit();
3384 if (IsStringLiteralInitUpdate && VerifyOnly) {
3385 // We're just verifying an update to a string literal init. We don't need
3386 // to split the string up into individual characters to do that.
3387 StructuredList = nullptr;
3388 } else if (IsStringLiteralInitUpdate) {
3389 // We're modifying a string literal init; we have to decompose the string
3390 // so we can modify the individual characters.
3391 ASTContext &Context = SemaRef.Context;
3392 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3393
3394 // Compute the character type
3395 QualType CharTy = AT->getElementType();
3396
3397 // Compute the type of the integer literals.
3398 QualType PromotedCharTy = CharTy;
3399 if (Context.isPromotableIntegerType(CharTy))
3400 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3401 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3402
3403 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3404 // Get the length of the string.
3405 uint64_t StrLen = SL->getLength();
3406 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3407 CAT && CAT->getSize().ult(StrLen))
3408 StrLen = CAT->getZExtSize();
3409 StructuredList->resizeInits(Context, StrLen);
3410
3411 // Build a literal for each character in the string, and put them into
3412 // the init list.
3413 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3414 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3415 Expr *Init = new (Context) IntegerLiteral(
3416 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3417 if (CharTy != PromotedCharTy)
3418 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3419 Init, nullptr, VK_PRValue,
3420 FPOptionsOverride());
3421 StructuredList->updateInit(Context, i, Init);
3422 }
3423 } else {
3424 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3425 std::string Str;
3426 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3427
3428 // Get the length of the string.
3429 uint64_t StrLen = Str.size();
3430 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3431 CAT && CAT->getSize().ult(StrLen))
3432 StrLen = CAT->getZExtSize();
3433 StructuredList->resizeInits(Context, StrLen);
3434
3435 // Build a literal for each character in the string, and put them into
3436 // the init list.
3437 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3438 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3439 Expr *Init = new (Context) IntegerLiteral(
3440 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3441 if (CharTy != PromotedCharTy)
3442 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3443 Init, nullptr, VK_PRValue,
3444 FPOptionsOverride());
3445 StructuredList->updateInit(Context, i, Init);
3446 }
3447 }
3448 }
3449
3450 // Make sure that our non-designated initializer list has space
3451 // for a subobject corresponding to this array element.
3452 if (StructuredList &&
3453 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3454 StructuredList->resizeInits(SemaRef.Context,
3455 DesignatedEndIndex.getZExtValue() + 1);
3456
3457 // Repeatedly perform subobject initializations in the range
3458 // [DesignatedStartIndex, DesignatedEndIndex].
3459
3460 // Move to the next designator
3461 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3462 unsigned OldIndex = Index;
3463
3464 InitializedEntity ElementEntity =
3466
3467 while (DesignatedStartIndex <= DesignatedEndIndex) {
3468 // Recurse to check later designated subobjects.
3469 QualType ElementType = AT->getElementType();
3470 Index = OldIndex;
3471
3472 ElementEntity.setElementIndex(ElementIndex);
3473 if (CheckDesignatedInitializer(
3474 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3475 nullptr, Index, StructuredList, ElementIndex,
3476 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3477 false))
3478 return true;
3479
3480 // Move to the next index in the array that we'll be initializing.
3481 ++DesignatedStartIndex;
3482 ElementIndex = DesignatedStartIndex.getZExtValue();
3483 }
3484
3485 // If this the first designator, our caller will continue checking
3486 // the rest of this array subobject.
3487 if (IsFirstDesignator) {
3488 if (NextElementIndex)
3489 *NextElementIndex = std::move(DesignatedStartIndex);
3490 StructuredIndex = ElementIndex;
3491 return false;
3492 }
3493
3494 if (!FinishSubobjectInit)
3495 return false;
3496
3497 // Check the remaining elements within this array subobject.
3498 bool prevHadError = hadError;
3499 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3500 /*SubobjectIsDesignatorContext=*/false, Index,
3501 StructuredList, ElementIndex);
3502 return hadError && !prevHadError;
3503}
3504
3505// Get the structured initializer list for a subobject of type
3506// @p CurrentObjectType.
3507InitListExpr *
3508InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3509 QualType CurrentObjectType,
3510 InitListExpr *StructuredList,
3511 unsigned StructuredIndex,
3512 SourceRange InitRange,
3513 bool IsFullyOverwritten) {
3514 if (!StructuredList)
3515 return nullptr;
3516
3517 Expr *ExistingInit = nullptr;
3518 if (StructuredIndex < StructuredList->getNumInits())
3519 ExistingInit = StructuredList->getInit(StructuredIndex);
3520
3521 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3522 // There might have already been initializers for subobjects of the current
3523 // object, but a subsequent initializer list will overwrite the entirety
3524 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3525 //
3526 // struct P { char x[6]; };
3527 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3528 //
3529 // The first designated initializer is ignored, and l.x is just "f".
3530 if (!IsFullyOverwritten)
3531 return Result;
3532
3533 if (ExistingInit) {
3534 // We are creating an initializer list that initializes the
3535 // subobjects of the current object, but there was already an
3536 // initialization that completely initialized the current
3537 // subobject:
3538 //
3539 // struct X { int a, b; };
3540 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3541 //
3542 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3543 // designated initializer overwrites the [0].b initializer
3544 // from the prior initialization.
3545 //
3546 // When the existing initializer is an expression rather than an
3547 // initializer list, we cannot decompose and update it in this way.
3548 // For example:
3549 //
3550 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3551 //
3552 // This case is handled by CheckDesignatedInitializer.
3553 diagnoseInitOverride(ExistingInit, InitRange);
3554 }
3555
3556 unsigned ExpectedNumInits = 0;
3557 if (Index < IList->getNumInits()) {
3558 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3559 ExpectedNumInits = Init->getNumInits();
3560 else
3561 ExpectedNumInits = IList->getNumInits() - Index;
3562 }
3563
3564 InitListExpr *Result = createInitListExpr(
3565 CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false);
3566
3567 // Link this new initializer list into the structured initializer
3568 // lists.
3569 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3570 return Result;
3571}
3572
3573InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType,
3574 SourceRange InitRange,
3575 unsigned ExpectedNumInits,
3576 bool IsExplicit) {
3577 InitListExpr *Result =
3578 new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(),
3579 {}, InitRange.getEnd(), IsExplicit);
3580
3581 QualType ResultType = CurrentObjectType;
3582 if (!ResultType->isArrayType())
3583 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3584 Result->setType(ResultType);
3585
3586 // Pre-allocate storage for the structured initializer list.
3587 unsigned NumElements = 0;
3588
3589 if (const ArrayType *AType
3590 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3591 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3592 NumElements = CAType->getZExtSize();
3593 // Simple heuristic so that we don't allocate a very large
3594 // initializer with many empty entries at the end.
3595 if (NumElements > ExpectedNumInits)
3596 NumElements = 0;
3597 }
3598 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3599 NumElements = VType->getNumElements();
3600 } else if (CurrentObjectType->isRecordType()) {
3601 NumElements = numStructUnionElements(CurrentObjectType);
3602 } else if (CurrentObjectType->isDependentType()) {
3603 NumElements = 1;
3604 }
3605
3606 Result->reserveInits(SemaRef.Context, NumElements);
3607
3608 return Result;
3609}
3610
3611/// Update the initializer at index @p StructuredIndex within the
3612/// structured initializer list to the value @p expr.
3613void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3614 unsigned &StructuredIndex,
3615 Expr *expr) {
3616 // No structured initializer list to update
3617 if (!StructuredList)
3618 return;
3619
3620 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3621 StructuredIndex, expr)) {
3622 // This initializer overwrites a previous initializer.
3623 // No need to diagnose when `expr` is nullptr because a more relevant
3624 // diagnostic has already been issued and this diagnostic is potentially
3625 // noise.
3626 if (expr)
3627 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3628 }
3629
3630 ++StructuredIndex;
3631}
3632
3634 const InitializedEntity &Entity, InitListExpr *From) {
3635 QualType Type = Entity.getType();
3636 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3637 /*TreatUnavailableAsInvalid=*/false,
3638 /*InOverloadResolution=*/true);
3639 return !Check.HadError();
3640}
3641
3642/// Check that the given Index expression is a valid array designator
3643/// value. This is essentially just a wrapper around
3644/// VerifyIntegerConstantExpression that also checks for negative values
3645/// and produces a reasonable diagnostic if there is a
3646/// failure. Returns the index expression, possibly with an implicit cast
3647/// added, on success. If everything went okay, Value will receive the
3648/// value of the constant expression.
3649static ExprResult
3650CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3651 SourceLocation Loc = Index->getBeginLoc();
3652
3653 // Make sure this is an integer constant expression.
3656 if (Result.isInvalid())
3657 return Result;
3658
3659 if (Value.isSigned() && Value.isNegative())
3660 return S.Diag(Loc, diag::err_array_designator_negative)
3661 << toString(Value, 10) << Index->getSourceRange();
3662
3663 Value.setIsUnsigned(true);
3664 return Result;
3665}
3666
3668 SourceLocation EqualOrColonLoc,
3669 bool GNUSyntax,
3670 ExprResult Init) {
3671 typedef DesignatedInitExpr::Designator ASTDesignator;
3672
3673 bool Invalid = false;
3675 SmallVector<Expr *, 32> InitExpressions;
3676
3677 // Build designators and check array designator expressions.
3678 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3679 const Designator &D = Desig.getDesignator(Idx);
3680
3681 if (D.isFieldDesignator()) {
3682 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3683 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3684 } else if (D.isArrayDesignator()) {
3685 Expr *Index = D.getArrayIndex();
3686 llvm::APSInt IndexValue;
3687 if (!Index->isTypeDependent() && !Index->isValueDependent())
3688 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3689 if (!Index)
3690 Invalid = true;
3691 else {
3692 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3693 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3694 InitExpressions.push_back(Index);
3695 }
3696 } else if (D.isArrayRangeDesignator()) {
3697 Expr *StartIndex = D.getArrayRangeStart();
3698 Expr *EndIndex = D.getArrayRangeEnd();
3699 llvm::APSInt StartValue;
3700 llvm::APSInt EndValue;
3701 bool StartDependent = StartIndex->isTypeDependent() ||
3702 StartIndex->isValueDependent();
3703 bool EndDependent = EndIndex->isTypeDependent() ||
3704 EndIndex->isValueDependent();
3705 if (!StartDependent)
3706 StartIndex =
3707 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3708 if (!EndDependent)
3709 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3710
3711 if (!StartIndex || !EndIndex)
3712 Invalid = true;
3713 else {
3714 // Make sure we're comparing values with the same bit width.
3715 if (StartDependent || EndDependent) {
3716 // Nothing to compute.
3717 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3718 EndValue = EndValue.extend(StartValue.getBitWidth());
3719 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3720 StartValue = StartValue.extend(EndValue.getBitWidth());
3721
3722 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3723 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3724 << toString(StartValue, 10) << toString(EndValue, 10)
3725 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3726 Invalid = true;
3727 } else {
3728 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3729 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3730 D.getRBracketLoc()));
3731 InitExpressions.push_back(StartIndex);
3732 InitExpressions.push_back(EndIndex);
3733 }
3734 }
3735 }
3736 }
3737
3738 if (Invalid || Init.isInvalid())
3739 return ExprError();
3740
3741 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3742 EqualOrColonLoc, GNUSyntax,
3743 Init.getAs<Expr>());
3744}
3745
3746//===----------------------------------------------------------------------===//
3747// Initialization entity
3748//===----------------------------------------------------------------------===//
3749
3750InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3751 const InitializedEntity &Parent)
3752 : Parent(&Parent), Index(Index)
3753{
3754 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3755 Kind = EK_ArrayElement;
3756 Type = AT->getElementType();
3757 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3758 Kind = EK_VectorElement;
3759 Type = VT->getElementType();
3760 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3761 Kind = EK_MatrixElement;
3762 Type = MT->getElementType();
3763 } else {
3764 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3765 assert(CT && "Unexpected type");
3766 Kind = EK_ComplexElement;
3767 Type = CT->getElementType();
3768 }
3769}
3770
3773 const CXXBaseSpecifier *Base,
3774 bool IsInheritedVirtualBase,
3775 const InitializedEntity *Parent) {
3776 InitializedEntity Result;
3777 Result.Kind = EK_Base;
3778 Result.Parent = Parent;
3779 Result.Base = {Base, IsInheritedVirtualBase};
3780 Result.Type = Base->getType();
3781 return Result;
3782}
3783
3785 switch (getKind()) {
3786 case EK_Parameter:
3788 ParmVarDecl *D = Parameter.getPointer();
3789 return (D ? D->getDeclName() : DeclarationName());
3790 }
3791
3792 case EK_Variable:
3793 case EK_Member:
3795 case EK_Binding:
3797 return Variable.VariableOrMember->getDeclName();
3798
3799 case EK_LambdaCapture:
3800 return DeclarationName(Capture.VarID);
3801
3802 case EK_Result:
3803 case EK_StmtExprResult:
3804 case EK_Exception:
3805 case EK_New:
3806 case EK_Temporary:
3807 case EK_Base:
3808 case EK_Delegating:
3809 case EK_ArrayElement:
3810 case EK_VectorElement:
3811 case EK_MatrixElement:
3812 case EK_ComplexElement:
3813 case EK_BlockElement:
3816 case EK_RelatedResult:
3817 return DeclarationName();
3818 }
3819
3820 llvm_unreachable("Invalid EntityKind!");
3821}
3822
3824 switch (getKind()) {
3825 case EK_Variable:
3826 case EK_Member:
3828 case EK_Binding:
3830 return cast<ValueDecl>(Variable.VariableOrMember);
3831
3832 case EK_Parameter:
3834 return Parameter.getPointer();
3835
3836 case EK_Result:
3837 case EK_StmtExprResult:
3838 case EK_Exception:
3839 case EK_New:
3840 case EK_Temporary:
3841 case EK_Base:
3842 case EK_Delegating:
3843 case EK_ArrayElement:
3844 case EK_VectorElement:
3845 case EK_MatrixElement:
3846 case EK_ComplexElement:
3847 case EK_BlockElement:
3849 case EK_LambdaCapture:
3851 case EK_RelatedResult:
3852 return nullptr;
3853 }
3854
3855 llvm_unreachable("Invalid EntityKind!");
3856}
3857
3859 switch (getKind()) {
3860 case EK_Result:
3861 case EK_Exception:
3862 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3863
3864 case EK_StmtExprResult:
3865 case EK_Variable:
3866 case EK_Parameter:
3869 case EK_Member:
3871 case EK_Binding:
3872 case EK_New:
3873 case EK_Temporary:
3875 case EK_Base:
3876 case EK_Delegating:
3877 case EK_ArrayElement:
3878 case EK_VectorElement:
3879 case EK_MatrixElement:
3880 case EK_ComplexElement:
3881 case EK_BlockElement:
3883 case EK_LambdaCapture:
3884 case EK_RelatedResult:
3885 break;
3886 }
3887
3888 return false;
3889}
3890
3891unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3892 assert(getParent() != this);
3893 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3894 for (unsigned I = 0; I != Depth; ++I)
3895 OS << "`-";
3896
3897 switch (getKind()) {
3898 case EK_Variable: OS << "Variable"; break;
3899 case EK_Parameter: OS << "Parameter"; break;
3900 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3901 break;
3902 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3903 case EK_Result: OS << "Result"; break;
3904 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3905 case EK_Exception: OS << "Exception"; break;
3906 case EK_Member:
3908 OS << "Member";
3909 break;
3910 case EK_Binding: OS << "Binding"; break;
3911 case EK_New: OS << "New"; break;
3912 case EK_Temporary: OS << "Temporary"; break;
3913 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3914 case EK_RelatedResult: OS << "RelatedResult"; break;
3915 case EK_Base: OS << "Base"; break;
3916 case EK_Delegating: OS << "Delegating"; break;
3917 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3918 case EK_VectorElement: OS << "VectorElement " << Index; break;
3919 case EK_MatrixElement:
3920 OS << "MatrixElement " << Index;
3921 break;
3922 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3923 case EK_BlockElement: OS << "Block"; break;
3925 OS << "Block (lambda)";
3926 break;
3927 case EK_LambdaCapture:
3928 OS << "LambdaCapture ";
3929 OS << DeclarationName(Capture.VarID);
3930 break;
3931 }
3932
3933 if (auto *D = getDecl()) {
3934 OS << " ";
3935 D->printQualifiedName(OS);
3936 }
3937
3938 OS << " '" << getType() << "'\n";
3939
3940 return Depth + 1;
3941}
3942
3943LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3944 dumpImpl(llvm::errs());
3945}
3946
3947//===----------------------------------------------------------------------===//
3948// Initialization sequence
3949//===----------------------------------------------------------------------===//
3950
3997
3999 // There can be some lvalue adjustments after the SK_BindReference step.
4000 for (const Step &S : llvm::reverse(Steps)) {
4001 if (S.Kind == SK_BindReference)
4002 return true;
4003 if (S.Kind == SK_BindReferenceToTemporary)
4004 return false;
4005 }
4006 return false;
4007}
4008
4010 if (!Failed())
4011 return false;
4012
4013 switch (getFailureKind()) {
4024 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4041 case FK_Incomplete:
4046 case FK_PlaceholderType:
4052 return false;
4053
4058 return FailedOverloadResult == OR_Ambiguous;
4059 }
4060
4061 llvm_unreachable("Invalid EntityKind!");
4062}
4063
4065 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4066}
4067
4068void
4069InitializationSequence
4070::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4072 bool HadMultipleCandidates) {
4073 Step S;
4075 S.Type = Function->getType();
4076 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4079 Steps.push_back(S);
4080}
4081
4083 ExprValueKind VK) {
4084 Step S;
4085 switch (VK) {
4086 case VK_PRValue:
4088 break;
4089 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4090 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4091 }
4092 S.Type = BaseType;
4093 Steps.push_back(S);
4094}
4095
4097 bool BindingTemporary) {
4098 Step S;
4099 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4100 S.Type = T;
4101 Steps.push_back(S);
4102}
4103
4105 Step S;
4106 S.Kind = SK_FinalCopy;
4107 S.Type = T;
4108 Steps.push_back(S);
4109}
4110
4112 Step S;
4114 S.Type = T;
4115 Steps.push_back(S);
4116}
4117
4118void
4120 DeclAccessPair FoundDecl,
4121 QualType T,
4122 bool HadMultipleCandidates) {
4123 Step S;
4125 S.Type = T;
4126 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4128 S.Function.FoundDecl = FoundDecl;
4129 Steps.push_back(S);
4130}
4131
4133 ExprValueKind VK) {
4134 Step S;
4135 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4136 switch (VK) {
4137 case VK_PRValue:
4139 break;
4140 case VK_XValue:
4142 break;
4143 case VK_LValue:
4145 break;
4146 }
4147 S.Type = Ty;
4148 Steps.push_back(S);
4149}
4150
4152 Step S;
4154 S.Type = Ty;
4155 Steps.push_back(S);
4156}
4157
4159 Step S;
4161 S.Type = Ty;
4162 Steps.push_back(S);
4163}
4164
4167 bool TopLevelOfInitList) {
4168 Step S;
4169 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4171 S.Type = T;
4172 S.ICS = new ImplicitConversionSequence(ICS);
4173 Steps.push_back(S);
4174}
4175
4177 Step S;
4179 S.Type = T;
4180 Steps.push_back(S);
4181}
4182
4185 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4186 Step S;
4187 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4190 S.Type = T;
4191 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4193 S.Function.FoundDecl = FoundDecl;
4194 Steps.push_back(S);
4195}
4196
4198 Step S;
4200 S.Type = T;
4201 Steps.push_back(S);
4202}
4203
4205 Step S;
4206 S.Kind = SK_CAssignment;
4207 S.Type = T;
4208 Steps.push_back(S);
4209}
4210
4212 Step S;
4213 S.Kind = SK_StringInit;
4214 S.Type = T;
4215 Steps.push_back(S);
4216}
4217
4219 Step S;
4221 S.Type = T;
4222 Steps.push_back(S);
4223}
4224
4226 Step S;
4227 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4228 S.Type = T;
4229 Steps.push_back(S);
4230}
4231
4233 Step S;
4235 S.Type = EltT;
4236 Steps.insert(Steps.begin(), S);
4237
4239 S.Type = T;
4240 Steps.push_back(S);
4241}
4242
4244 Step S;
4246 S.Type = T;
4247 Steps.push_back(S);
4248}
4249
4251 bool shouldCopy) {
4252 Step s;
4253 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4255 s.Type = type;
4256 Steps.push_back(s);
4257}
4258
4260 Step S;
4262 S.Type = T;
4263 Steps.push_back(S);
4264}
4265
4267 Step S;
4269 S.Type = T;
4270 Steps.push_back(S);
4271}
4272
4274 Step S;
4276 S.Type = T;
4277 Steps.push_back(S);
4278}
4279
4281 Step S;
4283 S.Type = T;
4284 Steps.push_back(S);
4285}
4286
4288 Step S;
4290 S.Type = T;
4291 Steps.push_back(S);
4292}
4293
4295 InitListExpr *Syntactic) {
4296 assert(Syntactic->getNumInits() == 1 &&
4297 "Can only unwrap trivial init lists.");
4298 Step S;
4300 S.Type = Syntactic->getInit(0)->getType();
4301 Steps.insert(Steps.begin(), S);
4302}
4303
4305 InitListExpr *Syntactic) {
4306 assert(Syntactic->getNumInits() == 1 &&
4307 "Can only rewrap trivial init lists.");
4308 Step S;
4310 S.Type = Syntactic->getInit(0)->getType();
4311 Steps.insert(Steps.begin(), S);
4312
4314 S.Type = T;
4315 S.WrappingSyntacticList = Syntactic;
4316 Steps.push_back(S);
4317}
4318
4320 Step S;
4322 S.Type = T;
4323 Steps.push_back(S);
4324}
4325
4329 this->Failure = Failure;
4330 this->FailedOverloadResult = Result;
4331}
4332
4333//===----------------------------------------------------------------------===//
4334// Attempt initialization
4335//===----------------------------------------------------------------------===//
4336
4337/// Tries to add a zero initializer. Returns true if that worked.
4338static bool
4340 const InitializedEntity &Entity) {
4342 return false;
4343
4344 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4345 if (VD->getInit() || VD->getEndLoc().isMacroID())
4346 return false;
4347
4348 QualType VariableTy = VD->getType().getCanonicalType();
4350 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4351 if (!Init.empty()) {
4352 Sequence.AddZeroInitializationStep(Entity.getType());
4353 Sequence.SetZeroInitializationFixit(Init, Loc);
4354 return true;
4355 }
4356 return false;
4357}
4358
4360 InitializationSequence &Sequence,
4361 const InitializedEntity &Entity) {
4362 if (!S.getLangOpts().ObjCAutoRefCount) return;
4363
4364 /// When initializing a parameter, produce the value if it's marked
4365 /// __attribute__((ns_consumed)).
4366 if (Entity.isParameterKind()) {
4367 if (!Entity.isParameterConsumed())
4368 return;
4369
4370 assert(Entity.getType()->isObjCRetainableType() &&
4371 "consuming an object of unretainable type?");
4372 Sequence.AddProduceObjCObjectStep(Entity.getType());
4373
4374 /// When initializing a return value, if the return type is a
4375 /// retainable type, then returns need to immediately retain the
4376 /// object. If an autorelease is required, it will be done at the
4377 /// last instant.
4378 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4380 if (!Entity.getType()->isObjCRetainableType())
4381 return;
4382
4383 Sequence.AddProduceObjCObjectStep(Entity.getType());
4384 }
4385}
4386
4387/// Initialize an array from another array
4388static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4389 const InitializedEntity &Entity, Expr *Initializer,
4390 QualType DestType, InitializationSequence &Sequence,
4391 bool TreatUnavailableAsInvalid) {
4392 // If source is a prvalue, use it directly.
4393 if (Initializer->isPRValue()) {
4394 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4395 return;
4396 }
4397
4398 // Emit element-at-a-time copy loop.
4399 InitializedEntity Element =
4401 QualType InitEltT =
4403
4404 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4405 // allocator at the moment
4407 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4408 Initializer->getObjectKind());
4409 Expr *OVEAsExpr = OVE;
4410 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4411 /*TopLevelOfInitList*/ false,
4412 TreatUnavailableAsInvalid);
4413 if (Sequence)
4414 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4415}
4416
4417static void TryListInitialization(Sema &S,
4418 const InitializedEntity &Entity,
4419 const InitializationKind &Kind,
4420 InitListExpr *InitList,
4421 InitializationSequence &Sequence,
4422 bool TreatUnavailableAsInvalid);
4423
4424/// When initializing from init list via constructor, handle
4425/// initialization of an object of type std::initializer_list<T>.
4426///
4427/// \return true if we have handled initialization of an object of type
4428/// std::initializer_list<T>, false otherwise.
4430 InitListExpr *List,
4431 QualType DestType,
4432 InitializationSequence &Sequence,
4433 bool TreatUnavailableAsInvalid) {
4434 QualType E;
4435 if (!S.isStdInitializerList(DestType, &E))
4436 return false;
4437
4438 if (!S.isCompleteType(List->getExprLoc(), E)) {
4439 Sequence.setIncompleteTypeFailure(E);
4440 return true;
4441 }
4442
4443 // Try initializing a temporary array from the init list.
4445 E.withConst(),
4446 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4449 InitializedEntity HiddenArray =
4452 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4453 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4454 TreatUnavailableAsInvalid);
4455 if (Sequence)
4456 Sequence.AddStdInitializerListConstructionStep(DestType);
4457 return true;
4458}
4459
4460/// Determine if the constructor has the signature of a copy or move
4461/// constructor for the type T of the class in which it was found. That is,
4462/// determine if its first parameter is of type T or reference to (possibly
4463/// cv-qualified) T.
4465 const ConstructorInfo &Info) {
4466 if (Info.Constructor->getNumParams() == 0)
4467 return false;
4468
4469 QualType ParmT =
4471 CanQualType ClassT = Ctx.getCanonicalTagType(
4473
4474 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4475}
4476
4478 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4479 OverloadCandidateSet &CandidateSet, QualType DestType,
4481 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4482 bool IsListInit, bool RequireActualConstructor,
4483 bool SecondStepOfCopyInit = false) {
4485 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4486
4487 for (NamedDecl *D : Ctors) {
4488 auto Info = getConstructorInfo(D);
4489 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4490 continue;
4491
4492 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4493 continue;
4494
4495 // C++11 [over.best.ics]p4:
4496 // ... and the constructor or user-defined conversion function is a
4497 // candidate by
4498 // - 13.3.1.3, when the argument is the temporary in the second step
4499 // of a class copy-initialization, or
4500 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4501 // - the second phase of 13.3.1.7 when the initializer list has exactly
4502 // one element that is itself an initializer list, and the target is
4503 // the first parameter of a constructor of class X, and the conversion
4504 // is to X or reference to (possibly cv-qualified X),
4505 // user-defined conversion sequences are not considered.
4506 bool SuppressUserConversions =
4507 SecondStepOfCopyInit ||
4508 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4510
4511 if (Info.ConstructorTmpl)
4513 Info.ConstructorTmpl, Info.FoundDecl,
4514 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4515 /*PartialOverloading=*/false, AllowExplicit);
4516 else {
4517 // C++ [over.match.copy]p1:
4518 // - When initializing a temporary to be bound to the first parameter
4519 // of a constructor [for type T] that takes a reference to possibly
4520 // cv-qualified T as its first argument, called with a single
4521 // argument in the context of direct-initialization, explicit
4522 // conversion functions are also considered.
4523 // FIXME: What if a constructor template instantiates to such a signature?
4524 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4525 Args.size() == 1 &&
4527 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4528 CandidateSet, SuppressUserConversions,
4529 /*PartialOverloading=*/false, AllowExplicit,
4530 AllowExplicitConv);
4531 }
4532 }
4533
4534 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4535 //
4536 // When initializing an object of class type T by constructor
4537 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4538 // from a single expression of class type U, conversion functions of
4539 // U that convert to the non-reference type cv T are candidates.
4540 // Explicit conversion functions are only candidates during
4541 // direct-initialization.
4542 //
4543 // Note: SecondStepOfCopyInit is only ever true in this case when
4544 // evaluating whether to produce a C++98 compatibility warning.
4545 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4546 !RequireActualConstructor && !SecondStepOfCopyInit) {
4547 Expr *Initializer = Args[0];
4548 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4549 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4550 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4551 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4552 NamedDecl *D = *I;
4554 D = D->getUnderlyingDecl();
4555
4556 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4557 CXXConversionDecl *Conv;
4558 if (ConvTemplate)
4559 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4560 else
4561 Conv = cast<CXXConversionDecl>(D);
4562
4563 if (ConvTemplate)
4565 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4566 CandidateSet, AllowExplicit, AllowExplicit,
4567 /*AllowResultConversion*/ false);
4568 else
4569 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4570 DestType, CandidateSet, AllowExplicit,
4571 AllowExplicit,
4572 /*AllowResultConversion*/ false);
4573 }
4574 }
4575 }
4576
4577 // Perform overload resolution and return the result.
4578 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4579}
4580
4581/// Attempt initialization by constructor (C++ [dcl.init]), which
4582/// enumerates the constructors of the initialized entity and performs overload
4583/// resolution to select the best.
4584/// \param DestType The destination class type.
4585/// \param DestArrayType The destination type, which is either DestType or
4586/// a (possibly multidimensional) array of DestType.
4587/// \param IsListInit Is this list-initialization?
4588/// \param IsInitListCopy Is this non-list-initialization resulting from a
4589/// list-initialization from {x} where x is the same
4590/// aggregate type as the entity?
4592 const InitializedEntity &Entity,
4593 const InitializationKind &Kind,
4594 MultiExprArg Args, QualType DestType,
4595 QualType DestArrayType,
4596 InitializationSequence &Sequence,
4597 bool IsListInit = false,
4598 bool IsInitListCopy = false) {
4599 assert(((!IsListInit && !IsInitListCopy) ||
4600 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4601 "IsListInit/IsInitListCopy must come with a single initializer list "
4602 "argument.");
4603 InitListExpr *ILE =
4604 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4605 MultiExprArg UnwrappedArgs =
4606 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4607
4608 // The type we're constructing needs to be complete.
4609 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4610 Sequence.setIncompleteTypeFailure(DestType);
4611 return;
4612 }
4613
4614 bool RequireActualConstructor =
4615 !(Entity.getKind() != InitializedEntity::EK_Base &&
4617 Entity.getKind() !=
4619
4620 bool CopyElisionPossible = false;
4621 auto ElideConstructor = [&] {
4622 // Convert qualifications if necessary.
4623 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4624 if (ILE)
4625 Sequence.RewrapReferenceInitList(DestType, ILE);
4626 };
4627
4628 // C++17 [dcl.init]p17:
4629 // - If the initializer expression is a prvalue and the cv-unqualified
4630 // version of the source type is the same class as the class of the
4631 // destination, the initializer expression is used to initialize the
4632 // destination object.
4633 // Per DR (no number yet), this does not apply when initializing a base
4634 // class or delegating to another constructor from a mem-initializer.
4635 // ObjC++: Lambda captured by the block in the lambda to block conversion
4636 // should avoid copy elision.
4637 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4638 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4639 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4640 if (ILE && !DestType->isAggregateType()) {
4641 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4642 // Make this an elision if this won't call an initializer-list
4643 // constructor. (Always on an aggregate type or check constructors first.)
4644
4645 // This effectively makes our resolution as follows. The parts in angle
4646 // brackets are additions.
4647 // C++17 [over.match.list]p(1.2):
4648 // - If no viable initializer-list constructor is found <and the
4649 // initializer list does not consist of exactly a single element with
4650 // the same cv-unqualified class type as T>, [...]
4651 // C++17 [dcl.init.list]p(3.6):
4652 // - Otherwise, if T is a class type, constructors are considered. The
4653 // applicable constructors are enumerated and the best one is chosen
4654 // through overload resolution. <If no constructor is found and the
4655 // initializer list consists of exactly a single element with the same
4656 // cv-unqualified class type as T, the object is initialized from that
4657 // element (by copy-initialization for copy-list-initialization, or by
4658 // direct-initialization for direct-list-initialization). Otherwise, >
4659 // if a narrowing conversion [...]
4660 assert(!IsInitListCopy &&
4661 "IsInitListCopy only possible with aggregate types");
4662 CopyElisionPossible = true;
4663 } else {
4664 ElideConstructor();
4665 return;
4666 }
4667 }
4668
4669 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4670 // Build the candidate set directly in the initialization sequence
4671 // structure, so that it will persist if we fail.
4672 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4673
4674 // Determine whether we are allowed to call explicit constructors or
4675 // explicit conversion operators.
4676 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4677 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4678
4679 // - Otherwise, if T is a class type, constructors are considered. The
4680 // applicable constructors are enumerated, and the best one is chosen
4681 // through overload resolution.
4682 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4683
4686 bool AsInitializerList = false;
4687
4688 // C++11 [over.match.list]p1, per DR1467:
4689 // When objects of non-aggregate type T are list-initialized, such that
4690 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4691 // according to the rules in this section, overload resolution selects
4692 // the constructor in two phases:
4693 //
4694 // - Initially, the candidate functions are the initializer-list
4695 // constructors of the class T and the argument list consists of the
4696 // initializer list as a single argument.
4697 if (IsListInit) {
4698 AsInitializerList = true;
4699
4700 // If the initializer list has no elements and T has a default constructor,
4701 // the first phase is omitted.
4702 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4704 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4705 CopyInitialization, AllowExplicit,
4706 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4707
4708 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4709 // No initializer list candidate
4710 ElideConstructor();
4711 return;
4712 }
4713 }
4714
4715 // if the initialization is direct-initialization, or if it is
4716 // copy-initialization where the cv-unqualified version of the source type is
4717 // the same as or is derived from the class of the destination type,
4718 // constructors are considered.
4719 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4720 Kind.getKind() == InitializationKind::IK_Copy) &&
4721 Args.size() == 1 &&
4723 Args[0]->getType().getNonReferenceType(),
4724 DestType.getNonReferenceType()))
4725 RequireActualConstructor = true;
4726
4727 // C++11 [over.match.list]p1:
4728 // - If no viable initializer-list constructor is found, overload resolution
4729 // is performed again, where the candidate functions are all the
4730 // constructors of the class T and the argument list consists of the
4731 // elements of the initializer list.
4733 AsInitializerList = false;
4735 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4736 Best, CopyInitialization, AllowExplicit,
4737 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4738 }
4739 if (Result) {
4740 Sequence.SetOverloadFailure(
4743 Result);
4744
4745 if (Result != OR_Deleted)
4746 return;
4747 }
4748
4749 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4750
4751 // In C++17, ResolveConstructorOverload can select a conversion function
4752 // instead of a constructor.
4753 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4754 // Add the user-defined conversion step that calls the conversion function.
4755 QualType ConvType = CD->getConversionType();
4756 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4757 "should not have selected this conversion function");
4758 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4759 HadMultipleCandidates);
4760 if (!S.Context.hasSameType(ConvType, DestType))
4761 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4762 if (IsListInit)
4763 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4764 return;
4765 }
4766
4767 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4768 if (Result != OR_Deleted) {
4769 if (!IsListInit &&
4770 (Kind.getKind() == InitializationKind::IK_Default ||
4771 Kind.getKind() == InitializationKind::IK_Direct) &&
4772 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4773 DestRecordDecl->isAggregate() &&
4774 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4775 !S.isUnevaluatedContext()) {
4776 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4777 << /* Var-in-Record */ 1 << DestRecordDecl;
4778 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4779 }
4780
4781 // C++11 [dcl.init]p6:
4782 // If a program calls for the default initialization of an object
4783 // of a const-qualified type T, T shall be a class type with a
4784 // user-provided default constructor.
4785 // C++ core issue 253 proposal:
4786 // If the implicit default constructor initializes all subobjects, no
4787 // initializer should be required.
4788 // The 253 proposal is for example needed to process libstdc++ headers
4789 // in 5.x.
4790 if (Kind.getKind() == InitializationKind::IK_Default &&
4791 Entity.getType().isConstQualified()) {
4792 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4793 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4795 return;
4796 }
4797 }
4798
4799 // C++11 [over.match.list]p1:
4800 // In copy-list-initialization, if an explicit constructor is chosen, the
4801 // initializer is ill-formed.
4802 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4804 return;
4805 }
4806 }
4807
4808 // [class.copy.elision]p3:
4809 // In some copy-initialization contexts, a two-stage overload resolution
4810 // is performed.
4811 // If the first overload resolution selects a deleted function, we also
4812 // need the initialization sequence to decide whether to perform the second
4813 // overload resolution.
4814 // For deleted functions in other contexts, there is no need to get the
4815 // initialization sequence.
4816 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4817 return;
4818
4819 // Add the constructor initialization step. Any cv-qualification conversion is
4820 // subsumed by the initialization.
4822 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4823 IsListInit | IsInitListCopy, AsInitializerList);
4824}
4825
4827 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4828 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4829 ExprResult *Result = nullptr);
4830
4831/// Attempt to initialize an object of a class type either by
4832/// direct-initialization, or by copy-initialization from an
4833/// expression of the same or derived class type. This corresponds
4834/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4835///
4836/// \param IsAggrListInit Is this non-list-initialization being done as
4837/// part of a list-initialization of an aggregate
4838/// from a single expression of the same or
4839/// derived class type (C++2c [dcl.init.list] p3.2)?
4841 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4842 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4843 bool IsAggrListInit) {
4844 // C++2c [dcl.init.general] p16.6:
4845 // * Otherwise, if the destination type is a class type:
4846 // * If the initializer expression is a prvalue and
4847 // the cv-unqualified version of the source type is the same
4848 // as the destination type, the initializer expression is used
4849 // to initialize the destination object.
4850 // * Otherwise, if the initialization is direct-initialization,
4851 // or if it is copy-initialization where the cv-unqualified
4852 // version of the source type is the same as or is derived from
4853 // the class of the destination type, constructors are considered.
4854 // The applicable constructors are enumerated, and the best one
4855 // is chosen through overload resolution. Then:
4856 // * If overload resolution is successful, the selected
4857 // constructor is called to initialize the object, with
4858 // the initializer expression or expression-list as its
4859 // argument(s).
4860 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4861 Sequence, /*IsListInit=*/false, IsAggrListInit);
4862
4863 // * Otherwise, if no constructor is viable, the destination type
4864 // is an aggregate class, and the initializer is a parenthesized
4865 // expression-list, the object is initialized as follows. [...]
4866 // Parenthesized initialization of aggregates is a C++20 feature.
4867 if (S.getLangOpts().CPlusPlus20 &&
4868 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4869 Sequence.getFailureKind() ==
4872 (IsAggrListInit || DestType->isAggregateType()))
4873 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4874 /*VerifyOnly=*/true);
4875
4876 // * Otherwise, the initialization is ill-formed.
4877}
4878
4879static bool
4882 QualType &SourceType,
4883 QualType &UnqualifiedSourceType,
4884 QualType UnqualifiedTargetType,
4885 InitializationSequence &Sequence) {
4886 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4887 S.Context.OverloadTy) {
4889 bool HadMultipleCandidates = false;
4890 if (FunctionDecl *Fn
4892 UnqualifiedTargetType,
4893 false, Found,
4894 &HadMultipleCandidates)) {
4896 HadMultipleCandidates);
4897 SourceType = Fn->getType();
4898 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4899 } else if (!UnqualifiedTargetType->isRecordType()) {
4901 return true;
4902 }
4903 }
4904 return false;
4905}
4906
4907static void TryReferenceInitializationCore(Sema &S,
4908 const InitializedEntity &Entity,
4909 const InitializationKind &Kind,
4910 Expr *Initializer,
4911 QualType cv1T1, QualType T1,
4912 Qualifiers T1Quals,
4913 QualType cv2T2, QualType T2,
4914 Qualifiers T2Quals,
4915 InitializationSequence &Sequence,
4916 bool TopLevelOfInitList);
4917
4918static void TryValueInitialization(Sema &S,
4919 const InitializedEntity &Entity,
4920 const InitializationKind &Kind,
4921 InitializationSequence &Sequence,
4922 InitListExpr *InitList = nullptr);
4923
4924/// Attempt list initialization of a reference.
4926 const InitializedEntity &Entity,
4927 const InitializationKind &Kind,
4928 InitListExpr *InitList,
4929 InitializationSequence &Sequence,
4930 bool TreatUnavailableAsInvalid) {
4931 // First, catch C++03 where this isn't possible.
4932 if (!S.getLangOpts().CPlusPlus11) {
4934 return;
4935 }
4936 // Can't reference initialize a compound literal.
4939 return;
4940 }
4941
4942 QualType DestType = Entity.getType();
4943 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4944 Qualifiers T1Quals;
4945 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4946
4947 // Reference initialization via an initializer list works thus:
4948 // If the initializer list consists of a single element that is
4949 // reference-related to the referenced type, bind directly to that element
4950 // (possibly creating temporaries).
4951 // Otherwise, initialize a temporary with the initializer list and
4952 // bind to that.
4953 if (InitList->getNumInits() == 1) {
4954 Expr *Initializer = InitList->getInit(0);
4956 Qualifiers T2Quals;
4957 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4958
4959 // If this fails, creating a temporary wouldn't work either.
4961 T1, Sequence))
4962 return;
4963
4964 SourceLocation DeclLoc = Initializer->getBeginLoc();
4965 Sema::ReferenceCompareResult RefRelationship
4966 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4967 if (RefRelationship >= Sema::Ref_Related) {
4968 // Try to bind the reference here.
4969 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4970 T1Quals, cv2T2, T2, T2Quals, Sequence,
4971 /*TopLevelOfInitList=*/true);
4972 if (Sequence)
4973 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4974 return;
4975 }
4976
4977 // Update the initializer if we've resolved an overloaded function.
4978 if (!Sequence.steps().empty())
4979 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4980 }
4981 // Perform address space compatibility check.
4982 QualType cv1T1IgnoreAS = cv1T1;
4983 if (T1Quals.hasAddressSpace()) {
4984 Qualifiers T2Quals;
4985 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4986 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4987 Sequence.SetFailed(
4989 return;
4990 }
4991 // Ignore address space of reference type at this point and perform address
4992 // space conversion after the reference binding step.
4993 cv1T1IgnoreAS =
4995 }
4996 // Not reference-related. Create a temporary and bind to that.
4997 InitializedEntity TempEntity =
4999
5000 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
5001 TreatUnavailableAsInvalid);
5002 if (Sequence) {
5003 if (DestType->isRValueReferenceType() ||
5004 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
5005 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
5006 /*BindingTemporary=*/true);
5007 if (S.getLangOpts().CPlusPlus20 &&
5009 DestType->isRValueReferenceType()) {
5010 // C++20 [dcl.init.list]p3.10:
5011 // List-initialization of an object or reference of type T is defined as
5012 // follows:
5013 // ..., unless T is “reference to array of unknown bound of U”, in which
5014 // case the type of the prvalue is the type of x in the declaration U
5015 // x[] H, where H is the initializer list.
5016
5017 // The call to AddReferenceBindingStep above converts the rvalue to an
5018 // xvalue. Convert that xvalue to the incomplete array type.
5020 }
5021 if (T1Quals.hasAddressSpace())
5023 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5024 } else
5025 Sequence.SetFailed(
5027 }
5028}
5029
5030/// Attempt list initialization (C++0x [dcl.init.list])
5032 const InitializedEntity &Entity,
5033 const InitializationKind &Kind,
5034 InitListExpr *InitList,
5035 InitializationSequence &Sequence,
5036 bool TreatUnavailableAsInvalid) {
5037 QualType DestType = Entity.getType();
5038
5039 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
5041 return;
5042 }
5043
5044 // C++ doesn't allow scalar initialization with more than one argument.
5045 // But C99 complex numbers are scalars and it makes sense there.
5046 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5047 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5049 return;
5050 }
5051 if (DestType->isReferenceType()) {
5052 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5053 TreatUnavailableAsInvalid);
5054 return;
5055 }
5056
5057 if (DestType->isRecordType() &&
5058 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
5059 Sequence.setIncompleteTypeFailure(DestType);
5060 return;
5061 }
5062
5063 // C++20 [dcl.init.list]p3:
5064 // - If the braced-init-list contains a designated-initializer-list, T shall
5065 // be an aggregate class. [...] Aggregate initialization is performed.
5066 //
5067 // We allow arrays here too in order to support array designators.
5068 //
5069 // FIXME: This check should precede the handling of reference initialization.
5070 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5071 // as a tentative DR resolution.
5072 bool IsDesignatedInit = InitList->hasDesignatedInit();
5073 if (!DestType->isAggregateType() && IsDesignatedInit) {
5074 Sequence.SetFailed(
5076 return;
5077 }
5078
5079 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5080 // - If T is an aggregate class and the initializer list has a single element
5081 // of type cv U, where U is T or a class derived from T, the object is
5082 // initialized from that element (by copy-initialization for
5083 // copy-list-initialization, or by direct-initialization for
5084 // direct-list-initialization).
5085 // - Otherwise, if T is a character array and the initializer list has a
5086 // single element that is an appropriately-typed string literal
5087 // (8.5.2 [dcl.init.string]), initialization is performed as described
5088 // in that section.
5089 // - Otherwise, if T is an aggregate, [...] (continue below).
5090 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5091 !IsDesignatedInit) {
5092 if (DestType->isRecordType() && DestType->isAggregateType()) {
5093 QualType InitType = InitList->getInit(0)->getType();
5094 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
5095 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
5096 InitializationKind SubKind =
5098 ? InitializationKind::CreateDirect(Kind.getLocation(),
5099 InitList->getLBraceLoc(),
5100 InitList->getRBraceLoc())
5101 : Kind;
5102 Expr *InitListAsExpr = InitList;
5104 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5105 /*IsAggrListInit=*/true);
5106 return;
5107 }
5108 }
5109 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5110 Expr *SubInit[1] = {InitList->getInit(0)};
5111
5112 // C++17 [dcl.struct.bind]p1:
5113 // ... If the assignment-expression in the initializer has array type A
5114 // and no ref-qualifier is present, e has type cv A and each element is
5115 // copy-initialized or direct-initialized from the corresponding element
5116 // of the assignment-expression as specified by the form of the
5117 // initializer. ...
5118 //
5119 // This is a special case not following list-initialization.
5120 if (isa<ConstantArrayType>(DestAT) &&
5122 isa<DecompositionDecl>(Entity.getDecl())) {
5123 assert(
5124 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5125 "Deduced to other type?");
5126 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5127 "List-initialize structured bindings but not "
5128 "direct-list-initialization?");
5129 TryArrayCopy(S,
5130 InitializationKind::CreateDirect(Kind.getLocation(),
5131 InitList->getLBraceLoc(),
5132 InitList->getRBraceLoc()),
5133 Entity, SubInit[0], DestType, Sequence,
5134 TreatUnavailableAsInvalid);
5135 if (Sequence)
5136 Sequence.AddUnwrapInitListInitStep(InitList);
5137 return;
5138 }
5139
5140 if (!isa<VariableArrayType>(DestAT) &&
5141 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5142 InitializationKind SubKind =
5144 ? InitializationKind::CreateDirect(Kind.getLocation(),
5145 InitList->getLBraceLoc(),
5146 InitList->getRBraceLoc())
5147 : Kind;
5148 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5149 /*TopLevelOfInitList*/ true,
5150 TreatUnavailableAsInvalid);
5151
5152 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5153 // the element is not an appropriately-typed string literal, in which
5154 // case we should proceed as in C++11 (below).
5155 if (Sequence) {
5156 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5157 return;
5158 }
5159 }
5160 }
5161 }
5162
5163 // C++11 [dcl.init.list]p3:
5164 // - If T is an aggregate, aggregate initialization is performed.
5165 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5166 (S.getLangOpts().CPlusPlus11 &&
5167 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5168 if (S.getLangOpts().CPlusPlus11) {
5169 // - Otherwise, if the initializer list has no elements and T is a
5170 // class type with a default constructor, the object is
5171 // value-initialized.
5172 if (InitList->getNumInits() == 0) {
5173 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5174 if (S.LookupDefaultConstructor(RD)) {
5175 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5176 return;
5177 }
5178 }
5179
5180 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5181 // an initializer_list object constructed [...]
5182 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5183 TreatUnavailableAsInvalid))
5184 return;
5185
5186 // - Otherwise, if T is a class type, constructors are considered.
5187 Expr *InitListAsExpr = InitList;
5188 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5189 DestType, Sequence, /*InitListSyntax*/true);
5190 } else
5192 return;
5193 }
5194
5195 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5196 InitList->getNumInits() == 1) {
5197 Expr *E = InitList->getInit(0);
5198
5199 // - Otherwise, if T is an enumeration with a fixed underlying type,
5200 // the initializer-list has a single element v, and the initialization
5201 // is direct-list-initialization, the object is initialized with the
5202 // value T(v); if a narrowing conversion is required to convert v to
5203 // the underlying type of T, the program is ill-formed.
5204 if (S.getLangOpts().CPlusPlus17 &&
5205 Kind.getKind() == InitializationKind::IK_DirectList &&
5206 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5207 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5209 E->getType()->isFloatingType())) {
5210 // There are two ways that T(v) can work when T is an enumeration type.
5211 // If there is either an implicit conversion sequence from v to T or
5212 // a conversion function that can convert from v to T, then we use that.
5213 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5214 // type, it is converted to the enumeration type via its underlying type.
5215 // There is no overlap possible between these two cases (except when the
5216 // source value is already of the destination type), and the first
5217 // case is handled by the general case for single-element lists below.
5219 ICS.setStandard();
5221 if (!E->isPRValue())
5223 // If E is of a floating-point type, then the conversion is ill-formed
5224 // due to narrowing, but go through the motions in order to produce the
5225 // right diagnostic.
5229 ICS.Standard.setFromType(E->getType());
5230 ICS.Standard.setToType(0, E->getType());
5231 ICS.Standard.setToType(1, DestType);
5232 ICS.Standard.setToType(2, DestType);
5233 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5234 /*TopLevelOfInitList*/true);
5235 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5236 return;
5237 }
5238
5239 // - Otherwise, if the initializer list has a single element of type E
5240 // [...references are handled above...], the object or reference is
5241 // initialized from that element (by copy-initialization for
5242 // copy-list-initialization, or by direct-initialization for
5243 // direct-list-initialization); if a narrowing conversion is required
5244 // to convert the element to T, the program is ill-formed.
5245 //
5246 // Per core-24034, this is direct-initialization if we were performing
5247 // direct-list-initialization and copy-initialization otherwise.
5248 // We can't use InitListChecker for this, because it always performs
5249 // copy-initialization. This only matters if we might use an 'explicit'
5250 // conversion operator, or for the special case conversion of nullptr_t to
5251 // bool, so we only need to handle those cases.
5252 //
5253 // FIXME: Why not do this in all cases?
5254 Expr *Init = InitList->getInit(0);
5255 if (Init->getType()->isRecordType() ||
5256 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5257 InitializationKind SubKind =
5259 ? InitializationKind::CreateDirect(Kind.getLocation(),
5260 InitList->getLBraceLoc(),
5261 InitList->getRBraceLoc())
5262 : Kind;
5263 Expr *SubInit[1] = { Init };
5264 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5265 /*TopLevelOfInitList*/true,
5266 TreatUnavailableAsInvalid);
5267 if (Sequence)
5268 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5269 return;
5270 }
5271 }
5272
5273 InitListChecker CheckInitList(S, Entity, InitList,
5274 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5275 if (CheckInitList.HadError()) {
5277 return;
5278 }
5279
5280 // Add the list initialization step with the built init list.
5281 Sequence.AddListInitializationStep(DestType);
5282}
5283
5284/// Try a reference initialization that involves calling a conversion
5285/// function.
5287 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5288 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5289 InitializationSequence &Sequence) {
5290 QualType DestType = Entity.getType();
5291 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5292 QualType T1 = cv1T1.getUnqualifiedType();
5293 QualType cv2T2 = Initializer->getType();
5294 QualType T2 = cv2T2.getUnqualifiedType();
5295
5296 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5297 "Must have incompatible references when binding via conversion");
5298
5299 // Build the candidate set directly in the initialization sequence
5300 // structure, so that it will persist if we fail.
5301 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5303
5304 // Determine whether we are allowed to call explicit conversion operators.
5305 // Note that none of [over.match.copy], [over.match.conv], nor
5306 // [over.match.ref] permit an explicit constructor to be chosen when
5307 // initializing a reference, not even for direct-initialization.
5308 bool AllowExplicitCtors = false;
5309 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5310
5311 if (AllowRValues && T1->isRecordType() &&
5312 S.isCompleteType(Kind.getLocation(), T1)) {
5313 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5314 if (T1RecordDecl->isInvalidDecl())
5315 return OR_No_Viable_Function;
5316 // The type we're converting to is a class type. Enumerate its constructors
5317 // to see if there is a suitable conversion.
5318 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5319 auto Info = getConstructorInfo(D);
5320 if (!Info.Constructor)
5321 continue;
5322
5323 if (!Info.Constructor->isInvalidDecl() &&
5324 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5325 if (Info.ConstructorTmpl)
5327 Info.ConstructorTmpl, Info.FoundDecl,
5328 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5329 /*SuppressUserConversions=*/true,
5330 /*PartialOverloading*/ false, AllowExplicitCtors);
5331 else
5333 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5334 /*SuppressUserConversions=*/true,
5335 /*PartialOverloading*/ false, AllowExplicitCtors);
5336 }
5337 }
5338 }
5339
5340 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5341 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5342 if (T2RecordDecl->isInvalidDecl())
5343 return OR_No_Viable_Function;
5344 // The type we're converting from is a class type, enumerate its conversion
5345 // functions.
5346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5348 NamedDecl *D = *I;
5350 if (isa<UsingShadowDecl>(D))
5351 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5352
5353 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5354 CXXConversionDecl *Conv;
5355 if (ConvTemplate)
5356 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5357 else
5358 Conv = cast<CXXConversionDecl>(D);
5359
5360 // If the conversion function doesn't return a reference type,
5361 // it can't be considered for this conversion unless we're allowed to
5362 // consider rvalues.
5363 // FIXME: Do we need to make sure that we only consider conversion
5364 // candidates with reference-compatible results? That might be needed to
5365 // break recursion.
5366 if ((AllowRValues ||
5368 if (ConvTemplate)
5370 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5371 CandidateSet,
5372 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5373 else
5375 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5376 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5377 }
5378 }
5379 }
5380
5381 SourceLocation DeclLoc = Initializer->getBeginLoc();
5382
5383 // Perform overload resolution. If it fails, return the failed result.
5386 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5387 return Result;
5388
5389 FunctionDecl *Function = Best->Function;
5390 // This is the overload that will be used for this initialization step if we
5391 // use this initialization. Mark it as referenced.
5392 Function->setReferenced();
5393
5394 // Compute the returned type and value kind of the conversion.
5395 QualType cv3T3;
5396 if (isa<CXXConversionDecl>(Function))
5397 cv3T3 = Function->getReturnType();
5398 else
5399 cv3T3 = T1;
5400
5402 if (cv3T3->isLValueReferenceType())
5403 VK = VK_LValue;
5404 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5405 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5406 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5407
5408 // Add the user-defined conversion step.
5409 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5410 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5411 HadMultipleCandidates);
5412
5413 // Determine whether we'll need to perform derived-to-base adjustments or
5414 // other conversions.
5416 Sema::ReferenceCompareResult NewRefRelationship =
5417 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5418
5419 // Add the final conversion sequence, if necessary.
5420 if (NewRefRelationship == Sema::Ref_Incompatible) {
5421 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5422 "should not have conversion after constructor");
5423
5425 ICS.setStandard();
5426 ICS.Standard = Best->FinalConversion;
5427 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5428
5429 // Every implicit conversion results in a prvalue, except for a glvalue
5430 // derived-to-base conversion, which we handle below.
5431 cv3T3 = ICS.Standard.getToType(2);
5432 VK = VK_PRValue;
5433 }
5434
5435 // If the converted initializer is a prvalue, its type T4 is adjusted to
5436 // type "cv1 T4" and the temporary materialization conversion is applied.
5437 //
5438 // We adjust the cv-qualifications to match the reference regardless of
5439 // whether we have a prvalue so that the AST records the change. In this
5440 // case, T4 is "cv3 T3".
5441 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5442 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5443 Sequence.AddQualificationConversionStep(cv1T4, VK);
5444 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5445 VK = IsLValueRef ? VK_LValue : VK_XValue;
5446
5447 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5448 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5449 else if (RefConv & Sema::ReferenceConversions::ObjC)
5450 Sequence.AddObjCObjectConversionStep(cv1T1);
5451 else if (RefConv & Sema::ReferenceConversions::Function)
5452 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5453 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5454 if (!S.Context.hasSameType(cv1T4, cv1T1))
5455 Sequence.AddQualificationConversionStep(cv1T1, VK);
5456 }
5457
5458 return OR_Success;
5459}
5460
5461static void CheckCXX98CompatAccessibleCopy(Sema &S,
5462 const InitializedEntity &Entity,
5463 Expr *CurInitExpr);
5464
5465/// Attempt reference initialization (C++0x [dcl.init.ref])
5467 const InitializationKind &Kind,
5469 InitializationSequence &Sequence,
5470 bool TopLevelOfInitList) {
5471 QualType DestType = Entity.getType();
5472 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5473 Qualifiers T1Quals;
5474 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5476 Qualifiers T2Quals;
5477 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5478
5479 // If the initializer is the address of an overloaded function, try
5480 // to resolve the overloaded function. If all goes well, T2 is the
5481 // type of the resulting function.
5483 T1, Sequence))
5484 return;
5485
5486 // Delegate everything else to a subfunction.
5487 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5488 T1Quals, cv2T2, T2, T2Quals, Sequence,
5489 TopLevelOfInitList);
5490}
5491
5492/// Determine whether an expression is a non-referenceable glvalue (one to
5493/// which a reference can never bind). Attempting to bind a reference to
5494/// such a glvalue will always create a temporary.
5496 return E->refersToBitField() || E->refersToVectorElement() ||
5498}
5499
5500/// Reference initialization without resolving overloaded functions.
5501///
5502/// We also can get here in C if we call a builtin which is declared as
5503/// a function with a parameter of reference type (such as __builtin_va_end()).
5505 const InitializedEntity &Entity,
5506 const InitializationKind &Kind,
5508 QualType cv1T1, QualType T1,
5509 Qualifiers T1Quals,
5510 QualType cv2T2, QualType T2,
5511 Qualifiers T2Quals,
5512 InitializationSequence &Sequence,
5513 bool TopLevelOfInitList) {
5514 QualType DestType = Entity.getType();
5515 SourceLocation DeclLoc = Initializer->getBeginLoc();
5516
5517 // Compute some basic properties of the types and the initializer.
5518 bool isLValueRef = DestType->isLValueReferenceType();
5519 bool isRValueRef = !isLValueRef;
5520 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5521
5523 Sema::ReferenceCompareResult RefRelationship =
5524 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5525
5526 // C++0x [dcl.init.ref]p5:
5527 // A reference to type "cv1 T1" is initialized by an expression of type
5528 // "cv2 T2" as follows:
5529 //
5530 // - If the reference is an lvalue reference and the initializer
5531 // expression
5532 // Note the analogous bullet points for rvalue refs to functions. Because
5533 // there are no function rvalues in C++, rvalue refs to functions are treated
5534 // like lvalue refs.
5535 OverloadingResult ConvOvlResult = OR_Success;
5536 bool T1Function = T1->isFunctionType();
5537 if (isLValueRef || T1Function) {
5538 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5539 (RefRelationship == Sema::Ref_Compatible ||
5540 (Kind.isCStyleOrFunctionalCast() &&
5541 RefRelationship == Sema::Ref_Related))) {
5542 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5543 // reference-compatible with "cv2 T2," or
5544 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5545 Sema::ReferenceConversions::ObjC)) {
5546 // If we're converting the pointee, add any qualifiers first;
5547 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5548 if (RefConv & (Sema::ReferenceConversions::Qualification))
5550 S.Context.getQualifiedType(T2, T1Quals),
5551 Initializer->getValueKind());
5552 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5553 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5554 else
5555 Sequence.AddObjCObjectConversionStep(cv1T1);
5556 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5557 // Perform a (possibly multi-level) qualification conversion.
5558 Sequence.AddQualificationConversionStep(cv1T1,
5559 Initializer->getValueKind());
5560 } else if (RefConv & Sema::ReferenceConversions::Function) {
5561 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5562 }
5563
5564 // We only create a temporary here when binding a reference to a
5565 // bit-field or vector element. Those cases are't supposed to be
5566 // handled by this bullet, but the outcome is the same either way.
5567 Sequence.AddReferenceBindingStep(cv1T1, false);
5568 return;
5569 }
5570
5571 // - has a class type (i.e., T2 is a class type), where T1 is not
5572 // reference-related to T2, and can be implicitly converted to an
5573 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5574 // with "cv3 T3" (this conversion is selected by enumerating the
5575 // applicable conversion functions (13.3.1.6) and choosing the best
5576 // one through overload resolution (13.3)),
5577 // If we have an rvalue ref to function type here, the rhs must be
5578 // an rvalue. DR1287 removed the "implicitly" here.
5579 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5580 (isLValueRef || InitCategory.isRValue())) {
5581 if (S.getLangOpts().CPlusPlus) {
5582 // Try conversion functions only for C++.
5583 ConvOvlResult = TryRefInitWithConversionFunction(
5584 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5585 /*IsLValueRef*/ isLValueRef, Sequence);
5586 if (ConvOvlResult == OR_Success)
5587 return;
5588 if (ConvOvlResult != OR_No_Viable_Function)
5589 Sequence.SetOverloadFailure(
5591 ConvOvlResult);
5592 } else {
5593 ConvOvlResult = OR_No_Viable_Function;
5594 }
5595 }
5596 }
5597
5598 // - Otherwise, the reference shall be an lvalue reference to a
5599 // non-volatile const type (i.e., cv1 shall be const), or the reference
5600 // shall be an rvalue reference.
5601 // For address spaces, we interpret this to mean that an addr space
5602 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5603 if (isLValueRef &&
5604 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5605 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5608 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5609 Sequence.SetOverloadFailure(
5611 ConvOvlResult);
5612 else if (!InitCategory.isLValue())
5613 Sequence.SetFailed(
5614 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5618 else {
5620 switch (RefRelationship) {
5622 if (Initializer->refersToBitField())
5623 FK = InitializationSequence::
5624 FK_NonConstLValueReferenceBindingToBitfield;
5625 else if (Initializer->refersToVectorElement())
5626 FK = InitializationSequence::
5627 FK_NonConstLValueReferenceBindingToVectorElement;
5628 else if (Initializer->refersToMatrixElement())
5629 FK = InitializationSequence::
5630 FK_NonConstLValueReferenceBindingToMatrixElement;
5631 else
5632 llvm_unreachable("unexpected kind of compatible initializer");
5633 break;
5634 case Sema::Ref_Related:
5636 break;
5638 FK = InitializationSequence::
5639 FK_NonConstLValueReferenceBindingToUnrelated;
5640 break;
5641 }
5642 Sequence.SetFailed(FK);
5643 }
5644 return;
5645 }
5646
5647 // - If the initializer expression
5648 // - is an
5649 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5650 // [1z] rvalue (but not a bit-field) or
5651 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5652 //
5653 // Note: functions are handled above and below rather than here...
5654 if (!T1Function &&
5655 (RefRelationship == Sema::Ref_Compatible ||
5656 (Kind.isCStyleOrFunctionalCast() &&
5657 RefRelationship == Sema::Ref_Related)) &&
5658 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5659 (InitCategory.isPRValue() &&
5660 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5661 T2->isArrayType())))) {
5662 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5663 if (InitCategory.isPRValue() && T2->isRecordType()) {
5664 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5665 // compiler the freedom to perform a copy here or bind to the
5666 // object, while C++0x requires that we bind directly to the
5667 // object. Hence, we always bind to the object without making an
5668 // extra copy. However, in C++03 requires that we check for the
5669 // presence of a suitable copy constructor:
5670 //
5671 // The constructor that would be used to make the copy shall
5672 // be callable whether or not the copy is actually done.
5673 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5674 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5675 else if (S.getLangOpts().CPlusPlus11)
5677 }
5678
5679 // C++1z [dcl.init.ref]/5.2.1.2:
5680 // If the converted initializer is a prvalue, its type T4 is adjusted
5681 // to type "cv1 T4" and the temporary materialization conversion is
5682 // applied.
5683 // Postpone address space conversions to after the temporary materialization
5684 // conversion to allow creating temporaries in the alloca address space.
5685 auto T1QualsIgnoreAS = T1Quals;
5686 auto T2QualsIgnoreAS = T2Quals;
5687 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5688 T1QualsIgnoreAS.removeAddressSpace();
5689 T2QualsIgnoreAS.removeAddressSpace();
5690 }
5691 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5692 // with T1's qualifiers.
5693 QualType T2ForQualConv = cv2T2;
5694 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5695 Qualifiers T2BaseQuals =
5696 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5697 T2ForQualConv = S.Context.getQualifiedType(
5698 T2ForQualConv.getUnqualifiedType(), T2BaseQuals);
5699 }
5700 QualType cv1T4 = S.Context.getQualifiedType(T2ForQualConv, T1QualsIgnoreAS);
5701 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5702 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5703 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5704 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5705 // Add addr space conversion if required.
5706 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5707 auto T4Quals = cv1T4.getQualifiers();
5708 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5709 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5710 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5711 cv1T4 = cv1T4WithAS;
5712 }
5713
5714 // In any case, the reference is bound to the resulting glvalue (or to
5715 // an appropriate base class subobject).
5716 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5717 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5718 else if (RefConv & Sema::ReferenceConversions::ObjC)
5719 Sequence.AddObjCObjectConversionStep(cv1T1);
5720 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5721 if (!S.Context.hasSameType(cv1T4, cv1T1))
5722 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5723 }
5724 return;
5725 }
5726
5727 // - has a class type (i.e., T2 is a class type), where T1 is not
5728 // reference-related to T2, and can be implicitly converted to an
5729 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5730 // where "cv1 T1" is reference-compatible with "cv3 T3",
5731 //
5732 // DR1287 removes the "implicitly" here.
5733 if (T2->isRecordType()) {
5734 if (RefRelationship == Sema::Ref_Incompatible) {
5735 ConvOvlResult = TryRefInitWithConversionFunction(
5736 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5737 /*IsLValueRef*/ isLValueRef, Sequence);
5738 if (ConvOvlResult)
5739 Sequence.SetOverloadFailure(
5741 ConvOvlResult);
5742
5743 return;
5744 }
5745
5746 if (RefRelationship == Sema::Ref_Compatible &&
5747 isRValueRef && InitCategory.isLValue()) {
5748 Sequence.SetFailed(
5750 return;
5751 }
5752
5754 return;
5755 }
5756
5757 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5758 // from the initializer expression using the rules for a non-reference
5759 // copy-initialization (8.5). The reference is then bound to the
5760 // temporary. [...]
5761
5762 // Ignore address space of reference type at this point and perform address
5763 // space conversion after the reference binding step.
5764 QualType cv1T1IgnoreAS =
5765 T1Quals.hasAddressSpace()
5767 : cv1T1;
5768
5769 InitializedEntity TempEntity =
5771
5772 // FIXME: Why do we use an implicit conversion here rather than trying
5773 // copy-initialization?
5775 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5776 /*SuppressUserConversions=*/false,
5777 Sema::AllowedExplicit::None,
5778 /*FIXME:InOverloadResolution=*/false,
5779 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5780 /*AllowObjCWritebackConversion=*/false);
5781
5782 if (ICS.isBad()) {
5783 // FIXME: Use the conversion function set stored in ICS to turn
5784 // this into an overloading ambiguity diagnostic. However, we need
5785 // to keep that set as an OverloadCandidateSet rather than as some
5786 // other kind of set.
5787 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5788 Sequence.SetOverloadFailure(
5790 ConvOvlResult);
5791 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5793 else
5795 return;
5796 } else {
5797 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5798 TopLevelOfInitList);
5799 }
5800
5801 // [...] If T1 is reference-related to T2, cv1 must be the
5802 // same cv-qualification as, or greater cv-qualification
5803 // than, cv2; otherwise, the program is ill-formed.
5804 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5805 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5806 if (RefRelationship == Sema::Ref_Related &&
5807 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5808 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5810 return;
5811 }
5812
5813 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5814 // reference, the initializer expression shall not be an lvalue.
5815 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5816 InitCategory.isLValue()) {
5817 Sequence.SetFailed(
5819 return;
5820 }
5821
5822 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5823
5824 if (T1Quals.hasAddressSpace()) {
5827 Sequence.SetFailed(
5829 return;
5830 }
5831 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5832 : VK_XValue);
5833 }
5834}
5835
5836/// Attempt character array initialization from a string literal
5837/// (C++ [dcl.init.string], C99 6.7.8).
5839 const InitializedEntity &Entity,
5840 const InitializationKind &Kind,
5842 InitializationSequence &Sequence) {
5843 Sequence.AddStringInitStep(Entity.getType());
5844}
5845
5846/// Attempt value initialization (C++ [dcl.init]p7).
5848 const InitializedEntity &Entity,
5849 const InitializationKind &Kind,
5850 InitializationSequence &Sequence,
5851 InitListExpr *InitList) {
5852 assert((!InitList || InitList->getNumInits() == 0) &&
5853 "Shouldn't use value-init for non-empty init lists");
5854
5855 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5856 //
5857 // To value-initialize an object of type T means:
5858 QualType T = Entity.getType();
5859 assert(!T->isVoidType() && "Cannot value-init void");
5860
5861 // -- if T is an array type, then each element is value-initialized;
5863
5864 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5865 bool NeedZeroInitialization = true;
5866 // C++98:
5867 // -- if T is a class type (clause 9) with a user-declared constructor
5868 // (12.1), then the default constructor for T is called (and the
5869 // initialization is ill-formed if T has no accessible default
5870 // constructor);
5871 // C++11:
5872 // -- if T is a class type (clause 9) with either no default constructor
5873 // (12.1 [class.ctor]) or a default constructor that is user-provided
5874 // or deleted, then the object is default-initialized;
5875 //
5876 // Note that the C++11 rule is the same as the C++98 rule if there are no
5877 // defaulted or deleted constructors, so we just use it unconditionally.
5879 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5880 NeedZeroInitialization = false;
5881
5882 // -- if T is a (possibly cv-qualified) non-union class type without a
5883 // user-provided or deleted default constructor, then the object is
5884 // zero-initialized and, if T has a non-trivial default constructor,
5885 // default-initialized;
5886 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5887 // constructor' part was removed by DR1507.
5888 if (NeedZeroInitialization)
5889 Sequence.AddZeroInitializationStep(Entity.getType());
5890
5891 // C++03:
5892 // -- if T is a non-union class type without a user-declared constructor,
5893 // then every non-static data member and base class component of T is
5894 // value-initialized;
5895 // [...] A program that calls for [...] value-initialization of an
5896 // entity of reference type is ill-formed.
5897 //
5898 // C++11 doesn't need this handling, because value-initialization does not
5899 // occur recursively there, and the implicit default constructor is
5900 // defined as deleted in the problematic cases.
5901 if (!S.getLangOpts().CPlusPlus11 &&
5902 ClassDecl->hasUninitializedReferenceMember()) {
5904 return;
5905 }
5906
5907 // If this is list-value-initialization, pass the empty init list on when
5908 // building the constructor call. This affects the semantics of a few
5909 // things (such as whether an explicit default constructor can be called).
5910 Expr *InitListAsExpr = InitList;
5911 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5912 bool InitListSyntax = InitList;
5913
5914 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5915 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5917 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5918 }
5919
5920 Sequence.AddZeroInitializationStep(Entity.getType());
5921}
5922
5923/// Attempt default initialization (C++ [dcl.init]p6).
5925 const InitializedEntity &Entity,
5926 const InitializationKind &Kind,
5927 InitializationSequence &Sequence) {
5928 assert(Kind.getKind() == InitializationKind::IK_Default);
5929
5930 // C++ [dcl.init]p6:
5931 // To default-initialize an object of type T means:
5932 // - if T is an array type, each element is default-initialized;
5933 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5934
5935 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5936 // constructor for T is called (and the initialization is ill-formed if
5937 // T has no accessible default constructor);
5938 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5939 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5940 Entity.getType(), Sequence);
5941 return;
5942 }
5943
5944 // - otherwise, no initialization is performed.
5945
5946 // If a program calls for the default initialization of an object of
5947 // a const-qualified type T, T shall be a class type with a user-provided
5948 // default constructor.
5949 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5950 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5952 return;
5953 }
5954
5955 // If the destination type has a lifetime property, zero-initialize it.
5956 if (DestType.getQualifiers().hasObjCLifetime()) {
5957 Sequence.AddZeroInitializationStep(Entity.getType());
5958 return;
5959 }
5960}
5961
5963 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5964 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5965 ExprResult *Result) {
5966 unsigned EntityIndexToProcess = 0;
5967 SmallVector<Expr *, 4> InitExprs;
5968 QualType ResultType;
5969 Expr *ArrayFiller = nullptr;
5970 FieldDecl *InitializedFieldInUnion = nullptr;
5971
5972 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5973 const InitializationKind &SubKind,
5974 Expr *Arg, Expr **InitExpr = nullptr) {
5976 S, SubEntity, SubKind,
5977 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5978
5979 if (IS.Failed()) {
5980 if (!VerifyOnly) {
5981 IS.Diagnose(S, SubEntity, SubKind,
5982 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5983 } else {
5984 Sequence.SetFailed(
5986 }
5987
5988 return false;
5989 }
5990 if (!VerifyOnly) {
5991 ExprResult ER;
5992 ER = IS.Perform(S, SubEntity, SubKind,
5993 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5994
5995 if (ER.isInvalid())
5996 return false;
5997
5998 if (InitExpr)
5999 *InitExpr = ER.get();
6000 else
6001 InitExprs.push_back(ER.get());
6002 }
6003 return true;
6004 };
6005
6006 if (const ArrayType *AT =
6007 S.getASTContext().getAsArrayType(Entity.getType())) {
6008 uint64_t ArrayLength;
6009 // C++ [dcl.init]p16.5
6010 // if the destination type is an array, the object is initialized as
6011 // follows. Let x1, . . . , xk be the elements of the expression-list. If
6012 // the destination type is an array of unknown bound, it is defined as
6013 // having k elements.
6014 if (const ConstantArrayType *CAT =
6016 ArrayLength = CAT->getZExtSize();
6017 ResultType = Entity.getType();
6018 } else if (const VariableArrayType *VAT =
6020 // Braced-initialization of variable array types is not allowed, even if
6021 // the size is greater than or equal to the number of args, so we don't
6022 // allow them to be initialized via parenthesized aggregate initialization
6023 // either.
6024 const Expr *SE = VAT->getSizeExpr();
6025 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
6026 << SE->getSourceRange();
6027 return;
6028 } else {
6029 assert(Entity.getType()->isIncompleteArrayType());
6030 ArrayLength = Args.size();
6031 }
6032 EntityIndexToProcess = ArrayLength;
6033
6034 // ...the ith array element is copy-initialized with xi for each
6035 // 1 <= i <= k
6036 for (Expr *E : Args) {
6038 S.getASTContext(), EntityIndexToProcess, Entity);
6040 E->getExprLoc(), /*isDirectInit=*/false, E);
6041 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6042 return;
6043 }
6044 // ...and value-initialized for each k < i <= n;
6045 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6047 S.getASTContext(), Args.size(), Entity);
6049 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6050 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6051 return;
6052 }
6053
6054 if (ResultType.isNull()) {
6055 ResultType = S.Context.getConstantArrayType(
6056 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
6057 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
6058 }
6059 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6060 bool IsUnion = RD->isUnion();
6061 if (RD->isInvalidDecl()) {
6062 // Exit early to avoid confusion when processing members.
6063 // We do the same for braced list initialization in
6064 // `CheckStructUnionTypes`.
6065 Sequence.SetFailed(
6067 return;
6068 }
6069
6070 if (!IsUnion) {
6071 for (const CXXBaseSpecifier &Base : RD->bases()) {
6073 S.getASTContext(), &Base, false, &Entity);
6074 if (EntityIndexToProcess < Args.size()) {
6075 // C++ [dcl.init]p16.6.2.2.
6076 // ...the object is initialized is follows. Let e1, ..., en be the
6077 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6078 // the elements of the expression-list...The element ei is
6079 // copy-initialized with xi for 1 <= i <= k.
6080 Expr *E = Args[EntityIndexToProcess];
6082 E->getExprLoc(), /*isDirectInit=*/false, E);
6083 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6084 return;
6085 } else {
6086 // We've processed all of the args, but there are still base classes
6087 // that have to be initialized.
6088 // C++ [dcl.init]p17.6.2.2
6089 // The remaining elements...otherwise are value initialzed
6091 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
6092 /*IsImplicit=*/true);
6093 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6094 return;
6095 }
6096 EntityIndexToProcess++;
6097 }
6098 }
6099
6100 for (FieldDecl *FD : RD->fields()) {
6101 // Unnamed bitfields should not be initialized at all, either with an arg
6102 // or by default.
6103 if (FD->isUnnamedBitField())
6104 continue;
6105
6106 InitializedEntity SubEntity =
6108
6109 if (EntityIndexToProcess < Args.size()) {
6110 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6111 Expr *E = Args[EntityIndexToProcess];
6112
6113 // Incomplete array types indicate flexible array members. Do not allow
6114 // paren list initializations of structs with these members, as GCC
6115 // doesn't either.
6116 if (FD->getType()->isIncompleteArrayType()) {
6117 if (!VerifyOnly) {
6118 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6119 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6120 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6121 }
6122 Sequence.SetFailed(
6124 return;
6125 }
6126
6128 E->getExprLoc(), /*isDirectInit=*/false, E);
6129 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6130 return;
6131
6132 // Unions should have only one initializer expression, so we bail out
6133 // after processing the first field. If there are more initializers then
6134 // it will be caught when we later check whether EntityIndexToProcess is
6135 // less than Args.size();
6136 if (IsUnion) {
6137 InitializedFieldInUnion = FD;
6138 EntityIndexToProcess = 1;
6139 break;
6140 }
6141 } else {
6142 // We've processed all of the args, but there are still members that
6143 // have to be initialized.
6144 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6145 !S.isUnevaluatedContext()) {
6146 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6147 << /* Var-in-Record */ 0 << FD;
6148 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6149 }
6150
6151 if (FD->hasInClassInitializer()) {
6152 if (!VerifyOnly) {
6153 // C++ [dcl.init]p16.6.2.2
6154 // The remaining elements are initialized with their default
6155 // member initializers, if any
6157 Kind.getParenOrBraceRange().getEnd(), FD);
6158 if (DIE.isInvalid())
6159 return;
6160 S.checkInitializerLifetime(SubEntity, DIE.get());
6161 InitExprs.push_back(DIE.get());
6162 }
6163 } else {
6164 // C++ [dcl.init]p17.6.2.2
6165 // The remaining elements...otherwise are value initialzed
6166 if (FD->getType()->isReferenceType()) {
6167 Sequence.SetFailed(
6169 if (!VerifyOnly) {
6170 SourceRange SR = Kind.getParenOrBraceRange();
6171 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6172 << FD->getType() << SR;
6173 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6174 }
6175 return;
6176 }
6178 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6179 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6180 return;
6181 }
6182 }
6183 EntityIndexToProcess++;
6184 }
6185 ResultType = Entity.getType();
6186 }
6187
6188 // Not all of the args have been processed, so there must've been more args
6189 // than were required to initialize the element.
6190 if (EntityIndexToProcess < Args.size()) {
6192 if (!VerifyOnly) {
6193 QualType T = Entity.getType();
6194 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6195 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6196 Args.back()->getEndLoc());
6197 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6198 << InitKind << ExcessInitSR;
6199 }
6200 return;
6201 }
6202
6203 if (VerifyOnly) {
6205 Sequence.AddParenthesizedListInitStep(Entity.getType());
6206 } else if (Result) {
6207 SourceRange SR = Kind.getParenOrBraceRange();
6208 auto *CPLIE = CXXParenListInitExpr::Create(
6209 S.getASTContext(), InitExprs, ResultType, Args.size(),
6210 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6211 if (ArrayFiller)
6212 CPLIE->setArrayFiller(ArrayFiller);
6213 if (InitializedFieldInUnion)
6214 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6215 *Result = CPLIE;
6216 S.Diag(Kind.getLocation(),
6217 diag::warn_cxx17_compat_aggregate_init_paren_list)
6218 << Kind.getLocation() << SR << ResultType;
6219 }
6220}
6221
6222/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6223/// which enumerates all conversion functions and performs overload resolution
6224/// to select the best.
6226 QualType DestType,
6227 const InitializationKind &Kind,
6229 InitializationSequence &Sequence,
6230 bool TopLevelOfInitList) {
6231 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6232 QualType SourceType = Initializer->getType();
6233 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6234 "Must have a class type to perform a user-defined conversion");
6235
6236 // Build the candidate set directly in the initialization sequence
6237 // structure, so that it will persist if we fail.
6238 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6240 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6241
6242 // Determine whether we are allowed to call explicit constructors or
6243 // explicit conversion operators.
6244 bool AllowExplicit = Kind.AllowExplicit();
6245
6246 if (DestType->isRecordType()) {
6247 // The type we're converting to is a class type. Enumerate its constructors
6248 // to see if there is a suitable conversion.
6249 // Try to complete the type we're converting to.
6250 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6251 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6252 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6253 auto Info = getConstructorInfo(D);
6254 if (!Info.Constructor)
6255 continue;
6256
6257 if (!Info.Constructor->isInvalidDecl() &&
6258 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6259 if (Info.ConstructorTmpl)
6261 Info.ConstructorTmpl, Info.FoundDecl,
6262 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6263 /*SuppressUserConversions=*/true,
6264 /*PartialOverloading*/ false, AllowExplicit);
6265 else
6266 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6267 Initializer, CandidateSet,
6268 /*SuppressUserConversions=*/true,
6269 /*PartialOverloading*/ false, AllowExplicit);
6270 }
6271 }
6272 }
6273 }
6274
6275 SourceLocation DeclLoc = Initializer->getBeginLoc();
6276
6277 if (SourceType->isRecordType()) {
6278 // The type we're converting from is a class type, enumerate its conversion
6279 // functions.
6280
6281 // We can only enumerate the conversion functions for a complete type; if
6282 // the type isn't complete, simply skip this step.
6283 if (S.isCompleteType(DeclLoc, SourceType)) {
6284 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6285 const auto &Conversions =
6286 SourceRecordDecl->getVisibleConversionFunctions();
6287 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6288 NamedDecl *D = *I;
6290 if (isa<UsingShadowDecl>(D))
6291 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6292
6293 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6294 CXXConversionDecl *Conv;
6295 if (ConvTemplate)
6296 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6297 else
6298 Conv = cast<CXXConversionDecl>(D);
6299
6300 if (ConvTemplate)
6302 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6303 CandidateSet, AllowExplicit, AllowExplicit);
6304 else
6305 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6306 DestType, CandidateSet, AllowExplicit,
6307 AllowExplicit);
6308 }
6309 }
6310 }
6311
6312 // Perform overload resolution. If it fails, return the failed result.
6315 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6316 Sequence.SetOverloadFailure(
6318
6319 // [class.copy.elision]p3:
6320 // In some copy-initialization contexts, a two-stage overload resolution
6321 // is performed.
6322 // If the first overload resolution selects a deleted function, we also
6323 // need the initialization sequence to decide whether to perform the second
6324 // overload resolution.
6325 if (!(Result == OR_Deleted &&
6326 Kind.getKind() == InitializationKind::IK_Copy))
6327 return;
6328 }
6329
6330 FunctionDecl *Function = Best->Function;
6331 Function->setReferenced();
6332 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6333
6334 if (isa<CXXConstructorDecl>(Function)) {
6335 // Add the user-defined conversion step. Any cv-qualification conversion is
6336 // subsumed by the initialization. Per DR5, the created temporary is of the
6337 // cv-unqualified type of the destination.
6338 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6339 DestType.getUnqualifiedType(),
6340 HadMultipleCandidates);
6341
6342 // C++14 and before:
6343 // - if the function is a constructor, the call initializes a temporary
6344 // of the cv-unqualified version of the destination type. The [...]
6345 // temporary [...] is then used to direct-initialize, according to the
6346 // rules above, the object that is the destination of the
6347 // copy-initialization.
6348 // Note that this just performs a simple object copy from the temporary.
6349 //
6350 // C++17:
6351 // - if the function is a constructor, the call is a prvalue of the
6352 // cv-unqualified version of the destination type whose return object
6353 // is initialized by the constructor. The call is used to
6354 // direct-initialize, according to the rules above, the object that
6355 // is the destination of the copy-initialization.
6356 // Therefore we need to do nothing further.
6357 //
6358 // FIXME: Mark this copy as extraneous.
6359 if (!S.getLangOpts().CPlusPlus17)
6360 Sequence.AddFinalCopy(DestType);
6361 else if (DestType.hasQualifiers())
6362 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6363 return;
6364 }
6365
6366 // Add the user-defined conversion step that calls the conversion function.
6367 QualType ConvType = Function->getCallResultType();
6368 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6369 HadMultipleCandidates);
6370
6371 if (ConvType->isRecordType()) {
6372 if (S.getLangOpts().HLSL &&
6373 ConvType.getAddressSpace() == LangAS::hlsl_constant &&
6374 S.Context.hasSameUnqualifiedType(ConvType, DestType)) {
6375 Sequence.AddHLSLBufferConversionStep(ConvType);
6376 return;
6377 }
6378
6379 // The call is used to direct-initialize [...] the object that is the
6380 // destination of the copy-initialization.
6381 //
6382 // In C++17, this does not call a constructor if we enter /17.6.1:
6383 // - If the initializer expression is a prvalue and the cv-unqualified
6384 // version of the source type is the same as the class of the
6385 // destination [... do not make an extra copy]
6386 //
6387 // FIXME: Mark this copy as extraneous.
6388 if (!S.getLangOpts().CPlusPlus17 ||
6389 Function->getReturnType()->isReferenceType() ||
6390 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6391 Sequence.AddFinalCopy(DestType);
6392 else if (!S.Context.hasSameType(ConvType, DestType))
6393 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6394 return;
6395 }
6396
6397 // If the conversion following the call to the conversion function
6398 // is interesting, add it as a separate step.
6399 assert(Best->HasFinalConversion);
6400 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6401 Best->FinalConversion.Third) {
6403 ICS.setStandard();
6404 ICS.Standard = Best->FinalConversion;
6405 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6406 }
6407}
6408
6409/// The non-zero enum values here are indexes into diagnostic alternatives.
6411
6412/// Determines whether this expression is an acceptable ICR source.
6414 bool isAddressOf, bool &isWeakAccess) {
6415 // Skip parens.
6416 e = e->IgnoreParens();
6417
6418 // Skip address-of nodes.
6419 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6420 if (op->getOpcode() == UO_AddrOf)
6421 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6422 isWeakAccess);
6423
6424 // Skip certain casts.
6425 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6426 switch (ce->getCastKind()) {
6427 case CK_Dependent:
6428 case CK_BitCast:
6429 case CK_LValueBitCast:
6430 case CK_NoOp:
6431 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6432
6433 case CK_ArrayToPointerDecay:
6434 return IIK_nonscalar;
6435
6436 case CK_NullToPointer:
6437 return IIK_okay;
6438
6439 default:
6440 break;
6441 }
6442
6443 // If we have a declaration reference, it had better be a local variable.
6444 } else if (isa<DeclRefExpr>(e)) {
6445 // set isWeakAccess to true, to mean that there will be an implicit
6446 // load which requires a cleanup.
6448 isWeakAccess = true;
6449
6450 if (!isAddressOf) return IIK_nonlocal;
6451
6452 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6453 if (!var) return IIK_nonlocal;
6454
6455 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6456
6457 // If we have a conditional operator, check both sides.
6458 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6459 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6460 isWeakAccess))
6461 return iik;
6462
6463 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6464
6465 // These are never scalar.
6466 } else if (isa<ArraySubscriptExpr>(e)) {
6467 return IIK_nonscalar;
6468
6469 // Otherwise, it needs to be a null pointer constant.
6470 } else {
6473 }
6474
6475 return IIK_nonlocal;
6476}
6477
6478/// Check whether the given expression is a valid operand for an
6479/// indirect copy/restore.
6481 assert(src->isPRValue());
6482 bool isWeakAccess = false;
6483 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6484 // If isWeakAccess to true, there will be an implicit
6485 // load which requires a cleanup.
6486 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6488
6489 if (iik == IIK_okay) return;
6490
6491 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6492 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6493 << src->getSourceRange();
6494}
6495
6496/// Determine whether we have compatible array types for the
6497/// purposes of GNU by-copy array initialization.
6498static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6499 const ArrayType *Source) {
6500 // If the source and destination array types are equivalent, we're
6501 // done.
6502 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6503 return true;
6504
6505 // Make sure that the element types are the same.
6506 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6507 return false;
6508
6509 // The only mismatch we allow is when the destination is an
6510 // incomplete array type and the source is a constant array type.
6511 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6512}
6513
6515 InitializationSequence &Sequence,
6516 const InitializedEntity &Entity,
6517 Expr *Initializer) {
6518 bool ArrayDecay = false;
6519 QualType ArgType = Initializer->getType();
6520 QualType ArgPointee;
6521 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6522 ArrayDecay = true;
6523 ArgPointee = ArgArrayType->getElementType();
6524 ArgType = S.Context.getPointerType(ArgPointee);
6525 }
6526
6527 // Handle write-back conversion.
6528 QualType ConvertedArgType;
6529 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6530 ConvertedArgType))
6531 return false;
6532
6533 // We should copy unless we're passing to an argument explicitly
6534 // marked 'out'.
6535 bool ShouldCopy = true;
6536 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6537 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6538
6539 // Do we need an lvalue conversion?
6540 if (ArrayDecay || Initializer->isGLValue()) {
6542 ICS.setStandard();
6544
6545 QualType ResultType;
6546 if (ArrayDecay) {
6548 ResultType = S.Context.getPointerType(ArgPointee);
6549 } else {
6551 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6552 }
6553
6554 Sequence.AddConversionSequenceStep(ICS, ResultType);
6555 }
6556
6557 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6558 return true;
6559}
6560
6562 InitializationSequence &Sequence,
6563 QualType DestType,
6564 Expr *Initializer) {
6565 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6566 (!Initializer->isIntegerConstantExpr(S.Context) &&
6567 !Initializer->getType()->isSamplerT()))
6568 return false;
6569
6570 Sequence.AddOCLSamplerInitStep(DestType);
6571 return true;
6572}
6573
6574static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6575 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6576 return Value && Value->isZero();
6577}
6578
6580 InitializationSequence &Sequence,
6581 QualType DestType,
6582 Expr *Initializer) {
6583 if (!S.getLangOpts().OpenCL)
6584 return false;
6585
6586 //
6587 // OpenCL 1.2 spec, s6.12.10
6588 //
6589 // The event argument can also be used to associate the
6590 // async_work_group_copy with a previous async copy allowing
6591 // an event to be shared by multiple async copies; otherwise
6592 // event should be zero.
6593 //
6594 if (DestType->isEventT() || DestType->isQueueT()) {
6596 return false;
6597
6598 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6599 return true;
6600 }
6601
6602 // We should allow zero initialization for all types defined in the
6603 // cl_intel_device_side_avc_motion_estimation extension, except
6604 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6606 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6607 DestType->isOCLIntelSubgroupAVCType()) {
6608 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6609 DestType->isOCLIntelSubgroupAVCMceResultType())
6610 return false;
6612 return false;
6613
6614 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6615 return true;
6616 }
6617
6618 return false;
6619}
6620
6622 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6623 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6624 : FailedOverloadResult(OR_Success),
6625 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6626 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6627 TreatUnavailableAsInvalid);
6628}
6629
6630/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6631/// address of that function, this returns true. Otherwise, it returns false.
6632static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6633 auto *DRE = dyn_cast<DeclRefExpr>(E);
6634 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6635 return false;
6636
6638 cast<FunctionDecl>(DRE->getDecl()));
6639}
6640
6641/// Determine whether we can perform an elementwise array copy for this kind
6642/// of entity.
6643static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6644 switch (Entity.getKind()) {
6646 // C++ [expr.prim.lambda]p24:
6647 // For array members, the array elements are direct-initialized in
6648 // increasing subscript order.
6649 return true;
6650
6652 // C++ [dcl.decomp]p1:
6653 // [...] each element is copy-initialized or direct-initialized from the
6654 // corresponding element of the assignment-expression [...]
6655 return isa<DecompositionDecl>(Entity.getDecl());
6656
6658 // C++ [class.copy.ctor]p14:
6659 // - if the member is an array, each element is direct-initialized with
6660 // the corresponding subobject of x
6661 return Entity.isImplicitMemberInitializer();
6662
6664 // All the above cases are intended to apply recursively, even though none
6665 // of them actually say that.
6666 if (auto *E = Entity.getParent())
6667 return canPerformArrayCopy(*E);
6668 break;
6669
6670 default:
6671 break;
6672 }
6673
6674 return false;
6675}
6676
6677static const FieldDecl *getConstField(const RecordDecl *RD) {
6678 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6679 for (const FieldDecl *FD : RD->fields()) {
6680 // If the field is a flexible array member, we don't want to consider it
6681 // as a const field because there's no way to initialize the FAM anyway.
6682 const ASTContext &Ctx = FD->getASTContext();
6684 Ctx, FD, FD->getType(),
6685 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6686 /*IgnoreTemplateOrMacroSubstitution=*/true))
6687 continue;
6688
6689 QualType QT = FD->getType();
6690 if (QT.isConstQualified())
6691 return FD;
6692 if (const auto *RD = QT->getAsRecordDecl()) {
6693 if (const FieldDecl *FD = getConstField(RD))
6694 return FD;
6695 }
6696 }
6697 return nullptr;
6698}
6699
6701 const InitializedEntity &Entity,
6702 const InitializationKind &Kind,
6703 MultiExprArg Args,
6704 bool TopLevelOfInitList,
6705 bool TreatUnavailableAsInvalid) {
6706 ASTContext &Context = S.Context;
6707
6708 // Eliminate non-overload placeholder types in the arguments. We
6709 // need to do this before checking whether types are dependent
6710 // because lowering a pseudo-object expression might well give us
6711 // something of dependent type.
6712 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6713 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6714 // FIXME: should we be doing this here?
6715 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6716 if (result.isInvalid()) {
6718 return;
6719 }
6720 Args[I] = result.get();
6721 }
6722
6723 // C++0x [dcl.init]p16:
6724 // The semantics of initializers are as follows. The destination type is
6725 // the type of the object or reference being initialized and the source
6726 // type is the type of the initializer expression. The source type is not
6727 // defined when the initializer is a braced-init-list or when it is a
6728 // parenthesized list of expressions.
6729 QualType DestType = Entity.getType();
6730
6731 if (DestType->isDependentType() ||
6734 return;
6735 }
6736
6737 // Almost everything is a normal sequence.
6739
6740 QualType SourceType;
6741 Expr *Initializer = nullptr;
6742 if (Args.size() == 1) {
6743 Initializer = Args[0];
6744 if (S.getLangOpts().ObjC) {
6746 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6747 Initializer) ||
6749 Args[0] = Initializer;
6750 }
6752 SourceType = Initializer->getType();
6753 }
6754
6755 // - If the initializer is a (non-parenthesized) braced-init-list, the
6756 // object is list-initialized (8.5.4).
6757 if (Kind.getKind() != InitializationKind::IK_Direct) {
6758 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6759 TryListInitialization(S, Entity, Kind, InitList, *this,
6760 TreatUnavailableAsInvalid);
6761 return;
6762 }
6763 }
6764
6765 if (!S.getLangOpts().CPlusPlus &&
6766 Kind.getKind() == InitializationKind::IK_Default) {
6767 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6768 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6769 if (Rec->hasUninitializedExplicitInitFields()) {
6770 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6771 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6772 << /* Var-in-Record */ 1 << Rec;
6774 }
6775 }
6776 // If the record has any members which are const (recursively checked),
6777 // then we want to diagnose those as being uninitialized if there is no
6778 // initializer present. However, we only do this for structure types, not
6779 // union types, because an unitialized field in a union is generally
6780 // reasonable, especially in C where unions can be used for type punning.
6781 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6782 if (const FieldDecl *FD = getConstField(Rec)) {
6783 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6784 if (Var->getStorageDuration() == SD_Static ||
6785 Var->getStorageDuration() == SD_Thread)
6786 DiagID = diag::warn_default_init_const_field;
6787
6788 bool EmitCppCompat = !S.Diags.isIgnored(
6789 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6790 Var->getLocation());
6791
6792 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6793 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6794 }
6795 }
6796 }
6797 }
6798
6799 // - If the destination type is a reference type, see 8.5.3.
6800 if (DestType->isReferenceType()) {
6801 // C++0x [dcl.init.ref]p1:
6802 // A variable declared to be a T& or T&&, that is, "reference to type T"
6803 // (8.3.2), shall be initialized by an object, or function, of type T or
6804 // by an object that can be converted into a T.
6805 // (Therefore, multiple arguments are not permitted.)
6806 if (Args.size() != 1)
6808 // C++17 [dcl.init.ref]p5:
6809 // A reference [...] is initialized by an expression [...] as follows:
6810 // If the initializer is not an expression, presumably we should reject,
6811 // but the standard fails to actually say so.
6812 else if (isa<InitListExpr>(Args[0]))
6814 else
6815 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6816 TopLevelOfInitList);
6817 return;
6818 }
6819
6820 // - If the initializer is (), the object is value-initialized.
6821 if (Kind.getKind() == InitializationKind::IK_Value ||
6822 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6823 TryValueInitialization(S, Entity, Kind, *this);
6824 return;
6825 }
6826
6827 // Handle default initialization.
6828 if (Kind.getKind() == InitializationKind::IK_Default) {
6829 TryDefaultInitialization(S, Entity, Kind, *this);
6830 return;
6831 }
6832
6833 // - If the destination type is an array of characters, an array of
6834 // char16_t, an array of char32_t, or an array of wchar_t, and the
6835 // initializer is a string literal, see 8.5.2.
6836 // - Otherwise, if the destination type is an array, the program is
6837 // ill-formed.
6838 // - Except in HLSL, where non-decaying array parameters behave like
6839 // non-array types for initialization.
6840 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6841 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6842 if (Initializer && isa<VariableArrayType>(DestAT)) {
6844 return;
6845 }
6846
6847 if (Initializer) {
6848 switch (IsStringInit(Initializer, DestAT, Context)) {
6849 case SIF_None:
6850 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6851 return;
6854 return;
6857 return;
6860 return;
6863 return;
6866 return;
6867 case SIF_Other:
6868 break;
6869 }
6870 }
6871
6872 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6873 QualType SrcType = Entity.getType();
6874 if (SrcType->isArrayParameterType())
6875 SrcType =
6876 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6877 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6878 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6879 TreatUnavailableAsInvalid);
6880 return;
6881 }
6882 }
6883
6884 // Some kinds of initialization permit an array to be initialized from
6885 // another array of the same type, and perform elementwise initialization.
6886 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6888 Entity.getType()) &&
6889 canPerformArrayCopy(Entity)) {
6890 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6891 TreatUnavailableAsInvalid);
6892 return;
6893 }
6894
6895 // Note: as an GNU C extension, we allow initialization of an
6896 // array from a compound literal that creates an array of the same
6897 // type, so long as the initializer has no side effects.
6898 if (!S.getLangOpts().CPlusPlus && Initializer &&
6899 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6900 Initializer->getType()->isArrayType()) {
6901 const ArrayType *SourceAT
6902 = Context.getAsArrayType(Initializer->getType());
6903 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6905 else if (Initializer->HasSideEffects(S.Context))
6907 else {
6908 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6909 }
6910 }
6911 // Note: as a GNU C++ extension, we allow list-initialization of a
6912 // class member of array type from a parenthesized initializer list.
6913 else if (S.getLangOpts().CPlusPlus &&
6915 isa_and_nonnull<InitListExpr>(Initializer)) {
6917 *this, TreatUnavailableAsInvalid);
6919 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6920 Kind.getKind() == InitializationKind::IK_Direct)
6921 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6922 /*VerifyOnly=*/true);
6923 else if (DestAT->getElementType()->isCharType())
6925 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6927 else
6929
6930 return;
6931 }
6932
6933 // Determine whether we should consider writeback conversions for
6934 // Objective-C ARC.
6935 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6936 Entity.isParameterKind();
6937
6938 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6939 return;
6940
6941 // We're at the end of the line for C: it's either a write-back conversion
6942 // or it's a C assignment. There's no need to check anything else.
6943 if (!S.getLangOpts().CPlusPlus) {
6944 assert(Initializer && "Initializer must be non-null");
6945 // If allowed, check whether this is an Objective-C writeback conversion.
6946 if (allowObjCWritebackConversion &&
6947 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6948 return;
6949 }
6950
6951 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6952 return;
6953
6954 // Handle initialization in C
6955 AddCAssignmentStep(DestType);
6956 MaybeProduceObjCObject(S, *this, Entity);
6957 return;
6958 }
6959
6960 assert(S.getLangOpts().CPlusPlus);
6961
6962 // - If the destination type is a (possibly cv-qualified) class type:
6963 // (except for HLSL, where user-defined record types do not have
6964 // constructors or conversion functions)
6965 if (DestType->isRecordType() &&
6966 (!S.getLangOpts().HLSL ||
6967 DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
6968 // - If the initialization is direct-initialization, or if it is
6969 // copy-initialization where the cv-unqualified version of the
6970 // source type is the same class as, or a derived class of, the
6971 // class of the destination, constructors are considered. [...]
6972 if (Kind.getKind() == InitializationKind::IK_Direct ||
6973 (Kind.getKind() == InitializationKind::IK_Copy &&
6974 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6975 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6976 SourceType, DestType))))) {
6977 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6978 *this, /*IsAggrListInit=*/false);
6979 } else {
6980 // - Otherwise (i.e., for the remaining copy-initialization cases),
6981 // user-defined conversion sequences that can convert from the
6982 // source type to the destination type or (when a conversion
6983 // function is used) to a derived class thereof are enumerated as
6984 // described in 13.3.1.4, and the best one is chosen through
6985 // overload resolution (13.3).
6986 assert(Initializer && "Initializer must be non-null");
6987 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6988 TopLevelOfInitList);
6989 }
6990 return;
6991 }
6992
6993 assert(Args.size() >= 1 && "Zero-argument case handled above");
6994
6995 // For HLSL ext vector types we allow list initialization behavior for C++
6996 // functional cast expressions which look like constructor syntax. This is
6997 // accomplished by converting initialization arguments to InitListExpr.
6998 auto ShouldTryListInitialization = [&]() -> bool {
6999 // Only try list initialization for HLSL.
7000 if (!S.getLangOpts().HLSL)
7001 return false;
7002
7003 bool DestIsVec = DestType->isExtVectorType();
7004 bool DestIsMat = DestType->isConstantMatrixType();
7005
7006 // If the destination type is neither a vector nor a matrix, then don't try
7007 // list initialization.
7008 if (!DestIsVec && !DestIsMat)
7009 return false;
7010
7011 // If there is only a single source argument, then only try list
7012 // initialization if initializing a matrix with a vector or vice versa.
7013 if (Args.size() == 1) {
7014 assert(!SourceType.isNull() &&
7015 "Source QualType should not be null when arg size is exactly 1");
7016 bool SourceIsVec = SourceType->isExtVectorType();
7017 bool SourceIsMat = SourceType->isConstantMatrixType();
7018
7019 if (DestIsMat && !SourceIsVec)
7020 return false;
7021 if (DestIsVec && !SourceIsMat)
7022 return false;
7023 }
7024
7025 // Try list initialization if the source type is null or if the
7026 // destination and source types differ.
7027 return SourceType.isNull() ||
7028 !Context.hasSameUnqualifiedType(SourceType, DestType);
7029 };
7030 if (ShouldTryListInitialization()) {
7031 InitListExpr *ILE = new (Context)
7032 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
7033 Args.back()->getEndLoc(), /*isExplicit=*/false);
7034 ILE->setType(DestType);
7035 Args[0] = ILE;
7036 TryListInitialization(S, Entity, Kind, ILE, *this,
7037 TreatUnavailableAsInvalid);
7038 return;
7039 }
7040
7041 // The remaining cases all need a source type.
7042 if (Args.size() > 1) {
7044 return;
7045 } else if (isa<InitListExpr>(Args[0])) {
7047 return;
7048 }
7049
7050 // - Otherwise, if the source type is a (possibly cv-qualified) class
7051 // type, conversion functions are considered.
7052 // (except for HLSL, where user-defined record types do not have
7053 // constructors or conversion functions).
7054 if (!SourceType.isNull() && SourceType->isRecordType() &&
7055 (!S.getLangOpts().HLSL ||
7056 SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
7057 assert(Initializer && "Initializer must be non-null");
7058 // For a conversion to _Atomic(T) from either T or a class type derived
7059 // from T, initialize the T object then convert to _Atomic type.
7060 bool NeedAtomicConversion = false;
7061 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7062 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
7063 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
7064 Atomic->getValueType())) {
7065 DestType = Atomic->getValueType();
7066 NeedAtomicConversion = true;
7067 }
7068 }
7069
7070 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7071 TopLevelOfInitList);
7072 MaybeProduceObjCObject(S, *this, Entity);
7073 if (!Failed() && NeedAtomicConversion)
7075 return;
7076 }
7077
7078 // - Otherwise, if the initialization is direct-initialization, the source
7079 // type is std::nullptr_t, and the destination type is bool, the initial
7080 // value of the object being initialized is false.
7081 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7082 DestType->isBooleanType() &&
7083 Kind.getKind() == InitializationKind::IK_Direct) {
7086 Initializer->isGLValue()),
7087 DestType);
7088 return;
7089 }
7090
7091 // - Otherwise, the initial value of the object being initialized is the
7092 // (possibly converted) value of the initializer expression. Standard
7093 // conversions (Clause 4) will be used, if necessary, to convert the
7094 // initializer expression to the cv-unqualified version of the
7095 // destination type; no user-defined conversions are considered.
7096
7098 = S.TryImplicitConversion(Initializer, DestType,
7099 /*SuppressUserConversions*/true,
7100 Sema::AllowedExplicit::None,
7101 /*InOverloadResolution*/ false,
7102 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7103 allowObjCWritebackConversion);
7104
7105 if (ICS.isStandard() &&
7107 // Objective-C ARC writeback conversion.
7108
7109 // We should copy unless we're passing to an argument explicitly
7110 // marked 'out'.
7111 bool ShouldCopy = true;
7112 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
7113 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7114
7115 // If there was an lvalue adjustment, add it as a separate conversion.
7116 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7119 LvalueICS.setStandard();
7121 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
7122 LvalueICS.Standard.First = ICS.Standard.First;
7123 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
7124 }
7125
7126 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
7127 } else if (ICS.isBad()) {
7129 Initializer->getType() == Context.OverloadTy &&
7131 /*Complain=*/false, Found))
7133 else if (Initializer->getType()->isFunctionType() &&
7136 else
7138 } else {
7139 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
7140
7141 MaybeProduceObjCObject(S, *this, Entity);
7142 }
7143}
7144
7146 for (auto &S : Steps)
7147 S.Destroy();
7148}
7149
7150//===----------------------------------------------------------------------===//
7151// Perform initialization
7152//===----------------------------------------------------------------------===//
7154 bool Diagnose = false) {
7155 switch(Entity.getKind()) {
7162
7164 if (Entity.getDecl() &&
7167
7169
7171 if (Entity.getDecl() &&
7174
7175 return !Diagnose ? AssignmentAction::Passing
7177
7179 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7181
7184 // FIXME: Can we tell apart casting vs. converting?
7186
7188 // This is really initialization, but refer to it as conversion for
7189 // consistency with CheckConvertedConstantExpression.
7191
7204 }
7205
7206 llvm_unreachable("Invalid EntityKind!");
7207}
7208
7209/// Whether we should bind a created object as a temporary when
7210/// initializing the given entity.
7243
7244/// Whether the given entity, when initialized with an object
7245/// created for that initialization, requires destruction.
7278
7279/// Get the location at which initialization diagnostics should appear.
7318
7319/// Make a (potentially elidable) temporary copy of the object
7320/// provided by the given initializer by calling the appropriate copy
7321/// constructor.
7322///
7323/// \param S The Sema object used for type-checking.
7324///
7325/// \param T The type of the temporary object, which must either be
7326/// the type of the initializer expression or a superclass thereof.
7327///
7328/// \param Entity The entity being initialized.
7329///
7330/// \param CurInit The initializer expression.
7331///
7332/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7333/// is permitted in C++03 (but not C++0x) when binding a reference to
7334/// an rvalue.
7335///
7336/// \returns An expression that copies the initializer expression into
7337/// a temporary object, or an error expression if a copy could not be
7338/// created.
7340 QualType T,
7341 const InitializedEntity &Entity,
7342 ExprResult CurInit,
7343 bool IsExtraneousCopy) {
7344 if (CurInit.isInvalid())
7345 return CurInit;
7346 // Determine which class type we're copying to.
7347 Expr *CurInitExpr = (Expr *)CurInit.get();
7348 auto *Class = T->getAsCXXRecordDecl();
7349 if (!Class)
7350 return CurInit;
7351
7352 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7353
7354 // Make sure that the type we are copying is complete.
7355 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7356 return CurInit;
7357
7358 // Perform overload resolution using the class's constructors. Per
7359 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7360 // is direct-initialization.
7363
7366 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7367 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7368 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7369 /*RequireActualConstructor=*/false,
7370 /*SecondStepOfCopyInit=*/true)) {
7371 case OR_Success:
7372 break;
7373
7375 CandidateSet.NoteCandidates(
7377 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7378 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7379 : diag::err_temp_copy_no_viable)
7380 << (int)Entity.getKind() << CurInitExpr->getType()
7381 << CurInitExpr->getSourceRange()),
7382 S, OCD_AllCandidates, CurInitExpr);
7383 if (!IsExtraneousCopy || S.isSFINAEContext())
7384 return ExprError();
7385 return CurInit;
7386
7387 case OR_Ambiguous:
7388 CandidateSet.NoteCandidates(
7389 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7390 << (int)Entity.getKind()
7391 << CurInitExpr->getType()
7392 << CurInitExpr->getSourceRange()),
7393 S, OCD_AmbiguousCandidates, CurInitExpr);
7394 return ExprError();
7395
7396 case OR_Deleted:
7397 S.Diag(Loc, diag::err_temp_copy_deleted)
7398 << (int)Entity.getKind() << CurInitExpr->getType()
7399 << CurInitExpr->getSourceRange();
7400 S.NoteDeletedFunction(Best->Function);
7401 return ExprError();
7402 }
7403
7404 bool HadMultipleCandidates = CandidateSet.size() > 1;
7405
7407 SmallVector<Expr*, 8> ConstructorArgs;
7408 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7409
7410 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7411 IsExtraneousCopy);
7412
7413 if (IsExtraneousCopy) {
7414 // If this is a totally extraneous copy for C++03 reference
7415 // binding purposes, just return the original initialization
7416 // expression. We don't generate an (elided) copy operation here
7417 // because doing so would require us to pass down a flag to avoid
7418 // infinite recursion, where each step adds another extraneous,
7419 // elidable copy.
7420
7421 // Instantiate the default arguments of any extra parameters in
7422 // the selected copy constructor, as if we were going to create a
7423 // proper call to the copy constructor.
7424 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7425 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7426 if (S.RequireCompleteType(Loc, Parm->getType(),
7427 diag::err_call_incomplete_argument))
7428 break;
7429
7430 // Build the default argument expression; we don't actually care
7431 // if this succeeds or not, because this routine will complain
7432 // if there was a problem.
7433 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7434 }
7435
7436 return CurInitExpr;
7437 }
7438
7439 // Determine the arguments required to actually perform the
7440 // constructor call (we might have derived-to-base conversions, or
7441 // the copy constructor may have default arguments).
7442 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7443 ConstructorArgs))
7444 return ExprError();
7445
7446 // C++0x [class.copy]p32:
7447 // When certain criteria are met, an implementation is allowed to
7448 // omit the copy/move construction of a class object, even if the
7449 // copy/move constructor and/or destructor for the object have
7450 // side effects. [...]
7451 // - when a temporary class object that has not been bound to a
7452 // reference (12.2) would be copied/moved to a class object
7453 // with the same cv-unqualified type, the copy/move operation
7454 // can be omitted by constructing the temporary object
7455 // directly into the target of the omitted copy/move
7456 //
7457 // Note that the other three bullets are handled elsewhere. Copy
7458 // elision for return statements and throw expressions are handled as part
7459 // of constructor initialization, while copy elision for exception handlers
7460 // is handled by the run-time.
7461 //
7462 // FIXME: If the function parameter is not the same type as the temporary, we
7463 // should still be able to elide the copy, but we don't have a way to
7464 // represent in the AST how much should be elided in this case.
7465 bool Elidable =
7466 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7468 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7469 CurInitExpr->getType());
7470
7471 // Actually perform the constructor call.
7472 CurInit = S.BuildCXXConstructExpr(
7473 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7474 HadMultipleCandidates,
7475 /*ListInit*/ false,
7476 /*StdInitListInit*/ false,
7477 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7478
7479 // If we're supposed to bind temporaries, do so.
7480 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7481 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7482 return CurInit;
7483}
7484
7485/// Check whether elidable copy construction for binding a reference to
7486/// a temporary would have succeeded if we were building in C++98 mode, for
7487/// -Wc++98-compat.
7489 const InitializedEntity &Entity,
7490 Expr *CurInitExpr) {
7491 assert(S.getLangOpts().CPlusPlus11);
7492
7493 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7494 if (!Record)
7495 return;
7496
7497 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7498 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7499 return;
7500
7501 // Find constructors which would have been considered.
7504
7505 // Perform overload resolution.
7508 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7509 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7510 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7511 /*RequireActualConstructor=*/false,
7512 /*SecondStepOfCopyInit=*/true);
7513
7514 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7515 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7516 << CurInitExpr->getSourceRange();
7517
7518 switch (OR) {
7519 case OR_Success:
7520 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7521 Best->FoundDecl, Entity, Diag);
7522 // FIXME: Check default arguments as far as that's possible.
7523 break;
7524
7526 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7527 OCD_AllCandidates, CurInitExpr);
7528 break;
7529
7530 case OR_Ambiguous:
7531 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7532 OCD_AmbiguousCandidates, CurInitExpr);
7533 break;
7534
7535 case OR_Deleted:
7536 S.Diag(Loc, Diag);
7537 S.NoteDeletedFunction(Best->Function);
7538 break;
7539 }
7540}
7541
7542void InitializationSequence::PrintInitLocationNote(Sema &S,
7543 const InitializedEntity &Entity) {
7544 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7545 if (Entity.getDecl()->getLocation().isInvalid())
7546 return;
7547
7548 if (Entity.getDecl()->getDeclName())
7549 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7550 << Entity.getDecl()->getDeclName();
7551 else
7552 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7553 }
7554 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7555 Entity.getMethodDecl())
7556 S.Diag(Entity.getMethodDecl()->getLocation(),
7557 diag::note_method_return_type_change)
7558 << Entity.getMethodDecl()->getDeclName();
7559}
7560
7561/// Returns true if the parameters describe a constructor initialization of
7562/// an explicit temporary object, e.g. "Point(x, y)".
7563static bool isExplicitTemporary(const InitializedEntity &Entity,
7564 const InitializationKind &Kind,
7565 unsigned NumArgs) {
7566 switch (Entity.getKind()) {
7570 break;
7571 default:
7572 return false;
7573 }
7574
7575 switch (Kind.getKind()) {
7577 return true;
7578 // FIXME: Hack to work around cast weirdness.
7581 return NumArgs != 1;
7582 default:
7583 return false;
7584 }
7585}
7586
7587static ExprResult
7589 const InitializedEntity &Entity,
7590 const InitializationKind &Kind,
7591 MultiExprArg Args,
7592 const InitializationSequence::Step& Step,
7593 bool &ConstructorInitRequiresZeroInit,
7594 bool IsListInitialization,
7595 bool IsStdInitListInitialization,
7596 SourceLocation LBraceLoc,
7597 SourceLocation RBraceLoc) {
7598 unsigned NumArgs = Args.size();
7601 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7602
7603 // Build a call to the selected constructor.
7604 SmallVector<Expr*, 8> ConstructorArgs;
7605 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7606 ? Kind.getEqualLoc()
7607 : Kind.getLocation();
7608
7609 if (Kind.getKind() == InitializationKind::IK_Default) {
7610 // Force even a trivial, implicit default constructor to be
7611 // semantically checked. We do this explicitly because we don't build
7612 // the definition for completely trivial constructors.
7613 assert(Constructor->getParent() && "No parent class for constructor.");
7614 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7615 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7616 S.runWithSufficientStackSpace(Loc, [&] {
7618 });
7619 }
7620 }
7621
7622 ExprResult CurInit((Expr *)nullptr);
7623
7624 // C++ [over.match.copy]p1:
7625 // - When initializing a temporary to be bound to the first parameter
7626 // of a constructor that takes a reference to possibly cv-qualified
7627 // T as its first argument, called with a single argument in the
7628 // context of direct-initialization, explicit conversion functions
7629 // are also considered.
7630 bool AllowExplicitConv =
7631 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7634
7635 // A smart pointer constructed from a nullable pointer is nullable.
7636 if (NumArgs == 1 && !Kind.isExplicitCast())
7638 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7639
7640 // Determine the arguments required to actually perform the constructor
7641 // call.
7642 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7643 ConstructorArgs, AllowExplicitConv,
7644 IsListInitialization))
7645 return ExprError();
7646
7647 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7648 // An explicitly-constructed temporary, e.g., X(1, 2).
7649 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7650 return ExprError();
7651
7652 if (Kind.getKind() == InitializationKind::IK_Value &&
7653 Constructor->isImplicit()) {
7654 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7655 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7656 unsigned I = 0;
7657 for (const FieldDecl *FD : RD->fields()) {
7658 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7659 !S.isUnevaluatedContext()) {
7660 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7661 << /* Var-in-Record */ 0 << FD;
7662 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7663 }
7664 ++I;
7665 }
7666 }
7667 }
7668
7669 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7670 if (!TSInfo)
7671 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7672 SourceRange ParenOrBraceRange =
7673 (Kind.getKind() == InitializationKind::IK_DirectList)
7674 ? SourceRange(LBraceLoc, RBraceLoc)
7675 : Kind.getParenOrBraceRange();
7676
7677 CXXConstructorDecl *CalleeDecl = Constructor;
7678 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7679 Step.Function.FoundDecl.getDecl())) {
7680 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7681 }
7682 S.MarkFunctionReferenced(Loc, CalleeDecl);
7683
7684 CurInit = S.CheckForImmediateInvocation(
7686 S.Context, CalleeDecl,
7687 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7688 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7689 IsListInitialization, IsStdInitListInitialization,
7690 ConstructorInitRequiresZeroInit),
7691 CalleeDecl);
7692 } else {
7694
7695 if (Entity.getKind() == InitializedEntity::EK_Base) {
7696 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7699 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7700 ConstructKind = CXXConstructionKind::Delegating;
7701 }
7702
7703 // Only get the parenthesis or brace range if it is a list initialization or
7704 // direct construction.
7705 SourceRange ParenOrBraceRange;
7706 if (IsListInitialization)
7707 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7708 else if (Kind.getKind() == InitializationKind::IK_Direct)
7709 ParenOrBraceRange = Kind.getParenOrBraceRange();
7710
7711 // If the entity allows NRVO, mark the construction as elidable
7712 // unconditionally.
7713 if (Entity.allowsNRVO())
7714 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7715 Step.Function.FoundDecl,
7716 Constructor, /*Elidable=*/true,
7717 ConstructorArgs,
7718 HadMultipleCandidates,
7719 IsListInitialization,
7720 IsStdInitListInitialization,
7721 ConstructorInitRequiresZeroInit,
7722 ConstructKind,
7723 ParenOrBraceRange);
7724 else
7725 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7726 Step.Function.FoundDecl,
7728 ConstructorArgs,
7729 HadMultipleCandidates,
7730 IsListInitialization,
7731 IsStdInitListInitialization,
7732 ConstructorInitRequiresZeroInit,
7733 ConstructKind,
7734 ParenOrBraceRange);
7735 }
7736 if (CurInit.isInvalid())
7737 return ExprError();
7738
7739 // Only check access if all of that succeeded.
7742 return ExprError();
7743
7744 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7746 return ExprError();
7747
7748 if (shouldBindAsTemporary(Entity))
7749 CurInit = S.MaybeBindToTemporary(CurInit.get());
7750
7751 return CurInit;
7752}
7753
7755 Expr *Init) {
7756 return sema::checkInitLifetime(*this, Entity, Init);
7757}
7758
7759static void DiagnoseNarrowingInInitList(Sema &S,
7760 const ImplicitConversionSequence &ICS,
7761 QualType PreNarrowingType,
7762 QualType EntityType,
7763 const Expr *PostInit);
7764
7765static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7766 QualType ToType, Expr *Init);
7767
7768/// Provide warnings when std::move is used on construction.
7769static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7770 bool IsReturnStmt) {
7771 if (!InitExpr)
7772 return;
7773
7775 return;
7776
7777 QualType DestType = InitExpr->getType();
7778 if (!DestType->isRecordType())
7779 return;
7780
7781 unsigned DiagID = 0;
7782 if (IsReturnStmt) {
7783 const CXXConstructExpr *CCE =
7784 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7785 if (!CCE || CCE->getNumArgs() != 1)
7786 return;
7787
7789 return;
7790
7791 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7792 }
7793
7794 // Find the std::move call and get the argument.
7795 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7796 if (!CE || !CE->isCallToStdMove())
7797 return;
7798
7799 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7800
7801 if (IsReturnStmt) {
7802 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7803 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7804 return;
7805
7806 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7807 if (!VD || !VD->hasLocalStorage())
7808 return;
7809
7810 // __block variables are not moved implicitly.
7811 if (VD->hasAttr<BlocksAttr>())
7812 return;
7813
7814 QualType SourceType = VD->getType();
7815 if (!SourceType->isRecordType())
7816 return;
7817
7818 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7819 return;
7820 }
7821
7822 // If we're returning a function parameter, copy elision
7823 // is not possible.
7824 if (isa<ParmVarDecl>(VD))
7825 DiagID = diag::warn_redundant_move_on_return;
7826 else
7827 DiagID = diag::warn_pessimizing_move_on_return;
7828 } else {
7829 DiagID = diag::warn_pessimizing_move_on_initialization;
7830 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7831 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7832 return;
7833 }
7834
7835 S.Diag(CE->getBeginLoc(), DiagID);
7836
7837 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7838 // is within a macro.
7839 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7840 if (CallBegin.isMacroID())
7841 return;
7842 SourceLocation RParen = CE->getRParenLoc();
7843 if (RParen.isMacroID())
7844 return;
7845 SourceLocation LParen;
7846 SourceLocation ArgLoc = Arg->getBeginLoc();
7847
7848 // Special testing for the argument location. Since the fix-it needs the
7849 // location right before the argument, the argument location can be in a
7850 // macro only if it is at the beginning of the macro.
7851 while (ArgLoc.isMacroID() &&
7854 }
7855
7856 if (LParen.isMacroID())
7857 return;
7858
7859 LParen = ArgLoc.getLocWithOffset(-1);
7860
7861 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7862 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7863 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7864}
7865
7866static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7867 // Check to see if we are dereferencing a null pointer. If so, this is
7868 // undefined behavior, so warn about it. This only handles the pattern
7869 // "*null", which is a very syntactic check.
7870 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7871 if (UO->getOpcode() == UO_Deref &&
7872 UO->getSubExpr()->IgnoreParenCasts()->
7873 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7874 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7875 S.PDiag(diag::warn_binding_null_to_reference)
7876 << UO->getSubExpr()->getSourceRange());
7877 }
7878}
7879
7882 bool BoundToLvalueReference) {
7883 auto MTE = new (Context)
7884 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7885
7886 // Order an ExprWithCleanups for lifetime marks.
7887 //
7888 // TODO: It'll be good to have a single place to check the access of the
7889 // destructor and generate ExprWithCleanups for various uses. Currently these
7890 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7891 // but there may be a chance to merge them.
7892 Cleanup.setExprNeedsCleanups(false);
7895 return MTE;
7896}
7897
7899 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7900 // same rule, but C99 is broken without this behavior and so we treat the
7901 // change as applying to all C language modes.
7902 // FIXME: This means that AST consumers need to deal with "prvalues" that
7903 // denote materialized temporaries. Maybe we should add another ValueKind
7904 // for "xvalue pretending to be a prvalue" for C++98 support.
7905 if (!E->isPRValue() ||
7907 return E;
7908
7909 // C++1z [conv.rval]/1: T shall be a complete type.
7910 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7911 // If so, we should check for a non-abstract class type here too.
7912 QualType T = E->getType();
7913 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7914 return ExprError();
7915
7916 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7917}
7918
7922
7923 CastKind CK = CK_NoOp;
7924
7925 if (VK == VK_PRValue) {
7926 auto PointeeTy = Ty->getPointeeType();
7927 auto ExprPointeeTy = E->getType()->getPointeeType();
7928 if (!PointeeTy.isNull() &&
7929 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7930 CK = CK_AddressSpaceConversion;
7931 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7932 CK = CK_AddressSpaceConversion;
7933 }
7934
7935 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7936}
7937
7939 const InitializedEntity &Entity,
7940 const InitializationKind &Kind,
7941 MultiExprArg Args,
7942 QualType *ResultType) {
7943 if (Failed()) {
7944 Diagnose(S, Entity, Kind, Args);
7945 return ExprError();
7946 }
7947 if (!ZeroInitializationFixit.empty()) {
7948 const Decl *D = Entity.getDecl();
7949 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7950 QualType DestType = Entity.getType();
7951
7952 // The initialization would have succeeded with this fixit. Since the fixit
7953 // is on the error, we need to build a valid AST in this case, so this isn't
7954 // handled in the Failed() branch above.
7955 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7956 // Use a more useful diagnostic for constexpr variables.
7957 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7958 << VD
7959 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7960 ZeroInitializationFixit);
7961 } else {
7962 unsigned DiagID = diag::err_default_init_const;
7963 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7964 DiagID = diag::ext_default_init_const;
7965
7966 S.Diag(Kind.getLocation(), DiagID)
7967 << DestType << DestType->isRecordType()
7968 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7969 ZeroInitializationFixit);
7970 }
7971 }
7972
7973 if (getKind() == DependentSequence) {
7974 // If the declaration is a non-dependent, incomplete array type
7975 // that has an initializer, then its type will be completed once
7976 // the initializer is instantiated.
7977 if (ResultType && !Entity.getType()->isDependentType() &&
7978 Args.size() == 1) {
7979 QualType DeclType = Entity.getType();
7980 if (const IncompleteArrayType *ArrayT
7981 = S.Context.getAsIncompleteArrayType(DeclType)) {
7982 // FIXME: We don't currently have the ability to accurately
7983 // compute the length of an initializer list without
7984 // performing full type-checking of the initializer list
7985 // (since we have to determine where braces are implicitly
7986 // introduced and such). So, we fall back to making the array
7987 // type a dependently-sized array type with no specified
7988 // bound.
7989 if (isa<InitListExpr>((Expr *)Args[0]))
7990 *ResultType = S.Context.getDependentSizedArrayType(
7991 ArrayT->getElementType(),
7992 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7993 ArrayT->getIndexTypeCVRQualifiers());
7994 }
7995 }
7996 if (Kind.getKind() == InitializationKind::IK_Direct &&
7997 !Kind.isExplicitCast()) {
7998 // Rebuild the ParenListExpr.
7999 SourceRange ParenRange = Kind.getParenOrBraceRange();
8000 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8001 Args);
8002 }
8003 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8004 Kind.isExplicitCast() ||
8005 Kind.getKind() == InitializationKind::IK_DirectList);
8006 return ExprResult(Args[0]);
8007 }
8008
8009 // No steps means no initialization.
8010 if (Steps.empty())
8011 return ExprResult((Expr *)nullptr);
8012
8013 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8014 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8015 !Entity.isParamOrTemplateParamKind()) {
8016 // Produce a C++98 compatibility warning if we are initializing a reference
8017 // from an initializer list. For parameters, we produce a better warning
8018 // elsewhere.
8019 Expr *Init = Args[0];
8020 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8021 << Init->getSourceRange();
8022 }
8023
8024 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8025 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8026 // Produce a Microsoft compatibility warning when initializing from a
8027 // predefined expression since MSVC treats predefined expressions as string
8028 // literals.
8029 Expr *Init = Args[0];
8030 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8031 }
8032
8033 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8034 QualType ETy = Entity.getType();
8035 bool HasGlobalAS = ETy.hasAddressSpace() &&
8037
8038 if (S.getLangOpts().OpenCLVersion >= 200 &&
8039 ETy->isAtomicType() && !HasGlobalAS &&
8040 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8041 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8042 << 1
8043 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8044 return ExprError();
8045 }
8046
8047 QualType DestType = Entity.getType().getNonReferenceType();
8048 // FIXME: Ugly hack around the fact that Entity.getType() is not
8049 // the same as Entity.getDecl()->getType() in cases involving type merging,
8050 // and we want latter when it makes sense.
8051 if (ResultType)
8052 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8053 Entity.getType();
8054
8055 ExprResult CurInit((Expr *)nullptr);
8056 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8057
8058 // HLSL allows vector/matrix initialization to function like list
8059 // initialization, but use the syntax of a C++-like constructor.
8060 bool IsHLSLVectorOrMatrixInit =
8061 S.getLangOpts().HLSL &&
8062 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8063 isa<InitListExpr>(Args[0]);
8064 (void)IsHLSLVectorOrMatrixInit;
8065
8066 // For initialization steps that start with a single initializer,
8067 // grab the only argument out the Args and place it into the "current"
8068 // initializer.
8069 switch (Steps.front().Kind) {
8074 case SK_BindReference:
8076 case SK_FinalCopy:
8078 case SK_UserConversion:
8087 case SK_UnwrapInitList:
8088 case SK_RewrapInitList:
8089 case SK_CAssignment:
8090 case SK_StringInit:
8092 case SK_ArrayLoopIndex:
8093 case SK_ArrayLoopInit:
8094 case SK_ArrayInit:
8095 case SK_GNUArrayInit:
8101 case SK_OCLSamplerInit:
8104 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8105 CurInit = Args[0];
8106 if (!CurInit.get()) return ExprError();
8107 break;
8108 }
8109
8115 break;
8116 }
8117
8118 // Promote from an unevaluated context to an unevaluated list context in
8119 // C++11 list-initialization; we need to instantiate entities usable in
8120 // constant expressions here in order to perform narrowing checks =(
8123 isa_and_nonnull<InitListExpr>(CurInit.get()));
8124
8125 // C++ [class.abstract]p2:
8126 // no objects of an abstract class can be created except as subobjects
8127 // of a class derived from it
8128 auto checkAbstractType = [&](QualType T) -> bool {
8129 if (Entity.getKind() == InitializedEntity::EK_Base ||
8131 return false;
8132 return S.RequireNonAbstractType(Kind.getLocation(), T,
8133 diag::err_allocation_of_abstract_type);
8134 };
8135
8136 // Walk through the computed steps for the initialization sequence,
8137 // performing the specified conversions along the way.
8138 bool ConstructorInitRequiresZeroInit = false;
8139 for (step_iterator Step = step_begin(), StepEnd = step_end();
8140 Step != StepEnd; ++Step) {
8141 if (CurInit.isInvalid())
8142 return ExprError();
8143
8144 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8145
8146 switch (Step->Kind) {
8148 // Overload resolution determined which function invoke; update the
8149 // initializer to reflect that choice.
8151 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8152 return ExprError();
8153 CurInit = S.FixOverloadedFunctionReference(CurInit,
8156 // We might get back another placeholder expression if we resolved to a
8157 // builtin.
8158 if (!CurInit.isInvalid())
8159 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8160 break;
8161
8165 // We have a derived-to-base cast that produces either an rvalue or an
8166 // lvalue. Perform that cast.
8167
8168 CXXCastPath BasePath;
8169
8170 // Casts to inaccessible base classes are allowed with C-style casts.
8171 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8173 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8174 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8175 return ExprError();
8176
8179 ? VK_LValue
8181 : VK_PRValue);
8183 CK_DerivedToBase, CurInit.get(),
8184 &BasePath, VK, FPOptionsOverride());
8185 break;
8186 }
8187
8188 case SK_BindReference:
8189 // Reference binding does not have any corresponding ASTs.
8190
8191 // Check exception specifications
8192 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8193 return ExprError();
8194
8195 // We don't check for e.g. function pointers here, since address
8196 // availability checks should only occur when the function first decays
8197 // into a pointer or reference.
8198 if (CurInit.get()->getType()->isFunctionProtoType()) {
8199 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8200 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8201 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8202 DRE->getBeginLoc()))
8203 return ExprError();
8204 }
8205 }
8206 }
8207
8208 CheckForNullPointerDereference(S, CurInit.get());
8209 break;
8210
8212 // Make sure the "temporary" is actually an rvalue.
8213 assert(CurInit.get()->isPRValue() && "not a temporary");
8214
8215 // Check exception specifications
8216 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8217 return ExprError();
8218
8219 QualType MTETy = Step->Type;
8220
8221 // When this is an incomplete array type (such as when this is
8222 // initializing an array of unknown bounds from an init list), use THAT
8223 // type instead so that we propagate the array bounds.
8224 if (MTETy->isIncompleteArrayType() &&
8225 !CurInit.get()->getType()->isIncompleteArrayType() &&
8228 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8229 MTETy = CurInit.get()->getType();
8230
8231 // Materialize the temporary into memory.
8233 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8234 CurInit = MTE;
8235
8236 // If we're extending this temporary to automatic storage duration -- we
8237 // need to register its cleanup during the full-expression's cleanups.
8238 if (MTE->getStorageDuration() == SD_Automatic &&
8239 MTE->getType().isDestructedType())
8241 break;
8242 }
8243
8244 case SK_FinalCopy:
8245 if (checkAbstractType(Step->Type))
8246 return ExprError();
8247
8248 // If the overall initialization is initializing a temporary, we already
8249 // bound our argument if it was necessary to do so. If not (if we're
8250 // ultimately initializing a non-temporary), our argument needs to be
8251 // bound since it's initializing a function parameter.
8252 // FIXME: This is a mess. Rationalize temporary destruction.
8253 if (!shouldBindAsTemporary(Entity))
8254 CurInit = S.MaybeBindToTemporary(CurInit.get());
8255 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8256 /*IsExtraneousCopy=*/false);
8257 break;
8258
8260 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8261 /*IsExtraneousCopy=*/true);
8262 break;
8263
8264 case SK_UserConversion: {
8265 // We have a user-defined conversion that invokes either a constructor
8266 // or a conversion function.
8270 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8271 bool CreatedObject = false;
8272 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8273 // Build a call to the selected constructor.
8274 SmallVector<Expr*, 8> ConstructorArgs;
8275 SourceLocation Loc = CurInit.get()->getBeginLoc();
8276
8277 // Determine the arguments required to actually perform the constructor
8278 // call.
8279 Expr *Arg = CurInit.get();
8281 MultiExprArg(&Arg, 1), Loc,
8282 ConstructorArgs))
8283 return ExprError();
8284
8285 // Build an expression that constructs a temporary.
8286 CurInit = S.BuildCXXConstructExpr(
8287 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8288 HadMultipleCandidates,
8289 /*ListInit*/ false,
8290 /*StdInitListInit*/ false,
8291 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8292 if (CurInit.isInvalid())
8293 return ExprError();
8294
8295 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8296 Entity);
8297 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8298 return ExprError();
8299
8300 CastKind = CK_ConstructorConversion;
8301 CreatedObject = true;
8302 } else {
8303 // Build a call to the conversion function.
8305 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8306 FoundFn);
8307 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8308 return ExprError();
8309
8310 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8311 HadMultipleCandidates);
8312 if (CurInit.isInvalid())
8313 return ExprError();
8314
8315 CastKind = CK_UserDefinedConversion;
8316 CreatedObject = Conversion->getReturnType()->isRecordType();
8317 }
8318
8319 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8320 return ExprError();
8321
8322 CurInit = ImplicitCastExpr::Create(
8323 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8324 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8325
8326 if (shouldBindAsTemporary(Entity))
8327 // The overall entity is temporary, so this expression should be
8328 // destroyed at the end of its full-expression.
8329 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8330 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8331 // The object outlasts the full-expression, but we need to prepare for
8332 // a destructor being run on it.
8333 // FIXME: It makes no sense to do this here. This should happen
8334 // regardless of how we initialized the entity.
8335 QualType T = CurInit.get()->getType();
8336 if (auto *Record = T->castAsCXXRecordDecl()) {
8339 S.PDiag(diag::err_access_dtor_temp) << T);
8341 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8342 return ExprError();
8343 }
8344 }
8345 break;
8346 }
8347
8351 // Perform a qualification conversion; these can never go wrong.
8354 ? VK_LValue
8356 : VK_PRValue);
8357 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8358 break;
8359 }
8360
8362 assert(CurInit.get()->isLValue() &&
8363 "function reference should be lvalue");
8364 CurInit =
8365 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8366 break;
8367
8368 case SK_AtomicConversion: {
8369 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8370 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8371 CK_NonAtomicToAtomic, VK_PRValue);
8372 break;
8373 }
8374
8377 if (const auto *FromPtrType =
8378 CurInit.get()->getType()->getAs<PointerType>()) {
8379 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8380 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8381 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8382 // Do not check static casts here because they are checked earlier
8383 // in Sema::ActOnCXXNamedCast()
8384 if (!Kind.isStaticCast()) {
8385 S.Diag(CurInit.get()->getExprLoc(),
8386 diag::warn_noderef_to_dereferenceable_pointer)
8387 << CurInit.get()->getSourceRange();
8388 }
8389 }
8390 }
8391 }
8392 Expr *Init = CurInit.get();
8394 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8395 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8396 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8398 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8399 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8400 if (CurInitExprRes.isInvalid())
8401 return ExprError();
8402
8404
8405 CurInit = CurInitExprRes;
8406
8408 S.getLangOpts().CPlusPlus)
8409 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8410 CurInit.get());
8411
8412 break;
8413 }
8414
8415 case SK_ListInitialization: {
8416 if (checkAbstractType(Step->Type))
8417 return ExprError();
8418
8419 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8420 // If we're not initializing the top-level entity, we need to create an
8421 // InitializeTemporary entity for our target type.
8422 QualType Ty = Step->Type;
8423 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8424 InitializedEntity InitEntity =
8425 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8426 InitListChecker PerformInitList(S, InitEntity,
8427 InitList, Ty, /*VerifyOnly=*/false,
8428 /*TreatUnavailableAsInvalid=*/false);
8429 if (PerformInitList.HadError())
8430 return ExprError();
8431
8432 // Hack: We must update *ResultType if available in order to set the
8433 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8434 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8435 if (ResultType &&
8436 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8437 if ((*ResultType)->isRValueReferenceType())
8439 else if ((*ResultType)->isLValueReferenceType())
8441 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8442 *ResultType = Ty;
8443 }
8444
8445 InitListExpr *StructuredInitList =
8446 PerformInitList.getFullyStructuredList();
8447 CurInit = shouldBindAsTemporary(InitEntity)
8448 ? S.MaybeBindToTemporary(StructuredInitList)
8449 : StructuredInitList;
8450 break;
8451 }
8452
8454 if (checkAbstractType(Step->Type))
8455 return ExprError();
8456
8457 // When an initializer list is passed for a parameter of type "reference
8458 // to object", we don't get an EK_Temporary entity, but instead an
8459 // EK_Parameter entity with reference type.
8460 // FIXME: This is a hack. What we really should do is create a user
8461 // conversion step for this case, but this makes it considerably more
8462 // complicated. For now, this will do.
8464 Entity.getType().getNonReferenceType());
8465 bool UseTemporary = Entity.getType()->isReferenceType();
8466 assert(Args.size() == 1 && "expected a single argument for list init");
8467 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8468 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8469 << InitList->getSourceRange();
8470 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8471 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8472 Entity,
8473 Kind, Arg, *Step,
8474 ConstructorInitRequiresZeroInit,
8475 /*IsListInitialization*/true,
8476 /*IsStdInitListInit*/false,
8477 InitList->getLBraceLoc(),
8478 InitList->getRBraceLoc());
8479 break;
8480 }
8481
8482 case SK_UnwrapInitList:
8483 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8484 break;
8485
8486 case SK_RewrapInitList: {
8487 Expr *E = CurInit.get();
8489 InitListExpr *ILE = new (S.Context)
8490 InitListExpr(S.Context, Syntactic->getLBraceLoc(), E,
8491 Syntactic->getRBraceLoc(), Syntactic->isExplicit());
8492 ILE->setSyntacticForm(Syntactic);
8493 ILE->setType(E->getType());
8494 ILE->setValueKind(E->getValueKind());
8495 CurInit = ILE;
8496 break;
8497 }
8498
8501 if (checkAbstractType(Step->Type))
8502 return ExprError();
8503
8504 // When an initializer list is passed for a parameter of type "reference
8505 // to object", we don't get an EK_Temporary entity, but instead an
8506 // EK_Parameter entity with reference type.
8507 // FIXME: This is a hack. What we really should do is create a user
8508 // conversion step for this case, but this makes it considerably more
8509 // complicated. For now, this will do.
8511 Entity.getType().getNonReferenceType());
8512 bool UseTemporary = Entity.getType()->isReferenceType();
8513 bool IsStdInitListInit =
8515 Expr *Source = CurInit.get();
8516 SourceRange Range = Kind.hasParenOrBraceRange()
8517 ? Kind.getParenOrBraceRange()
8518 : SourceRange();
8520 S, UseTemporary ? TempEntity : Entity, Kind,
8521 Source ? MultiExprArg(Source) : Args, *Step,
8522 ConstructorInitRequiresZeroInit,
8523 /*IsListInitialization*/ IsStdInitListInit,
8524 /*IsStdInitListInitialization*/ IsStdInitListInit,
8525 /*LBraceLoc*/ Range.getBegin(),
8526 /*RBraceLoc*/ Range.getEnd());
8527 break;
8528 }
8529
8530 case SK_ZeroInitialization: {
8531 step_iterator NextStep = Step;
8532 ++NextStep;
8533 if (NextStep != StepEnd &&
8534 (NextStep->Kind == SK_ConstructorInitialization ||
8535 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8536 // The need for zero-initialization is recorded directly into
8537 // the call to the object's constructor within the next step.
8538 ConstructorInitRequiresZeroInit = true;
8539 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8540 S.getLangOpts().CPlusPlus &&
8541 !Kind.isImplicitValueInit()) {
8542 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8543 if (!TSInfo)
8545 Kind.getRange().getBegin());
8546
8547 CurInit = new (S.Context) CXXScalarValueInitExpr(
8548 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8549 Kind.getRange().getEnd());
8550 } else {
8551 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8552 // Note the return value isn't used to return a ExprError() when
8553 // initialization fails . For struct initialization allows all field
8554 // assignments to be checked rather than bailing on the first error.
8555 S.BoundsSafetyCheckInitialization(Entity, Kind,
8557 Step->Type, CurInit.get());
8558 }
8559 break;
8560 }
8561
8562 case SK_CAssignment: {
8563 QualType SourceType = CurInit.get()->getType();
8564 Expr *Init = CurInit.get();
8565
8566 // Save off the initial CurInit in case we need to emit a diagnostic
8567 ExprResult InitialCurInit = Init;
8570 Step->Type, Result, true,
8572 if (Result.isInvalid())
8573 return ExprError();
8574 CurInit = Result;
8575
8576 // If this is a call, allow conversion to a transparent union.
8577 ExprResult CurInitExprRes = CurInit;
8578 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8580 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8582 if (CurInitExprRes.isInvalid())
8583 return ExprError();
8584 CurInit = CurInitExprRes;
8585
8586 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8587 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8588 CurInit.get());
8589
8590 // C23 6.7.1p6: If an object or subobject declared with storage-class
8591 // specifier constexpr has pointer, integer, or arithmetic type, any
8592 // explicit initializer value for it shall be null, an integer
8593 // constant expression, or an arithmetic constant expression,
8594 // respectively.
8596 if (Entity.getType()->getAs<PointerType>() &&
8597 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8598 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8599 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8600 return ExprError();
8601 }
8602 }
8603
8604 // Note the return value isn't used to return a ExprError() when
8605 // initialization fails. For struct initialization this allows all field
8606 // assignments to be checked rather than bailing on the first error.
8607 S.BoundsSafetyCheckInitialization(Entity, Kind,
8608 getAssignmentAction(Entity, true),
8609 Step->Type, InitialCurInit.get());
8610
8611 bool Complained;
8612 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8613 Step->Type, SourceType,
8614 InitialCurInit.get(),
8615 getAssignmentAction(Entity, true),
8616 &Complained)) {
8617 PrintInitLocationNote(S, Entity);
8618 return ExprError();
8619 } else if (Complained)
8620 PrintInitLocationNote(S, Entity);
8621 break;
8622 }
8623
8624 case SK_StringInit: {
8625 QualType Ty = Step->Type;
8626 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8627 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8628 S.Context.getAsArrayType(Ty), S, Entity,
8629 S.getLangOpts().C23 &&
8631 break;
8632 }
8633
8635 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8636 CK_ObjCObjectLValueCast,
8637 CurInit.get()->getValueKind());
8638 break;
8639
8640 case SK_ArrayLoopIndex: {
8641 Expr *Cur = CurInit.get();
8642 Expr *BaseExpr = new (S.Context)
8643 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8644 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8645 Expr *IndexExpr =
8648 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8649 ArrayLoopCommonExprs.push_back(BaseExpr);
8650 break;
8651 }
8652
8653 case SK_ArrayLoopInit: {
8654 assert(!ArrayLoopCommonExprs.empty() &&
8655 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8656 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8657 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8658 CurInit.get());
8659 break;
8660 }
8661
8662 case SK_GNUArrayInit:
8663 // Okay: we checked everything before creating this step. Note that
8664 // this is a GNU extension.
8665 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8666 << Step->Type << CurInit.get()->getType()
8667 << CurInit.get()->getSourceRange();
8669 [[fallthrough]];
8670 case SK_ArrayInit:
8671 // If the destination type is an incomplete array type, update the
8672 // type accordingly.
8673 if (ResultType) {
8674 if (const IncompleteArrayType *IncompleteDest
8676 if (const ConstantArrayType *ConstantSource
8677 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8678 *ResultType = S.Context.getConstantArrayType(
8679 IncompleteDest->getElementType(), ConstantSource->getSize(),
8680 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8681 }
8682 }
8683 }
8684 break;
8685
8687 // Okay: we checked everything before creating this step. Note that
8688 // this is a GNU extension.
8689 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8690 << CurInit.get()->getSourceRange();
8691 break;
8692
8695 checkIndirectCopyRestoreSource(S, CurInit.get());
8696 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8697 CurInit.get(), Step->Type,
8699 break;
8700
8702 CurInit = ImplicitCastExpr::Create(
8703 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8705 break;
8706
8707 case SK_StdInitializerList: {
8708 S.Diag(CurInit.get()->getExprLoc(),
8709 diag::warn_cxx98_compat_initializer_list_init)
8710 << CurInit.get()->getSourceRange();
8711
8712 // Materialize the temporary into memory.
8714 CurInit.get()->getType(), CurInit.get(),
8715 /*BoundToLvalueReference=*/false);
8716
8717 // Wrap it in a construction of a std::initializer_list<T>.
8718 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8719
8720 if (!Step->Type->isDependentType()) {
8721 QualType ElementType;
8722 [[maybe_unused]] bool IsStdInitializerList =
8723 S.isStdInitializerList(Step->Type, &ElementType);
8724 assert(IsStdInitializerList &&
8725 "StdInitializerList step to non-std::initializer_list");
8726 const auto *Record = Step->Type->castAsCXXRecordDecl();
8727 assert(Record->isCompleteDefinition() &&
8728 "std::initializer_list should have already be "
8729 "complete/instantiated by this point");
8730
8731 auto InvalidType = [&] {
8732 S.Diag(Record->getLocation(),
8733 diag::err_std_initializer_list_malformed)
8735 return ExprError();
8736 };
8737
8738 if (Record->isUnion() || Record->getNumBases() != 0 ||
8739 Record->isPolymorphic())
8740 return InvalidType();
8741
8742 RecordDecl::field_iterator Field = Record->field_begin();
8743 if (Field == Record->field_end())
8744 return InvalidType();
8745
8746 // Start pointer
8747 if (!Field->getType()->isPointerType() ||
8748 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8749 ElementType.withConst()))
8750 return InvalidType();
8751
8752 if (++Field == Record->field_end())
8753 return InvalidType();
8754
8755 // Size or end pointer
8756 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8757 if (!S.Context.hasSameType(PT->getPointeeType(),
8758 ElementType.withConst()))
8759 return InvalidType();
8760 } else {
8761 if (Field->isBitField() ||
8762 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8763 return InvalidType();
8764 }
8765
8766 if (++Field != Record->field_end())
8767 return InvalidType();
8768 }
8769
8770 // Bind the result, in case the library has given initializer_list a
8771 // non-trivial destructor.
8772 if (shouldBindAsTemporary(Entity))
8773 CurInit = S.MaybeBindToTemporary(CurInit.get());
8774 break;
8775 }
8776
8777 case SK_OCLSamplerInit: {
8778 // Sampler initialization have 5 cases:
8779 // 1. function argument passing
8780 // 1a. argument is a file-scope variable
8781 // 1b. argument is a function-scope variable
8782 // 1c. argument is one of caller function's parameters
8783 // 2. variable initialization
8784 // 2a. initializing a file-scope variable
8785 // 2b. initializing a function-scope variable
8786 //
8787 // For file-scope variables, since they cannot be initialized by function
8788 // call of __translate_sampler_initializer in LLVM IR, their references
8789 // need to be replaced by a cast from their literal initializers to
8790 // sampler type. Since sampler variables can only be used in function
8791 // calls as arguments, we only need to replace them when handling the
8792 // argument passing.
8793 assert(Step->Type->isSamplerT() &&
8794 "Sampler initialization on non-sampler type.");
8795 Expr *Init = CurInit.get()->IgnoreParens();
8796 QualType SourceType = Init->getType();
8797 // Case 1
8798 if (Entity.isParameterKind()) {
8799 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8800 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8801 << SourceType;
8802 break;
8803 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8804 auto Var = cast<VarDecl>(DRE->getDecl());
8805 // Case 1b and 1c
8806 // No cast from integer to sampler is needed.
8807 if (!Var->hasGlobalStorage()) {
8808 CurInit = ImplicitCastExpr::Create(
8809 S.Context, Step->Type, CK_LValueToRValue, Init,
8810 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8811 break;
8812 }
8813 // Case 1a
8814 // For function call with a file-scope sampler variable as argument,
8815 // get the integer literal.
8816 // Do not diagnose if the file-scope variable does not have initializer
8817 // since this has already been diagnosed when parsing the variable
8818 // declaration.
8819 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8820 break;
8821 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8822 Var->getInit()))->getSubExpr();
8823 SourceType = Init->getType();
8824 }
8825 } else {
8826 // Case 2
8827 // Check initializer is 32 bit integer constant.
8828 // If the initializer is taken from global variable, do not diagnose since
8829 // this has already been done when parsing the variable declaration.
8830 if (!Init->isConstantInitializer(S.Context))
8831 break;
8832
8833 if (!SourceType->isIntegerType() ||
8834 32 != S.Context.getIntWidth(SourceType)) {
8835 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8836 << SourceType;
8837 break;
8838 }
8839
8840 Expr::EvalResult EVResult;
8841 Init->EvaluateAsInt(EVResult, S.Context);
8842 llvm::APSInt Result = EVResult.Val.getInt();
8843 const uint64_t SamplerValue = Result.getLimitedValue();
8844 // 32-bit value of sampler's initializer is interpreted as
8845 // bit-field with the following structure:
8846 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8847 // |31 6|5 4|3 1| 0|
8848 // This structure corresponds to enum values of sampler properties
8849 // defined in SPIR spec v1.2 and also opencl-c.h
8850 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8851 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8852 if (FilterMode != 1 && FilterMode != 2 &&
8854 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8855 S.Diag(Kind.getLocation(),
8856 diag::warn_sampler_initializer_invalid_bits)
8857 << "Filter Mode";
8858 if (AddressingMode > 4)
8859 S.Diag(Kind.getLocation(),
8860 diag::warn_sampler_initializer_invalid_bits)
8861 << "Addressing Mode";
8862 }
8863
8864 // Cases 1a, 2a and 2b
8865 // Insert cast from integer to sampler.
8867 CK_IntToOCLSampler);
8868 break;
8869 }
8870 case SK_OCLZeroOpaqueType: {
8871 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8873 "Wrong type for initialization of OpenCL opaque type.");
8874
8875 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8876 CK_ZeroToOCLOpaqueType,
8877 CurInit.get()->getValueKind());
8878 break;
8879 }
8881 CurInit = nullptr;
8882 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8883 /*VerifyOnly=*/false, &CurInit);
8884 if (CurInit.get() && ResultType)
8885 *ResultType = CurInit.get()->getType();
8886 if (shouldBindAsTemporary(Entity))
8887 CurInit = S.MaybeBindToTemporary(CurInit.get());
8888 break;
8889 }
8891 CurInit = ImplicitCastExpr::Create(
8892 S.Context, Step->Type.getLocalUnqualifiedType(), CK_LValueToRValue,
8893 CurInit.get(),
8894 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8895 break;
8896 }
8897 }
8898 }
8899
8900 Expr *Init = CurInit.get();
8901 if (!Init)
8902 return ExprError();
8903
8904 // Check whether the initializer has a shorter lifetime than the initialized
8905 // entity, and if not, either lifetime-extend or warn as appropriate.
8906 S.checkInitializerLifetime(Entity, Init);
8907
8908 // Diagnose non-fatal problems with the completed initialization.
8909 if (InitializedEntity::EntityKind EK = Entity.getKind();
8912 cast<FieldDecl>(Entity.getDecl())->isBitField())
8913 S.CheckBitFieldInitialization(Kind.getLocation(),
8914 cast<FieldDecl>(Entity.getDecl()), Init);
8915
8916 // Check for std::move on construction.
8919
8920 return Init;
8921}
8922
8923/// Somewhere within T there is an uninitialized reference subobject.
8924/// Dig it out and diagnose it.
8926 QualType T) {
8927 if (T->isReferenceType()) {
8928 S.Diag(Loc, diag::err_reference_without_init)
8929 << T.getNonReferenceType();
8930 return true;
8931 }
8932
8933 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8934 if (!RD || !RD->hasUninitializedReferenceMember())
8935 return false;
8936
8937 for (const auto *FI : RD->fields()) {
8938 if (FI->isUnnamedBitField())
8939 continue;
8940
8941 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8942 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8943 return true;
8944 }
8945 }
8946
8947 for (const auto &BI : RD->bases()) {
8948 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8949 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8950 return true;
8951 }
8952 }
8953
8954 return false;
8955}
8956
8957
8958//===----------------------------------------------------------------------===//
8959// Diagnose initialization failures
8960//===----------------------------------------------------------------------===//
8961
8962/// Emit notes associated with an initialization that failed due to a
8963/// "simple" conversion failure.
8964static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8965 Expr *op) {
8966 QualType destType = entity.getType();
8967 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8969
8970 // Emit a possible note about the conversion failing because the
8971 // operand is a message send with a related result type.
8973
8974 // Emit a possible note about a return failing because we're
8975 // expecting a related result type.
8976 if (entity.getKind() == InitializedEntity::EK_Result)
8978 }
8979 QualType fromType = op->getType();
8980 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8981 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8982 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8983 auto *destDecl = destType->getPointeeCXXRecordDecl();
8984 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8985 destDecl->getDeclKind() == Decl::CXXRecord &&
8986 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8987 !fromDecl->hasDefinition() &&
8988 destPointeeType.getQualifiers().compatiblyIncludes(
8989 fromPointeeType.getQualifiers(), S.getASTContext()))
8990 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8991 << S.getASTContext().getCanonicalTagType(fromDecl)
8992 << S.getASTContext().getCanonicalTagType(destDecl);
8993}
8994
8995static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8996 InitListExpr *InitList) {
8997 QualType DestType = Entity.getType();
8998
8999 QualType E;
9000 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9002 E.withConst(),
9003 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9004 InitList->getNumInits()),
9006 InitializedEntity HiddenArray =
9008 return diagnoseListInit(S, HiddenArray, InitList);
9009 }
9010
9011 if (DestType->isReferenceType()) {
9012 // A list-initialization failure for a reference means that we tried to
9013 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9014 // inner initialization failed.
9015 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9017 SourceLocation Loc = InitList->getBeginLoc();
9018 if (auto *D = Entity.getDecl())
9019 Loc = D->getLocation();
9020 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9021 return;
9022 }
9023
9024 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9025 /*VerifyOnly=*/false,
9026 /*TreatUnavailableAsInvalid=*/false);
9027 assert(DiagnoseInitList.HadError() &&
9028 "Inconsistent init list check result.");
9029}
9030
9032 const InitializedEntity &Entity,
9033 const InitializationKind &Kind,
9034 ArrayRef<Expr *> Args) {
9035 if (!Failed())
9036 return false;
9037
9038 QualType DestType = Entity.getType();
9039
9040 // When we want to diagnose only one element of a braced-init-list,
9041 // we need to factor it out.
9042 Expr *OnlyArg;
9043 if (Args.size() == 1) {
9044 auto *List = dyn_cast<InitListExpr>(Args[0]);
9045 if (List && List->getNumInits() == 1)
9046 OnlyArg = List->getInit(0);
9047 else
9048 OnlyArg = Args[0];
9049
9050 if (OnlyArg->getType() == S.Context.OverloadTy) {
9053 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9054 Found)) {
9055 if (Expr *Resolved =
9056 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9057 OnlyArg = Resolved;
9058 }
9059 }
9060 }
9061 else
9062 OnlyArg = nullptr;
9063
9064 switch (Failure) {
9066 // FIXME: Customize for the initialized entity?
9067 if (Args.empty()) {
9068 // Dig out the reference subobject which is uninitialized and diagnose it.
9069 // If this is value-initialization, this could be nested some way within
9070 // the target type.
9071 assert(Kind.getKind() == InitializationKind::IK_Value ||
9072 DestType->isReferenceType());
9073 bool Diagnosed =
9074 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9075 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9076 (void)Diagnosed;
9077 } else // FIXME: diagnostic below could be better!
9078 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9079 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9080 break;
9082 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9083 << 1 << Entity.getType() << Args[0]->getSourceRange();
9084 break;
9085
9087 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9088 break;
9090 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9091 break;
9093 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9094 break;
9096 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9097 break;
9099 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9100 break;
9102 S.Diag(Kind.getLocation(),
9103 diag::err_array_init_incompat_wide_string_into_wchar);
9104 break;
9106 S.Diag(Kind.getLocation(),
9107 diag::err_array_init_plain_string_into_char8_t);
9108 S.Diag(Args.front()->getBeginLoc(),
9109 diag::note_array_init_plain_string_into_char8_t)
9110 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9111 break;
9113 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9114 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9115 break;
9118 S.Diag(Kind.getLocation(),
9119 (Failure == FK_ArrayTypeMismatch
9120 ? diag::err_array_init_different_type
9121 : diag::err_array_init_non_constant_array))
9122 << DestType.getNonReferenceType()
9123 << OnlyArg->getType()
9124 << Args[0]->getSourceRange();
9125 break;
9126
9128 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9129 << Args[0]->getSourceRange();
9130 break;
9131
9135 DestType.getNonReferenceType(),
9136 true,
9137 Found);
9138 break;
9139 }
9140
9142 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9143 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9144 OnlyArg->getBeginLoc());
9145 break;
9146 }
9147
9150 switch (FailedOverloadResult) {
9151 case OR_Ambiguous:
9152
9153 FailedCandidateSet.NoteCandidates(
9155 Kind.getLocation(),
9157 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9158 << OnlyArg->getType() << DestType
9159 << Args[0]->getSourceRange())
9160 : (S.PDiag(diag::err_ref_init_ambiguous)
9161 << DestType << OnlyArg->getType()
9162 << Args[0]->getSourceRange())),
9163 S, OCD_AmbiguousCandidates, Args);
9164 break;
9165
9166 case OR_No_Viable_Function: {
9167 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9168 if (!S.RequireCompleteType(Kind.getLocation(),
9169 DestType.getNonReferenceType(),
9170 diag::err_typecheck_nonviable_condition_incomplete,
9171 OnlyArg->getType(), Args[0]->getSourceRange()))
9172 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9173 << (Entity.getKind() == InitializedEntity::EK_Result)
9174 << OnlyArg->getType() << Args[0]->getSourceRange()
9175 << DestType.getNonReferenceType();
9176
9177 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9178 break;
9179 }
9180 case OR_Deleted: {
9183 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9184
9185 StringLiteral *Msg = Best->Function->getDeletedMessage();
9186 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9187 << OnlyArg->getType() << DestType.getNonReferenceType()
9188 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9189 << Args[0]->getSourceRange();
9190 if (Ovl == OR_Deleted) {
9191 S.NoteDeletedFunction(Best->Function);
9192 } else {
9193 llvm_unreachable("Inconsistent overload resolution?");
9194 }
9195 break;
9196 }
9197
9198 case OR_Success:
9199 llvm_unreachable("Conversion did not fail!");
9200 }
9201 break;
9202
9204 if (isa<InitListExpr>(Args[0])) {
9205 S.Diag(Kind.getLocation(),
9206 diag::err_lvalue_reference_bind_to_initlist)
9208 << DestType.getNonReferenceType()
9209 << Args[0]->getSourceRange();
9210 break;
9211 }
9212 [[fallthrough]];
9213
9215 S.Diag(Kind.getLocation(),
9217 ? diag::err_lvalue_reference_bind_to_temporary
9218 : diag::err_lvalue_reference_bind_to_unrelated)
9220 << DestType.getNonReferenceType()
9221 << OnlyArg->getType()
9222 << Args[0]->getSourceRange();
9223 break;
9224
9226 // We don't necessarily have an unambiguous source bit-field.
9227 FieldDecl *BitField = Args[0]->getSourceBitField();
9228 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9229 << DestType.isVolatileQualified()
9230 << (BitField ? BitField->getDeclName() : DeclarationName())
9231 << (BitField != nullptr)
9232 << Args[0]->getSourceRange();
9233 if (BitField)
9234 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9235 break;
9236 }
9237
9239 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9240 << DestType.isVolatileQualified()
9241 << Args[0]->getSourceRange();
9242 break;
9243
9245 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9246 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9247 break;
9248
9250 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9251 << DestType.getNonReferenceType() << OnlyArg->getType()
9252 << Args[0]->getSourceRange();
9253 break;
9254
9256 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9257 << DestType << Args[0]->getSourceRange();
9258 break;
9259
9261 QualType SourceType = OnlyArg->getType();
9262 QualType NonRefType = DestType.getNonReferenceType();
9263 Qualifiers DroppedQualifiers =
9264 SourceType.getQualifiers() - NonRefType.getQualifiers();
9265
9266 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9267 SourceType.getQualifiers(), S.getASTContext()))
9268 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9269 << NonRefType << SourceType << 1 /*addr space*/
9270 << Args[0]->getSourceRange();
9271 else if (DroppedQualifiers.hasQualifiers())
9272 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9273 << NonRefType << SourceType << 0 /*cv quals*/
9274 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9275 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9276 else
9277 // FIXME: Consider decomposing the type and explaining which qualifiers
9278 // were dropped where, or on which level a 'const' is missing, etc.
9279 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9280 << NonRefType << SourceType << 2 /*incompatible quals*/
9281 << Args[0]->getSourceRange();
9282 break;
9283 }
9284
9286 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9287 << DestType.getNonReferenceType()
9288 << DestType.getNonReferenceType()->isIncompleteType()
9289 << OnlyArg->isLValue()
9290 << OnlyArg->getType()
9291 << Args[0]->getSourceRange();
9292 emitBadConversionNotes(S, Entity, Args[0]);
9293 break;
9294
9295 case FK_ConversionFailed: {
9296 QualType FromType = OnlyArg->getType();
9297 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9298 // type, although this is almost always an error and we advise against it.
9299 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9300 DestType == S.Context.getLogicalOperationType()) {
9301 S.Diag(OnlyArg->getExprLoc(),
9302 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9303 << OnlyArg << DestType;
9304 break;
9305 }
9306 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9307 << (int)Entity.getKind()
9308 << DestType
9309 << OnlyArg->isLValue()
9310 << FromType
9311 << Args[0]->getSourceRange();
9312 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9313 S.Diag(Kind.getLocation(), PDiag);
9314 emitBadConversionNotes(S, Entity, Args[0]);
9315 break;
9316 }
9317
9319 // No-op. This error has already been reported.
9320 break;
9321
9323 SourceRange R;
9324
9325 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9326 if (InitList && InitList->getNumInits() >= 1) {
9327 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9328 } else {
9329 assert(Args.size() > 1 && "Expected multiple initializers!");
9330 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9331 }
9332
9333 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9334 if (Kind.isCStyleOrFunctionalCast())
9335 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9336 << R;
9337 else
9338 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9339 << /*scalar=*/3 << R;
9340 break;
9341 }
9342
9344 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9345 << 0 << Entity.getType() << Args[0]->getSourceRange();
9346 break;
9347
9349 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9350 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9351 break;
9352
9354 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9355 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9356 break;
9357
9360 SourceRange ArgsRange;
9361 if (Args.size())
9362 ArgsRange =
9363 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9364
9365 if (Failure == FK_ListConstructorOverloadFailed) {
9366 assert(Args.size() == 1 &&
9367 "List construction from other than 1 argument.");
9368 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9369 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9370 }
9371
9372 // FIXME: Using "DestType" for the entity we're printing is probably
9373 // bad.
9374 switch (FailedOverloadResult) {
9375 case OR_Ambiguous:
9376 FailedCandidateSet.NoteCandidates(
9377 PartialDiagnosticAt(Kind.getLocation(),
9378 S.PDiag(diag::err_ovl_ambiguous_init)
9379 << DestType << ArgsRange),
9380 S, OCD_AmbiguousCandidates, Args);
9381 break;
9382
9384 if (Kind.getKind() == InitializationKind::IK_Default &&
9385 (Entity.getKind() == InitializedEntity::EK_Base ||
9389 // This is implicit default initialization of a member or
9390 // base within a constructor. If no viable function was
9391 // found, notify the user that they need to explicitly
9392 // initialize this base/member.
9395 const CXXRecordDecl *InheritedFrom = nullptr;
9396 if (auto Inherited = Constructor->getInheritedConstructor())
9397 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9398 if (Entity.getKind() == InitializedEntity::EK_Base) {
9399 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9400 << (InheritedFrom ? 2
9401 : Constructor->isImplicit() ? 1
9402 : 0)
9403 << S.Context.getCanonicalTagType(Constructor->getParent())
9404 << /*base=*/0 << Entity.getType() << InheritedFrom;
9405
9406 auto *BaseDecl =
9408 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9409 << S.Context.getCanonicalTagType(BaseDecl);
9410 } else {
9411 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9412 << (InheritedFrom ? 2
9413 : Constructor->isImplicit() ? 1
9414 : 0)
9415 << S.Context.getCanonicalTagType(Constructor->getParent())
9416 << /*member=*/1 << Entity.getName() << InheritedFrom;
9417 S.Diag(Entity.getDecl()->getLocation(),
9418 diag::note_member_declared_at);
9419
9420 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9421 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9422 << S.Context.getCanonicalTagType(Record->getDecl());
9423 }
9424 break;
9425 }
9426
9427 FailedCandidateSet.NoteCandidates(
9429 Kind.getLocation(),
9430 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9431 << DestType << ArgsRange),
9432 S, OCD_AllCandidates, Args);
9433 break;
9434
9435 case OR_Deleted: {
9438 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9439 if (Ovl != OR_Deleted) {
9440 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9441 << DestType << ArgsRange;
9442 llvm_unreachable("Inconsistent overload resolution?");
9443 break;
9444 }
9445
9446 // If this is a defaulted or implicitly-declared function, then
9447 // it was implicitly deleted. Make it clear that the deletion was
9448 // implicit.
9449 if (S.isImplicitlyDeleted(Best->Function))
9450 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9451 << cast<CXXMethodDecl>(Best->Function)->getSpecialMemberKind()
9452 << DestType << ArgsRange;
9453 else {
9454 StringLiteral *Msg = Best->Function->getDeletedMessage();
9455 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9456 << DestType << (Msg != nullptr)
9457 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9458 }
9459
9460 // If it's a default constructed member, but it's not in the
9461 // constructor's initializer list, explicitly note where the member is
9462 // declared so the user can see which member is erroneously initialized
9463 // with a deleted default constructor.
9464 if (Kind.getKind() == InitializationKind::IK_Default &&
9467 S.Diag(Entity.getDecl()->getLocation(),
9468 diag::note_default_constructed_field)
9469 << Entity.getDecl();
9470 }
9471 S.NoteDeletedFunction(Best->Function);
9472 break;
9473 }
9474
9475 case OR_Success:
9476 llvm_unreachable("Conversion did not fail!");
9477 }
9478 }
9479 break;
9480
9482 if (Entity.getKind() == InitializedEntity::EK_Member &&
9484 // This is implicit default-initialization of a const member in
9485 // a constructor. Complain that it needs to be explicitly
9486 // initialized.
9488 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9489 << (Constructor->getInheritedConstructor() ? 2
9490 : Constructor->isImplicit() ? 1
9491 : 0)
9492 << S.Context.getCanonicalTagType(Constructor->getParent())
9493 << /*const=*/1 << Entity.getName();
9494 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9495 << Entity.getName();
9496 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9497 VD && VD->isConstexpr()) {
9498 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9499 << VD;
9500 } else {
9501 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9502 << DestType << DestType->isRecordType();
9503 }
9504 break;
9505
9506 case FK_Incomplete:
9507 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9508 diag::err_init_incomplete_type);
9509 break;
9510
9512 // Run the init list checker again to emit diagnostics.
9513 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9514 diagnoseListInit(S, Entity, InitList);
9515 break;
9516 }
9517
9518 case FK_PlaceholderType: {
9519 // FIXME: Already diagnosed!
9520 break;
9521 }
9522
9524 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9525 // allows us to diagnose the failure when it happens in the
9526 // TryListInitialization call instead of delaying the diagnosis, which is
9527 // beneficial because the flattening is also expensive.
9528 break;
9529 }
9530
9532 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9533 << Args[0]->getSourceRange();
9536 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9537 (void)Ovl;
9538 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9539 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9540 S.Diag(CtorDecl->getLocation(),
9541 diag::note_explicit_ctor_deduction_guide_here) << false;
9542 break;
9543 }
9544
9546 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9547 /*VerifyOnly=*/false);
9548 break;
9549
9551 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9552 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9553 << Entity.getType() << InitList->getSourceRange();
9554 break;
9555 }
9556
9557 PrintInitLocationNote(S, Entity);
9558 return true;
9559}
9560
9561void InitializationSequence::dump(raw_ostream &OS) const {
9562 switch (SequenceKind) {
9563 case FailedSequence: {
9564 OS << "Failed sequence: ";
9565 switch (Failure) {
9567 OS << "too many initializers for reference";
9568 break;
9569
9571 OS << "parenthesized list init for reference";
9572 break;
9573
9575 OS << "array requires initializer list";
9576 break;
9577
9579 OS << "address of unaddressable function was taken";
9580 break;
9581
9583 OS << "array requires initializer list or string literal";
9584 break;
9585
9587 OS << "array requires initializer list or wide string literal";
9588 break;
9589
9591 OS << "narrow string into wide char array";
9592 break;
9593
9595 OS << "wide string into char array";
9596 break;
9597
9599 OS << "incompatible wide string into wide char array";
9600 break;
9601
9603 OS << "plain string literal into char8_t array";
9604 break;
9605
9607 OS << "u8 string literal into char array";
9608 break;
9609
9611 OS << "array type mismatch";
9612 break;
9613
9615 OS << "non-constant array initializer";
9616 break;
9617
9619 OS << "address of overloaded function failed";
9620 break;
9621
9623 OS << "overload resolution for reference initialization failed";
9624 break;
9625
9627 OS << "non-const lvalue reference bound to temporary";
9628 break;
9629
9631 OS << "non-const lvalue reference bound to bit-field";
9632 break;
9633
9635 OS << "non-const lvalue reference bound to vector element";
9636 break;
9637
9639 OS << "non-const lvalue reference bound to matrix element";
9640 break;
9641
9643 OS << "non-const lvalue reference bound to unrelated type";
9644 break;
9645
9647 OS << "rvalue reference bound to an lvalue";
9648 break;
9649
9651 OS << "reference initialization drops qualifiers";
9652 break;
9653
9655 OS << "reference with mismatching address space bound to temporary";
9656 break;
9657
9659 OS << "reference initialization failed";
9660 break;
9661
9663 OS << "conversion failed";
9664 break;
9665
9667 OS << "conversion from property failed";
9668 break;
9669
9671 OS << "too many initializers for scalar";
9672 break;
9673
9675 OS << "parenthesized list init for reference";
9676 break;
9677
9679 OS << "referencing binding to initializer list";
9680 break;
9681
9683 OS << "initializer list for non-aggregate, non-scalar type";
9684 break;
9685
9687 OS << "overloading failed for user-defined conversion";
9688 break;
9689
9691 OS << "constructor overloading failed";
9692 break;
9693
9695 OS << "default initialization of a const variable";
9696 break;
9697
9698 case FK_Incomplete:
9699 OS << "initialization of incomplete type";
9700 break;
9701
9703 OS << "list initialization checker failure";
9704 break;
9705
9707 OS << "variable length array has an initializer";
9708 break;
9709
9710 case FK_PlaceholderType:
9711 OS << "initializer expression isn't contextually valid";
9712 break;
9713
9715 OS << "list constructor overloading failed";
9716 break;
9717
9719 OS << "list copy initialization chose explicit constructor";
9720 break;
9721
9723 OS << "parenthesized list initialization failed";
9724 break;
9725
9727 OS << "designated initializer for non-aggregate type";
9728 break;
9729
9731 OS << "HLSL initialization list flattening failed";
9732 break;
9733 }
9734 OS << '\n';
9735 return;
9736 }
9737
9738 case DependentSequence:
9739 OS << "Dependent sequence\n";
9740 return;
9741
9742 case NormalSequence:
9743 OS << "Normal sequence: ";
9744 break;
9745 }
9746
9747 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9748 if (S != step_begin()) {
9749 OS << " -> ";
9750 }
9751
9752 switch (S->Kind) {
9754 OS << "resolve address of overloaded function";
9755 break;
9756
9758 OS << "derived-to-base (prvalue)";
9759 break;
9760
9762 OS << "derived-to-base (xvalue)";
9763 break;
9764
9766 OS << "derived-to-base (lvalue)";
9767 break;
9768
9769 case SK_BindReference:
9770 OS << "bind reference to lvalue";
9771 break;
9772
9774 OS << "bind reference to a temporary";
9775 break;
9776
9777 case SK_FinalCopy:
9778 OS << "final copy in class direct-initialization";
9779 break;
9780
9782 OS << "extraneous C++03 copy to temporary";
9783 break;
9784
9785 case SK_UserConversion:
9786 OS << "user-defined conversion via " << *S->Function.Function;
9787 break;
9788
9790 OS << "qualification conversion (prvalue)";
9791 break;
9792
9794 OS << "qualification conversion (xvalue)";
9795 break;
9796
9798 OS << "qualification conversion (lvalue)";
9799 break;
9800
9802 OS << "function reference conversion";
9803 break;
9804
9806 OS << "non-atomic-to-atomic conversion";
9807 break;
9808
9810 OS << "implicit conversion sequence (";
9811 S->ICS->dump(); // FIXME: use OS
9812 OS << ")";
9813 break;
9814
9816 OS << "implicit conversion sequence with narrowing prohibited (";
9817 S->ICS->dump(); // FIXME: use OS
9818 OS << ")";
9819 break;
9820
9822 OS << "list aggregate initialization";
9823 break;
9824
9825 case SK_UnwrapInitList:
9826 OS << "unwrap reference initializer list";
9827 break;
9828
9829 case SK_RewrapInitList:
9830 OS << "rewrap reference initializer list";
9831 break;
9832
9834 OS << "constructor initialization";
9835 break;
9836
9838 OS << "list initialization via constructor";
9839 break;
9840
9842 OS << "zero initialization";
9843 break;
9844
9845 case SK_CAssignment:
9846 OS << "C assignment";
9847 break;
9848
9849 case SK_StringInit:
9850 OS << "string initialization";
9851 break;
9852
9854 OS << "Objective-C object conversion";
9855 break;
9856
9857 case SK_ArrayLoopIndex:
9858 OS << "indexing for array initialization loop";
9859 break;
9860
9861 case SK_ArrayLoopInit:
9862 OS << "array initialization loop";
9863 break;
9864
9865 case SK_ArrayInit:
9866 OS << "array initialization";
9867 break;
9868
9869 case SK_GNUArrayInit:
9870 OS << "array initialization (GNU extension)";
9871 break;
9872
9874 OS << "parenthesized array initialization";
9875 break;
9876
9878 OS << "pass by indirect copy and restore";
9879 break;
9880
9882 OS << "pass by indirect restore";
9883 break;
9884
9886 OS << "Objective-C object retension";
9887 break;
9888
9890 OS << "std::initializer_list from initializer list";
9891 break;
9892
9894 OS << "list initialization from std::initializer_list";
9895 break;
9896
9897 case SK_OCLSamplerInit:
9898 OS << "OpenCL sampler_t from integer constant";
9899 break;
9900
9902 OS << "OpenCL opaque type from zero";
9903 break;
9904
9906 OS << "initialization from a parenthesized list of values";
9907 break;
9908
9910 OS << "HLSL buffer conversion";
9911 break;
9912 }
9913
9914 OS << " [" << S->Type << ']';
9915 }
9916
9917 OS << '\n';
9918}
9919
9921 dump(llvm::errs());
9922}
9923
9925 const ImplicitConversionSequence &ICS,
9926 QualType PreNarrowingType,
9927 QualType EntityType,
9928 const Expr *PostInit) {
9929 const StandardConversionSequence *SCS = nullptr;
9930 switch (ICS.getKind()) {
9932 SCS = &ICS.Standard;
9933 break;
9935 SCS = &ICS.UserDefined.After;
9936 break;
9941 return;
9942 }
9943
9944 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9945 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9946 unsigned DiagID;
9947 auto &L = S.getLangOpts();
9948 if (L.CPlusPlus11 && !L.HLSL &&
9949 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9950 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9951 else
9952 DiagID = WarnDiagID;
9953 return S.Diag(PostInit->getBeginLoc(), DiagID)
9954 << PostInit->getSourceRange();
9955 };
9956
9957 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9958 APValue ConstantValue;
9959 QualType ConstantType;
9960 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9961 ConstantType)) {
9962 case NK_Not_Narrowing:
9964 // No narrowing occurred.
9965 return;
9966
9967 case NK_Type_Narrowing: {
9968 // This was a floating-to-integer conversion, which is always considered a
9969 // narrowing conversion even if the value is a constant and can be
9970 // represented exactly as an integer.
9971 QualType T = EntityType.getNonReferenceType();
9972 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9973 diag::ext_init_list_type_narrowing_const_reference,
9974 diag::warn_init_list_type_narrowing)
9975 << PreNarrowingType.getLocalUnqualifiedType()
9976 << T.getLocalUnqualifiedType();
9977 break;
9978 }
9979
9980 case NK_Constant_Narrowing: {
9981 // A constant value was narrowed.
9982 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9983 diag::ext_init_list_constant_narrowing,
9984 diag::ext_init_list_constant_narrowing_const_reference,
9985 diag::warn_init_list_constant_narrowing)
9986 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9988 break;
9989 }
9990
9991 case NK_Variable_Narrowing: {
9992 // A variable's value may have been narrowed.
9993 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9994 diag::ext_init_list_variable_narrowing,
9995 diag::ext_init_list_variable_narrowing_const_reference,
9996 diag::warn_init_list_variable_narrowing)
9997 << PreNarrowingType.getLocalUnqualifiedType()
9999 break;
10000 }
10001 }
10002
10003 SmallString<128> StaticCast;
10004 llvm::raw_svector_ostream OS(StaticCast);
10005 OS << "static_cast<";
10006 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10007 // It's important to use the typedef's name if there is one so that the
10008 // fixit doesn't break code using types like int64_t.
10009 //
10010 // FIXME: This will break if the typedef requires qualification. But
10011 // getQualifiedNameAsString() includes non-machine-parsable components.
10012 OS << *TT->getDecl();
10013 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10014 OS << BT->getName(S.getLangOpts());
10015 else {
10016 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10017 // with a broken cast.
10018 return;
10019 }
10020 OS << ">(";
10021 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10022 << PostInit->getSourceRange()
10023 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10025 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10026}
10027
10029 QualType ToType, Expr *Init) {
10030 assert(S.getLangOpts().C23);
10032 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10033 Sema::AllowedExplicit::None,
10034 /*InOverloadResolution*/ false,
10035 /*CStyle*/ false,
10036 /*AllowObjCWritebackConversion=*/false);
10037
10038 if (!ICS.isStandard())
10039 return;
10040
10041 APValue Value;
10042 QualType PreNarrowingType;
10043 // Reuse C++ narrowing check.
10044 switch (ICS.Standard.getNarrowingKind(
10045 S.Context, Init, Value, PreNarrowingType,
10046 /*IgnoreFloatToIntegralConversion*/ false)) {
10047 // The value doesn't fit.
10049 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10050 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10051 return;
10052
10053 // Conversion to a narrower type.
10054 case NK_Type_Narrowing:
10055 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10056 << ToType << FromType;
10057 return;
10058
10059 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10060 // not really interested in these cases.
10063 case NK_Not_Narrowing:
10064 return;
10065 }
10066 llvm_unreachable("unhandled case in switch");
10067}
10068
10070 Sema &SemaRef, QualType &TT) {
10071 assert(SemaRef.getLangOpts().C23);
10072 // character that string literal contains fits into TT - target type.
10073 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10074 QualType CharType = AT->getElementType();
10075 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10076 bool isUnsigned = CharType->isUnsignedIntegerType();
10077 llvm::APSInt Value(BitWidth, isUnsigned);
10078 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10079 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10080 Value = C;
10081 if (Value != C) {
10082 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10083 diag::err_c23_constexpr_init_not_representable)
10084 << C << CharType;
10085 return;
10086 }
10087 }
10088}
10089
10090//===----------------------------------------------------------------------===//
10091// Initialization helper functions
10092//===----------------------------------------------------------------------===//
10093bool
10095 ExprResult Init) {
10096 if (Init.isInvalid())
10097 return false;
10098
10099 Expr *InitE = Init.get();
10100 assert(InitE && "No initialization expression");
10101
10102 InitializationKind Kind =
10104 InitializationSequence Seq(*this, Entity, Kind, InitE);
10105 return !Seq.Failed();
10106}
10107
10110 SourceLocation EqualLoc,
10112 bool TopLevelOfInitList,
10113 bool AllowExplicit) {
10114 if (Init.isInvalid())
10115 return ExprError();
10116
10117 Expr *InitE = Init.get();
10118 assert(InitE && "No initialization expression?");
10119
10120 if (EqualLoc.isInvalid())
10121 EqualLoc = InitE->getBeginLoc();
10122
10123 if (Entity.getType().getDesugaredType(Context) ==
10124 Context.AMDGPUFeaturePredicateTy &&
10125 Entity.getDecl()) {
10126 Diag(EqualLoc, diag::err_amdgcn_predicate_type_is_not_constructible)
10127 << Entity.getDecl();
10128 return ExprError();
10129 }
10130
10132 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10133 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10134
10135 // Prevent infinite recursion when performing parameter copy-initialization.
10136 const bool ShouldTrackCopy =
10137 Entity.isParameterKind() && Seq.isConstructorInitialization();
10138 if (ShouldTrackCopy) {
10139 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10140 Seq.SetOverloadFailure(
10143
10144 // Try to give a meaningful diagnostic note for the problematic
10145 // constructor.
10146 const auto LastStep = Seq.step_end() - 1;
10147 assert(LastStep->Kind ==
10149 const FunctionDecl *Function = LastStep->Function.Function;
10150 auto Candidate =
10151 llvm::find_if(Seq.getFailedCandidateSet(),
10152 [Function](const OverloadCandidate &Candidate) -> bool {
10153 return Candidate.Viable &&
10154 Candidate.Function == Function &&
10155 Candidate.Conversions.size() > 0;
10156 });
10157 if (Candidate != Seq.getFailedCandidateSet().end() &&
10158 Function->getNumParams() > 0) {
10159 Candidate->Viable = false;
10162 InitE,
10163 Function->getParamDecl(0)->getType());
10164 }
10165 }
10166 CurrentParameterCopyTypes.push_back(Entity.getType());
10167 }
10168
10169 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10170
10171 if (ShouldTrackCopy)
10172 CurrentParameterCopyTypes.pop_back();
10173
10174 return Result;
10175}
10176
10177/// Determine whether RD is, or is derived from, a specialization of CTD.
10179 ClassTemplateDecl *CTD) {
10180 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10181 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10182 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10183 };
10184 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10185}
10186
10188 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10189 const InitializationKind &Kind, MultiExprArg Inits) {
10190 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10191 TSInfo->getType()->getContainedDeducedType());
10192 assert(DeducedTST && "not a deduced template specialization type");
10193
10194 auto TemplateName = DeducedTST->getTemplateName();
10196 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10197
10198 // We can only perform deduction for class templates or alias templates.
10199 auto *Template =
10200 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10201 TemplateDecl *LookupTemplateDecl = Template;
10202 if (!Template) {
10203 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10205 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10206 LookupTemplateDecl = AliasTemplate;
10207 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10208 ->getUnderlyingType()
10209 .getCanonicalType();
10210 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10211 // of the form
10212 // [typename] [nested-name-specifier] [template] simple-template-id
10213 if (const auto *TST =
10214 UnderlyingType->getAs<TemplateSpecializationType>()) {
10215 Template = dyn_cast_or_null<ClassTemplateDecl>(
10216 TST->getTemplateName().getAsTemplateDecl());
10217 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10218 // Cases where template arguments in the RHS of the alias are not
10219 // dependent. e.g.
10220 // using AliasFoo = Foo<bool>;
10221 if (const auto *CTSD =
10222 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10223 Template = CTSD->getSpecializedTemplate();
10224 }
10225 }
10226 }
10227 if (!Template) {
10228 Diag(Kind.getLocation(),
10229 diag::err_deduced_non_class_or_alias_template_specialization_type)
10231 if (auto *TD = TemplateName.getAsTemplateDecl())
10233 return QualType();
10234 }
10235
10236 // Can't deduce from dependent arguments.
10238 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10239 diag::warn_cxx14_compat_class_template_argument_deduction)
10240 << TSInfo->getTypeLoc().getSourceRange() << 0;
10241 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10242 }
10243
10244 // FIXME: Perform "exact type" matching first, per CWG discussion?
10245 // Or implement this via an implied 'T(T) -> T' deduction guide?
10246
10247 // Look up deduction guides, including those synthesized from constructors.
10248 //
10249 // C++1z [over.match.class.deduct]p1:
10250 // A set of functions and function templates is formed comprising:
10251 // - For each constructor of the class template designated by the
10252 // template-name, a function template [...]
10253 // - For each deduction-guide, a function or function template [...]
10254 DeclarationNameInfo NameInfo(
10255 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10256 TSInfo->getTypeLoc().getEndLoc());
10257 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10258 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10259
10260 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10261 // clear on this, but they're not found by name so access does not apply.
10262 Guides.suppressDiagnostics();
10263
10264 // Figure out if this is list-initialization.
10266 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10267 ? dyn_cast<InitListExpr>(Inits[0])
10268 : nullptr;
10269
10270 // C++1z [over.match.class.deduct]p1:
10271 // Initialization and overload resolution are performed as described in
10272 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10273 // (as appropriate for the type of initialization performed) for an object
10274 // of a hypothetical class type, where the selected functions and function
10275 // templates are considered to be the constructors of that class type
10276 //
10277 // Since we know we're initializing a class type of a type unrelated to that
10278 // of the initializer, this reduces to something fairly reasonable.
10279 OverloadCandidateSet Candidates(Kind.getLocation(),
10282
10283 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10284
10285 // Return true if the candidate is added successfully, false otherwise.
10286 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10288 DeclAccessPair FoundDecl,
10289 bool OnlyListConstructors,
10290 bool AllowAggregateDeductionCandidate) {
10291 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10292 // For copy-initialization, the candidate functions are all the
10293 // converting constructors (12.3.1) of that class.
10294 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10295 // The converting constructors of T are candidate functions.
10296 if (!AllowExplicit) {
10297 // Overload resolution checks whether the deduction guide is declared
10298 // explicit for us.
10299
10300 // When looking for a converting constructor, deduction guides that
10301 // could never be called with one argument are not interesting to
10302 // check or note.
10303 if (GD->getMinRequiredArguments() > 1 ||
10304 (GD->getNumParams() == 0 && !GD->isVariadic()))
10305 return;
10306 }
10307
10308 // C++ [over.match.list]p1.1: (first phase list initialization)
10309 // Initially, the candidate functions are the initializer-list
10310 // constructors of the class T
10311 if (OnlyListConstructors && !isInitListConstructor(GD))
10312 return;
10313
10314 if (!AllowAggregateDeductionCandidate &&
10315 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10316 return;
10317
10318 // C++ [over.match.list]p1.2: (second phase list initialization)
10319 // the candidate functions are all the constructors of the class T
10320 // C++ [over.match.ctor]p1: (all other cases)
10321 // the candidate functions are all the constructors of the class of
10322 // the object being initialized
10323
10324 // C++ [over.best.ics]p4:
10325 // When [...] the constructor [...] is a candidate by
10326 // - [over.match.copy] (in all cases)
10327 if (TD) {
10328
10329 // As template candidates are not deduced immediately,
10330 // persist the array in the overload set.
10331 MutableArrayRef<Expr *> TmpInits =
10332 Candidates.getPersistentArgsArray(Inits.size());
10333
10334 for (auto [I, E] : llvm::enumerate(Inits)) {
10335 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10336 TmpInits[I] = DI->getInit();
10337 else
10338 TmpInits[I] = E;
10339 }
10340
10342 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10343 /*SuppressUserConversions=*/false,
10344 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10345 /*PO=*/{}, AllowAggregateDeductionCandidate);
10346 } else {
10347 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10348 /*SuppressUserConversions=*/false,
10349 /*PartialOverloading=*/false, AllowExplicit);
10350 }
10351 };
10352
10353 bool FoundDeductionGuide = false;
10354
10355 auto TryToResolveOverload =
10356 [&](bool OnlyListConstructors) -> OverloadingResult {
10358 bool HasAnyDeductionGuide = false;
10359
10360 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10361 auto *Pattern = Template;
10362 while (Pattern->getInstantiatedFromMemberTemplate()) {
10363 if (Pattern->isMemberSpecialization())
10364 break;
10365 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10366 }
10367
10368 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10369 if (!(RD->getDefinition() && RD->isAggregate()))
10370 return;
10371 QualType Ty = Context.getCanonicalTagType(RD);
10372 SmallVector<QualType, 8> ElementTypes;
10373
10374 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10375 if (!CheckInitList.HadError()) {
10376 // C++ [over.match.class.deduct]p1.8:
10377 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10378 // rvalue reference to the declared type of e_i and
10379 // C++ [over.match.class.deduct]p1.9:
10380 // if e_i is of array type and x_i is a string-literal, T_i is an
10381 // lvalue reference to the const-qualified declared type of e_i and
10382 // C++ [over.match.class.deduct]p1.10:
10383 // otherwise, T_i is the declared type of e_i
10384 for (int I = 0, E = ListInit->getNumInits();
10385 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10386 if (ElementTypes[I]->isArrayType()) {
10388 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10389 else if (isa<StringLiteral>(
10390 ListInit->getInit(I)->IgnoreParenImpCasts()))
10391 ElementTypes[I] =
10392 Context.getLValueReferenceType(ElementTypes[I].withConst());
10393 }
10394
10395 if (CXXDeductionGuideDecl *GD =
10397 LookupTemplateDecl, ElementTypes,
10398 TSInfo->getTypeLoc().getEndLoc())) {
10399 auto *TD = GD->getDescribedFunctionTemplate();
10400 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10401 OnlyListConstructors,
10402 /*AllowAggregateDeductionCandidate=*/true);
10403 HasAnyDeductionGuide = true;
10404 }
10405 }
10406 };
10407
10408 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10409 NamedDecl *D = (*I)->getUnderlyingDecl();
10410 if (D->isInvalidDecl())
10411 continue;
10412
10413 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10414 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10415 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10416 if (!GD)
10417 continue;
10418
10419 if (!GD->isImplicit())
10420 HasAnyDeductionGuide = true;
10421
10422 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10423 /*AllowAggregateDeductionCandidate=*/false);
10424 }
10425
10426 // C++ [over.match.class.deduct]p1.4:
10427 // if C is defined and its definition satisfies the conditions for an
10428 // aggregate class ([dcl.init.aggr]) with the assumption that any
10429 // dependent base class has no virtual functions and no virtual base
10430 // classes, and the initializer is a non-empty braced-init-list or
10431 // parenthesized expression-list, and there are no deduction-guides for
10432 // C, the set contains an additional function template, called the
10433 // aggregate deduction candidate, defined as follows.
10434 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10435 if (ListInit && ListInit->getNumInits()) {
10436 SynthesizeAggrGuide(ListInit);
10437 } else if (Inits.size()) { // parenthesized expression-list
10438 // Inits are expressions inside the parentheses. We don't have
10439 // the parentheses source locations, use the begin/end of Inits as the
10440 // best heuristic.
10441 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10442 Inits, Inits.back()->getEndLoc(),
10443 /*isExplicit=*/false);
10444 SynthesizeAggrGuide(&TempListInit);
10445 }
10446 }
10447
10448 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10449
10450 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10451 };
10452
10454
10455 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10456 // try initializer-list constructors.
10457 if (ListInit) {
10458 bool TryListConstructors = true;
10459
10460 // Try list constructors unless the list is empty and the class has one or
10461 // more default constructors, in which case those constructors win.
10462 if (!ListInit->getNumInits()) {
10463 for (NamedDecl *D : Guides) {
10464 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10465 if (FD && FD->getMinRequiredArguments() == 0) {
10466 TryListConstructors = false;
10467 break;
10468 }
10469 }
10470 } else if (ListInit->getNumInits() == 1) {
10471 // C++ [over.match.class.deduct]:
10472 // As an exception, the first phase in [over.match.list] (considering
10473 // initializer-list constructors) is omitted if the initializer list
10474 // consists of a single expression of type cv U, where U is a
10475 // specialization of C or a class derived from a specialization of C.
10476 Expr *E = ListInit->getInit(0);
10477 auto *RD = E->getType()->getAsCXXRecordDecl();
10478 if (!isa<InitListExpr>(E) && RD &&
10479 isCompleteType(Kind.getLocation(), E->getType()) &&
10481 TryListConstructors = false;
10482 }
10483
10484 if (TryListConstructors)
10485 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10486 // Then unwrap the initializer list and try again considering all
10487 // constructors.
10488 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10489 }
10490
10491 // If list-initialization fails, or if we're doing any other kind of
10492 // initialization, we (eventually) consider constructors.
10494 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10495
10496 switch (Result) {
10497 case OR_Ambiguous:
10498 // FIXME: For list-initialization candidates, it'd usually be better to
10499 // list why they were not viable when given the initializer list itself as
10500 // an argument.
10501 Candidates.NoteCandidates(
10503 Kind.getLocation(),
10504 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10505 << TemplateName),
10507 return QualType();
10508
10509 case OR_No_Viable_Function: {
10510 CXXRecordDecl *Primary =
10511 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10512 bool Complete = isCompleteType(Kind.getLocation(),
10513 Context.getCanonicalTagType(Primary));
10514 Candidates.NoteCandidates(
10516 Kind.getLocation(),
10517 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10518 : diag::err_deduced_class_template_incomplete)
10519 << TemplateName << !Guides.empty()),
10520 *this, OCD_AllCandidates, Inits);
10521 return QualType();
10522 }
10523
10524 case OR_Deleted: {
10525 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10526 // like we ever get here; attempts to trigger this seem to yield a
10527 // generic c'all to deleted function' diagnostic instead.
10528 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10529 << TemplateName;
10530 NoteDeletedFunction(Best->Function);
10531 return QualType();
10532 }
10533
10534 case OR_Success:
10535 // C++ [over.match.list]p1:
10536 // In copy-list-initialization, if an explicit constructor is chosen, the
10537 // initialization is ill-formed.
10538 if (Kind.isCopyInit() && ListInit &&
10539 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10540 bool IsDeductionGuide = !Best->Function->isImplicit();
10541 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10542 << TemplateName << IsDeductionGuide;
10543 Diag(Best->Function->getLocation(),
10544 diag::note_explicit_ctor_deduction_guide_here)
10545 << IsDeductionGuide;
10546 return QualType();
10547 }
10548
10549 // Make sure we didn't select an unusable deduction guide, and mark it
10550 // as referenced.
10551 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10552 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10553 break;
10554 }
10555
10556 // C++ [dcl.type.class.deduct]p1:
10557 // The placeholder is replaced by the return type of the function selected
10558 // by overload resolution for class template deduction.
10559 QualType DeducedType =
10560 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10561 ->getType();
10562 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10563 diag::warn_cxx14_compat_class_template_argument_deduction)
10564 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10565
10566 // Warn if CTAD was used on a type that does not have any user-defined
10567 // deduction guides.
10568 if (!FoundDeductionGuide) {
10569 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10570 diag::warn_ctad_maybe_unsupported)
10571 << TemplateName;
10572 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10573 }
10574
10575 return DeducedType;
10576}
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
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:565
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:511
bool isLValue() const
Definition APValue.h:493
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
bool isNullPointer() const
Definition APValue.cpp:1056
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:980
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:942
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:6038
Represents a loop initializing the elements of an array.
Definition Expr.h:5985
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3292
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:1551
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1694
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1691
Represents a C++ constructor within a class.
Definition DeclCXX.h:2637
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2877
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2714
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2972
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3008
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:1996
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2288
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1997
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:1989
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:2199
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:803
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:2954
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3158
SourceLocation getBeginLoc() const
Definition Expr.h:3288
bool isCallToStdMove() const
Definition Expr.cpp:3654
Expr * getCallee()
Definition Expr.h:3101
SourceLocation getRParenLoc() const
Definition Expr.h:3285
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3687
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:4402
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
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:3950
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4523
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:2259
DeclContextLookupResult lookup_result
Definition DeclBase.h:2607
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:2403
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1281
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1485
ValueDecl * getDecl()
Definition Expr.h:1349
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:463
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
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:5611
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:5773
void setFieldDecl(FieldDecl *FD)
Definition Expr.h:5709
FieldDecl * getFieldDecl() const
Definition Expr.h:5702
SourceLocation getFieldLoc() const
Definition Expr.h:5719
const IdentifierInfo * getFieldName() const
Definition Expr.cpp:4799
SourceLocation getDotLoc() const
Definition Expr.h:5714
SourceLocation getLBracketLoc() const
Definition Expr.h:5755
Represents a C99 designated initializer expression.
Definition Expr.h:5568
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition Expr.h:5828
Expr * getArrayRangeEnd(const Designator &D) const
Definition Expr.cpp:4908
Expr * getSubExpr(unsigned Idx) const
Definition Expr.h:5850
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition Expr.h:5832
Expr * getArrayRangeStart(const Designator &D) const
Definition Expr.cpp:4903
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:4915
MutableArrayRef< Designator > designators()
Definition Expr.h:5801
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4898
Designator * getDesignator(unsigned Idx)
Definition Expr.h:5809
Expr * getInit() const
Retrieve the initializer value.
Definition Expr.h:5836
unsigned size() const
Returns the number of designators in this initializer.
Definition Expr.h:5798
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4877
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4894
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition Expr.h:5823
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition Expr.h:5848
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition Expr.cpp:4840
InitListExpr * getUpdater() const
Definition Expr.h:5953
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:972
Represents a reference to emded data.
Definition Expr.h:5146
StringLiteral * getDataStringLiteral() const
Definition Expr.h:5163
EmbedDataStorage * getData() const
Definition Expr.h:5165
SourceLocation getLocation() const
Definition Expr.h:5159
size_t getDataElementCount() const
Definition Expr.h:5168
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:4372
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:3106
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:4296
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:3101
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
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:3350
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:842
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:846
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:3700
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
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:3264
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:4081
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:3294
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3474
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4889
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3379
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3400
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:2058
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2927
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3890
QualType getReturnType() const
Definition Decl.h:2975
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2666
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2511
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3869
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:2081
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:623
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:674
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:678
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:828
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6074
Represents a C array with an unspecified size.
Definition TypeBase.h:4023
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3601
chain_iterator chain_end() const
Definition Decl.h:3624
chain_iterator chain_begin() const
Definition Decl.h:3623
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition Decl.h:3620
Describes an C or C++ initializer list.
Definition Expr.h:5319
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition Expr.h:5432
void setSyntacticForm(InitListExpr *Init)
Definition Expr.h:5493
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition Expr.h:5394
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5435
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2473
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2433
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5446
unsigned getNumInits() const
Definition Expr.h:5352
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2507
void setInit(unsigned Init, Expr *expr)
Definition Expr.h:5384
SourceLocation getLBraceLoc() const
Definition Expr.h:5477
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:2437
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2449
InitListExpr * getSyntacticForm() const
Definition Expr.h:5489
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5422
bool isExplicit() const
Definition Expr.h:5462
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5356
SourceLocation getRBraceLoc() const
Definition Expr.h:5479
InitListExpr * getSemanticForm() const
Definition Expr.h:5483
const Expr * getInit(unsigned Init) const
Definition Expr.h:5374
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition Expr.cpp:2496
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2525
void setInitializedFieldInUnion(FieldDecl *FD)
Definition Expr.h:5452
bool isSyntacticForm() const
Definition Expr.h:5486
void setRBraceLoc(SourceLocation Loc)
Definition Expr.h:5480
ArrayRef< Expr * > inits() const
Definition Expr.h:5372
void sawArrayRangeDesignator(bool ARD=true)
Definition Expr.h:5503
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5365
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:3731
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:1075
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:4919
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4944
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4451
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4465
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:5894
QualType getEncodedType() const
Definition ExprObjC.h:460
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition ExprObjC.h:1615
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1189
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:1161
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition Overload.h:1487
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:1409
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1182
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1177
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:1350
Represents a parameter to a function.
Definition Decl.h:1819
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8588
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8593
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3716
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8504
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8630
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
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:8689
QualType getCanonicalType() const
Definition TypeBase.h:8556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8598
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8577
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8625
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
bool hasConst() const
Definition TypeBase.h:458
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition TypeBase.h:647
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasAddressSpace() const
Definition TypeBase.h:571
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:709
Qualifiers withoutAddressSpace() const
Definition TypeBase.h:539
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:436
bool hasVolatile() const
Definition TypeBase.h:468
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:534
LangAS getAddressSpace() const
Definition TypeBase.h:572
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3749
Represents a struct/union/class.
Definition Decl.h:4459
field_iterator field_end() const
Definition Decl.h:4665
field_range fields() const
Definition Decl.h:4662
bool isRandomized() const
Definition Decl.h:4617
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4643
bool hasUninitializedExplicitInitFields() const
Definition Decl.h:4585
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4659
bool field_empty() const
Definition Decl.h:4670
field_iterator field_begin() const
Definition Decl.cpp:5338
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
bool isSpelledAsLValue() const
Definition TypeBase.h:3700
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:864
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9359
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9367
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:10433
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10436
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10442
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10440
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:935
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6953
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:2080
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:6965
ASTContext & Context
Definition Sema.h:1305
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:701
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:1517
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:763
ASTContext & getASTContext() const
Definition Sema.h:936
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:777
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:9041
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:929
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:1482
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:6989
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10461
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:8202
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8069
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7001
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1445
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:8194
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:14045
SourceManager & getSourceManager() const
Definition Sema.h:934
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:13788
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15559
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:6764
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:1308
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
DiagnosticsEngine & Diags
Definition Sema.h:1307
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:930
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:1587
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:646
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.
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
QualType getToType(unsigned Idx) const
Definition Overload.h:411
Stmt - This represents one statement.
Definition Stmt.h:85
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:1810
unsigned getLength() const
Definition Expr.h:1920
StringLiteralKind getKind() const
Definition Expr.h:1923
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition Expr.h:1907
StringRef getString() const
Definition Expr.h:1878
bool isUnion() const
Definition Decl.h:4062
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:8475
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:8486
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9113
bool isBooleanType() const
Definition TypeBase.h:9250
bool isMFloat8Type() const
Definition TypeBase.h:9138
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9300
bool isIncompleteArrayType() const
Definition TypeBase.h:8848
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
bool isRValueReferenceType() const
Definition TypeBase.h:8773
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:8840
bool isCharType() const
Definition Type.cpp:2223
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:8908
bool isArrayParameterType() const
Definition TypeBase.h:8856
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9157
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
bool isReferenceType() const
Definition TypeBase.h:8765
bool isEnumeralType() const
Definition TypeBase.h:8872
bool isScalarType() const
Definition TypeBase.h:9219
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:1984
bool isChar8Type() const
Definition Type.cpp:2239
bool isSizelessBuiltinType() const
Definition Type.cpp:2653
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:8884
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:9026
bool isLValueReferenceType() const
Definition TypeBase.h:8769
bool isOpenCLSpecificType() const
Definition TypeBase.h:9041
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2533
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8876
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2139
bool isQueueT() const
Definition TypeBase.h:8997
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9293
bool isAtomicType() const
Definition TypeBase.h:8933
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8904
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isObjCObjectType() const
Definition TypeBase.h:8924
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9393
bool isEventT() const
Definition TypeBase.h:8989
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2557
bool isFunctionType() const
Definition TypeBase.h:8737
bool isObjCObjectPointerType() const
Definition TypeBase.h:8920
bool isVectorType() const
Definition TypeBase.h:8880
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isFloatingType() const
Definition Type.cpp:2419
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:2362
bool isSamplerT() const
Definition TypeBase.h:8985
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9340
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:9150
bool isRecordType() const
Definition TypeBase.h:8868
bool isObjCRetainableType() const
Definition Type.cpp:5465
bool isUnionType() const
Definition Type.cpp:755
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2255
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:1391
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:4080
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
VectorKind getVectorKind() const
Definition TypeBase.h:4309
QualType getElementType() const
Definition TypeBase.h:4303
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...
Top level wrappers for InstallAPI frontend operations.
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:863
@ 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:1543
@ 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:341
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:340
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ 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:684
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:686
ExprResult ExprError()
Definition Ownership.h:265
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:218
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:1520
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2251
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:433
@ Implicit
An implicit conversion.
Definition Sema.h:435
@ CStyleCast
A C-style cast.
Definition Sema.h:437
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:441
@ FunctionalCast
A functional-style cast.
Definition Sema.h:439
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:1512
DeclAccessPair FoundDecl
Definition Overload.h:1511
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:657
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:659
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:934
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1016
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:957
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:964
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6875
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6843
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6881
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6898
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:507