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