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