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