clang 23.0.0git
SemaInit.cpp
Go to the documentation of this file.
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeBase.h"
21#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/Lookup.h"
31#include "clang/Sema/SemaHLSL.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/PointerIntPair.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// Sema Initialization Checking
47//===----------------------------------------------------------------------===//
48
49/// Check whether T is compatible with a wide character type (wchar_t,
50/// char16_t or char32_t).
51static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
52 if (Context.typesAreCompatible(Context.getWideCharType(), T))
53 return true;
54 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
55 return Context.typesAreCompatible(Context.Char16Ty, T) ||
56 Context.typesAreCompatible(Context.Char32Ty, T);
57 }
58 return false;
59}
60
70
71/// Check whether the array of type AT can be initialized by the Init
72/// expression by means of string initialization. Returns SIF_None if so,
73/// otherwise returns a StringInitFailureKind that describes why the
74/// initialization would not work.
76 ASTContext &Context) {
78 return SIF_Other;
79
80 // See if this is a string literal or @encode.
81 Init = Init->IgnoreParens();
82
83 // Handle @encode, which is a narrow string.
85 return SIF_None;
86
87 // Otherwise we can only handle string literals.
88 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
89 if (!SL)
90 return SIF_Other;
91
92 const QualType ElemTy =
94
95 auto IsCharOrUnsignedChar = [](const QualType &T) {
96 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
97 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
98 };
99
100 switch (SL->getKind()) {
102 // char8_t array can be initialized with a UTF-8 string.
103 // - C++20 [dcl.init.string] (DR)
104 // Additionally, an array of char or unsigned char may be initialized
105 // by a UTF-8 string literal.
106 if (ElemTy->isChar8Type() ||
107 (Context.getLangOpts().Char8 &&
108 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
109 return SIF_None;
110 [[fallthrough]];
113 // char array can be initialized with a narrow string.
114 // Only allow char x[] = "foo"; not char x[] = L"foo";
115 if (ElemTy->isCharType())
116 return (SL->getKind() == StringLiteralKind::UTF8 &&
117 Context.getLangOpts().Char8)
119 : SIF_None;
120 if (ElemTy->isChar8Type())
122 if (IsWideCharCompatible(ElemTy, Context))
124 return SIF_Other;
125 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
126 // "An array with element type compatible with a qualified or unqualified
127 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
128 // string literal with the corresponding encoding prefix (L, u, or U,
129 // respectively), optionally enclosed in braces.
131 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
132 return SIF_None;
133 if (ElemTy->isCharType() || ElemTy->isChar8Type())
135 if (IsWideCharCompatible(ElemTy, Context))
137 return SIF_Other;
139 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
140 return SIF_None;
141 if (ElemTy->isCharType() || ElemTy->isChar8Type())
143 if (IsWideCharCompatible(ElemTy, Context))
145 return SIF_Other;
147 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
148 return SIF_None;
149 if (ElemTy->isCharType() || ElemTy->isChar8Type())
151 if (IsWideCharCompatible(ElemTy, Context))
153 return SIF_Other;
155 assert(false && "Unevaluated string literal in initialization");
156 break;
157 }
158
159 llvm_unreachable("missed a StringLiteral kind?");
160}
161
163 ASTContext &Context) {
164 const ArrayType *arrayType = Context.getAsArrayType(declType);
165 if (!arrayType)
166 return SIF_Other;
167 return IsStringInit(init, arrayType, Context);
168}
169
171 return ::IsStringInit(Init, AT, Context) == SIF_None;
172}
173
174/// Update the type of a string literal, including any surrounding parentheses,
175/// to match the type of the object which it is initializing.
177 while (true) {
178 E->setType(Ty);
181 break;
183 }
184}
185
186/// Fix a compound literal initializing an array so it's correctly marked
187/// as an rvalue.
189 while (true) {
192 break;
194 }
195}
196
198 Decl *D = Entity.getDecl();
199 const InitializedEntity *Parent = &Entity;
200
201 while (Parent) {
202 D = Parent->getDecl();
203 Parent = Parent->getParent();
204 }
205
206 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
207 return true;
208
209 return false;
210}
211
213 Sema &SemaRef, QualType &TT);
214
215static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
216 Sema &S, const InitializedEntity &Entity,
217 bool CheckC23ConstexprInit = false) {
218 // Get the length of the string as parsed.
219 auto *ConstantArrayTy =
221 uint64_t StrLength = ConstantArrayTy->getZExtSize();
222
223 if (CheckC23ConstexprInit)
224 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
226
227 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
228 // C99 6.7.8p14. We have an array of character type with unknown size
229 // being initialized to a string literal.
230 llvm::APInt ConstVal(32, StrLength);
231 // Return a new array type (C99 6.7.8p22).
233 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
234 updateStringLiteralType(Str, DeclT);
235 return;
236 }
237
239 uint64_t ArrayLen = CAT->getZExtSize();
240
241 // We have an array of character type with known size. However,
242 // the size may be smaller or larger than the string we are initializing.
243 // FIXME: Avoid truncation for 64-bit length strings.
244 if (S.getLangOpts().CPlusPlus) {
245 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
246 // For Pascal strings it's OK to strip off the terminating null character,
247 // so the example below is valid:
248 //
249 // unsigned char a[2] = "\pa";
250 if (SL->isPascal())
251 StrLength--;
252 }
253
254 // [dcl.init.string]p2
255 if (StrLength > ArrayLen)
256 S.Diag(Str->getBeginLoc(),
257 diag::err_initializer_string_for_char_array_too_long)
258 << ArrayLen << StrLength << Str->getSourceRange();
259 } else {
260 // C99 6.7.8p14.
261 if (StrLength - 1 > ArrayLen)
262 S.Diag(Str->getBeginLoc(),
263 diag::ext_initializer_string_for_char_array_too_long)
264 << Str->getSourceRange();
265 else if (StrLength - 1 == ArrayLen) {
266 // In C, if the string literal is null-terminated explicitly, e.g., `char
267 // a[4] = "ABC\0"`, there should be no warning:
268 const auto *SL = dyn_cast<StringLiteral>(Str->IgnoreParens());
269 bool IsSLSafe = SL && SL->getLength() > 0 &&
270 SL->getCodeUnit(SL->getLength() - 1) == 0;
271
272 if (!IsSLSafe) {
273 // If the entity being initialized has the nonstring attribute, then
274 // silence the "missing nonstring" diagnostic. If there's no entity,
275 // check whether we're initializing an array of arrays; if so, walk the
276 // parents to find an entity.
277 auto FindCorrectEntity =
278 [](const InitializedEntity *Entity) -> const ValueDecl * {
279 while (Entity) {
280 if (const ValueDecl *VD = Entity->getDecl())
281 return VD;
282 if (!Entity->getType()->isArrayType())
283 return nullptr;
284 Entity = Entity->getParent();
285 }
286
287 return nullptr;
288 };
289 if (const ValueDecl *D = FindCorrectEntity(&Entity);
290 !D || !D->hasAttr<NonStringAttr>())
291 S.Diag(
292 Str->getBeginLoc(),
293 diag::
294 warn_initializer_string_for_char_array_too_long_no_nonstring)
295 << ArrayLen << StrLength << Str->getSourceRange();
296 }
297 // Always emit the C++ compatibility diagnostic.
298 S.Diag(Str->getBeginLoc(),
299 diag::warn_initializer_string_for_char_array_too_long_for_cpp)
300 << ArrayLen << StrLength << Str->getSourceRange();
301 }
302 }
303
304 // Set the type to the actual size that we are initializing. If we have
305 // something like:
306 // char x[1] = "foo";
307 // then this will set the string literal's type to char[1].
308 updateStringLiteralType(Str, DeclT);
309}
310
312 for (const FieldDecl *Field : R->fields()) {
313 if (Field->hasAttr<ExplicitInitAttr>())
314 S.Diag(Field->getLocation(), diag::note_entity_declared_at) << Field;
315 }
316}
317
318//===----------------------------------------------------------------------===//
319// Semantic checking for initializer lists.
320//===----------------------------------------------------------------------===//
321
322namespace {
323
324/// Semantic checking for initializer lists.
325///
326/// The InitListChecker class contains a set of routines that each
327/// handle the initialization of a certain kind of entity, e.g.,
328/// arrays, vectors, struct/union types, scalars, etc. The
329/// InitListChecker itself performs a recursive walk of the subobject
330/// structure of the type to be initialized, while stepping through
331/// the initializer list one element at a time. The IList and Index
332/// parameters to each of the Check* routines contain the active
333/// (syntactic) initializer list and the index into that initializer
334/// list that represents the current initializer. Each routine is
335/// responsible for moving that Index forward as it consumes elements.
336///
337/// Each Check* routine also has a StructuredList/StructuredIndex
338/// arguments, which contains the current "structured" (semantic)
339/// initializer list and the index into that initializer list where we
340/// are copying initializers as we map them over to the semantic
341/// list. Once we have completed our recursive walk of the subobject
342/// structure, we will have constructed a full semantic initializer
343/// list.
344///
345/// C99 designators cause changes in the initializer list traversal,
346/// because they make the initialization "jump" into a specific
347/// subobject and then continue the initialization from that
348/// point. CheckDesignatedInitializer() recursively steps into the
349/// designated subobject and manages backing out the recursion to
350/// initialize the subobjects after the one designated.
351///
352/// If an initializer list contains any designators, we build a placeholder
353/// structured list even in 'verify only' mode, so that we can track which
354/// elements need 'empty' initializtion.
355class InitListChecker {
356 Sema &SemaRef;
357 bool hadError = false;
358 bool VerifyOnly; // No diagnostics.
359 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
360 bool InOverloadResolution;
361 InitListExpr *FullyStructuredList = nullptr;
362 NoInitExpr *DummyExpr = nullptr;
363 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
364 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
365 unsigned CurEmbedIndex = 0;
366
367 NoInitExpr *getDummyInit() {
368 if (!DummyExpr)
369 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
370 return DummyExpr;
371 }
372
373 void CheckImplicitInitList(const InitializedEntity &Entity,
374 InitListExpr *ParentIList, QualType T,
375 unsigned &Index, InitListExpr *StructuredList,
376 unsigned &StructuredIndex);
377 void CheckExplicitInitList(const InitializedEntity &Entity,
378 InitListExpr *IList, QualType &T,
379 InitListExpr *StructuredList,
380 bool TopLevelObject = false);
381 void CheckListElementTypes(const InitializedEntity &Entity,
382 InitListExpr *IList, QualType &DeclType,
383 bool SubobjectIsDesignatorContext,
384 unsigned &Index,
385 InitListExpr *StructuredList,
386 unsigned &StructuredIndex,
387 bool TopLevelObject = false);
388 void CheckSubElementType(const InitializedEntity &Entity,
389 InitListExpr *IList, QualType ElemType,
390 unsigned &Index,
391 InitListExpr *StructuredList,
392 unsigned &StructuredIndex,
393 bool DirectlyDesignated = false);
394 void CheckComplexType(const InitializedEntity &Entity,
395 InitListExpr *IList, QualType DeclType,
396 unsigned &Index,
397 InitListExpr *StructuredList,
398 unsigned &StructuredIndex);
399 void CheckScalarType(const InitializedEntity &Entity,
400 InitListExpr *IList, QualType DeclType,
401 unsigned &Index,
402 InitListExpr *StructuredList,
403 unsigned &StructuredIndex);
404 void CheckReferenceType(const InitializedEntity &Entity,
405 InitListExpr *IList, QualType DeclType,
406 unsigned &Index,
407 InitListExpr *StructuredList,
408 unsigned &StructuredIndex);
409 void CheckMatrixType(const InitializedEntity &Entity, InitListExpr *IList,
410 QualType DeclType, unsigned &Index,
411 InitListExpr *StructuredList, unsigned &StructuredIndex);
412 void CheckVectorType(const InitializedEntity &Entity,
413 InitListExpr *IList, QualType DeclType, unsigned &Index,
414 InitListExpr *StructuredList,
415 unsigned &StructuredIndex);
416 void CheckStructUnionTypes(const InitializedEntity &Entity,
417 InitListExpr *IList, QualType DeclType,
420 bool SubobjectIsDesignatorContext, unsigned &Index,
421 InitListExpr *StructuredList,
422 unsigned &StructuredIndex,
423 bool TopLevelObject = false);
424 void CheckArrayType(const InitializedEntity &Entity,
425 InitListExpr *IList, QualType &DeclType,
426 llvm::APSInt elementIndex,
427 bool SubobjectIsDesignatorContext, unsigned &Index,
428 InitListExpr *StructuredList,
429 unsigned &StructuredIndex);
430 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
431 InitListExpr *IList, DesignatedInitExpr *DIE,
432 unsigned DesigIdx,
433 QualType &CurrentObjectType,
435 llvm::APSInt *NextElementIndex,
436 unsigned &Index,
437 InitListExpr *StructuredList,
438 unsigned &StructuredIndex,
439 bool FinishSubobjectInit,
440 bool TopLevelObject);
441 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
442 QualType CurrentObjectType,
443 InitListExpr *StructuredList,
444 unsigned StructuredIndex,
445 SourceRange InitRange,
446 bool IsFullyOverwritten = false);
447 void UpdateStructuredListElement(InitListExpr *StructuredList,
448 unsigned &StructuredIndex,
449 Expr *expr);
450 InitListExpr *createInitListExpr(QualType CurrentObjectType,
451 SourceRange InitRange,
452 unsigned ExpectedNumInits);
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 // Note: In HLSL, elements of the InitListExpr are in row-major order, so no
1919 // change is needed to the Index.
1920 Element.setElementIndex(Index);
1921 CheckSubElementType(Element, IList, ElemTy, Index, StructuredList,
1922 StructuredIndex);
1923 }
1924}
1925
1926void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1927 InitListExpr *IList, QualType DeclType,
1928 unsigned &Index,
1929 InitListExpr *StructuredList,
1930 unsigned &StructuredIndex) {
1931 const VectorType *VT = DeclType->castAs<VectorType>();
1932 unsigned maxElements = VT->getNumElements();
1933 unsigned numEltsInit = 0;
1934 QualType elementType = VT->getElementType();
1935
1936 if (Index >= IList->getNumInits()) {
1937 // Make sure the element type can be value-initialized.
1938 CheckEmptyInitializable(
1940 IList->getEndLoc());
1941 return;
1942 }
1943
1944 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1945 // If the initializing element is a vector, try to copy-initialize
1946 // instead of breaking it apart (which is doomed to failure anyway).
1947 Expr *Init = IList->getInit(Index);
1948 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1950 if (VerifyOnly) {
1951 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1952 Result = getDummyInit();
1953 else
1954 Result = ExprError();
1955 } else {
1956 Result =
1957 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1958 /*TopLevelOfInitList=*/true);
1959 }
1960
1961 Expr *ResultExpr = nullptr;
1962 if (Result.isInvalid())
1963 hadError = true; // types weren't compatible.
1964 else {
1965 ResultExpr = Result.getAs<Expr>();
1966
1967 if (ResultExpr != Init && !VerifyOnly) {
1968 // The type was promoted, update initializer list.
1969 // FIXME: Why are we updating the syntactic init list?
1970 IList->setInit(Index, ResultExpr);
1971 }
1972 }
1973 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1974 ++Index;
1975 if (AggrDeductionCandidateParamTypes)
1976 AggrDeductionCandidateParamTypes->push_back(elementType);
1977 return;
1978 }
1979
1980 InitializedEntity ElementEntity =
1982
1983 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1984 // Don't attempt to go past the end of the init list
1985 if (Index >= IList->getNumInits()) {
1986 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1987 break;
1988 }
1989
1990 ElementEntity.setElementIndex(Index);
1991 CheckSubElementType(ElementEntity, IList, elementType, Index,
1992 StructuredList, StructuredIndex);
1993 }
1994
1995 if (VerifyOnly)
1996 return;
1997
1998 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1999 const VectorType *T = Entity.getType()->castAs<VectorType>();
2000 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2001 T->getVectorKind() == VectorKind::NeonPoly)) {
2002 // The ability to use vector initializer lists is a GNU vector extension
2003 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2004 // endian machines it works fine, however on big endian machines it
2005 // exhibits surprising behaviour:
2006 //
2007 // uint32x2_t x = {42, 64};
2008 // return vget_lane_u32(x, 0); // Will return 64.
2009 //
2010 // Because of this, explicitly call out that it is non-portable.
2011 //
2012 SemaRef.Diag(IList->getBeginLoc(),
2013 diag::warn_neon_vector_initializer_non_portable);
2014
2015 const char *typeCode;
2016 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
2017
2018 if (elementType->isFloatingType())
2019 typeCode = "f";
2020 else if (elementType->isSignedIntegerType())
2021 typeCode = "s";
2022 else if (elementType->isUnsignedIntegerType())
2023 typeCode = "u";
2024 else if (elementType->isMFloat8Type())
2025 typeCode = "mf";
2026 else
2027 llvm_unreachable("Invalid element type!");
2028
2029 SemaRef.Diag(IList->getBeginLoc(),
2030 SemaRef.Context.getTypeSize(VT) > 64
2031 ? diag::note_neon_vector_initializer_non_portable_q
2032 : diag::note_neon_vector_initializer_non_portable)
2033 << typeCode << typeSize;
2034 }
2035
2036 return;
2037 }
2038
2039 InitializedEntity ElementEntity =
2041
2042 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2043 for (unsigned i = 0; i < maxElements; ++i) {
2044 // Don't attempt to go past the end of the init list
2045 if (Index >= IList->getNumInits())
2046 break;
2047
2048 ElementEntity.setElementIndex(Index);
2049
2050 QualType IType = IList->getInit(Index)->getType();
2051 if (!IType->isVectorType()) {
2052 CheckSubElementType(ElementEntity, IList, elementType, Index,
2053 StructuredList, StructuredIndex);
2054 ++numEltsInit;
2055 } else {
2056 QualType VecType;
2057 const VectorType *IVT = IType->castAs<VectorType>();
2058 unsigned numIElts = IVT->getNumElements();
2059
2060 if (IType->isExtVectorType())
2061 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
2062 else
2063 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
2064 IVT->getVectorKind());
2065 CheckSubElementType(ElementEntity, IList, VecType, Index,
2066 StructuredList, StructuredIndex);
2067 numEltsInit += numIElts;
2068 }
2069 }
2070
2071 // OpenCL and HLSL require all elements to be initialized.
2072 if (numEltsInit != maxElements) {
2073 if (!VerifyOnly)
2074 SemaRef.Diag(IList->getBeginLoc(),
2075 diag::err_vector_incorrect_num_elements)
2076 << (numEltsInit < maxElements) << maxElements << numEltsInit
2077 << /*initialization*/ 0;
2078 hadError = true;
2079 }
2080}
2081
2082/// Check if the type of a class element has an accessible destructor, and marks
2083/// it referenced. Returns true if we shouldn't form a reference to the
2084/// destructor.
2085///
2086/// Aggregate initialization requires a class element's destructor be
2087/// accessible per 11.6.1 [dcl.init.aggr]:
2088///
2089/// The destructor for each element of class type is potentially invoked
2090/// (15.4 [class.dtor]) from the context where the aggregate initialization
2091/// occurs.
2093 Sema &SemaRef) {
2094 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2095 if (!CXXRD)
2096 return false;
2097
2099 if (!Destructor)
2100 return false;
2101
2102 SemaRef.CheckDestructorAccess(Loc, Destructor,
2103 SemaRef.PDiag(diag::err_access_dtor_temp)
2104 << ElementType);
2105 SemaRef.MarkFunctionReferenced(Loc, Destructor);
2106 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2107}
2108
2109static bool
2111 const InitializedEntity &Entity,
2112 ASTContext &Context) {
2113 QualType InitType = Entity.getType();
2114 const InitializedEntity *Parent = &Entity;
2115
2116 while (Parent) {
2117 InitType = Parent->getType();
2118 Parent = Parent->getParent();
2119 }
2120
2121 // Only one initializer, it's an embed and the types match;
2122 EmbedExpr *EE =
2123 ExprList.size() == 1
2124 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2125 : nullptr;
2126 if (!EE)
2127 return false;
2128
2129 if (InitType->isArrayType()) {
2130 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2132 return IsStringInit(SL, InitArrayType, Context) == SIF_None;
2133 }
2134 return false;
2135}
2136
2137void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2138 InitListExpr *IList, QualType &DeclType,
2139 llvm::APSInt elementIndex,
2140 bool SubobjectIsDesignatorContext,
2141 unsigned &Index,
2142 InitListExpr *StructuredList,
2143 unsigned &StructuredIndex) {
2144 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2145
2146 if (!VerifyOnly) {
2147 if (checkDestructorReference(arrayType->getElementType(),
2148 IList->getEndLoc(), SemaRef)) {
2149 hadError = true;
2150 return;
2151 }
2152 }
2153
2154 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2155 SemaRef.Context)) {
2156 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2157 IList->setInit(0, Embed->getDataStringLiteral());
2158 }
2159
2160 // Check for the special-case of initializing an array with a string.
2161 if (Index < IList->getNumInits()) {
2162 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2163 SIF_None) {
2164 // We place the string literal directly into the resulting
2165 // initializer list. This is the only place where the structure
2166 // of the structured initializer list doesn't match exactly,
2167 // because doing so would involve allocating one character
2168 // constant for each string.
2169 // FIXME: Should we do these checks in verify-only mode too?
2170 if (!VerifyOnly)
2172 IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
2173 SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2174 if (StructuredList) {
2175 UpdateStructuredListElement(StructuredList, StructuredIndex,
2176 IList->getInit(Index));
2177 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2178 }
2179 ++Index;
2180 if (AggrDeductionCandidateParamTypes)
2181 AggrDeductionCandidateParamTypes->push_back(DeclType);
2182 return;
2183 }
2184 }
2185 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2186 // Check for VLAs; in standard C it would be possible to check this
2187 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2188 // them in all sorts of strange places).
2189 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2190 if (!VerifyOnly) {
2191 // C23 6.7.10p4: An entity of variable length array type shall not be
2192 // initialized except by an empty initializer.
2193 //
2194 // The C extension warnings are issued from ParseBraceInitializer() and
2195 // do not need to be issued here. However, we continue to issue an error
2196 // in the case there are initializers or we are compiling C++. We allow
2197 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2198 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2199 // FIXME: should we allow this construct in C++ when it makes sense to do
2200 // so?
2201 if (HasErr)
2202 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2203 diag::err_variable_object_no_init)
2204 << VAT->getSizeExpr()->getSourceRange();
2205 }
2206 hadError = HasErr;
2207 ++Index;
2208 ++StructuredIndex;
2209 return;
2210 }
2211
2212 // We might know the maximum number of elements in advance.
2213 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2214 elementIndex.isUnsigned());
2215 bool maxElementsKnown = false;
2216 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2217 maxElements = CAT->getSize();
2218 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2219 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2220 maxElementsKnown = true;
2221 }
2222
2223 QualType elementType = arrayType->getElementType();
2224 while (Index < IList->getNumInits()) {
2225 Expr *Init = IList->getInit(Index);
2226 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2227 // If we're not the subobject that matches up with the '{' for
2228 // the designator, we shouldn't be handling the
2229 // designator. Return immediately.
2230 if (!SubobjectIsDesignatorContext)
2231 return;
2232
2233 // Handle this designated initializer. elementIndex will be
2234 // updated to be the next array element we'll initialize.
2235 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2236 DeclType, nullptr, &elementIndex, Index,
2237 StructuredList, StructuredIndex, true,
2238 false)) {
2239 hadError = true;
2240 continue;
2241 }
2242
2243 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2244 maxElements = maxElements.extend(elementIndex.getBitWidth());
2245 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2246 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2247 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2248
2249 // If the array is of incomplete type, keep track of the number of
2250 // elements in the initializer.
2251 if (!maxElementsKnown && elementIndex > maxElements)
2252 maxElements = elementIndex;
2253
2254 continue;
2255 }
2256
2257 // If we know the maximum number of elements, and we've already
2258 // hit it, stop consuming elements in the initializer list.
2259 if (maxElementsKnown && elementIndex == maxElements)
2260 break;
2261
2262 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2263 SemaRef.Context, StructuredIndex, Entity);
2264 ElementEntity.setElementIndex(elementIndex.getExtValue());
2265
2266 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2267 // Check this element.
2268 CheckSubElementType(ElementEntity, IList, elementType, Index,
2269 StructuredList, StructuredIndex);
2270 ++elementIndex;
2271 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2272 if (CurEmbed) {
2273 elementIndex =
2274 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2275 } else {
2276 auto Embed = cast<EmbedExpr>(Init);
2277 elementIndex = elementIndex + Embed->getDataElementCount() -
2278 EmbedElementIndexBeforeInit - 1;
2279 }
2280 }
2281
2282 // If the array is of incomplete type, keep track of the number of
2283 // elements in the initializer.
2284 if (!maxElementsKnown && elementIndex > maxElements)
2285 maxElements = elementIndex;
2286 }
2287 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2288 // If this is an incomplete array type, the actual type needs to
2289 // be calculated here.
2290 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2291 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2292 // Sizing an array implicitly to zero is not allowed by ISO C,
2293 // but is supported by GNU.
2294 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2295 }
2296
2297 DeclType = SemaRef.Context.getConstantArrayType(
2298 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2299 }
2300 if (!hadError) {
2301 // If there are any members of the array that get value-initialized, check
2302 // that is possible. That happens if we know the bound and don't have
2303 // enough elements, or if we're performing an array new with an unknown
2304 // bound.
2305 if ((maxElementsKnown && elementIndex < maxElements) ||
2306 Entity.isVariableLengthArrayNew())
2307 CheckEmptyInitializable(
2309 IList->getEndLoc());
2310 }
2311}
2312
2313bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2314 Expr *InitExpr,
2315 FieldDecl *Field,
2316 bool TopLevelObject) {
2317 // Handle GNU flexible array initializers.
2318 unsigned FlexArrayDiag;
2319 if (isa<InitListExpr>(InitExpr) &&
2320 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2321 // Empty flexible array init always allowed as an extension
2322 FlexArrayDiag = diag::ext_flexible_array_init;
2323 } else if (!TopLevelObject) {
2324 // Disallow flexible array init on non-top-level object
2325 FlexArrayDiag = diag::err_flexible_array_init;
2326 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2327 // Disallow flexible array init on anything which is not a variable.
2328 FlexArrayDiag = diag::err_flexible_array_init;
2329 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2330 // Disallow flexible array init on local variables.
2331 FlexArrayDiag = diag::err_flexible_array_init;
2332 } else {
2333 // Allow other cases.
2334 FlexArrayDiag = diag::ext_flexible_array_init;
2335 }
2336
2337 if (!VerifyOnly) {
2338 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2339 << InitExpr->getBeginLoc();
2340 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2341 << Field;
2342 }
2343
2344 return FlexArrayDiag != diag::ext_flexible_array_init;
2345}
2346
2347static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2348 return StructuredList && StructuredList->getNumInits() == 1U;
2349}
2350
2351void InitListChecker::CheckStructUnionTypes(
2352 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2354 bool SubobjectIsDesignatorContext, unsigned &Index,
2355 InitListExpr *StructuredList, unsigned &StructuredIndex,
2356 bool TopLevelObject) {
2357 const RecordDecl *RD = DeclType->getAsRecordDecl();
2358
2359 // If the record is invalid, some of it's members are invalid. To avoid
2360 // confusion, we forgo checking the initializer for the entire record.
2361 if (RD->isInvalidDecl()) {
2362 // Assume it was supposed to consume a single initializer.
2363 ++Index;
2364 hadError = true;
2365 return;
2366 }
2367
2368 if (RD->isUnion() && IList->getNumInits() == 0) {
2369 if (!VerifyOnly)
2370 for (FieldDecl *FD : RD->fields()) {
2371 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2372 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2373 hadError = true;
2374 return;
2375 }
2376 }
2377
2378 // If there's a default initializer, use it.
2379 if (isa<CXXRecordDecl>(RD) &&
2380 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2381 if (!StructuredList)
2382 return;
2383 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2384 Field != FieldEnd; ++Field) {
2385 if (Field->hasInClassInitializer() ||
2386 (Field->isAnonymousStructOrUnion() &&
2387 Field->getType()
2388 ->castAsCXXRecordDecl()
2389 ->hasInClassInitializer())) {
2390 StructuredList->setInitializedFieldInUnion(*Field);
2391 // FIXME: Actually build a CXXDefaultInitExpr?
2392 return;
2393 }
2394 }
2395 llvm_unreachable("Couldn't find in-class initializer");
2396 }
2397
2398 // Value-initialize the first member of the union that isn't an unnamed
2399 // bitfield.
2400 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2401 Field != FieldEnd; ++Field) {
2402 if (!Field->isUnnamedBitField()) {
2403 CheckEmptyInitializable(
2404 InitializedEntity::InitializeMember(*Field, &Entity),
2405 IList->getEndLoc());
2406 if (StructuredList)
2407 StructuredList->setInitializedFieldInUnion(*Field);
2408 break;
2409 }
2410 }
2411 return;
2412 }
2413
2414 bool InitializedSomething = false;
2415
2416 // If we have any base classes, they are initialized prior to the fields.
2417 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2418 auto &Base = *I;
2419 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2420
2421 // Designated inits always initialize fields, so if we see one, all
2422 // remaining base classes have no explicit initializer.
2423 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2424 Init = nullptr;
2425
2426 // C++ [over.match.class.deduct]p1.6:
2427 // each non-trailing aggregate element that is a pack expansion is assumed
2428 // to correspond to no elements of the initializer list, and (1.7) a
2429 // trailing aggregate element that is a pack expansion is assumed to
2430 // correspond to all remaining elements of the initializer list (if any).
2431
2432 // C++ [over.match.class.deduct]p1.9:
2433 // ... except that additional parameter packs of the form P_j... are
2434 // inserted into the parameter list in their original aggregate element
2435 // position corresponding to each non-trailing aggregate element of
2436 // type P_j that was skipped because it was a parameter pack, and the
2437 // trailing sequence of parameters corresponding to a trailing
2438 // aggregate element that is a pack expansion (if any) is replaced
2439 // by a single parameter of the form T_n....
2440 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2441 AggrDeductionCandidateParamTypes->push_back(
2442 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2443
2444 // Trailing pack expansion
2445 if (I + 1 == E && RD->field_empty()) {
2446 if (Index < IList->getNumInits())
2447 Index = IList->getNumInits();
2448 return;
2449 }
2450
2451 continue;
2452 }
2453
2454 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2455 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2456 SemaRef.Context, &Base, false, &Entity);
2457 if (Init) {
2458 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2459 StructuredList, StructuredIndex);
2460 InitializedSomething = true;
2461 } else {
2462 CheckEmptyInitializable(BaseEntity, InitLoc);
2463 }
2464
2465 if (!VerifyOnly)
2466 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2467 hadError = true;
2468 return;
2469 }
2470 }
2471
2472 // If structDecl is a forward declaration, this loop won't do
2473 // anything except look at designated initializers; That's okay,
2474 // because an error should get printed out elsewhere. It might be
2475 // worthwhile to skip over the rest of the initializer, though.
2476 RecordDecl::field_iterator FieldEnd = RD->field_end();
2477 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2478 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2479 });
2480 bool HasDesignatedInit = false;
2481
2482 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2483
2484 while (Index < IList->getNumInits()) {
2485 Expr *Init = IList->getInit(Index);
2486 SourceLocation InitLoc = Init->getBeginLoc();
2487
2488 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2489 // If we're not the subobject that matches up with the '{' for
2490 // the designator, we shouldn't be handling the
2491 // designator. Return immediately.
2492 if (!SubobjectIsDesignatorContext)
2493 return;
2494
2495 HasDesignatedInit = true;
2496
2497 // Handle this designated initializer. Field will be updated to
2498 // the next field that we'll be initializing.
2499 bool DesignatedInitFailed = CheckDesignatedInitializer(
2500 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2501 StructuredList, StructuredIndex, true, TopLevelObject);
2502 if (DesignatedInitFailed)
2503 hadError = true;
2504
2505 // Find the field named by the designated initializer.
2506 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2507 if (!VerifyOnly && D->isFieldDesignator()) {
2508 FieldDecl *F = D->getFieldDecl();
2509 InitializedFields.insert(F);
2510 if (!DesignatedInitFailed) {
2511 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2512 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2513 hadError = true;
2514 return;
2515 }
2516 }
2517 }
2518
2519 InitializedSomething = true;
2520 continue;
2521 }
2522
2523 // Check if this is an initializer of forms:
2524 //
2525 // struct foo f = {};
2526 // struct foo g = {0};
2527 //
2528 // These are okay for randomized structures. [C99 6.7.8p19]
2529 //
2530 // Also, if there is only one element in the structure, we allow something
2531 // like this, because it's really not randomized in the traditional sense.
2532 //
2533 // struct foo h = {bar};
2534 auto IsZeroInitializer = [&](const Expr *I) {
2535 if (IList->getNumInits() == 1) {
2536 if (NumRecordDecls == 1)
2537 return true;
2538 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2539 return IL->getValue().isZero();
2540 }
2541 return false;
2542 };
2543
2544 // Don't allow non-designated initializers on randomized structures.
2545 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2546 if (!VerifyOnly)
2547 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2548 hadError = true;
2549 break;
2550 }
2551
2552 if (Field == FieldEnd) {
2553 // We've run out of fields. We're done.
2554 break;
2555 }
2556
2557 // We've already initialized a member of a union. We can stop entirely.
2558 if (InitializedSomething && RD->isUnion())
2559 return;
2560
2561 // Stop if we've hit a flexible array member.
2562 if (Field->getType()->isIncompleteArrayType())
2563 break;
2564
2565 if (Field->isUnnamedBitField()) {
2566 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2567 ++Field;
2568 continue;
2569 }
2570
2571 // Make sure we can use this declaration.
2572 bool InvalidUse;
2573 if (VerifyOnly)
2574 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2575 else
2576 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2577 *Field, IList->getInit(Index)->getBeginLoc());
2578 if (InvalidUse) {
2579 ++Index;
2580 ++Field;
2581 hadError = true;
2582 continue;
2583 }
2584
2585 if (!VerifyOnly) {
2586 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2587 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2588 hadError = true;
2589 return;
2590 }
2591 }
2592
2593 InitializedEntity MemberEntity =
2594 InitializedEntity::InitializeMember(*Field, &Entity);
2595 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2596 StructuredList, StructuredIndex);
2597 InitializedSomething = true;
2598 InitializedFields.insert(*Field);
2599 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2600 // Initialize the first field within the union.
2601 StructuredList->setInitializedFieldInUnion(*Field);
2602 }
2603
2604 ++Field;
2605 }
2606
2607 // Emit warnings for missing struct field initializers.
2608 // This check is disabled for designated initializers in C.
2609 // This matches gcc behaviour.
2610 bool IsCDesignatedInitializer =
2611 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2612 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2613 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2614 !IsCDesignatedInitializer) {
2615 // It is possible we have one or more unnamed bitfields remaining.
2616 // Find first (if any) named field and emit warning.
2617 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2618 : Field,
2619 end = RD->field_end();
2620 it != end; ++it) {
2621 if (HasDesignatedInit && InitializedFields.count(*it))
2622 continue;
2623
2624 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2625 !it->getType()->isIncompleteArrayType()) {
2626 auto Diag = HasDesignatedInit
2627 ? diag::warn_missing_designated_field_initializers
2628 : diag::warn_missing_field_initializers;
2629 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2630 break;
2631 }
2632 }
2633 }
2634
2635 // Check that any remaining fields can be value-initialized if we're not
2636 // building a structured list. (If we are, we'll check this later.)
2637 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2638 !Field->getType()->isIncompleteArrayType()) {
2639 for (; Field != FieldEnd && !hadError; ++Field) {
2640 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2641 CheckEmptyInitializable(
2642 InitializedEntity::InitializeMember(*Field, &Entity),
2643 IList->getEndLoc());
2644 }
2645 }
2646
2647 // Check that the types of the remaining fields have accessible destructors.
2648 if (!VerifyOnly) {
2649 // If the initializer expression has a designated initializer, check the
2650 // elements for which a designated initializer is not provided too.
2651 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2652 : Field;
2653 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2654 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2655 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2656 hadError = true;
2657 return;
2658 }
2659 }
2660 }
2661
2662 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2663 Index >= IList->getNumInits())
2664 return;
2665
2666 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2667 TopLevelObject)) {
2668 hadError = true;
2669 ++Index;
2670 return;
2671 }
2672
2673 InitializedEntity MemberEntity =
2674 InitializedEntity::InitializeMember(*Field, &Entity);
2675
2676 if (isa<InitListExpr>(IList->getInit(Index)) ||
2677 AggrDeductionCandidateParamTypes)
2678 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2679 StructuredList, StructuredIndex);
2680 else
2681 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2682 StructuredList, StructuredIndex);
2683
2684 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2685 // Initialize the first field within the union.
2686 StructuredList->setInitializedFieldInUnion(*Field);
2687 }
2688}
2689
2690/// Expand a field designator that refers to a member of an
2691/// anonymous struct or union into a series of field designators that
2692/// refers to the field within the appropriate subobject.
2693///
2695 DesignatedInitExpr *DIE,
2696 unsigned DesigIdx,
2697 IndirectFieldDecl *IndirectField) {
2699
2700 // Build the replacement designators.
2701 SmallVector<Designator, 4> Replacements;
2702 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2703 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2704 if (PI + 1 == PE)
2705 Replacements.push_back(Designator::CreateFieldDesignator(
2706 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2707 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2708 else
2709 Replacements.push_back(Designator::CreateFieldDesignator(
2710 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2711 assert(isa<FieldDecl>(*PI));
2712 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2713 }
2714
2715 // Expand the current designator into the set of replacement
2716 // designators, so we have a full subobject path down to where the
2717 // member of the anonymous struct/union is actually stored.
2718 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2719 &Replacements[0] + Replacements.size());
2720}
2721
2723 DesignatedInitExpr *DIE) {
2724 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2725 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2726 for (unsigned I = 0; I < NumIndexExprs; ++I)
2727 IndexExprs[I] = DIE->getSubExpr(I + 1);
2728 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2729 IndexExprs,
2730 DIE->getEqualOrColonLoc(),
2731 DIE->usesGNUSyntax(), DIE->getInit());
2732}
2733
2734namespace {
2735
2736// Callback to only accept typo corrections that are for field members of
2737// the given struct or union.
2738class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2739 public:
2740 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2741 : Record(RD) {}
2742
2743 bool ValidateCandidate(const TypoCorrection &candidate) override {
2744 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2745 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2746 }
2747
2748 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2749 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2750 }
2751
2752 private:
2753 const RecordDecl *Record;
2754};
2755
2756} // end anonymous namespace
2757
2758/// Check the well-formedness of a C99 designated initializer.
2759///
2760/// Determines whether the designated initializer @p DIE, which
2761/// resides at the given @p Index within the initializer list @p
2762/// IList, is well-formed for a current object of type @p DeclType
2763/// (C99 6.7.8). The actual subobject that this designator refers to
2764/// within the current subobject is returned in either
2765/// @p NextField or @p NextElementIndex (whichever is appropriate).
2766///
2767/// @param IList The initializer list in which this designated
2768/// initializer occurs.
2769///
2770/// @param DIE The designated initializer expression.
2771///
2772/// @param DesigIdx The index of the current designator.
2773///
2774/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2775/// into which the designation in @p DIE should refer.
2776///
2777/// @param NextField If non-NULL and the first designator in @p DIE is
2778/// a field, this will be set to the field declaration corresponding
2779/// to the field named by the designator. On input, this is expected to be
2780/// the next field that would be initialized in the absence of designation,
2781/// if the complete object being initialized is a struct.
2782///
2783/// @param NextElementIndex If non-NULL and the first designator in @p
2784/// DIE is an array designator or GNU array-range designator, this
2785/// will be set to the last index initialized by this designator.
2786///
2787/// @param Index Index into @p IList where the designated initializer
2788/// @p DIE occurs.
2789///
2790/// @param StructuredList The initializer list expression that
2791/// describes all of the subobject initializers in the order they'll
2792/// actually be initialized.
2793///
2794/// @returns true if there was an error, false otherwise.
2795bool
2796InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2797 InitListExpr *IList,
2798 DesignatedInitExpr *DIE,
2799 unsigned DesigIdx,
2800 QualType &CurrentObjectType,
2801 RecordDecl::field_iterator *NextField,
2802 llvm::APSInt *NextElementIndex,
2803 unsigned &Index,
2804 InitListExpr *StructuredList,
2805 unsigned &StructuredIndex,
2806 bool FinishSubobjectInit,
2807 bool TopLevelObject) {
2808 if (DesigIdx == DIE->size()) {
2809 // C++20 designated initialization can result in direct-list-initialization
2810 // of the designated subobject. This is the only way that we can end up
2811 // performing direct initialization as part of aggregate initialization, so
2812 // it needs special handling.
2813 if (DIE->isDirectInit()) {
2814 Expr *Init = DIE->getInit();
2815 assert(isa<InitListExpr>(Init) &&
2816 "designator result in direct non-list initialization?");
2817 InitializationKind Kind = InitializationKind::CreateDirectList(
2818 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2819 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2820 /*TopLevelOfInitList*/ true);
2821 if (StructuredList) {
2822 ExprResult Result = VerifyOnly
2823 ? getDummyInit()
2824 : Seq.Perform(SemaRef, Entity, Kind, Init);
2825 UpdateStructuredListElement(StructuredList, StructuredIndex,
2826 Result.get());
2827 }
2828 ++Index;
2829 if (AggrDeductionCandidateParamTypes)
2830 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2831 return !Seq;
2832 }
2833
2834 // Check the actual initialization for the designated object type.
2835 bool prevHadError = hadError;
2836
2837 // Temporarily remove the designator expression from the
2838 // initializer list that the child calls see, so that we don't try
2839 // to re-process the designator.
2840 unsigned OldIndex = Index;
2841 auto *OldDIE =
2842 dyn_cast_if_present<DesignatedInitExpr>(IList->getInit(OldIndex));
2843 if (!OldDIE)
2844 OldDIE = DIE;
2845 IList->setInit(OldIndex, OldDIE->getInit());
2846
2847 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2848 StructuredIndex, /*DirectlyDesignated=*/true);
2849
2850 // Restore the designated initializer expression in the syntactic
2851 // form of the initializer list.
2852 if (IList->getInit(OldIndex) != OldDIE->getInit())
2853 OldDIE->setInit(IList->getInit(OldIndex));
2854 IList->setInit(OldIndex, OldDIE);
2855
2856 return hadError && !prevHadError;
2857 }
2858
2859 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2860 bool IsFirstDesignator = (DesigIdx == 0);
2861 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2862 // Determine the structural initializer list that corresponds to the
2863 // current subobject.
2864 if (IsFirstDesignator)
2865 StructuredList = FullyStructuredList;
2866 else {
2867 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2868 StructuredList->getInit(StructuredIndex) : nullptr;
2869 if (!ExistingInit && StructuredList->hasArrayFiller())
2870 ExistingInit = StructuredList->getArrayFiller();
2871
2872 if (!ExistingInit)
2873 StructuredList = getStructuredSubobjectInit(
2874 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2875 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2876 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2877 StructuredList = Result;
2878 else {
2879 // We are creating an initializer list that initializes the
2880 // subobjects of the current object, but there was already an
2881 // initialization that completely initialized the current
2882 // subobject, e.g., by a compound literal:
2883 //
2884 // struct X { int a, b; };
2885 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2886 //
2887 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2888 // designated initializer re-initializes only its current object
2889 // subobject [0].b.
2890 diagnoseInitOverride(ExistingInit,
2891 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2892 /*UnionOverride=*/false,
2893 /*FullyOverwritten=*/false);
2894
2895 if (!VerifyOnly) {
2896 if (DesignatedInitUpdateExpr *E =
2897 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2898 StructuredList = E->getUpdater();
2899 else {
2900 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2901 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2902 ExistingInit, DIE->getEndLoc());
2903 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2904 StructuredList = DIUE->getUpdater();
2905 }
2906 } else {
2907 // We don't need to track the structured representation of a
2908 // designated init update of an already-fully-initialized object in
2909 // verify-only mode. The only reason we would need the structure is
2910 // to determine where the uninitialized "holes" are, and in this
2911 // case, we know there aren't any and we can't introduce any.
2912 StructuredList = nullptr;
2913 }
2914 }
2915 }
2916 }
2917
2918 if (D->isFieldDesignator()) {
2919 // C99 6.7.8p7:
2920 //
2921 // If a designator has the form
2922 //
2923 // . identifier
2924 //
2925 // then the current object (defined below) shall have
2926 // structure or union type and the identifier shall be the
2927 // name of a member of that type.
2928 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2929 if (!RD) {
2930 SourceLocation Loc = D->getDotLoc();
2931 if (Loc.isInvalid())
2932 Loc = D->getFieldLoc();
2933 if (!VerifyOnly)
2934 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2935 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2936 ++Index;
2937 return true;
2938 }
2939
2940 FieldDecl *KnownField = D->getFieldDecl();
2941 if (!KnownField) {
2942 const IdentifierInfo *FieldName = D->getFieldName();
2943 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2944 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2945 KnownField = FD;
2946 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2947 // In verify mode, don't modify the original.
2948 if (VerifyOnly)
2949 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2950 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2951 D = DIE->getDesignator(DesigIdx);
2952 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2953 }
2954 if (!KnownField) {
2955 if (VerifyOnly) {
2956 ++Index;
2957 return true; // No typo correction when just trying this out.
2958 }
2959
2960 // We found a placeholder variable
2961 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2962 FieldName)) {
2963 ++Index;
2964 return true;
2965 }
2966 // Name lookup found something, but it wasn't a field.
2967 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2968 !Lookup.empty()) {
2969 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2970 << FieldName;
2971 SemaRef.Diag(Lookup.front()->getLocation(),
2972 diag::note_field_designator_found);
2973 ++Index;
2974 return true;
2975 }
2976
2977 // Name lookup didn't find anything.
2978 // Determine whether this was a typo for another field name.
2979 FieldInitializerValidatorCCC CCC(RD);
2980 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2981 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2982 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2983 CorrectTypoKind::ErrorRecovery, RD)) {
2984 SemaRef.diagnoseTypo(
2985 Corrected,
2986 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2987 << FieldName << CurrentObjectType);
2988 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2989 hadError = true;
2990 } else {
2991 // Typo correction didn't find anything.
2992 SourceLocation Loc = D->getFieldLoc();
2993
2994 // The loc can be invalid with a "null" designator (i.e. an anonymous
2995 // union/struct). Do our best to approximate the location.
2996 if (Loc.isInvalid())
2997 Loc = IList->getBeginLoc();
2998
2999 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
3000 << FieldName << CurrentObjectType << DIE->getSourceRange();
3001 ++Index;
3002 return true;
3003 }
3004 }
3005 }
3006
3007 unsigned NumBases = 0;
3008 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3009 NumBases = CXXRD->getNumBases();
3010
3011 unsigned FieldIndex = NumBases;
3012
3013 for (auto *FI : RD->fields()) {
3014 if (FI->isUnnamedBitField())
3015 continue;
3016 if (declaresSameEntity(KnownField, FI)) {
3017 KnownField = FI;
3018 break;
3019 }
3020 ++FieldIndex;
3021 }
3022
3024 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3025
3026 // All of the fields of a union are located at the same place in
3027 // the initializer list.
3028 if (RD->isUnion()) {
3029 FieldIndex = 0;
3030 if (StructuredList) {
3031 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3032 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
3033 assert(StructuredList->getNumInits() == 1
3034 && "A union should never have more than one initializer!");
3035
3036 Expr *ExistingInit = StructuredList->getInit(0);
3037 if (ExistingInit) {
3038 // We're about to throw away an initializer, emit warning.
3039 diagnoseInitOverride(
3040 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3041 /*UnionOverride=*/true,
3042 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3043 : true);
3044 }
3045
3046 // remove existing initializer
3047 StructuredList->resizeInits(SemaRef.Context, 0);
3048 StructuredList->setInitializedFieldInUnion(nullptr);
3049 }
3050
3051 StructuredList->setInitializedFieldInUnion(*Field);
3052 }
3053 }
3054
3055 // Make sure we can use this declaration.
3056 bool InvalidUse;
3057 if (VerifyOnly)
3058 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
3059 else
3060 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
3061 if (InvalidUse) {
3062 ++Index;
3063 return true;
3064 }
3065
3066 // C++20 [dcl.init.list]p3:
3067 // The ordered identifiers in the designators of the designated-
3068 // initializer-list shall form a subsequence of the ordered identifiers
3069 // in the direct non-static data members of T.
3070 //
3071 // Note that this is not a condition on forming the aggregate
3072 // initialization, only on actually performing initialization,
3073 // so it is not checked in VerifyOnly mode.
3074 //
3075 // FIXME: This is the only reordering diagnostic we produce, and it only
3076 // catches cases where we have a top-level field designator that jumps
3077 // backwards. This is the only such case that is reachable in an
3078 // otherwise-valid C++20 program, so is the only case that's required for
3079 // conformance, but for consistency, we should diagnose all the other
3080 // cases where a designator takes us backwards too.
3081 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3082 NextField &&
3083 (*NextField == RD->field_end() ||
3084 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3085 // Find the field that we just initialized.
3086 FieldDecl *PrevField = nullptr;
3087 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3088 if (FI->isUnnamedBitField())
3089 continue;
3090 if (*NextField != RD->field_end() &&
3091 declaresSameEntity(*FI, **NextField))
3092 break;
3093 PrevField = *FI;
3094 }
3095
3096 const auto GenerateDesignatedInitReorderingFixit =
3097 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3098 struct ReorderInfo {
3099 int Pos{};
3100 const Expr *InitExpr{};
3101 };
3102
3103 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3104 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3105
3106 const auto *CxxRecord =
3108
3109 for (const FieldDecl *Field : CxxRecord->fields())
3110 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3111
3112 for (const Expr *Init : IList->inits()) {
3113 if (const auto *DI =
3114 dyn_cast_if_present<DesignatedInitExpr>(Init)) {
3115 // We expect only one Designator
3116 if (DI->size() != 1)
3117 return;
3118
3119 const IdentifierInfo *const FieldName =
3120 DI->getDesignator(0)->getFieldName();
3121 // In case we have an unknown initializer in the source, not in
3122 // the record
3123 if (MemberNameInx.contains(FieldName))
3124 ReorderedInitExprs.emplace_back(
3125 ReorderInfo{MemberNameInx.at(FieldName), Init});
3126 }
3127 }
3128
3129 llvm::sort(ReorderedInitExprs,
3130 [](const ReorderInfo &A, const ReorderInfo &B) {
3131 return A.Pos < B.Pos;
3132 });
3133
3134 llvm::SmallString<128> FixedInitList{};
3135 SourceManager &SM = SemaRef.getSourceManager();
3136 const LangOptions &LangOpts = SemaRef.getLangOpts();
3137
3138 // In a derived Record, first n base-classes are initialized first.
3139 // They do not use designated init, so skip them
3140 const ArrayRef<clang::Expr *> IListInits =
3141 IList->inits().drop_front(CxxRecord->getNumBases());
3142 // loop over each existing expressions and apply replacement
3143 for (const auto &[OrigExpr, Repl] :
3144 llvm::zip(IListInits, ReorderedInitExprs)) {
3145 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3146 Repl.InitExpr->getSourceRange());
3147 const StringRef InitText =
3148 Lexer::getSourceText(CharRange, SM, LangOpts);
3149
3150 Diag << FixItHint::CreateReplacement(OrigExpr->getSourceRange(),
3151 InitText.str());
3152 }
3153 };
3154
3155 if (PrevField &&
3156 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3157 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3158 diag::ext_designated_init_reordered)
3159 << KnownField << PrevField << DIE->getSourceRange();
3160
3161 unsigned OldIndex = StructuredIndex - 1;
3162 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3163 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3164 auto Diag = SemaRef.Diag(PrevInit->getBeginLoc(),
3165 diag::note_previous_field_init)
3166 << PrevField << PrevInit->getSourceRange();
3167 GenerateDesignatedInitReorderingFixit(Diag);
3168 }
3169 }
3170 }
3171 }
3172
3173
3174 // Update the designator with the field declaration.
3175 if (!VerifyOnly)
3176 D->setFieldDecl(*Field);
3177
3178 // Make sure that our non-designated initializer list has space
3179 // for a subobject corresponding to this field.
3180 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3181 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3182
3183 // This designator names a flexible array member.
3184 if (Field->getType()->isIncompleteArrayType()) {
3185 bool Invalid = false;
3186 if ((DesigIdx + 1) != DIE->size()) {
3187 // We can't designate an object within the flexible array
3188 // member (because GCC doesn't allow it).
3189 if (!VerifyOnly) {
3190 DesignatedInitExpr::Designator *NextD
3191 = DIE->getDesignator(DesigIdx + 1);
3192 SemaRef.Diag(NextD->getBeginLoc(),
3193 diag::err_designator_into_flexible_array_member)
3194 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3195 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3196 << *Field;
3197 }
3198 Invalid = true;
3199 }
3200
3201 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3202 !isa<StringLiteral>(DIE->getInit())) {
3203 // The initializer is not an initializer list.
3204 if (!VerifyOnly) {
3205 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3206 diag::err_flexible_array_init_needs_braces)
3207 << DIE->getInit()->getSourceRange();
3208 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3209 << *Field;
3210 }
3211 Invalid = true;
3212 }
3213
3214 // Check GNU flexible array initializer.
3215 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3216 TopLevelObject))
3217 Invalid = true;
3218
3219 if (Invalid) {
3220 ++Index;
3221 return true;
3222 }
3223
3224 // Initialize the array.
3225 bool prevHadError = hadError;
3226 unsigned newStructuredIndex = FieldIndex;
3227 unsigned OldIndex = Index;
3228 IList->setInit(Index, DIE->getInit());
3229
3230 InitializedEntity MemberEntity =
3231 InitializedEntity::InitializeMember(*Field, &Entity);
3232 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3233 StructuredList, newStructuredIndex);
3234
3235 IList->setInit(OldIndex, DIE);
3236 if (hadError && !prevHadError) {
3237 ++Field;
3238 ++FieldIndex;
3239 if (NextField)
3240 *NextField = Field;
3241 StructuredIndex = FieldIndex;
3242 return true;
3243 }
3244 } else {
3245 // Recurse to check later designated subobjects.
3246 QualType FieldType = Field->getType();
3247 unsigned newStructuredIndex = FieldIndex;
3248
3249 InitializedEntity MemberEntity =
3250 InitializedEntity::InitializeMember(*Field, &Entity);
3251 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3252 FieldType, nullptr, nullptr, Index,
3253 StructuredList, newStructuredIndex,
3254 FinishSubobjectInit, false))
3255 return true;
3256 }
3257
3258 // Find the position of the next field to be initialized in this
3259 // subobject.
3260 ++Field;
3261 ++FieldIndex;
3262
3263 // If this the first designator, our caller will continue checking
3264 // the rest of this struct/class/union subobject.
3265 if (IsFirstDesignator) {
3266 if (Field != RD->field_end() && Field->isUnnamedBitField())
3267 ++Field;
3268
3269 if (NextField)
3270 *NextField = Field;
3271
3272 StructuredIndex = FieldIndex;
3273 return false;
3274 }
3275
3276 if (!FinishSubobjectInit)
3277 return false;
3278
3279 // We've already initialized something in the union; we're done.
3280 if (RD->isUnion())
3281 return hadError;
3282
3283 // Check the remaining fields within this class/struct/union subobject.
3284 bool prevHadError = hadError;
3285
3286 auto NoBases =
3289 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3290 false, Index, StructuredList, FieldIndex);
3291 return hadError && !prevHadError;
3292 }
3293
3294 // C99 6.7.8p6:
3295 //
3296 // If a designator has the form
3297 //
3298 // [ constant-expression ]
3299 //
3300 // then the current object (defined below) shall have array
3301 // type and the expression shall be an integer constant
3302 // expression. If the array is of unknown size, any
3303 // nonnegative value is valid.
3304 //
3305 // Additionally, cope with the GNU extension that permits
3306 // designators of the form
3307 //
3308 // [ constant-expression ... constant-expression ]
3309 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3310 if (!AT) {
3311 if (!VerifyOnly)
3312 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3313 << CurrentObjectType;
3314 ++Index;
3315 return true;
3316 }
3317
3318 Expr *IndexExpr = nullptr;
3319 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3320 if (D->isArrayDesignator()) {
3321 IndexExpr = DIE->getArrayIndex(*D);
3322 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3323 DesignatedEndIndex = DesignatedStartIndex;
3324 } else {
3325 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3326
3327 DesignatedStartIndex =
3329 DesignatedEndIndex =
3331 IndexExpr = DIE->getArrayRangeEnd(*D);
3332
3333 // Codegen can't handle evaluating array range designators that have side
3334 // effects, because we replicate the AST value for each initialized element.
3335 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3336 // elements with something that has a side effect, so codegen can emit an
3337 // "error unsupported" error instead of miscompiling the app.
3338 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3339 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3340 FullyStructuredList->sawArrayRangeDesignator();
3341 }
3342
3343 if (isa<ConstantArrayType>(AT)) {
3344 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3345 DesignatedStartIndex
3346 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3347 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3348 DesignatedEndIndex
3349 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3350 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3351 if (DesignatedEndIndex >= MaxElements) {
3352 if (!VerifyOnly)
3353 SemaRef.Diag(IndexExpr->getBeginLoc(),
3354 diag::err_array_designator_too_large)
3355 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3356 << IndexExpr->getSourceRange();
3357 ++Index;
3358 return true;
3359 }
3360 } else {
3361 unsigned DesignatedIndexBitWidth =
3363 DesignatedStartIndex =
3364 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3365 DesignatedEndIndex =
3366 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3367 DesignatedStartIndex.setIsUnsigned(true);
3368 DesignatedEndIndex.setIsUnsigned(true);
3369 }
3370
3371 bool IsStringLiteralInitUpdate =
3372 StructuredList && StructuredList->isStringLiteralInit();
3373 if (IsStringLiteralInitUpdate && VerifyOnly) {
3374 // We're just verifying an update to a string literal init. We don't need
3375 // to split the string up into individual characters to do that.
3376 StructuredList = nullptr;
3377 } else if (IsStringLiteralInitUpdate) {
3378 // We're modifying a string literal init; we have to decompose the string
3379 // so we can modify the individual characters.
3380 ASTContext &Context = SemaRef.Context;
3381 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3382
3383 // Compute the character type
3384 QualType CharTy = AT->getElementType();
3385
3386 // Compute the type of the integer literals.
3387 QualType PromotedCharTy = CharTy;
3388 if (Context.isPromotableIntegerType(CharTy))
3389 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3390 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3391
3392 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3393 // Get the length of the string.
3394 uint64_t StrLen = SL->getLength();
3395 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3396 CAT && CAT->getSize().ult(StrLen))
3397 StrLen = CAT->getZExtSize();
3398 StructuredList->resizeInits(Context, StrLen);
3399
3400 // Build a literal for each character in the string, and put them into
3401 // the init list.
3402 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3403 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3404 Expr *Init = new (Context) IntegerLiteral(
3405 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3406 if (CharTy != PromotedCharTy)
3407 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3408 Init, nullptr, VK_PRValue,
3409 FPOptionsOverride());
3410 StructuredList->updateInit(Context, i, Init);
3411 }
3412 } else {
3413 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3414 std::string Str;
3415 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3416
3417 // Get the length of the string.
3418 uint64_t StrLen = Str.size();
3419 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
3420 CAT && CAT->getSize().ult(StrLen))
3421 StrLen = CAT->getZExtSize();
3422 StructuredList->resizeInits(Context, StrLen);
3423
3424 // Build a literal for each character in the string, and put them into
3425 // the init list.
3426 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3427 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3428 Expr *Init = new (Context) IntegerLiteral(
3429 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3430 if (CharTy != PromotedCharTy)
3431 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3432 Init, nullptr, VK_PRValue,
3433 FPOptionsOverride());
3434 StructuredList->updateInit(Context, i, Init);
3435 }
3436 }
3437 }
3438
3439 // Make sure that our non-designated initializer list has space
3440 // for a subobject corresponding to this array element.
3441 if (StructuredList &&
3442 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3443 StructuredList->resizeInits(SemaRef.Context,
3444 DesignatedEndIndex.getZExtValue() + 1);
3445
3446 // Repeatedly perform subobject initializations in the range
3447 // [DesignatedStartIndex, DesignatedEndIndex].
3448
3449 // Move to the next designator
3450 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3451 unsigned OldIndex = Index;
3452
3453 InitializedEntity ElementEntity =
3455
3456 while (DesignatedStartIndex <= DesignatedEndIndex) {
3457 // Recurse to check later designated subobjects.
3458 QualType ElementType = AT->getElementType();
3459 Index = OldIndex;
3460
3461 ElementEntity.setElementIndex(ElementIndex);
3462 if (CheckDesignatedInitializer(
3463 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3464 nullptr, Index, StructuredList, ElementIndex,
3465 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3466 false))
3467 return true;
3468
3469 // Move to the next index in the array that we'll be initializing.
3470 ++DesignatedStartIndex;
3471 ElementIndex = DesignatedStartIndex.getZExtValue();
3472 }
3473
3474 // If this the first designator, our caller will continue checking
3475 // the rest of this array subobject.
3476 if (IsFirstDesignator) {
3477 if (NextElementIndex)
3478 *NextElementIndex = std::move(DesignatedStartIndex);
3479 StructuredIndex = ElementIndex;
3480 return false;
3481 }
3482
3483 if (!FinishSubobjectInit)
3484 return false;
3485
3486 // Check the remaining elements within this array subobject.
3487 bool prevHadError = hadError;
3488 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3489 /*SubobjectIsDesignatorContext=*/false, Index,
3490 StructuredList, ElementIndex);
3491 return hadError && !prevHadError;
3492}
3493
3494// Get the structured initializer list for a subobject of type
3495// @p CurrentObjectType.
3496InitListExpr *
3497InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3498 QualType CurrentObjectType,
3499 InitListExpr *StructuredList,
3500 unsigned StructuredIndex,
3501 SourceRange InitRange,
3502 bool IsFullyOverwritten) {
3503 if (!StructuredList)
3504 return nullptr;
3505
3506 Expr *ExistingInit = nullptr;
3507 if (StructuredIndex < StructuredList->getNumInits())
3508 ExistingInit = StructuredList->getInit(StructuredIndex);
3509
3510 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3511 // There might have already been initializers for subobjects of the current
3512 // object, but a subsequent initializer list will overwrite the entirety
3513 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3514 //
3515 // struct P { char x[6]; };
3516 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3517 //
3518 // The first designated initializer is ignored, and l.x is just "f".
3519 if (!IsFullyOverwritten)
3520 return Result;
3521
3522 if (ExistingInit) {
3523 // We are creating an initializer list that initializes the
3524 // subobjects of the current object, but there was already an
3525 // initialization that completely initialized the current
3526 // subobject:
3527 //
3528 // struct X { int a, b; };
3529 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3530 //
3531 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3532 // designated initializer overwrites the [0].b initializer
3533 // from the prior initialization.
3534 //
3535 // When the existing initializer is an expression rather than an
3536 // initializer list, we cannot decompose and update it in this way.
3537 // For example:
3538 //
3539 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3540 //
3541 // This case is handled by CheckDesignatedInitializer.
3542 diagnoseInitOverride(ExistingInit, InitRange);
3543 }
3544
3545 unsigned ExpectedNumInits = 0;
3546 if (Index < IList->getNumInits()) {
3547 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3548 ExpectedNumInits = Init->getNumInits();
3549 else
3550 ExpectedNumInits = IList->getNumInits() - Index;
3551 }
3552
3553 InitListExpr *Result =
3554 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3555
3556 // Link this new initializer list into the structured initializer
3557 // lists.
3558 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3559 return Result;
3560}
3561
3562InitListExpr *
3563InitListChecker::createInitListExpr(QualType CurrentObjectType,
3564 SourceRange InitRange,
3565 unsigned ExpectedNumInits) {
3566 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3567 SemaRef.Context, InitRange.getBegin(), {}, InitRange.getEnd());
3568
3569 QualType ResultType = CurrentObjectType;
3570 if (!ResultType->isArrayType())
3571 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3572 Result->setType(ResultType);
3573
3574 // Pre-allocate storage for the structured initializer list.
3575 unsigned NumElements = 0;
3576
3577 if (const ArrayType *AType
3578 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3579 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3580 NumElements = CAType->getZExtSize();
3581 // Simple heuristic so that we don't allocate a very large
3582 // initializer with many empty entries at the end.
3583 if (NumElements > ExpectedNumInits)
3584 NumElements = 0;
3585 }
3586 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3587 NumElements = VType->getNumElements();
3588 } else if (CurrentObjectType->isRecordType()) {
3589 NumElements = numStructUnionElements(CurrentObjectType);
3590 } else if (CurrentObjectType->isDependentType()) {
3591 NumElements = 1;
3592 }
3593
3594 Result->reserveInits(SemaRef.Context, NumElements);
3595
3596 return Result;
3597}
3598
3599/// Update the initializer at index @p StructuredIndex within the
3600/// structured initializer list to the value @p expr.
3601void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3602 unsigned &StructuredIndex,
3603 Expr *expr) {
3604 // No structured initializer list to update
3605 if (!StructuredList)
3606 return;
3607
3608 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3609 StructuredIndex, expr)) {
3610 // This initializer overwrites a previous initializer.
3611 // No need to diagnose when `expr` is nullptr because a more relevant
3612 // diagnostic has already been issued and this diagnostic is potentially
3613 // noise.
3614 if (expr)
3615 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3616 }
3617
3618 ++StructuredIndex;
3619}
3620
3622 const InitializedEntity &Entity, InitListExpr *From) {
3623 QualType Type = Entity.getType();
3624 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3625 /*TreatUnavailableAsInvalid=*/false,
3626 /*InOverloadResolution=*/true);
3627 return !Check.HadError();
3628}
3629
3630/// Check that the given Index expression is a valid array designator
3631/// value. This is essentially just a wrapper around
3632/// VerifyIntegerConstantExpression that also checks for negative values
3633/// and produces a reasonable diagnostic if there is a
3634/// failure. Returns the index expression, possibly with an implicit cast
3635/// added, on success. If everything went okay, Value will receive the
3636/// value of the constant expression.
3637static ExprResult
3638CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3639 SourceLocation Loc = Index->getBeginLoc();
3640
3641 // Make sure this is an integer constant expression.
3644 if (Result.isInvalid())
3645 return Result;
3646
3647 if (Value.isSigned() && Value.isNegative())
3648 return S.Diag(Loc, diag::err_array_designator_negative)
3649 << toString(Value, 10) << Index->getSourceRange();
3650
3651 Value.setIsUnsigned(true);
3652 return Result;
3653}
3654
3656 SourceLocation EqualOrColonLoc,
3657 bool GNUSyntax,
3658 ExprResult Init) {
3659 typedef DesignatedInitExpr::Designator ASTDesignator;
3660
3661 bool Invalid = false;
3663 SmallVector<Expr *, 32> InitExpressions;
3664
3665 // Build designators and check array designator expressions.
3666 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3667 const Designator &D = Desig.getDesignator(Idx);
3668
3669 if (D.isFieldDesignator()) {
3670 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3671 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3672 } else if (D.isArrayDesignator()) {
3673 Expr *Index = D.getArrayIndex();
3674 llvm::APSInt IndexValue;
3675 if (!Index->isTypeDependent() && !Index->isValueDependent())
3676 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3677 if (!Index)
3678 Invalid = true;
3679 else {
3680 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3681 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3682 InitExpressions.push_back(Index);
3683 }
3684 } else if (D.isArrayRangeDesignator()) {
3685 Expr *StartIndex = D.getArrayRangeStart();
3686 Expr *EndIndex = D.getArrayRangeEnd();
3687 llvm::APSInt StartValue;
3688 llvm::APSInt EndValue;
3689 bool StartDependent = StartIndex->isTypeDependent() ||
3690 StartIndex->isValueDependent();
3691 bool EndDependent = EndIndex->isTypeDependent() ||
3692 EndIndex->isValueDependent();
3693 if (!StartDependent)
3694 StartIndex =
3695 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3696 if (!EndDependent)
3697 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3698
3699 if (!StartIndex || !EndIndex)
3700 Invalid = true;
3701 else {
3702 // Make sure we're comparing values with the same bit width.
3703 if (StartDependent || EndDependent) {
3704 // Nothing to compute.
3705 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3706 EndValue = EndValue.extend(StartValue.getBitWidth());
3707 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3708 StartValue = StartValue.extend(EndValue.getBitWidth());
3709
3710 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3711 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3712 << toString(StartValue, 10) << toString(EndValue, 10)
3713 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3714 Invalid = true;
3715 } else {
3716 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3717 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3718 D.getRBracketLoc()));
3719 InitExpressions.push_back(StartIndex);
3720 InitExpressions.push_back(EndIndex);
3721 }
3722 }
3723 }
3724 }
3725
3726 if (Invalid || Init.isInvalid())
3727 return ExprError();
3728
3729 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3730 EqualOrColonLoc, GNUSyntax,
3731 Init.getAs<Expr>());
3732}
3733
3734//===----------------------------------------------------------------------===//
3735// Initialization entity
3736//===----------------------------------------------------------------------===//
3737
3738InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3739 const InitializedEntity &Parent)
3740 : Parent(&Parent), Index(Index)
3741{
3742 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3743 Kind = EK_ArrayElement;
3744 Type = AT->getElementType();
3745 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3746 Kind = EK_VectorElement;
3747 Type = VT->getElementType();
3748 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3749 Kind = EK_MatrixElement;
3750 Type = MT->getElementType();
3751 } else {
3752 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3753 assert(CT && "Unexpected type");
3754 Kind = EK_ComplexElement;
3755 Type = CT->getElementType();
3756 }
3757}
3758
3761 const CXXBaseSpecifier *Base,
3762 bool IsInheritedVirtualBase,
3763 const InitializedEntity *Parent) {
3764 InitializedEntity Result;
3765 Result.Kind = EK_Base;
3766 Result.Parent = Parent;
3767 Result.Base = {Base, IsInheritedVirtualBase};
3768 Result.Type = Base->getType();
3769 return Result;
3770}
3771
3773 switch (getKind()) {
3774 case EK_Parameter:
3776 ParmVarDecl *D = Parameter.getPointer();
3777 return (D ? D->getDeclName() : DeclarationName());
3778 }
3779
3780 case EK_Variable:
3781 case EK_Member:
3783 case EK_Binding:
3785 return Variable.VariableOrMember->getDeclName();
3786
3787 case EK_LambdaCapture:
3788 return DeclarationName(Capture.VarID);
3789
3790 case EK_Result:
3791 case EK_StmtExprResult:
3792 case EK_Exception:
3793 case EK_New:
3794 case EK_Temporary:
3795 case EK_Base:
3796 case EK_Delegating:
3797 case EK_ArrayElement:
3798 case EK_VectorElement:
3799 case EK_MatrixElement:
3800 case EK_ComplexElement:
3801 case EK_BlockElement:
3804 case EK_RelatedResult:
3805 return DeclarationName();
3806 }
3807
3808 llvm_unreachable("Invalid EntityKind!");
3809}
3810
3812 switch (getKind()) {
3813 case EK_Variable:
3814 case EK_Member:
3816 case EK_Binding:
3818 return cast<ValueDecl>(Variable.VariableOrMember);
3819
3820 case EK_Parameter:
3822 return Parameter.getPointer();
3823
3824 case EK_Result:
3825 case EK_StmtExprResult:
3826 case EK_Exception:
3827 case EK_New:
3828 case EK_Temporary:
3829 case EK_Base:
3830 case EK_Delegating:
3831 case EK_ArrayElement:
3832 case EK_VectorElement:
3833 case EK_MatrixElement:
3834 case EK_ComplexElement:
3835 case EK_BlockElement:
3837 case EK_LambdaCapture:
3839 case EK_RelatedResult:
3840 return nullptr;
3841 }
3842
3843 llvm_unreachable("Invalid EntityKind!");
3844}
3845
3847 switch (getKind()) {
3848 case EK_Result:
3849 case EK_Exception:
3850 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3851
3852 case EK_StmtExprResult:
3853 case EK_Variable:
3854 case EK_Parameter:
3857 case EK_Member:
3859 case EK_Binding:
3860 case EK_New:
3861 case EK_Temporary:
3863 case EK_Base:
3864 case EK_Delegating:
3865 case EK_ArrayElement:
3866 case EK_VectorElement:
3867 case EK_MatrixElement:
3868 case EK_ComplexElement:
3869 case EK_BlockElement:
3871 case EK_LambdaCapture:
3872 case EK_RelatedResult:
3873 break;
3874 }
3875
3876 return false;
3877}
3878
3879unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3880 assert(getParent() != this);
3881 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3882 for (unsigned I = 0; I != Depth; ++I)
3883 OS << "`-";
3884
3885 switch (getKind()) {
3886 case EK_Variable: OS << "Variable"; break;
3887 case EK_Parameter: OS << "Parameter"; break;
3888 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3889 break;
3890 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3891 case EK_Result: OS << "Result"; break;
3892 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3893 case EK_Exception: OS << "Exception"; break;
3894 case EK_Member:
3896 OS << "Member";
3897 break;
3898 case EK_Binding: OS << "Binding"; break;
3899 case EK_New: OS << "New"; break;
3900 case EK_Temporary: OS << "Temporary"; break;
3901 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3902 case EK_RelatedResult: OS << "RelatedResult"; break;
3903 case EK_Base: OS << "Base"; break;
3904 case EK_Delegating: OS << "Delegating"; break;
3905 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3906 case EK_VectorElement: OS << "VectorElement " << Index; break;
3907 case EK_MatrixElement:
3908 OS << "MatrixElement " << Index;
3909 break;
3910 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3911 case EK_BlockElement: OS << "Block"; break;
3913 OS << "Block (lambda)";
3914 break;
3915 case EK_LambdaCapture:
3916 OS << "LambdaCapture ";
3917 OS << DeclarationName(Capture.VarID);
3918 break;
3919 }
3920
3921 if (auto *D = getDecl()) {
3922 OS << " ";
3923 D->printQualifiedName(OS);
3924 }
3925
3926 OS << " '" << getType() << "'\n";
3927
3928 return Depth + 1;
3929}
3930
3931LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3932 dumpImpl(llvm::errs());
3933}
3934
3935//===----------------------------------------------------------------------===//
3936// Initialization sequence
3937//===----------------------------------------------------------------------===//
3938
3984
3986 // There can be some lvalue adjustments after the SK_BindReference step.
3987 for (const Step &S : llvm::reverse(Steps)) {
3988 if (S.Kind == SK_BindReference)
3989 return true;
3990 if (S.Kind == SK_BindReferenceToTemporary)
3991 return false;
3992 }
3993 return false;
3994}
3995
3997 if (!Failed())
3998 return false;
3999
4000 switch (getFailureKind()) {
4011 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4028 case FK_Incomplete:
4033 case FK_PlaceholderType:
4039 return false;
4040
4045 return FailedOverloadResult == OR_Ambiguous;
4046 }
4047
4048 llvm_unreachable("Invalid EntityKind!");
4049}
4050
4052 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4053}
4054
4055void
4056InitializationSequence
4057::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4059 bool HadMultipleCandidates) {
4060 Step S;
4062 S.Type = Function->getType();
4063 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4066 Steps.push_back(S);
4067}
4068
4070 ExprValueKind VK) {
4071 Step S;
4072 switch (VK) {
4073 case VK_PRValue:
4075 break;
4076 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4077 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4078 }
4079 S.Type = BaseType;
4080 Steps.push_back(S);
4081}
4082
4084 bool BindingTemporary) {
4085 Step S;
4086 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4087 S.Type = T;
4088 Steps.push_back(S);
4089}
4090
4092 Step S;
4093 S.Kind = SK_FinalCopy;
4094 S.Type = T;
4095 Steps.push_back(S);
4096}
4097
4099 Step S;
4101 S.Type = T;
4102 Steps.push_back(S);
4103}
4104
4105void
4107 DeclAccessPair FoundDecl,
4108 QualType T,
4109 bool HadMultipleCandidates) {
4110 Step S;
4112 S.Type = T;
4113 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4115 S.Function.FoundDecl = FoundDecl;
4116 Steps.push_back(S);
4117}
4118
4120 ExprValueKind VK) {
4121 Step S;
4122 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4123 switch (VK) {
4124 case VK_PRValue:
4126 break;
4127 case VK_XValue:
4129 break;
4130 case VK_LValue:
4132 break;
4133 }
4134 S.Type = Ty;
4135 Steps.push_back(S);
4136}
4137
4139 Step S;
4141 S.Type = Ty;
4142 Steps.push_back(S);
4143}
4144
4146 Step S;
4148 S.Type = Ty;
4149 Steps.push_back(S);
4150}
4151
4154 bool TopLevelOfInitList) {
4155 Step S;
4156 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4158 S.Type = T;
4159 S.ICS = new ImplicitConversionSequence(ICS);
4160 Steps.push_back(S);
4161}
4162
4164 Step S;
4166 S.Type = T;
4167 Steps.push_back(S);
4168}
4169
4172 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4173 Step S;
4174 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4177 S.Type = T;
4178 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4180 S.Function.FoundDecl = FoundDecl;
4181 Steps.push_back(S);
4182}
4183
4185 Step S;
4187 S.Type = T;
4188 Steps.push_back(S);
4189}
4190
4192 Step S;
4193 S.Kind = SK_CAssignment;
4194 S.Type = T;
4195 Steps.push_back(S);
4196}
4197
4199 Step S;
4200 S.Kind = SK_StringInit;
4201 S.Type = T;
4202 Steps.push_back(S);
4203}
4204
4206 Step S;
4208 S.Type = T;
4209 Steps.push_back(S);
4210}
4211
4213 Step S;
4214 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4215 S.Type = T;
4216 Steps.push_back(S);
4217}
4218
4220 Step S;
4222 S.Type = EltT;
4223 Steps.insert(Steps.begin(), S);
4224
4226 S.Type = T;
4227 Steps.push_back(S);
4228}
4229
4231 Step S;
4233 S.Type = T;
4234 Steps.push_back(S);
4235}
4236
4238 bool shouldCopy) {
4239 Step s;
4240 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4242 s.Type = type;
4243 Steps.push_back(s);
4244}
4245
4247 Step S;
4249 S.Type = T;
4250 Steps.push_back(S);
4251}
4252
4254 Step S;
4256 S.Type = T;
4257 Steps.push_back(S);
4258}
4259
4261 Step S;
4263 S.Type = T;
4264 Steps.push_back(S);
4265}
4266
4268 Step S;
4270 S.Type = T;
4271 Steps.push_back(S);
4272}
4273
4275 Step S;
4277 S.Type = T;
4278 Steps.push_back(S);
4279}
4280
4282 InitListExpr *Syntactic) {
4283 assert(Syntactic->getNumInits() == 1 &&
4284 "Can only unwrap trivial init lists.");
4285 Step S;
4287 S.Type = Syntactic->getInit(0)->getType();
4288 Steps.insert(Steps.begin(), S);
4289}
4290
4292 InitListExpr *Syntactic) {
4293 assert(Syntactic->getNumInits() == 1 &&
4294 "Can only rewrap trivial init lists.");
4295 Step S;
4297 S.Type = Syntactic->getInit(0)->getType();
4298 Steps.insert(Steps.begin(), S);
4299
4301 S.Type = T;
4302 S.WrappingSyntacticList = Syntactic;
4303 Steps.push_back(S);
4304}
4305
4309 this->Failure = Failure;
4310 this->FailedOverloadResult = Result;
4311}
4312
4313//===----------------------------------------------------------------------===//
4314// Attempt initialization
4315//===----------------------------------------------------------------------===//
4316
4317/// Tries to add a zero initializer. Returns true if that worked.
4318static bool
4320 const InitializedEntity &Entity) {
4322 return false;
4323
4324 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4325 if (VD->getInit() || VD->getEndLoc().isMacroID())
4326 return false;
4327
4328 QualType VariableTy = VD->getType().getCanonicalType();
4330 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4331 if (!Init.empty()) {
4332 Sequence.AddZeroInitializationStep(Entity.getType());
4333 Sequence.SetZeroInitializationFixit(Init, Loc);
4334 return true;
4335 }
4336 return false;
4337}
4338
4340 InitializationSequence &Sequence,
4341 const InitializedEntity &Entity) {
4342 if (!S.getLangOpts().ObjCAutoRefCount) return;
4343
4344 /// When initializing a parameter, produce the value if it's marked
4345 /// __attribute__((ns_consumed)).
4346 if (Entity.isParameterKind()) {
4347 if (!Entity.isParameterConsumed())
4348 return;
4349
4350 assert(Entity.getType()->isObjCRetainableType() &&
4351 "consuming an object of unretainable type?");
4352 Sequence.AddProduceObjCObjectStep(Entity.getType());
4353
4354 /// When initializing a return value, if the return type is a
4355 /// retainable type, then returns need to immediately retain the
4356 /// object. If an autorelease is required, it will be done at the
4357 /// last instant.
4358 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4360 if (!Entity.getType()->isObjCRetainableType())
4361 return;
4362
4363 Sequence.AddProduceObjCObjectStep(Entity.getType());
4364 }
4365}
4366
4367/// Initialize an array from another array
4368static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4369 const InitializedEntity &Entity, Expr *Initializer,
4370 QualType DestType, InitializationSequence &Sequence,
4371 bool TreatUnavailableAsInvalid) {
4372 // If source is a prvalue, use it directly.
4373 if (Initializer->isPRValue()) {
4374 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4375 return;
4376 }
4377
4378 // Emit element-at-a-time copy loop.
4379 InitializedEntity Element =
4381 QualType InitEltT =
4383
4384 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4385 // allocator at the moment
4387 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4388 Initializer->getObjectKind());
4389 Expr *OVEAsExpr = OVE;
4390 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4391 /*TopLevelOfInitList*/ false,
4392 TreatUnavailableAsInvalid);
4393 if (Sequence)
4394 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4395}
4396
4397static void TryListInitialization(Sema &S,
4398 const InitializedEntity &Entity,
4399 const InitializationKind &Kind,
4400 InitListExpr *InitList,
4401 InitializationSequence &Sequence,
4402 bool TreatUnavailableAsInvalid);
4403
4404/// When initializing from init list via constructor, handle
4405/// initialization of an object of type std::initializer_list<T>.
4406///
4407/// \return true if we have handled initialization of an object of type
4408/// std::initializer_list<T>, false otherwise.
4410 InitListExpr *List,
4411 QualType DestType,
4412 InitializationSequence &Sequence,
4413 bool TreatUnavailableAsInvalid) {
4414 QualType E;
4415 if (!S.isStdInitializerList(DestType, &E))
4416 return false;
4417
4418 if (!S.isCompleteType(List->getExprLoc(), E)) {
4419 Sequence.setIncompleteTypeFailure(E);
4420 return true;
4421 }
4422
4423 // Try initializing a temporary array from the init list.
4425 E.withConst(),
4426 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4429 InitializedEntity HiddenArray =
4432 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4433 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4434 TreatUnavailableAsInvalid);
4435 if (Sequence)
4436 Sequence.AddStdInitializerListConstructionStep(DestType);
4437 return true;
4438}
4439
4440/// Determine if the constructor has the signature of a copy or move
4441/// constructor for the type T of the class in which it was found. That is,
4442/// determine if its first parameter is of type T or reference to (possibly
4443/// cv-qualified) T.
4445 const ConstructorInfo &Info) {
4446 if (Info.Constructor->getNumParams() == 0)
4447 return false;
4448
4449 QualType ParmT =
4451 CanQualType ClassT = Ctx.getCanonicalTagType(
4453
4454 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4455}
4456
4458 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4459 OverloadCandidateSet &CandidateSet, QualType DestType,
4461 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4462 bool IsListInit, bool RequireActualConstructor,
4463 bool SecondStepOfCopyInit = false) {
4465 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4466
4467 for (NamedDecl *D : Ctors) {
4468 auto Info = getConstructorInfo(D);
4469 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4470 continue;
4471
4472 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4473 continue;
4474
4475 // C++11 [over.best.ics]p4:
4476 // ... and the constructor or user-defined conversion function is a
4477 // candidate by
4478 // - 13.3.1.3, when the argument is the temporary in the second step
4479 // of a class copy-initialization, or
4480 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4481 // - the second phase of 13.3.1.7 when the initializer list has exactly
4482 // one element that is itself an initializer list, and the target is
4483 // the first parameter of a constructor of class X, and the conversion
4484 // is to X or reference to (possibly cv-qualified X),
4485 // user-defined conversion sequences are not considered.
4486 bool SuppressUserConversions =
4487 SecondStepOfCopyInit ||
4488 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4490
4491 if (Info.ConstructorTmpl)
4493 Info.ConstructorTmpl, Info.FoundDecl,
4494 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4495 /*PartialOverloading=*/false, AllowExplicit);
4496 else {
4497 // C++ [over.match.copy]p1:
4498 // - When initializing a temporary to be bound to the first parameter
4499 // of a constructor [for type T] that takes a reference to possibly
4500 // cv-qualified T as its first argument, called with a single
4501 // argument in the context of direct-initialization, explicit
4502 // conversion functions are also considered.
4503 // FIXME: What if a constructor template instantiates to such a signature?
4504 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4505 Args.size() == 1 &&
4507 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4508 CandidateSet, SuppressUserConversions,
4509 /*PartialOverloading=*/false, AllowExplicit,
4510 AllowExplicitConv);
4511 }
4512 }
4513
4514 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4515 //
4516 // When initializing an object of class type T by constructor
4517 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4518 // from a single expression of class type U, conversion functions of
4519 // U that convert to the non-reference type cv T are candidates.
4520 // Explicit conversion functions are only candidates during
4521 // direct-initialization.
4522 //
4523 // Note: SecondStepOfCopyInit is only ever true in this case when
4524 // evaluating whether to produce a C++98 compatibility warning.
4525 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4526 !RequireActualConstructor && !SecondStepOfCopyInit) {
4527 Expr *Initializer = Args[0];
4528 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4529 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4530 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4531 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4532 NamedDecl *D = *I;
4534 D = D->getUnderlyingDecl();
4535
4536 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4537 CXXConversionDecl *Conv;
4538 if (ConvTemplate)
4539 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4540 else
4541 Conv = cast<CXXConversionDecl>(D);
4542
4543 if (ConvTemplate)
4545 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4546 CandidateSet, AllowExplicit, AllowExplicit,
4547 /*AllowResultConversion*/ false);
4548 else
4549 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4550 DestType, CandidateSet, AllowExplicit,
4551 AllowExplicit,
4552 /*AllowResultConversion*/ false);
4553 }
4554 }
4555 }
4556
4557 // Perform overload resolution and return the result.
4558 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4559}
4560
4561/// Attempt initialization by constructor (C++ [dcl.init]), which
4562/// enumerates the constructors of the initialized entity and performs overload
4563/// resolution to select the best.
4564/// \param DestType The destination class type.
4565/// \param DestArrayType The destination type, which is either DestType or
4566/// a (possibly multidimensional) array of DestType.
4567/// \param IsListInit Is this list-initialization?
4568/// \param IsInitListCopy Is this non-list-initialization resulting from a
4569/// list-initialization from {x} where x is the same
4570/// aggregate type as the entity?
4572 const InitializedEntity &Entity,
4573 const InitializationKind &Kind,
4574 MultiExprArg Args, QualType DestType,
4575 QualType DestArrayType,
4576 InitializationSequence &Sequence,
4577 bool IsListInit = false,
4578 bool IsInitListCopy = false) {
4579 assert(((!IsListInit && !IsInitListCopy) ||
4580 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4581 "IsListInit/IsInitListCopy must come with a single initializer list "
4582 "argument.");
4583 InitListExpr *ILE =
4584 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4585 MultiExprArg UnwrappedArgs =
4586 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4587
4588 // The type we're constructing needs to be complete.
4589 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4590 Sequence.setIncompleteTypeFailure(DestType);
4591 return;
4592 }
4593
4594 bool RequireActualConstructor =
4595 !(Entity.getKind() != InitializedEntity::EK_Base &&
4597 Entity.getKind() !=
4599
4600 bool CopyElisionPossible = false;
4601 auto ElideConstructor = [&] {
4602 // Convert qualifications if necessary.
4603 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4604 if (ILE)
4605 Sequence.RewrapReferenceInitList(DestType, ILE);
4606 };
4607
4608 // C++17 [dcl.init]p17:
4609 // - If the initializer expression is a prvalue and the cv-unqualified
4610 // version of the source type is the same class as the class of the
4611 // destination, the initializer expression is used to initialize the
4612 // destination object.
4613 // Per DR (no number yet), this does not apply when initializing a base
4614 // class or delegating to another constructor from a mem-initializer.
4615 // ObjC++: Lambda captured by the block in the lambda to block conversion
4616 // should avoid copy elision.
4617 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4618 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4619 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4620 if (ILE && !DestType->isAggregateType()) {
4621 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4622 // Make this an elision if this won't call an initializer-list
4623 // constructor. (Always on an aggregate type or check constructors first.)
4624
4625 // This effectively makes our resolution as follows. The parts in angle
4626 // brackets are additions.
4627 // C++17 [over.match.list]p(1.2):
4628 // - If no viable initializer-list constructor is found <and the
4629 // initializer list does not consist of exactly a single element with
4630 // the same cv-unqualified class type as T>, [...]
4631 // C++17 [dcl.init.list]p(3.6):
4632 // - Otherwise, if T is a class type, constructors are considered. The
4633 // applicable constructors are enumerated and the best one is chosen
4634 // through overload resolution. <If no constructor is found and the
4635 // initializer list consists of exactly a single element with the same
4636 // cv-unqualified class type as T, the object is initialized from that
4637 // element (by copy-initialization for copy-list-initialization, or by
4638 // direct-initialization for direct-list-initialization). Otherwise, >
4639 // if a narrowing conversion [...]
4640 assert(!IsInitListCopy &&
4641 "IsInitListCopy only possible with aggregate types");
4642 CopyElisionPossible = true;
4643 } else {
4644 ElideConstructor();
4645 return;
4646 }
4647 }
4648
4649 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4650 // Build the candidate set directly in the initialization sequence
4651 // structure, so that it will persist if we fail.
4652 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4653
4654 // Determine whether we are allowed to call explicit constructors or
4655 // explicit conversion operators.
4656 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4657 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4658
4659 // - Otherwise, if T is a class type, constructors are considered. The
4660 // applicable constructors are enumerated, and the best one is chosen
4661 // through overload resolution.
4662 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4663
4666 bool AsInitializerList = false;
4667
4668 // C++11 [over.match.list]p1, per DR1467:
4669 // When objects of non-aggregate type T are list-initialized, such that
4670 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4671 // according to the rules in this section, overload resolution selects
4672 // the constructor in two phases:
4673 //
4674 // - Initially, the candidate functions are the initializer-list
4675 // constructors of the class T and the argument list consists of the
4676 // initializer list as a single argument.
4677 if (IsListInit) {
4678 AsInitializerList = true;
4679
4680 // If the initializer list has no elements and T has a default constructor,
4681 // the first phase is omitted.
4682 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4684 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4685 CopyInitialization, AllowExplicit,
4686 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4687
4688 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4689 // No initializer list candidate
4690 ElideConstructor();
4691 return;
4692 }
4693 }
4694
4695 // if the initialization is direct-initialization, or if it is
4696 // copy-initialization where the cv-unqualified version of the source type is
4697 // the same as or is derived from the class of the destination type,
4698 // constructors are considered.
4699 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4700 Kind.getKind() == InitializationKind::IK_Copy) &&
4701 Args.size() == 1 &&
4703 Args[0]->getType().getNonReferenceType(),
4704 DestType.getNonReferenceType()))
4705 RequireActualConstructor = true;
4706
4707 // C++11 [over.match.list]p1:
4708 // - If no viable initializer-list constructor is found, overload resolution
4709 // is performed again, where the candidate functions are all the
4710 // constructors of the class T and the argument list consists of the
4711 // elements of the initializer list.
4713 AsInitializerList = false;
4715 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4716 Best, CopyInitialization, AllowExplicit,
4717 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4718 }
4719 if (Result) {
4720 Sequence.SetOverloadFailure(
4723 Result);
4724
4725 if (Result != OR_Deleted)
4726 return;
4727 }
4728
4729 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4730
4731 // In C++17, ResolveConstructorOverload can select a conversion function
4732 // instead of a constructor.
4733 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4734 // Add the user-defined conversion step that calls the conversion function.
4735 QualType ConvType = CD->getConversionType();
4736 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4737 "should not have selected this conversion function");
4738 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4739 HadMultipleCandidates);
4740 if (!S.Context.hasSameType(ConvType, DestType))
4741 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4742 if (IsListInit)
4743 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4744 return;
4745 }
4746
4747 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4748 if (Result != OR_Deleted) {
4749 if (!IsListInit &&
4750 (Kind.getKind() == InitializationKind::IK_Default ||
4751 Kind.getKind() == InitializationKind::IK_Direct) &&
4752 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4753 DestRecordDecl->isAggregate() &&
4754 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4755 !S.isUnevaluatedContext()) {
4756 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
4757 << /* Var-in-Record */ 1 << DestRecordDecl;
4758 emitUninitializedExplicitInitFields(S, DestRecordDecl);
4759 }
4760
4761 // C++11 [dcl.init]p6:
4762 // If a program calls for the default initialization of an object
4763 // of a const-qualified type T, T shall be a class type with a
4764 // user-provided default constructor.
4765 // C++ core issue 253 proposal:
4766 // If the implicit default constructor initializes all subobjects, no
4767 // initializer should be required.
4768 // The 253 proposal is for example needed to process libstdc++ headers
4769 // in 5.x.
4770 if (Kind.getKind() == InitializationKind::IK_Default &&
4771 Entity.getType().isConstQualified()) {
4772 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4773 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4775 return;
4776 }
4777 }
4778
4779 // C++11 [over.match.list]p1:
4780 // In copy-list-initialization, if an explicit constructor is chosen, the
4781 // initializer is ill-formed.
4782 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4784 return;
4785 }
4786 }
4787
4788 // [class.copy.elision]p3:
4789 // In some copy-initialization contexts, a two-stage overload resolution
4790 // is performed.
4791 // If the first overload resolution selects a deleted function, we also
4792 // need the initialization sequence to decide whether to perform the second
4793 // overload resolution.
4794 // For deleted functions in other contexts, there is no need to get the
4795 // initialization sequence.
4796 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4797 return;
4798
4799 // Add the constructor initialization step. Any cv-qualification conversion is
4800 // subsumed by the initialization.
4802 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4803 IsListInit | IsInitListCopy, AsInitializerList);
4804}
4805
4807 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4808 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4809 ExprResult *Result = nullptr);
4810
4811/// Attempt to initialize an object of a class type either by
4812/// direct-initialization, or by copy-initialization from an
4813/// expression of the same or derived class type. This corresponds
4814/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4815///
4816/// \param IsAggrListInit Is this non-list-initialization being done as
4817/// part of a list-initialization of an aggregate
4818/// from a single expression of the same or
4819/// derived class type (C++2c [dcl.init.list] p3.2)?
4821 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4822 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4823 bool IsAggrListInit) {
4824 // C++2c [dcl.init.general] p16.6:
4825 // * Otherwise, if the destination type is a class type:
4826 // * If the initializer expression is a prvalue and
4827 // the cv-unqualified version of the source type is the same
4828 // as the destination type, the initializer expression is used
4829 // to initialize the destination object.
4830 // * Otherwise, if the initialization is direct-initialization,
4831 // or if it is copy-initialization where the cv-unqualified
4832 // version of the source type is the same as or is derived from
4833 // the class of the destination type, constructors are considered.
4834 // The applicable constructors are enumerated, and the best one
4835 // is chosen through overload resolution. Then:
4836 // * If overload resolution is successful, the selected
4837 // constructor is called to initialize the object, with
4838 // the initializer expression or expression-list as its
4839 // argument(s).
4840 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
4841 Sequence, /*IsListInit=*/false, IsAggrListInit);
4842
4843 // * Otherwise, if no constructor is viable, the destination type
4844 // is an aggregate class, and the initializer is a parenthesized
4845 // expression-list, the object is initialized as follows. [...]
4846 // Parenthesized initialization of aggregates is a C++20 feature.
4847 if (S.getLangOpts().CPlusPlus20 &&
4848 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4849 Sequence.getFailureKind() ==
4852 (IsAggrListInit || DestType->isAggregateType()))
4853 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4854 /*VerifyOnly=*/true);
4855
4856 // * Otherwise, the initialization is ill-formed.
4857}
4858
4859static bool
4862 QualType &SourceType,
4863 QualType &UnqualifiedSourceType,
4864 QualType UnqualifiedTargetType,
4865 InitializationSequence &Sequence) {
4866 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4867 S.Context.OverloadTy) {
4869 bool HadMultipleCandidates = false;
4870 if (FunctionDecl *Fn
4872 UnqualifiedTargetType,
4873 false, Found,
4874 &HadMultipleCandidates)) {
4876 HadMultipleCandidates);
4877 SourceType = Fn->getType();
4878 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4879 } else if (!UnqualifiedTargetType->isRecordType()) {
4881 return true;
4882 }
4883 }
4884 return false;
4885}
4886
4887static void TryReferenceInitializationCore(Sema &S,
4888 const InitializedEntity &Entity,
4889 const InitializationKind &Kind,
4890 Expr *Initializer,
4891 QualType cv1T1, QualType T1,
4892 Qualifiers T1Quals,
4893 QualType cv2T2, QualType T2,
4894 Qualifiers T2Quals,
4895 InitializationSequence &Sequence,
4896 bool TopLevelOfInitList);
4897
4898static void TryValueInitialization(Sema &S,
4899 const InitializedEntity &Entity,
4900 const InitializationKind &Kind,
4901 InitializationSequence &Sequence,
4902 InitListExpr *InitList = nullptr);
4903
4904/// Attempt list initialization of a reference.
4906 const InitializedEntity &Entity,
4907 const InitializationKind &Kind,
4908 InitListExpr *InitList,
4909 InitializationSequence &Sequence,
4910 bool TreatUnavailableAsInvalid) {
4911 // First, catch C++03 where this isn't possible.
4912 if (!S.getLangOpts().CPlusPlus11) {
4914 return;
4915 }
4916 // Can't reference initialize a compound literal.
4919 return;
4920 }
4921
4922 QualType DestType = Entity.getType();
4923 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4924 Qualifiers T1Quals;
4925 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4926
4927 // Reference initialization via an initializer list works thus:
4928 // If the initializer list consists of a single element that is
4929 // reference-related to the referenced type, bind directly to that element
4930 // (possibly creating temporaries).
4931 // Otherwise, initialize a temporary with the initializer list and
4932 // bind to that.
4933 if (InitList->getNumInits() == 1) {
4934 Expr *Initializer = InitList->getInit(0);
4936 Qualifiers T2Quals;
4937 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4938
4939 // If this fails, creating a temporary wouldn't work either.
4941 T1, Sequence))
4942 return;
4943
4944 SourceLocation DeclLoc = Initializer->getBeginLoc();
4945 Sema::ReferenceCompareResult RefRelationship
4946 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4947 if (RefRelationship >= Sema::Ref_Related) {
4948 // Try to bind the reference here.
4949 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4950 T1Quals, cv2T2, T2, T2Quals, Sequence,
4951 /*TopLevelOfInitList=*/true);
4952 if (Sequence)
4953 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4954 return;
4955 }
4956
4957 // Update the initializer if we've resolved an overloaded function.
4958 if (!Sequence.steps().empty())
4959 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4960 }
4961 // Perform address space compatibility check.
4962 QualType cv1T1IgnoreAS = cv1T1;
4963 if (T1Quals.hasAddressSpace()) {
4964 Qualifiers T2Quals;
4965 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4966 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4967 Sequence.SetFailed(
4969 return;
4970 }
4971 // Ignore address space of reference type at this point and perform address
4972 // space conversion after the reference binding step.
4973 cv1T1IgnoreAS =
4975 }
4976 // Not reference-related. Create a temporary and bind to that.
4977 InitializedEntity TempEntity =
4979
4980 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4981 TreatUnavailableAsInvalid);
4982 if (Sequence) {
4983 if (DestType->isRValueReferenceType() ||
4984 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4985 if (S.getLangOpts().CPlusPlus20 &&
4987 DestType->isRValueReferenceType()) {
4988 // C++20 [dcl.init.list]p3.10:
4989 // List-initialization of an object or reference of type T is defined as
4990 // follows:
4991 // ..., unless T is “reference to array of unknown bound of U”, in which
4992 // case the type of the prvalue is the type of x in the declaration U
4993 // x[] H, where H is the initializer list.
4995 }
4996 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4997 /*BindingTemporary=*/true);
4998 if (T1Quals.hasAddressSpace())
5000 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5001 } else
5002 Sequence.SetFailed(
5004 }
5005}
5006
5007/// Attempt list initialization (C++0x [dcl.init.list])
5009 const InitializedEntity &Entity,
5010 const InitializationKind &Kind,
5011 InitListExpr *InitList,
5012 InitializationSequence &Sequence,
5013 bool TreatUnavailableAsInvalid) {
5014 QualType DestType = Entity.getType();
5015
5016 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, InitList)) {
5018 return;
5019 }
5020
5021 // C++ doesn't allow scalar initialization with more than one argument.
5022 // But C99 complex numbers are scalars and it makes sense there.
5023 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5024 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5026 return;
5027 }
5028 if (DestType->isReferenceType()) {
5029 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5030 TreatUnavailableAsInvalid);
5031 return;
5032 }
5033
5034 if (DestType->isRecordType() &&
5035 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
5036 Sequence.setIncompleteTypeFailure(DestType);
5037 return;
5038 }
5039
5040 // C++20 [dcl.init.list]p3:
5041 // - If the braced-init-list contains a designated-initializer-list, T shall
5042 // be an aggregate class. [...] Aggregate initialization is performed.
5043 //
5044 // We allow arrays here too in order to support array designators.
5045 //
5046 // FIXME: This check should precede the handling of reference initialization.
5047 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5048 // as a tentative DR resolution.
5049 bool IsDesignatedInit = InitList->hasDesignatedInit();
5050 if (!DestType->isAggregateType() && IsDesignatedInit) {
5051 Sequence.SetFailed(
5053 return;
5054 }
5055
5056 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5057 // - If T is an aggregate class and the initializer list has a single element
5058 // of type cv U, where U is T or a class derived from T, the object is
5059 // initialized from that element (by copy-initialization for
5060 // copy-list-initialization, or by direct-initialization for
5061 // direct-list-initialization).
5062 // - Otherwise, if T is a character array and the initializer list has a
5063 // single element that is an appropriately-typed string literal
5064 // (8.5.2 [dcl.init.string]), initialization is performed as described
5065 // in that section.
5066 // - Otherwise, if T is an aggregate, [...] (continue below).
5067 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5068 !IsDesignatedInit) {
5069 if (DestType->isRecordType() && DestType->isAggregateType()) {
5070 QualType InitType = InitList->getInit(0)->getType();
5071 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
5072 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
5073 InitializationKind SubKind =
5075 ? InitializationKind::CreateDirect(Kind.getLocation(),
5076 InitList->getLBraceLoc(),
5077 InitList->getRBraceLoc())
5078 : Kind;
5079 Expr *InitListAsExpr = InitList;
5081 S, Entity, SubKind, InitListAsExpr, DestType, Sequence,
5082 /*IsAggrListInit=*/true);
5083 return;
5084 }
5085 }
5086 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
5087 Expr *SubInit[1] = {InitList->getInit(0)};
5088
5089 // C++17 [dcl.struct.bind]p1:
5090 // ... If the assignment-expression in the initializer has array type A
5091 // and no ref-qualifier is present, e has type cv A and each element is
5092 // copy-initialized or direct-initialized from the corresponding element
5093 // of the assignment-expression as specified by the form of the
5094 // initializer. ...
5095 //
5096 // This is a special case not following list-initialization.
5097 if (isa<ConstantArrayType>(DestAT) &&
5099 isa<DecompositionDecl>(Entity.getDecl())) {
5100 assert(
5101 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5102 "Deduced to other type?");
5103 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5104 "List-initialize structured bindings but not "
5105 "direct-list-initialization?");
5106 TryArrayCopy(S,
5107 InitializationKind::CreateDirect(Kind.getLocation(),
5108 InitList->getLBraceLoc(),
5109 InitList->getRBraceLoc()),
5110 Entity, SubInit[0], DestType, Sequence,
5111 TreatUnavailableAsInvalid);
5112 if (Sequence)
5113 Sequence.AddUnwrapInitListInitStep(InitList);
5114 return;
5115 }
5116
5117 if (!isa<VariableArrayType>(DestAT) &&
5118 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
5119 InitializationKind SubKind =
5121 ? InitializationKind::CreateDirect(Kind.getLocation(),
5122 InitList->getLBraceLoc(),
5123 InitList->getRBraceLoc())
5124 : Kind;
5125 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5126 /*TopLevelOfInitList*/ true,
5127 TreatUnavailableAsInvalid);
5128
5129 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5130 // the element is not an appropriately-typed string literal, in which
5131 // case we should proceed as in C++11 (below).
5132 if (Sequence) {
5133 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5134 return;
5135 }
5136 }
5137 }
5138 }
5139
5140 // C++11 [dcl.init.list]p3:
5141 // - If T is an aggregate, aggregate initialization is performed.
5142 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5143 (S.getLangOpts().CPlusPlus11 &&
5144 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
5145 if (S.getLangOpts().CPlusPlus11) {
5146 // - Otherwise, if the initializer list has no elements and T is a
5147 // class type with a default constructor, the object is
5148 // value-initialized.
5149 if (InitList->getNumInits() == 0) {
5150 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5151 if (S.LookupDefaultConstructor(RD)) {
5152 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5153 return;
5154 }
5155 }
5156
5157 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5158 // an initializer_list object constructed [...]
5159 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
5160 TreatUnavailableAsInvalid))
5161 return;
5162
5163 // - Otherwise, if T is a class type, constructors are considered.
5164 Expr *InitListAsExpr = InitList;
5165 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
5166 DestType, Sequence, /*InitListSyntax*/true);
5167 } else
5169 return;
5170 }
5171
5172 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5173 InitList->getNumInits() == 1) {
5174 Expr *E = InitList->getInit(0);
5175
5176 // - Otherwise, if T is an enumeration with a fixed underlying type,
5177 // the initializer-list has a single element v, and the initialization
5178 // is direct-list-initialization, the object is initialized with the
5179 // value T(v); if a narrowing conversion is required to convert v to
5180 // the underlying type of T, the program is ill-formed.
5181 if (S.getLangOpts().CPlusPlus17 &&
5182 Kind.getKind() == InitializationKind::IK_DirectList &&
5183 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5184 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
5186 E->getType()->isFloatingType())) {
5187 // There are two ways that T(v) can work when T is an enumeration type.
5188 // If there is either an implicit conversion sequence from v to T or
5189 // a conversion function that can convert from v to T, then we use that.
5190 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5191 // type, it is converted to the enumeration type via its underlying type.
5192 // There is no overlap possible between these two cases (except when the
5193 // source value is already of the destination type), and the first
5194 // case is handled by the general case for single-element lists below.
5196 ICS.setStandard();
5198 if (!E->isPRValue())
5200 // If E is of a floating-point type, then the conversion is ill-formed
5201 // due to narrowing, but go through the motions in order to produce the
5202 // right diagnostic.
5206 ICS.Standard.setFromType(E->getType());
5207 ICS.Standard.setToType(0, E->getType());
5208 ICS.Standard.setToType(1, DestType);
5209 ICS.Standard.setToType(2, DestType);
5210 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
5211 /*TopLevelOfInitList*/true);
5212 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5213 return;
5214 }
5215
5216 // - Otherwise, if the initializer list has a single element of type E
5217 // [...references are handled above...], the object or reference is
5218 // initialized from that element (by copy-initialization for
5219 // copy-list-initialization, or by direct-initialization for
5220 // direct-list-initialization); if a narrowing conversion is required
5221 // to convert the element to T, the program is ill-formed.
5222 //
5223 // Per core-24034, this is direct-initialization if we were performing
5224 // direct-list-initialization and copy-initialization otherwise.
5225 // We can't use InitListChecker for this, because it always performs
5226 // copy-initialization. This only matters if we might use an 'explicit'
5227 // conversion operator, or for the special case conversion of nullptr_t to
5228 // bool, so we only need to handle those cases.
5229 //
5230 // FIXME: Why not do this in all cases?
5231 Expr *Init = InitList->getInit(0);
5232 if (Init->getType()->isRecordType() ||
5233 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5234 InitializationKind SubKind =
5236 ? InitializationKind::CreateDirect(Kind.getLocation(),
5237 InitList->getLBraceLoc(),
5238 InitList->getRBraceLoc())
5239 : Kind;
5240 Expr *SubInit[1] = { Init };
5241 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
5242 /*TopLevelOfInitList*/true,
5243 TreatUnavailableAsInvalid);
5244 if (Sequence)
5245 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
5246 return;
5247 }
5248 }
5249
5250 InitListChecker CheckInitList(S, Entity, InitList,
5251 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5252 if (CheckInitList.HadError()) {
5254 return;
5255 }
5256
5257 // Add the list initialization step with the built init list.
5258 Sequence.AddListInitializationStep(DestType);
5259}
5260
5261/// Try a reference initialization that involves calling a conversion
5262/// function.
5264 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5265 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5266 InitializationSequence &Sequence) {
5267 QualType DestType = Entity.getType();
5268 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5269 QualType T1 = cv1T1.getUnqualifiedType();
5270 QualType cv2T2 = Initializer->getType();
5271 QualType T2 = cv2T2.getUnqualifiedType();
5272
5273 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5274 "Must have incompatible references when binding via conversion");
5275
5276 // Build the candidate set directly in the initialization sequence
5277 // structure, so that it will persist if we fail.
5278 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5280
5281 // Determine whether we are allowed to call explicit conversion operators.
5282 // Note that none of [over.match.copy], [over.match.conv], nor
5283 // [over.match.ref] permit an explicit constructor to be chosen when
5284 // initializing a reference, not even for direct-initialization.
5285 bool AllowExplicitCtors = false;
5286 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5287
5288 if (AllowRValues && T1->isRecordType() &&
5289 S.isCompleteType(Kind.getLocation(), T1)) {
5290 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5291 if (T1RecordDecl->isInvalidDecl())
5292 return OR_No_Viable_Function;
5293 // The type we're converting to is a class type. Enumerate its constructors
5294 // to see if there is a suitable conversion.
5295 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
5296 auto Info = getConstructorInfo(D);
5297 if (!Info.Constructor)
5298 continue;
5299
5300 if (!Info.Constructor->isInvalidDecl() &&
5301 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5302 if (Info.ConstructorTmpl)
5304 Info.ConstructorTmpl, Info.FoundDecl,
5305 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5306 /*SuppressUserConversions=*/true,
5307 /*PartialOverloading*/ false, AllowExplicitCtors);
5308 else
5310 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
5311 /*SuppressUserConversions=*/true,
5312 /*PartialOverloading*/ false, AllowExplicitCtors);
5313 }
5314 }
5315 }
5316
5317 if (T2->isRecordType() && S.isCompleteType(Kind.getLocation(), T2)) {
5318 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5319 if (T2RecordDecl->isInvalidDecl())
5320 return OR_No_Viable_Function;
5321 // The type we're converting from is a class type, enumerate its conversion
5322 // functions.
5323 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5324 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5325 NamedDecl *D = *I;
5327 if (isa<UsingShadowDecl>(D))
5328 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5329
5330 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5331 CXXConversionDecl *Conv;
5332 if (ConvTemplate)
5333 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5334 else
5335 Conv = cast<CXXConversionDecl>(D);
5336
5337 // If the conversion function doesn't return a reference type,
5338 // it can't be considered for this conversion unless we're allowed to
5339 // consider rvalues.
5340 // FIXME: Do we need to make sure that we only consider conversion
5341 // candidates with reference-compatible results? That might be needed to
5342 // break recursion.
5343 if ((AllowRValues ||
5345 if (ConvTemplate)
5347 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5348 CandidateSet,
5349 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5350 else
5352 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
5353 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
5354 }
5355 }
5356 }
5357
5358 SourceLocation DeclLoc = Initializer->getBeginLoc();
5359
5360 // Perform overload resolution. If it fails, return the failed result.
5363 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
5364 return Result;
5365
5366 FunctionDecl *Function = Best->Function;
5367 // This is the overload that will be used for this initialization step if we
5368 // use this initialization. Mark it as referenced.
5369 Function->setReferenced();
5370
5371 // Compute the returned type and value kind of the conversion.
5372 QualType cv3T3;
5373 if (isa<CXXConversionDecl>(Function))
5374 cv3T3 = Function->getReturnType();
5375 else
5376 cv3T3 = T1;
5377
5379 if (cv3T3->isLValueReferenceType())
5380 VK = VK_LValue;
5381 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5382 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5383 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
5384
5385 // Add the user-defined conversion step.
5386 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5387 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
5388 HadMultipleCandidates);
5389
5390 // Determine whether we'll need to perform derived-to-base adjustments or
5391 // other conversions.
5393 Sema::ReferenceCompareResult NewRefRelationship =
5394 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
5395
5396 // Add the final conversion sequence, if necessary.
5397 if (NewRefRelationship == Sema::Ref_Incompatible) {
5398 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5399 "should not have conversion after constructor");
5400
5402 ICS.setStandard();
5403 ICS.Standard = Best->FinalConversion;
5404 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
5405
5406 // Every implicit conversion results in a prvalue, except for a glvalue
5407 // derived-to-base conversion, which we handle below.
5408 cv3T3 = ICS.Standard.getToType(2);
5409 VK = VK_PRValue;
5410 }
5411
5412 // If the converted initializer is a prvalue, its type T4 is adjusted to
5413 // type "cv1 T4" and the temporary materialization conversion is applied.
5414 //
5415 // We adjust the cv-qualifications to match the reference regardless of
5416 // whether we have a prvalue so that the AST records the change. In this
5417 // case, T4 is "cv3 T3".
5418 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
5419 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5420 Sequence.AddQualificationConversionStep(cv1T4, VK);
5421 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
5422 VK = IsLValueRef ? VK_LValue : VK_XValue;
5423
5424 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5425 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
5426 else if (RefConv & Sema::ReferenceConversions::ObjC)
5427 Sequence.AddObjCObjectConversionStep(cv1T1);
5428 else if (RefConv & Sema::ReferenceConversions::Function)
5429 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5430 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5431 if (!S.Context.hasSameType(cv1T4, cv1T1))
5432 Sequence.AddQualificationConversionStep(cv1T1, VK);
5433 }
5434
5435 return OR_Success;
5436}
5437
5438static void CheckCXX98CompatAccessibleCopy(Sema &S,
5439 const InitializedEntity &Entity,
5440 Expr *CurInitExpr);
5441
5442/// Attempt reference initialization (C++0x [dcl.init.ref])
5444 const InitializationKind &Kind,
5446 InitializationSequence &Sequence,
5447 bool TopLevelOfInitList) {
5448 QualType DestType = Entity.getType();
5449 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5450 Qualifiers T1Quals;
5451 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
5453 Qualifiers T2Quals;
5454 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
5455
5456 // If the initializer is the address of an overloaded function, try
5457 // to resolve the overloaded function. If all goes well, T2 is the
5458 // type of the resulting function.
5460 T1, Sequence))
5461 return;
5462
5463 // Delegate everything else to a subfunction.
5464 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5465 T1Quals, cv2T2, T2, T2Quals, Sequence,
5466 TopLevelOfInitList);
5467}
5468
5469/// Determine whether an expression is a non-referenceable glvalue (one to
5470/// which a reference can never bind). Attempting to bind a reference to
5471/// such a glvalue will always create a temporary.
5473 return E->refersToBitField() || E->refersToVectorElement() ||
5475}
5476
5477/// Reference initialization without resolving overloaded functions.
5478///
5479/// We also can get here in C if we call a builtin which is declared as
5480/// a function with a parameter of reference type (such as __builtin_va_end()).
5482 const InitializedEntity &Entity,
5483 const InitializationKind &Kind,
5485 QualType cv1T1, QualType T1,
5486 Qualifiers T1Quals,
5487 QualType cv2T2, QualType T2,
5488 Qualifiers T2Quals,
5489 InitializationSequence &Sequence,
5490 bool TopLevelOfInitList) {
5491 QualType DestType = Entity.getType();
5492 SourceLocation DeclLoc = Initializer->getBeginLoc();
5493
5494 // Compute some basic properties of the types and the initializer.
5495 bool isLValueRef = DestType->isLValueReferenceType();
5496 bool isRValueRef = !isLValueRef;
5497 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5498
5500 Sema::ReferenceCompareResult RefRelationship =
5501 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5502
5503 // C++0x [dcl.init.ref]p5:
5504 // A reference to type "cv1 T1" is initialized by an expression of type
5505 // "cv2 T2" as follows:
5506 //
5507 // - If the reference is an lvalue reference and the initializer
5508 // expression
5509 // Note the analogous bullet points for rvalue refs to functions. Because
5510 // there are no function rvalues in C++, rvalue refs to functions are treated
5511 // like lvalue refs.
5512 OverloadingResult ConvOvlResult = OR_Success;
5513 bool T1Function = T1->isFunctionType();
5514 if (isLValueRef || T1Function) {
5515 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5516 (RefRelationship == Sema::Ref_Compatible ||
5517 (Kind.isCStyleOrFunctionalCast() &&
5518 RefRelationship == Sema::Ref_Related))) {
5519 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5520 // reference-compatible with "cv2 T2," or
5521 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5522 Sema::ReferenceConversions::ObjC)) {
5523 // If we're converting the pointee, add any qualifiers first;
5524 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5525 if (RefConv & (Sema::ReferenceConversions::Qualification))
5527 S.Context.getQualifiedType(T2, T1Quals),
5528 Initializer->getValueKind());
5529 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5530 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5531 else
5532 Sequence.AddObjCObjectConversionStep(cv1T1);
5533 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5534 // Perform a (possibly multi-level) qualification conversion.
5535 Sequence.AddQualificationConversionStep(cv1T1,
5536 Initializer->getValueKind());
5537 } else if (RefConv & Sema::ReferenceConversions::Function) {
5538 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5539 }
5540
5541 // We only create a temporary here when binding a reference to a
5542 // bit-field or vector element. Those cases are't supposed to be
5543 // handled by this bullet, but the outcome is the same either way.
5544 Sequence.AddReferenceBindingStep(cv1T1, false);
5545 return;
5546 }
5547
5548 // - has a class type (i.e., T2 is a class type), where T1 is not
5549 // reference-related to T2, and can be implicitly converted to an
5550 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5551 // with "cv3 T3" (this conversion is selected by enumerating the
5552 // applicable conversion functions (13.3.1.6) and choosing the best
5553 // one through overload resolution (13.3)),
5554 // If we have an rvalue ref to function type here, the rhs must be
5555 // an rvalue. DR1287 removed the "implicitly" here.
5556 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5557 (isLValueRef || InitCategory.isRValue())) {
5558 if (S.getLangOpts().CPlusPlus) {
5559 // Try conversion functions only for C++.
5560 ConvOvlResult = TryRefInitWithConversionFunction(
5561 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5562 /*IsLValueRef*/ isLValueRef, Sequence);
5563 if (ConvOvlResult == OR_Success)
5564 return;
5565 if (ConvOvlResult != OR_No_Viable_Function)
5566 Sequence.SetOverloadFailure(
5568 ConvOvlResult);
5569 } else {
5570 ConvOvlResult = OR_No_Viable_Function;
5571 }
5572 }
5573 }
5574
5575 // - Otherwise, the reference shall be an lvalue reference to a
5576 // non-volatile const type (i.e., cv1 shall be const), or the reference
5577 // shall be an rvalue reference.
5578 // For address spaces, we interpret this to mean that an addr space
5579 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5580 if (isLValueRef &&
5581 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5582 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5585 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5586 Sequence.SetOverloadFailure(
5588 ConvOvlResult);
5589 else if (!InitCategory.isLValue())
5590 Sequence.SetFailed(
5591 T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())
5595 else {
5597 switch (RefRelationship) {
5599 if (Initializer->refersToBitField())
5600 FK = InitializationSequence::
5601 FK_NonConstLValueReferenceBindingToBitfield;
5602 else if (Initializer->refersToVectorElement())
5603 FK = InitializationSequence::
5604 FK_NonConstLValueReferenceBindingToVectorElement;
5605 else if (Initializer->refersToMatrixElement())
5606 FK = InitializationSequence::
5607 FK_NonConstLValueReferenceBindingToMatrixElement;
5608 else
5609 llvm_unreachable("unexpected kind of compatible initializer");
5610 break;
5611 case Sema::Ref_Related:
5613 break;
5615 FK = InitializationSequence::
5616 FK_NonConstLValueReferenceBindingToUnrelated;
5617 break;
5618 }
5619 Sequence.SetFailed(FK);
5620 }
5621 return;
5622 }
5623
5624 // - If the initializer expression
5625 // - is an
5626 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5627 // [1z] rvalue (but not a bit-field) or
5628 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5629 //
5630 // Note: functions are handled above and below rather than here...
5631 if (!T1Function &&
5632 (RefRelationship == Sema::Ref_Compatible ||
5633 (Kind.isCStyleOrFunctionalCast() &&
5634 RefRelationship == Sema::Ref_Related)) &&
5635 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5636 (InitCategory.isPRValue() &&
5637 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5638 T2->isArrayType())))) {
5639 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5640 if (InitCategory.isPRValue() && T2->isRecordType()) {
5641 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5642 // compiler the freedom to perform a copy here or bind to the
5643 // object, while C++0x requires that we bind directly to the
5644 // object. Hence, we always bind to the object without making an
5645 // extra copy. However, in C++03 requires that we check for the
5646 // presence of a suitable copy constructor:
5647 //
5648 // The constructor that would be used to make the copy shall
5649 // be callable whether or not the copy is actually done.
5650 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5651 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5652 else if (S.getLangOpts().CPlusPlus11)
5654 }
5655
5656 // C++1z [dcl.init.ref]/5.2.1.2:
5657 // If the converted initializer is a prvalue, its type T4 is adjusted
5658 // to type "cv1 T4" and the temporary materialization conversion is
5659 // applied.
5660 // Postpone address space conversions to after the temporary materialization
5661 // conversion to allow creating temporaries in the alloca address space.
5662 auto T1QualsIgnoreAS = T1Quals;
5663 auto T2QualsIgnoreAS = T2Quals;
5664 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5665 T1QualsIgnoreAS.removeAddressSpace();
5666 T2QualsIgnoreAS.removeAddressSpace();
5667 }
5668 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5669 // with T1's qualifiers.
5670 QualType T2ForQualConv = cv2T2;
5671 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5672 Qualifiers T2BaseQuals =
5673 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5674 T2ForQualConv = S.Context.getQualifiedType(
5675 T2ForQualConv.getUnqualifiedType(), T2BaseQuals);
5676 }
5677 QualType cv1T4 = S.Context.getQualifiedType(T2ForQualConv, T1QualsIgnoreAS);
5678 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5679 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5680 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5681 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5682 // Add addr space conversion if required.
5683 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5684 auto T4Quals = cv1T4.getQualifiers();
5685 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5686 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5687 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5688 cv1T4 = cv1T4WithAS;
5689 }
5690
5691 // In any case, the reference is bound to the resulting glvalue (or to
5692 // an appropriate base class subobject).
5693 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5694 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5695 else if (RefConv & Sema::ReferenceConversions::ObjC)
5696 Sequence.AddObjCObjectConversionStep(cv1T1);
5697 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5698 if (!S.Context.hasSameType(cv1T4, cv1T1))
5699 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5700 }
5701 return;
5702 }
5703
5704 // - has a class type (i.e., T2 is a class type), where T1 is not
5705 // reference-related to T2, and can be implicitly converted to an
5706 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5707 // where "cv1 T1" is reference-compatible with "cv3 T3",
5708 //
5709 // DR1287 removes the "implicitly" here.
5710 if (T2->isRecordType()) {
5711 if (RefRelationship == Sema::Ref_Incompatible) {
5712 ConvOvlResult = TryRefInitWithConversionFunction(
5713 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5714 /*IsLValueRef*/ isLValueRef, Sequence);
5715 if (ConvOvlResult)
5716 Sequence.SetOverloadFailure(
5718 ConvOvlResult);
5719
5720 return;
5721 }
5722
5723 if (RefRelationship == Sema::Ref_Compatible &&
5724 isRValueRef && InitCategory.isLValue()) {
5725 Sequence.SetFailed(
5727 return;
5728 }
5729
5731 return;
5732 }
5733
5734 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5735 // from the initializer expression using the rules for a non-reference
5736 // copy-initialization (8.5). The reference is then bound to the
5737 // temporary. [...]
5738
5739 // Ignore address space of reference type at this point and perform address
5740 // space conversion after the reference binding step.
5741 QualType cv1T1IgnoreAS =
5742 T1Quals.hasAddressSpace()
5744 : cv1T1;
5745
5746 InitializedEntity TempEntity =
5748
5749 // FIXME: Why do we use an implicit conversion here rather than trying
5750 // copy-initialization?
5752 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5753 /*SuppressUserConversions=*/false,
5754 Sema::AllowedExplicit::None,
5755 /*FIXME:InOverloadResolution=*/false,
5756 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5757 /*AllowObjCWritebackConversion=*/false);
5758
5759 if (ICS.isBad()) {
5760 // FIXME: Use the conversion function set stored in ICS to turn
5761 // this into an overloading ambiguity diagnostic. However, we need
5762 // to keep that set as an OverloadCandidateSet rather than as some
5763 // other kind of set.
5764 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5765 Sequence.SetOverloadFailure(
5767 ConvOvlResult);
5768 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5770 else
5772 return;
5773 } else {
5774 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5775 TopLevelOfInitList);
5776 }
5777
5778 // [...] If T1 is reference-related to T2, cv1 must be the
5779 // same cv-qualification as, or greater cv-qualification
5780 // than, cv2; otherwise, the program is ill-formed.
5781 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5782 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5783 if (RefRelationship == Sema::Ref_Related &&
5784 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5785 !T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext()))) {
5787 return;
5788 }
5789
5790 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5791 // reference, the initializer expression shall not be an lvalue.
5792 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5793 InitCategory.isLValue()) {
5794 Sequence.SetFailed(
5796 return;
5797 }
5798
5799 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5800
5801 if (T1Quals.hasAddressSpace()) {
5804 Sequence.SetFailed(
5806 return;
5807 }
5808 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5809 : VK_XValue);
5810 }
5811}
5812
5813/// Attempt character array initialization from a string literal
5814/// (C++ [dcl.init.string], C99 6.7.8).
5816 const InitializedEntity &Entity,
5817 const InitializationKind &Kind,
5819 InitializationSequence &Sequence) {
5820 Sequence.AddStringInitStep(Entity.getType());
5821}
5822
5823/// Attempt value initialization (C++ [dcl.init]p7).
5825 const InitializedEntity &Entity,
5826 const InitializationKind &Kind,
5827 InitializationSequence &Sequence,
5828 InitListExpr *InitList) {
5829 assert((!InitList || InitList->getNumInits() == 0) &&
5830 "Shouldn't use value-init for non-empty init lists");
5831
5832 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5833 //
5834 // To value-initialize an object of type T means:
5835 QualType T = Entity.getType();
5836 assert(!T->isVoidType() && "Cannot value-init void");
5837
5838 // -- if T is an array type, then each element is value-initialized;
5839 T = S.Context.getBaseElementType(T);
5840
5841 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5842 bool NeedZeroInitialization = true;
5843 // C++98:
5844 // -- if T is a class type (clause 9) with a user-declared constructor
5845 // (12.1), then the default constructor for T is called (and the
5846 // initialization is ill-formed if T has no accessible default
5847 // constructor);
5848 // C++11:
5849 // -- if T is a class type (clause 9) with either no default constructor
5850 // (12.1 [class.ctor]) or a default constructor that is user-provided
5851 // or deleted, then the object is default-initialized;
5852 //
5853 // Note that the C++11 rule is the same as the C++98 rule if there are no
5854 // defaulted or deleted constructors, so we just use it unconditionally.
5856 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5857 NeedZeroInitialization = false;
5858
5859 // -- if T is a (possibly cv-qualified) non-union class type without a
5860 // user-provided or deleted default constructor, then the object is
5861 // zero-initialized and, if T has a non-trivial default constructor,
5862 // default-initialized;
5863 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5864 // constructor' part was removed by DR1507.
5865 if (NeedZeroInitialization)
5866 Sequence.AddZeroInitializationStep(Entity.getType());
5867
5868 // C++03:
5869 // -- if T is a non-union class type without a user-declared constructor,
5870 // then every non-static data member and base class component of T is
5871 // value-initialized;
5872 // [...] A program that calls for [...] value-initialization of an
5873 // entity of reference type is ill-formed.
5874 //
5875 // C++11 doesn't need this handling, because value-initialization does not
5876 // occur recursively there, and the implicit default constructor is
5877 // defined as deleted in the problematic cases.
5878 if (!S.getLangOpts().CPlusPlus11 &&
5879 ClassDecl->hasUninitializedReferenceMember()) {
5881 return;
5882 }
5883
5884 // If this is list-value-initialization, pass the empty init list on when
5885 // building the constructor call. This affects the semantics of a few
5886 // things (such as whether an explicit default constructor can be called).
5887 Expr *InitListAsExpr = InitList;
5888 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5889 bool InitListSyntax = InitList;
5890
5891 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5892 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5894 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5895 }
5896
5897 Sequence.AddZeroInitializationStep(Entity.getType());
5898}
5899
5900/// Attempt default initialization (C++ [dcl.init]p6).
5902 const InitializedEntity &Entity,
5903 const InitializationKind &Kind,
5904 InitializationSequence &Sequence) {
5905 assert(Kind.getKind() == InitializationKind::IK_Default);
5906
5907 // C++ [dcl.init]p6:
5908 // To default-initialize an object of type T means:
5909 // - if T is an array type, each element is default-initialized;
5910 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5911
5912 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5913 // constructor for T is called (and the initialization is ill-formed if
5914 // T has no accessible default constructor);
5915 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5916 TryConstructorInitialization(S, Entity, Kind, {}, DestType,
5917 Entity.getType(), Sequence);
5918 return;
5919 }
5920
5921 // - otherwise, no initialization is performed.
5922
5923 // If a program calls for the default initialization of an object of
5924 // a const-qualified type T, T shall be a class type with a user-provided
5925 // default constructor.
5926 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5927 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5929 return;
5930 }
5931
5932 // If the destination type has a lifetime property, zero-initialize it.
5933 if (DestType.getQualifiers().hasObjCLifetime()) {
5934 Sequence.AddZeroInitializationStep(Entity.getType());
5935 return;
5936 }
5937}
5938
5940 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5941 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5942 ExprResult *Result) {
5943 unsigned EntityIndexToProcess = 0;
5944 SmallVector<Expr *, 4> InitExprs;
5945 QualType ResultType;
5946 Expr *ArrayFiller = nullptr;
5947 FieldDecl *InitializedFieldInUnion = nullptr;
5948
5949 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5950 const InitializationKind &SubKind,
5951 Expr *Arg, Expr **InitExpr = nullptr) {
5953 S, SubEntity, SubKind,
5954 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5955
5956 if (IS.Failed()) {
5957 if (!VerifyOnly) {
5958 IS.Diagnose(S, SubEntity, SubKind,
5959 Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5960 } else {
5961 Sequence.SetFailed(
5963 }
5964
5965 return false;
5966 }
5967 if (!VerifyOnly) {
5968 ExprResult ER;
5969 ER = IS.Perform(S, SubEntity, SubKind,
5970 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5971
5972 if (ER.isInvalid())
5973 return false;
5974
5975 if (InitExpr)
5976 *InitExpr = ER.get();
5977 else
5978 InitExprs.push_back(ER.get());
5979 }
5980 return true;
5981 };
5982
5983 if (const ArrayType *AT =
5984 S.getASTContext().getAsArrayType(Entity.getType())) {
5985 uint64_t ArrayLength;
5986 // C++ [dcl.init]p16.5
5987 // if the destination type is an array, the object is initialized as
5988 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5989 // the destination type is an array of unknown bound, it is defined as
5990 // having k elements.
5991 if (const ConstantArrayType *CAT =
5993 ArrayLength = CAT->getZExtSize();
5994 ResultType = Entity.getType();
5995 } else if (const VariableArrayType *VAT =
5997 // Braced-initialization of variable array types is not allowed, even if
5998 // the size is greater than or equal to the number of args, so we don't
5999 // allow them to be initialized via parenthesized aggregate initialization
6000 // either.
6001 const Expr *SE = VAT->getSizeExpr();
6002 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
6003 << SE->getSourceRange();
6004 return;
6005 } else {
6006 assert(Entity.getType()->isIncompleteArrayType());
6007 ArrayLength = Args.size();
6008 }
6009 EntityIndexToProcess = ArrayLength;
6010
6011 // ...the ith array element is copy-initialized with xi for each
6012 // 1 <= i <= k
6013 for (Expr *E : Args) {
6015 S.getASTContext(), EntityIndexToProcess, Entity);
6017 E->getExprLoc(), /*isDirectInit=*/false, E);
6018 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6019 return;
6020 }
6021 // ...and value-initialized for each k < i <= n;
6022 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6024 S.getASTContext(), Args.size(), Entity);
6026 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6027 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6028 return;
6029 }
6030
6031 if (ResultType.isNull()) {
6032 ResultType = S.Context.getConstantArrayType(
6033 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
6034 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
6035 }
6036 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6037 bool IsUnion = RD->isUnion();
6038 if (RD->isInvalidDecl()) {
6039 // Exit early to avoid confusion when processing members.
6040 // We do the same for braced list initialization in
6041 // `CheckStructUnionTypes`.
6042 Sequence.SetFailed(
6044 return;
6045 }
6046
6047 if (!IsUnion) {
6048 for (const CXXBaseSpecifier &Base : RD->bases()) {
6050 S.getASTContext(), &Base, false, &Entity);
6051 if (EntityIndexToProcess < Args.size()) {
6052 // C++ [dcl.init]p16.6.2.2.
6053 // ...the object is initialized is follows. Let e1, ..., en be the
6054 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6055 // the elements of the expression-list...The element ei is
6056 // copy-initialized with xi for 1 <= i <= k.
6057 Expr *E = Args[EntityIndexToProcess];
6059 E->getExprLoc(), /*isDirectInit=*/false, E);
6060 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6061 return;
6062 } else {
6063 // We've processed all of the args, but there are still base classes
6064 // that have to be initialized.
6065 // C++ [dcl.init]p17.6.2.2
6066 // The remaining elements...otherwise are value initialzed
6068 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
6069 /*IsImplicit=*/true);
6070 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6071 return;
6072 }
6073 EntityIndexToProcess++;
6074 }
6075 }
6076
6077 for (FieldDecl *FD : RD->fields()) {
6078 // Unnamed bitfields should not be initialized at all, either with an arg
6079 // or by default.
6080 if (FD->isUnnamedBitField())
6081 continue;
6082
6083 InitializedEntity SubEntity =
6085
6086 if (EntityIndexToProcess < Args.size()) {
6087 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6088 Expr *E = Args[EntityIndexToProcess];
6089
6090 // Incomplete array types indicate flexible array members. Do not allow
6091 // paren list initializations of structs with these members, as GCC
6092 // doesn't either.
6093 if (FD->getType()->isIncompleteArrayType()) {
6094 if (!VerifyOnly) {
6095 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
6096 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6097 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
6098 }
6099 Sequence.SetFailed(
6101 return;
6102 }
6103
6105 E->getExprLoc(), /*isDirectInit=*/false, E);
6106 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6107 return;
6108
6109 // Unions should have only one initializer expression, so we bail out
6110 // after processing the first field. If there are more initializers then
6111 // it will be caught when we later check whether EntityIndexToProcess is
6112 // less than Args.size();
6113 if (IsUnion) {
6114 InitializedFieldInUnion = FD;
6115 EntityIndexToProcess = 1;
6116 break;
6117 }
6118 } else {
6119 // We've processed all of the args, but there are still members that
6120 // have to be initialized.
6121 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6122 !S.isUnevaluatedContext()) {
6123 S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
6124 << /* Var-in-Record */ 0 << FD;
6125 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
6126 }
6127
6128 if (FD->hasInClassInitializer()) {
6129 if (!VerifyOnly) {
6130 // C++ [dcl.init]p16.6.2.2
6131 // The remaining elements are initialized with their default
6132 // member initializers, if any
6134 Kind.getParenOrBraceRange().getEnd(), FD);
6135 if (DIE.isInvalid())
6136 return;
6137 S.checkInitializerLifetime(SubEntity, DIE.get());
6138 InitExprs.push_back(DIE.get());
6139 }
6140 } else {
6141 // C++ [dcl.init]p17.6.2.2
6142 // The remaining elements...otherwise are value initialzed
6143 if (FD->getType()->isReferenceType()) {
6144 Sequence.SetFailed(
6146 if (!VerifyOnly) {
6147 SourceRange SR = Kind.getParenOrBraceRange();
6148 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
6149 << FD->getType() << SR;
6150 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
6151 }
6152 return;
6153 }
6155 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
6156 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6157 return;
6158 }
6159 }
6160 EntityIndexToProcess++;
6161 }
6162 ResultType = Entity.getType();
6163 }
6164
6165 // Not all of the args have been processed, so there must've been more args
6166 // than were required to initialize the element.
6167 if (EntityIndexToProcess < Args.size()) {
6169 if (!VerifyOnly) {
6170 QualType T = Entity.getType();
6171 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6172 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6173 Args.back()->getEndLoc());
6174 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6175 << InitKind << ExcessInitSR;
6176 }
6177 return;
6178 }
6179
6180 if (VerifyOnly) {
6182 Sequence.AddParenthesizedListInitStep(Entity.getType());
6183 } else if (Result) {
6184 SourceRange SR = Kind.getParenOrBraceRange();
6185 auto *CPLIE = CXXParenListInitExpr::Create(
6186 S.getASTContext(), InitExprs, ResultType, Args.size(),
6187 Kind.getLocation(), SR.getBegin(), SR.getEnd());
6188 if (ArrayFiller)
6189 CPLIE->setArrayFiller(ArrayFiller);
6190 if (InitializedFieldInUnion)
6191 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6192 *Result = CPLIE;
6193 S.Diag(Kind.getLocation(),
6194 diag::warn_cxx17_compat_aggregate_init_paren_list)
6195 << Kind.getLocation() << SR << ResultType;
6196 }
6197}
6198
6199/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6200/// which enumerates all conversion functions and performs overload resolution
6201/// to select the best.
6203 QualType DestType,
6204 const InitializationKind &Kind,
6206 InitializationSequence &Sequence,
6207 bool TopLevelOfInitList) {
6208 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6209 QualType SourceType = Initializer->getType();
6210 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6211 "Must have a class type to perform a user-defined conversion");
6212
6213 // Build the candidate set directly in the initialization sequence
6214 // structure, so that it will persist if we fail.
6215 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6217 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6218
6219 // Determine whether we are allowed to call explicit constructors or
6220 // explicit conversion operators.
6221 bool AllowExplicit = Kind.AllowExplicit();
6222
6223 if (DestType->isRecordType()) {
6224 // The type we're converting to is a class type. Enumerate its constructors
6225 // to see if there is a suitable conversion.
6226 // Try to complete the type we're converting to.
6227 if (S.isCompleteType(Kind.getLocation(), DestType)) {
6228 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6229 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
6230 auto Info = getConstructorInfo(D);
6231 if (!Info.Constructor)
6232 continue;
6233
6234 if (!Info.Constructor->isInvalidDecl() &&
6235 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6236 if (Info.ConstructorTmpl)
6238 Info.ConstructorTmpl, Info.FoundDecl,
6239 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
6240 /*SuppressUserConversions=*/true,
6241 /*PartialOverloading*/ false, AllowExplicit);
6242 else
6243 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
6244 Initializer, CandidateSet,
6245 /*SuppressUserConversions=*/true,
6246 /*PartialOverloading*/ false, AllowExplicit);
6247 }
6248 }
6249 }
6250 }
6251
6252 SourceLocation DeclLoc = Initializer->getBeginLoc();
6253
6254 if (SourceType->isRecordType()) {
6255 // The type we're converting from is a class type, enumerate its conversion
6256 // functions.
6257
6258 // We can only enumerate the conversion functions for a complete type; if
6259 // the type isn't complete, simply skip this step.
6260 if (S.isCompleteType(DeclLoc, SourceType)) {
6261 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6262 const auto &Conversions =
6263 SourceRecordDecl->getVisibleConversionFunctions();
6264 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6265 NamedDecl *D = *I;
6267 if (isa<UsingShadowDecl>(D))
6268 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6269
6270 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6271 CXXConversionDecl *Conv;
6272 if (ConvTemplate)
6273 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6274 else
6275 Conv = cast<CXXConversionDecl>(D);
6276
6277 if (ConvTemplate)
6279 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
6280 CandidateSet, AllowExplicit, AllowExplicit);
6281 else
6282 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
6283 DestType, CandidateSet, AllowExplicit,
6284 AllowExplicit);
6285 }
6286 }
6287 }
6288
6289 // Perform overload resolution. If it fails, return the failed result.
6292 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
6293 Sequence.SetOverloadFailure(
6295
6296 // [class.copy.elision]p3:
6297 // In some copy-initialization contexts, a two-stage overload resolution
6298 // is performed.
6299 // If the first overload resolution selects a deleted function, we also
6300 // need the initialization sequence to decide whether to perform the second
6301 // overload resolution.
6302 if (!(Result == OR_Deleted &&
6303 Kind.getKind() == InitializationKind::IK_Copy))
6304 return;
6305 }
6306
6307 FunctionDecl *Function = Best->Function;
6308 Function->setReferenced();
6309 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6310
6311 if (isa<CXXConstructorDecl>(Function)) {
6312 // Add the user-defined conversion step. Any cv-qualification conversion is
6313 // subsumed by the initialization. Per DR5, the created temporary is of the
6314 // cv-unqualified type of the destination.
6315 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
6316 DestType.getUnqualifiedType(),
6317 HadMultipleCandidates);
6318
6319 // C++14 and before:
6320 // - if the function is a constructor, the call initializes a temporary
6321 // of the cv-unqualified version of the destination type. The [...]
6322 // temporary [...] is then used to direct-initialize, according to the
6323 // rules above, the object that is the destination of the
6324 // copy-initialization.
6325 // Note that this just performs a simple object copy from the temporary.
6326 //
6327 // C++17:
6328 // - if the function is a constructor, the call is a prvalue of the
6329 // cv-unqualified version of the destination type whose return object
6330 // is initialized by the constructor. The call is used to
6331 // direct-initialize, according to the rules above, the object that
6332 // is the destination of the copy-initialization.
6333 // Therefore we need to do nothing further.
6334 //
6335 // FIXME: Mark this copy as extraneous.
6336 if (!S.getLangOpts().CPlusPlus17)
6337 Sequence.AddFinalCopy(DestType);
6338 else if (DestType.hasQualifiers())
6339 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6340 return;
6341 }
6342
6343 // Add the user-defined conversion step that calls the conversion function.
6344 QualType ConvType = Function->getCallResultType();
6345 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
6346 HadMultipleCandidates);
6347
6348 if (ConvType->isRecordType()) {
6349 // The call is used to direct-initialize [...] the object that is the
6350 // destination of the copy-initialization.
6351 //
6352 // In C++17, this does not call a constructor if we enter /17.6.1:
6353 // - If the initializer expression is a prvalue and the cv-unqualified
6354 // version of the source type is the same as the class of the
6355 // destination [... do not make an extra copy]
6356 //
6357 // FIXME: Mark this copy as extraneous.
6358 if (!S.getLangOpts().CPlusPlus17 ||
6359 Function->getReturnType()->isReferenceType() ||
6360 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
6361 Sequence.AddFinalCopy(DestType);
6362 else if (!S.Context.hasSameType(ConvType, DestType))
6363 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
6364 return;
6365 }
6366
6367 // If the conversion following the call to the conversion function
6368 // is interesting, add it as a separate step.
6369 assert(Best->HasFinalConversion);
6370 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6371 Best->FinalConversion.Third) {
6373 ICS.setStandard();
6374 ICS.Standard = Best->FinalConversion;
6375 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6376 }
6377}
6378
6379/// The non-zero enum values here are indexes into diagnostic alternatives.
6381
6382/// Determines whether this expression is an acceptable ICR source.
6384 bool isAddressOf, bool &isWeakAccess) {
6385 // Skip parens.
6386 e = e->IgnoreParens();
6387
6388 // Skip address-of nodes.
6389 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
6390 if (op->getOpcode() == UO_AddrOf)
6391 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
6392 isWeakAccess);
6393
6394 // Skip certain casts.
6395 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
6396 switch (ce->getCastKind()) {
6397 case CK_Dependent:
6398 case CK_BitCast:
6399 case CK_LValueBitCast:
6400 case CK_NoOp:
6401 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
6402
6403 case CK_ArrayToPointerDecay:
6404 return IIK_nonscalar;
6405
6406 case CK_NullToPointer:
6407 return IIK_okay;
6408
6409 default:
6410 break;
6411 }
6412
6413 // If we have a declaration reference, it had better be a local variable.
6414 } else if (isa<DeclRefExpr>(e)) {
6415 // set isWeakAccess to true, to mean that there will be an implicit
6416 // load which requires a cleanup.
6418 isWeakAccess = true;
6419
6420 if (!isAddressOf) return IIK_nonlocal;
6421
6422 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
6423 if (!var) return IIK_nonlocal;
6424
6425 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6426
6427 // If we have a conditional operator, check both sides.
6428 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
6429 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
6430 isWeakAccess))
6431 return iik;
6432
6433 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
6434
6435 // These are never scalar.
6436 } else if (isa<ArraySubscriptExpr>(e)) {
6437 return IIK_nonscalar;
6438
6439 // Otherwise, it needs to be a null pointer constant.
6440 } else {
6443 }
6444
6445 return IIK_nonlocal;
6446}
6447
6448/// Check whether the given expression is a valid operand for an
6449/// indirect copy/restore.
6451 assert(src->isPRValue());
6452 bool isWeakAccess = false;
6453 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
6454 // If isWeakAccess to true, there will be an implicit
6455 // load which requires a cleanup.
6456 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6458
6459 if (iik == IIK_okay) return;
6460
6461 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
6462 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6463 << src->getSourceRange();
6464}
6465
6466/// Determine whether we have compatible array types for the
6467/// purposes of GNU by-copy array initialization.
6468static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6469 const ArrayType *Source) {
6470 // If the source and destination array types are equivalent, we're
6471 // done.
6472 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
6473 return true;
6474
6475 // Make sure that the element types are the same.
6476 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
6477 return false;
6478
6479 // The only mismatch we allow is when the destination is an
6480 // incomplete array type and the source is a constant array type.
6481 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6482}
6483
6485 InitializationSequence &Sequence,
6486 const InitializedEntity &Entity,
6487 Expr *Initializer) {
6488 bool ArrayDecay = false;
6489 QualType ArgType = Initializer->getType();
6490 QualType ArgPointee;
6491 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6492 ArrayDecay = true;
6493 ArgPointee = ArgArrayType->getElementType();
6494 ArgType = S.Context.getPointerType(ArgPointee);
6495 }
6496
6497 // Handle write-back conversion.
6498 QualType ConvertedArgType;
6499 if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),
6500 ConvertedArgType))
6501 return false;
6502
6503 // We should copy unless we're passing to an argument explicitly
6504 // marked 'out'.
6505 bool ShouldCopy = true;
6506 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6507 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6508
6509 // Do we need an lvalue conversion?
6510 if (ArrayDecay || Initializer->isGLValue()) {
6512 ICS.setStandard();
6514
6515 QualType ResultType;
6516 if (ArrayDecay) {
6518 ResultType = S.Context.getPointerType(ArgPointee);
6519 } else {
6521 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6522 }
6523
6524 Sequence.AddConversionSequenceStep(ICS, ResultType);
6525 }
6526
6527 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6528 return true;
6529}
6530
6532 InitializationSequence &Sequence,
6533 QualType DestType,
6534 Expr *Initializer) {
6535 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6536 (!Initializer->isIntegerConstantExpr(S.Context) &&
6537 !Initializer->getType()->isSamplerT()))
6538 return false;
6539
6540 Sequence.AddOCLSamplerInitStep(DestType);
6541 return true;
6542}
6543
6544static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6545 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6546 return Value && Value->isZero();
6547}
6548
6550 InitializationSequence &Sequence,
6551 QualType DestType,
6552 Expr *Initializer) {
6553 if (!S.getLangOpts().OpenCL)
6554 return false;
6555
6556 //
6557 // OpenCL 1.2 spec, s6.12.10
6558 //
6559 // The event argument can also be used to associate the
6560 // async_work_group_copy with a previous async copy allowing
6561 // an event to be shared by multiple async copies; otherwise
6562 // event should be zero.
6563 //
6564 if (DestType->isEventT() || DestType->isQueueT()) {
6566 return false;
6567
6568 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6569 return true;
6570 }
6571
6572 // We should allow zero initialization for all types defined in the
6573 // cl_intel_device_side_avc_motion_estimation extension, except
6574 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6576 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6577 DestType->isOCLIntelSubgroupAVCType()) {
6578 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6579 DestType->isOCLIntelSubgroupAVCMceResultType())
6580 return false;
6582 return false;
6583
6584 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6585 return true;
6586 }
6587
6588 return false;
6589}
6590
6592 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6593 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6594 : FailedOverloadResult(OR_Success),
6595 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6596 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6597 TreatUnavailableAsInvalid);
6598}
6599
6600/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6601/// address of that function, this returns true. Otherwise, it returns false.
6602static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6603 auto *DRE = dyn_cast<DeclRefExpr>(E);
6604 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6605 return false;
6606
6608 cast<FunctionDecl>(DRE->getDecl()));
6609}
6610
6611/// Determine whether we can perform an elementwise array copy for this kind
6612/// of entity.
6613static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6614 switch (Entity.getKind()) {
6616 // C++ [expr.prim.lambda]p24:
6617 // For array members, the array elements are direct-initialized in
6618 // increasing subscript order.
6619 return true;
6620
6622 // C++ [dcl.decomp]p1:
6623 // [...] each element is copy-initialized or direct-initialized from the
6624 // corresponding element of the assignment-expression [...]
6625 return isa<DecompositionDecl>(Entity.getDecl());
6626
6628 // C++ [class.copy.ctor]p14:
6629 // - if the member is an array, each element is direct-initialized with
6630 // the corresponding subobject of x
6631 return Entity.isImplicitMemberInitializer();
6632
6634 // All the above cases are intended to apply recursively, even though none
6635 // of them actually say that.
6636 if (auto *E = Entity.getParent())
6637 return canPerformArrayCopy(*E);
6638 break;
6639
6640 default:
6641 break;
6642 }
6643
6644 return false;
6645}
6646
6647static const FieldDecl *getConstField(const RecordDecl *RD) {
6648 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6649 for (const FieldDecl *FD : RD->fields()) {
6650 // If the field is a flexible array member, we don't want to consider it
6651 // as a const field because there's no way to initialize the FAM anyway.
6652 const ASTContext &Ctx = FD->getASTContext();
6654 Ctx, FD, FD->getType(),
6655 Ctx.getLangOpts().getStrictFlexArraysLevel(),
6656 /*IgnoreTemplateOrMacroSubstitution=*/true))
6657 continue;
6658
6659 QualType QT = FD->getType();
6660 if (QT.isConstQualified())
6661 return FD;
6662 if (const auto *RD = QT->getAsRecordDecl()) {
6663 if (const FieldDecl *FD = getConstField(RD))
6664 return FD;
6665 }
6666 }
6667 return nullptr;
6668}
6669
6671 const InitializedEntity &Entity,
6672 const InitializationKind &Kind,
6673 MultiExprArg Args,
6674 bool TopLevelOfInitList,
6675 bool TreatUnavailableAsInvalid) {
6676 ASTContext &Context = S.Context;
6677
6678 // Eliminate non-overload placeholder types in the arguments. We
6679 // need to do this before checking whether types are dependent
6680 // because lowering a pseudo-object expression might well give us
6681 // something of dependent type.
6682 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6683 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6684 // FIXME: should we be doing this here?
6685 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6686 if (result.isInvalid()) {
6688 return;
6689 }
6690 Args[I] = result.get();
6691 }
6692
6693 // C++0x [dcl.init]p16:
6694 // The semantics of initializers are as follows. The destination type is
6695 // the type of the object or reference being initialized and the source
6696 // type is the type of the initializer expression. The source type is not
6697 // defined when the initializer is a braced-init-list or when it is a
6698 // parenthesized list of expressions.
6699 QualType DestType = Entity.getType();
6700
6701 if (DestType->isDependentType() ||
6704 return;
6705 }
6706
6707 // Almost everything is a normal sequence.
6709
6710 QualType SourceType;
6711 Expr *Initializer = nullptr;
6712 if (Args.size() == 1) {
6713 Initializer = Args[0];
6714 if (S.getLangOpts().ObjC) {
6716 Initializer->getBeginLoc(), DestType, Initializer->getType(),
6717 Initializer) ||
6719 Args[0] = Initializer;
6720 }
6722 SourceType = Initializer->getType();
6723 }
6724
6725 // - If the initializer is a (non-parenthesized) braced-init-list, the
6726 // object is list-initialized (8.5.4).
6727 if (Kind.getKind() != InitializationKind::IK_Direct) {
6728 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6729 TryListInitialization(S, Entity, Kind, InitList, *this,
6730 TreatUnavailableAsInvalid);
6731 return;
6732 }
6733 }
6734
6735 if (!S.getLangOpts().CPlusPlus &&
6736 Kind.getKind() == InitializationKind::IK_Default) {
6737 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6738 VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6739 if (Rec->hasUninitializedExplicitInitFields()) {
6740 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6741 S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6742 << /* Var-in-Record */ 1 << Rec;
6744 }
6745 }
6746 // If the record has any members which are const (recursively checked),
6747 // then we want to diagnose those as being uninitialized if there is no
6748 // initializer present. However, we only do this for structure types, not
6749 // union types, because an unitialized field in a union is generally
6750 // reasonable, especially in C where unions can be used for type punning.
6751 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6752 if (const FieldDecl *FD = getConstField(Rec)) {
6753 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6754 if (Var->getStorageDuration() == SD_Static ||
6755 Var->getStorageDuration() == SD_Thread)
6756 DiagID = diag::warn_default_init_const_field;
6757
6758 bool EmitCppCompat = !S.Diags.isIgnored(
6759 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6760 Var->getLocation());
6761
6762 S.Diag(Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6763 S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6764 }
6765 }
6766 }
6767 }
6768
6769 // - If the destination type is a reference type, see 8.5.3.
6770 if (DestType->isReferenceType()) {
6771 // C++0x [dcl.init.ref]p1:
6772 // A variable declared to be a T& or T&&, that is, "reference to type T"
6773 // (8.3.2), shall be initialized by an object, or function, of type T or
6774 // by an object that can be converted into a T.
6775 // (Therefore, multiple arguments are not permitted.)
6776 if (Args.size() != 1)
6778 // C++17 [dcl.init.ref]p5:
6779 // A reference [...] is initialized by an expression [...] as follows:
6780 // If the initializer is not an expression, presumably we should reject,
6781 // but the standard fails to actually say so.
6782 else if (isa<InitListExpr>(Args[0]))
6784 else
6785 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6786 TopLevelOfInitList);
6787 return;
6788 }
6789
6790 // - If the initializer is (), the object is value-initialized.
6791 if (Kind.getKind() == InitializationKind::IK_Value ||
6792 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6793 TryValueInitialization(S, Entity, Kind, *this);
6794 return;
6795 }
6796
6797 // Handle default initialization.
6798 if (Kind.getKind() == InitializationKind::IK_Default) {
6799 TryDefaultInitialization(S, Entity, Kind, *this);
6800 return;
6801 }
6802
6803 // - If the destination type is an array of characters, an array of
6804 // char16_t, an array of char32_t, or an array of wchar_t, and the
6805 // initializer is a string literal, see 8.5.2.
6806 // - Otherwise, if the destination type is an array, the program is
6807 // ill-formed.
6808 // - Except in HLSL, where non-decaying array parameters behave like
6809 // non-array types for initialization.
6810 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6811 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6812 if (Initializer && isa<VariableArrayType>(DestAT)) {
6814 return;
6815 }
6816
6817 if (Initializer) {
6818 switch (IsStringInit(Initializer, DestAT, Context)) {
6819 case SIF_None:
6820 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6821 return;
6824 return;
6827 return;
6830 return;
6833 return;
6836 return;
6837 case SIF_Other:
6838 break;
6839 }
6840 }
6841
6842 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(DestAT)) {
6843 QualType SrcType = Entity.getType();
6844 if (SrcType->isArrayParameterType())
6845 SrcType =
6846 cast<ArrayParameterType>(SrcType)->getConstantArrayType(Context);
6847 if (S.Context.hasSameUnqualifiedType(DestType, SrcType)) {
6848 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6849 TreatUnavailableAsInvalid);
6850 return;
6851 }
6852 }
6853
6854 // Some kinds of initialization permit an array to be initialized from
6855 // another array of the same type, and perform elementwise initialization.
6856 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6858 Entity.getType()) &&
6859 canPerformArrayCopy(Entity)) {
6860 TryArrayCopy(S, Kind, Entity, Initializer, DestType, *this,
6861 TreatUnavailableAsInvalid);
6862 return;
6863 }
6864
6865 // Note: as an GNU C extension, we allow initialization of an
6866 // array from a compound literal that creates an array of the same
6867 // type, so long as the initializer has no side effects.
6868 if (!S.getLangOpts().CPlusPlus && Initializer &&
6869 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6870 Initializer->getType()->isArrayType()) {
6871 const ArrayType *SourceAT
6872 = Context.getAsArrayType(Initializer->getType());
6873 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6875 else if (Initializer->HasSideEffects(S.Context))
6877 else {
6878 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6879 }
6880 }
6881 // Note: as a GNU C++ extension, we allow list-initialization of a
6882 // class member of array type from a parenthesized initializer list.
6883 else if (S.getLangOpts().CPlusPlus &&
6885 isa_and_nonnull<InitListExpr>(Initializer)) {
6887 *this, TreatUnavailableAsInvalid);
6889 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6890 Kind.getKind() == InitializationKind::IK_Direct)
6891 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6892 /*VerifyOnly=*/true);
6893 else if (DestAT->getElementType()->isCharType())
6895 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6897 else
6899
6900 return;
6901 }
6902
6903 // Determine whether we should consider writeback conversions for
6904 // Objective-C ARC.
6905 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6906 Entity.isParameterKind();
6907
6908 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6909 return;
6910
6911 // We're at the end of the line for C: it's either a write-back conversion
6912 // or it's a C assignment. There's no need to check anything else.
6913 if (!S.getLangOpts().CPlusPlus) {
6914 assert(Initializer && "Initializer must be non-null");
6915 // If allowed, check whether this is an Objective-C writeback conversion.
6916 if (allowObjCWritebackConversion &&
6917 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6918 return;
6919 }
6920
6921 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6922 return;
6923
6924 // Handle initialization in C
6925 AddCAssignmentStep(DestType);
6926 MaybeProduceObjCObject(S, *this, Entity);
6927 return;
6928 }
6929
6930 assert(S.getLangOpts().CPlusPlus);
6931
6932 // - If the destination type is a (possibly cv-qualified) class type:
6933 if (DestType->isRecordType()) {
6934 // - If the initialization is direct-initialization, or if it is
6935 // copy-initialization where the cv-unqualified version of the
6936 // source type is the same class as, or a derived class of, the
6937 // class of the destination, constructors are considered. [...]
6938 if (Kind.getKind() == InitializationKind::IK_Direct ||
6939 (Kind.getKind() == InitializationKind::IK_Copy &&
6940 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6941 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6942 SourceType, DestType))))) {
6943 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6944 *this, /*IsAggrListInit=*/false);
6945 } else {
6946 // - Otherwise (i.e., for the remaining copy-initialization cases),
6947 // user-defined conversion sequences that can convert from the
6948 // source type to the destination type or (when a conversion
6949 // function is used) to a derived class thereof are enumerated as
6950 // described in 13.3.1.4, and the best one is chosen through
6951 // overload resolution (13.3).
6952 assert(Initializer && "Initializer must be non-null");
6953 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6954 TopLevelOfInitList);
6955 }
6956 return;
6957 }
6958
6959 assert(Args.size() >= 1 && "Zero-argument case handled above");
6960
6961 // For HLSL ext vector types we allow list initialization behavior for C++
6962 // functional cast expressions which look like constructor syntax. This is
6963 // accomplished by converting initialization arguments to InitListExpr.
6964 auto ShouldTryListInitialization = [&]() -> bool {
6965 // Only try list initialization for HLSL.
6966 if (!S.getLangOpts().HLSL)
6967 return false;
6968
6969 bool DestIsVec = DestType->isExtVectorType();
6970 bool DestIsMat = DestType->isConstantMatrixType();
6971
6972 // If the destination type is neither a vector nor a matrix, then don't try
6973 // list initialization.
6974 if (!DestIsVec && !DestIsMat)
6975 return false;
6976
6977 // If there is only a single source argument, then only try list
6978 // initialization if initializing a matrix with a vector or vice versa.
6979 if (Args.size() == 1) {
6980 assert(!SourceType.isNull() &&
6981 "Source QualType should not be null when arg size is exactly 1");
6982 bool SourceIsVec = SourceType->isExtVectorType();
6983 bool SourceIsMat = SourceType->isConstantMatrixType();
6984
6985 if (DestIsMat && !SourceIsVec)
6986 return false;
6987 if (DestIsVec && !SourceIsMat)
6988 return false;
6989 }
6990
6991 // Try list initialization if the source type is null or if the
6992 // destination and source types differ.
6993 return SourceType.isNull() ||
6994 !Context.hasSameUnqualifiedType(SourceType, DestType);
6995 };
6996 if (ShouldTryListInitialization()) {
6997 InitListExpr *ILE = new (Context)
6998 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
6999 Args.back()->getEndLoc());
7000 ILE->setType(DestType);
7001 Args[0] = ILE;
7002 TryListInitialization(S, Entity, Kind, ILE, *this,
7003 TreatUnavailableAsInvalid);
7004 return;
7005 }
7006
7007 // The remaining cases all need a source type.
7008 if (Args.size() > 1) {
7010 return;
7011 } else if (isa<InitListExpr>(Args[0])) {
7013 return;
7014 }
7015
7016 // - Otherwise, if the source type is a (possibly cv-qualified) class
7017 // type, conversion functions are considered.
7018 if (!SourceType.isNull() && SourceType->isRecordType()) {
7019 assert(Initializer && "Initializer must be non-null");
7020 // For a conversion to _Atomic(T) from either T or a class type derived
7021 // from T, initialize the T object then convert to _Atomic type.
7022 bool NeedAtomicConversion = false;
7023 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7024 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
7025 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
7026 Atomic->getValueType())) {
7027 DestType = Atomic->getValueType();
7028 NeedAtomicConversion = true;
7029 }
7030 }
7031
7032 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
7033 TopLevelOfInitList);
7034 MaybeProduceObjCObject(S, *this, Entity);
7035 if (!Failed() && NeedAtomicConversion)
7037 return;
7038 }
7039
7040 // - Otherwise, if the initialization is direct-initialization, the source
7041 // type is std::nullptr_t, and the destination type is bool, the initial
7042 // value of the object being initialized is false.
7043 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7044 DestType->isBooleanType() &&
7045 Kind.getKind() == InitializationKind::IK_Direct) {
7048 Initializer->isGLValue()),
7049 DestType);
7050 return;
7051 }
7052
7053 // - Otherwise, the initial value of the object being initialized is the
7054 // (possibly converted) value of the initializer expression. Standard
7055 // conversions (Clause 4) will be used, if necessary, to convert the
7056 // initializer expression to the cv-unqualified version of the
7057 // destination type; no user-defined conversions are considered.
7058
7060 = S.TryImplicitConversion(Initializer, DestType,
7061 /*SuppressUserConversions*/true,
7062 Sema::AllowedExplicit::None,
7063 /*InOverloadResolution*/ false,
7064 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7065 allowObjCWritebackConversion);
7066
7067 if (ICS.isStandard() &&
7069 // Objective-C ARC writeback conversion.
7070
7071 // We should copy unless we're passing to an argument explicitly
7072 // marked 'out'.
7073 bool ShouldCopy = true;
7074 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
7075 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7076
7077 // If there was an lvalue adjustment, add it as a separate conversion.
7078 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7081 LvalueICS.setStandard();
7083 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
7084 LvalueICS.Standard.First = ICS.Standard.First;
7085 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
7086 }
7087
7088 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
7089 } else if (ICS.isBad()) {
7091 Initializer->getType() == Context.OverloadTy &&
7093 /*Complain=*/false, Found))
7095 else if (Initializer->getType()->isFunctionType() &&
7098 else
7100 } else {
7101 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
7102
7103 MaybeProduceObjCObject(S, *this, Entity);
7104 }
7105}
7106
7108 for (auto &S : Steps)
7109 S.Destroy();
7110}
7111
7112//===----------------------------------------------------------------------===//
7113// Perform initialization
7114//===----------------------------------------------------------------------===//
7116 bool Diagnose = false) {
7117 switch(Entity.getKind()) {
7124
7126 if (Entity.getDecl() &&
7129
7131
7133 if (Entity.getDecl() &&
7136
7137 return !Diagnose ? AssignmentAction::Passing
7139
7141 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7143
7146 // FIXME: Can we tell apart casting vs. converting?
7148
7150 // This is really initialization, but refer to it as conversion for
7151 // consistency with CheckConvertedConstantExpression.
7153
7166 }
7167
7168 llvm_unreachable("Invalid EntityKind!");
7169}
7170
7171/// Whether we should bind a created object as a temporary when
7172/// initializing the given entity.
7205
7206/// Whether the given entity, when initialized with an object
7207/// created for that initialization, requires destruction.
7240
7241/// Get the location at which initialization diagnostics should appear.
7280
7281/// Make a (potentially elidable) temporary copy of the object
7282/// provided by the given initializer by calling the appropriate copy
7283/// constructor.
7284///
7285/// \param S The Sema object used for type-checking.
7286///
7287/// \param T The type of the temporary object, which must either be
7288/// the type of the initializer expression or a superclass thereof.
7289///
7290/// \param Entity The entity being initialized.
7291///
7292/// \param CurInit The initializer expression.
7293///
7294/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7295/// is permitted in C++03 (but not C++0x) when binding a reference to
7296/// an rvalue.
7297///
7298/// \returns An expression that copies the initializer expression into
7299/// a temporary object, or an error expression if a copy could not be
7300/// created.
7302 QualType T,
7303 const InitializedEntity &Entity,
7304 ExprResult CurInit,
7305 bool IsExtraneousCopy) {
7306 if (CurInit.isInvalid())
7307 return CurInit;
7308 // Determine which class type we're copying to.
7309 Expr *CurInitExpr = (Expr *)CurInit.get();
7310 auto *Class = T->getAsCXXRecordDecl();
7311 if (!Class)
7312 return CurInit;
7313
7314 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
7315
7316 // Make sure that the type we are copying is complete.
7317 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
7318 return CurInit;
7319
7320 // Perform overload resolution using the class's constructors. Per
7321 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7322 // is direct-initialization.
7325
7328 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
7329 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7330 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7331 /*RequireActualConstructor=*/false,
7332 /*SecondStepOfCopyInit=*/true)) {
7333 case OR_Success:
7334 break;
7335
7337 CandidateSet.NoteCandidates(
7339 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
7340 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7341 : diag::err_temp_copy_no_viable)
7342 << (int)Entity.getKind() << CurInitExpr->getType()
7343 << CurInitExpr->getSourceRange()),
7344 S, OCD_AllCandidates, CurInitExpr);
7345 if (!IsExtraneousCopy || S.isSFINAEContext())
7346 return ExprError();
7347 return CurInit;
7348
7349 case OR_Ambiguous:
7350 CandidateSet.NoteCandidates(
7351 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
7352 << (int)Entity.getKind()
7353 << CurInitExpr->getType()
7354 << CurInitExpr->getSourceRange()),
7355 S, OCD_AmbiguousCandidates, CurInitExpr);
7356 return ExprError();
7357
7358 case OR_Deleted:
7359 S.Diag(Loc, diag::err_temp_copy_deleted)
7360 << (int)Entity.getKind() << CurInitExpr->getType()
7361 << CurInitExpr->getSourceRange();
7362 S.NoteDeletedFunction(Best->Function);
7363 return ExprError();
7364 }
7365
7366 bool HadMultipleCandidates = CandidateSet.size() > 1;
7367
7369 SmallVector<Expr*, 8> ConstructorArgs;
7370 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7371
7372 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
7373 IsExtraneousCopy);
7374
7375 if (IsExtraneousCopy) {
7376 // If this is a totally extraneous copy for C++03 reference
7377 // binding purposes, just return the original initialization
7378 // expression. We don't generate an (elided) copy operation here
7379 // because doing so would require us to pass down a flag to avoid
7380 // infinite recursion, where each step adds another extraneous,
7381 // elidable copy.
7382
7383 // Instantiate the default arguments of any extra parameters in
7384 // the selected copy constructor, as if we were going to create a
7385 // proper call to the copy constructor.
7386 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7387 ParmVarDecl *Parm = Constructor->getParamDecl(I);
7388 if (S.RequireCompleteType(Loc, Parm->getType(),
7389 diag::err_call_incomplete_argument))
7390 break;
7391
7392 // Build the default argument expression; we don't actually care
7393 // if this succeeds or not, because this routine will complain
7394 // if there was a problem.
7395 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
7396 }
7397
7398 return CurInitExpr;
7399 }
7400
7401 // Determine the arguments required to actually perform the
7402 // constructor call (we might have derived-to-base conversions, or
7403 // the copy constructor may have default arguments).
7404 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
7405 ConstructorArgs))
7406 return ExprError();
7407
7408 // C++0x [class.copy]p32:
7409 // When certain criteria are met, an implementation is allowed to
7410 // omit the copy/move construction of a class object, even if the
7411 // copy/move constructor and/or destructor for the object have
7412 // side effects. [...]
7413 // - when a temporary class object that has not been bound to a
7414 // reference (12.2) would be copied/moved to a class object
7415 // with the same cv-unqualified type, the copy/move operation
7416 // can be omitted by constructing the temporary object
7417 // directly into the target of the omitted copy/move
7418 //
7419 // Note that the other three bullets are handled elsewhere. Copy
7420 // elision for return statements and throw expressions are handled as part
7421 // of constructor initialization, while copy elision for exception handlers
7422 // is handled by the run-time.
7423 //
7424 // FIXME: If the function parameter is not the same type as the temporary, we
7425 // should still be able to elide the copy, but we don't have a way to
7426 // represent in the AST how much should be elided in this case.
7427 bool Elidable =
7428 CurInitExpr->isTemporaryObject(S.Context, Class) &&
7430 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
7431 CurInitExpr->getType());
7432
7433 // Actually perform the constructor call.
7434 CurInit = S.BuildCXXConstructExpr(
7435 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
7436 HadMultipleCandidates,
7437 /*ListInit*/ false,
7438 /*StdInitListInit*/ false,
7439 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
7440
7441 // If we're supposed to bind temporaries, do so.
7442 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7443 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7444 return CurInit;
7445}
7446
7447/// Check whether elidable copy construction for binding a reference to
7448/// a temporary would have succeeded if we were building in C++98 mode, for
7449/// -Wc++98-compat.
7451 const InitializedEntity &Entity,
7452 Expr *CurInitExpr) {
7453 assert(S.getLangOpts().CPlusPlus11);
7454
7455 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7456 if (!Record)
7457 return;
7458
7459 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
7460 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
7461 return;
7462
7463 // Find constructors which would have been considered.
7466
7467 // Perform overload resolution.
7470 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
7471 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7472 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7473 /*RequireActualConstructor=*/false,
7474 /*SecondStepOfCopyInit=*/true);
7475
7476 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
7477 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7478 << CurInitExpr->getSourceRange();
7479
7480 switch (OR) {
7481 case OR_Success:
7482 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
7483 Best->FoundDecl, Entity, Diag);
7484 // FIXME: Check default arguments as far as that's possible.
7485 break;
7486
7488 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7489 OCD_AllCandidates, CurInitExpr);
7490 break;
7491
7492 case OR_Ambiguous:
7493 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
7494 OCD_AmbiguousCandidates, CurInitExpr);
7495 break;
7496
7497 case OR_Deleted:
7498 S.Diag(Loc, Diag);
7499 S.NoteDeletedFunction(Best->Function);
7500 break;
7501 }
7502}
7503
7504void InitializationSequence::PrintInitLocationNote(Sema &S,
7505 const InitializedEntity &Entity) {
7506 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7507 if (Entity.getDecl()->getLocation().isInvalid())
7508 return;
7509
7510 if (Entity.getDecl()->getDeclName())
7511 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7512 << Entity.getDecl()->getDeclName();
7513 else
7514 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7515 }
7516 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7517 Entity.getMethodDecl())
7518 S.Diag(Entity.getMethodDecl()->getLocation(),
7519 diag::note_method_return_type_change)
7520 << Entity.getMethodDecl()->getDeclName();
7521}
7522
7523/// Returns true if the parameters describe a constructor initialization of
7524/// an explicit temporary object, e.g. "Point(x, y)".
7525static bool isExplicitTemporary(const InitializedEntity &Entity,
7526 const InitializationKind &Kind,
7527 unsigned NumArgs) {
7528 switch (Entity.getKind()) {
7532 break;
7533 default:
7534 return false;
7535 }
7536
7537 switch (Kind.getKind()) {
7539 return true;
7540 // FIXME: Hack to work around cast weirdness.
7543 return NumArgs != 1;
7544 default:
7545 return false;
7546 }
7547}
7548
7549static ExprResult
7551 const InitializedEntity &Entity,
7552 const InitializationKind &Kind,
7553 MultiExprArg Args,
7554 const InitializationSequence::Step& Step,
7555 bool &ConstructorInitRequiresZeroInit,
7556 bool IsListInitialization,
7557 bool IsStdInitListInitialization,
7558 SourceLocation LBraceLoc,
7559 SourceLocation RBraceLoc) {
7560 unsigned NumArgs = Args.size();
7563 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7564
7565 // Build a call to the selected constructor.
7566 SmallVector<Expr*, 8> ConstructorArgs;
7567 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7568 ? Kind.getEqualLoc()
7569 : Kind.getLocation();
7570
7571 if (Kind.getKind() == InitializationKind::IK_Default) {
7572 // Force even a trivial, implicit default constructor to be
7573 // semantically checked. We do this explicitly because we don't build
7574 // the definition for completely trivial constructors.
7575 assert(Constructor->getParent() && "No parent class for constructor.");
7576 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7577 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7578 S.runWithSufficientStackSpace(Loc, [&] {
7580 });
7581 }
7582 }
7583
7584 ExprResult CurInit((Expr *)nullptr);
7585
7586 // C++ [over.match.copy]p1:
7587 // - When initializing a temporary to be bound to the first parameter
7588 // of a constructor that takes a reference to possibly cv-qualified
7589 // T as its first argument, called with a single argument in the
7590 // context of direct-initialization, explicit conversion functions
7591 // are also considered.
7592 bool AllowExplicitConv =
7593 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7596
7597 // A smart pointer constructed from a nullable pointer is nullable.
7598 if (NumArgs == 1 && !Kind.isExplicitCast())
7600 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7601
7602 // Determine the arguments required to actually perform the constructor
7603 // call.
7604 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7605 ConstructorArgs, AllowExplicitConv,
7606 IsListInitialization))
7607 return ExprError();
7608
7609 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7610 // An explicitly-constructed temporary, e.g., X(1, 2).
7611 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7612 return ExprError();
7613
7614 if (Kind.getKind() == InitializationKind::IK_Value &&
7615 Constructor->isImplicit()) {
7616 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7617 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7618 unsigned I = 0;
7619 for (const FieldDecl *FD : RD->fields()) {
7620 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7621 !S.isUnevaluatedContext()) {
7622 S.Diag(Loc, diag::warn_field_requires_explicit_init)
7623 << /* Var-in-Record */ 0 << FD;
7624 S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
7625 }
7626 ++I;
7627 }
7628 }
7629 }
7630
7631 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7632 if (!TSInfo)
7633 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7634 SourceRange ParenOrBraceRange =
7635 (Kind.getKind() == InitializationKind::IK_DirectList)
7636 ? SourceRange(LBraceLoc, RBraceLoc)
7637 : Kind.getParenOrBraceRange();
7638
7639 CXXConstructorDecl *CalleeDecl = Constructor;
7640 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7641 Step.Function.FoundDecl.getDecl())) {
7642 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7643 }
7644 S.MarkFunctionReferenced(Loc, CalleeDecl);
7645
7646 CurInit = S.CheckForImmediateInvocation(
7648 S.Context, CalleeDecl,
7649 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7650 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7651 IsListInitialization, IsStdInitListInitialization,
7652 ConstructorInitRequiresZeroInit),
7653 CalleeDecl);
7654 } else {
7656
7657 if (Entity.getKind() == InitializedEntity::EK_Base) {
7658 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7661 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7662 ConstructKind = CXXConstructionKind::Delegating;
7663 }
7664
7665 // Only get the parenthesis or brace range if it is a list initialization or
7666 // direct construction.
7667 SourceRange ParenOrBraceRange;
7668 if (IsListInitialization)
7669 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7670 else if (Kind.getKind() == InitializationKind::IK_Direct)
7671 ParenOrBraceRange = Kind.getParenOrBraceRange();
7672
7673 // If the entity allows NRVO, mark the construction as elidable
7674 // unconditionally.
7675 if (Entity.allowsNRVO())
7676 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7677 Step.Function.FoundDecl,
7678 Constructor, /*Elidable=*/true,
7679 ConstructorArgs,
7680 HadMultipleCandidates,
7681 IsListInitialization,
7682 IsStdInitListInitialization,
7683 ConstructorInitRequiresZeroInit,
7684 ConstructKind,
7685 ParenOrBraceRange);
7686 else
7687 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7688 Step.Function.FoundDecl,
7690 ConstructorArgs,
7691 HadMultipleCandidates,
7692 IsListInitialization,
7693 IsStdInitListInitialization,
7694 ConstructorInitRequiresZeroInit,
7695 ConstructKind,
7696 ParenOrBraceRange);
7697 }
7698 if (CurInit.isInvalid())
7699 return ExprError();
7700
7701 // Only check access if all of that succeeded.
7704 return ExprError();
7705
7706 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7708 return ExprError();
7709
7710 if (shouldBindAsTemporary(Entity))
7711 CurInit = S.MaybeBindToTemporary(CurInit.get());
7712
7713 return CurInit;
7714}
7715
7717 Expr *Init) {
7718 return sema::checkInitLifetime(*this, Entity, Init);
7719}
7720
7721static void DiagnoseNarrowingInInitList(Sema &S,
7722 const ImplicitConversionSequence &ICS,
7723 QualType PreNarrowingType,
7724 QualType EntityType,
7725 const Expr *PostInit);
7726
7727static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7728 QualType ToType, Expr *Init);
7729
7730/// Provide warnings when std::move is used on construction.
7731static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7732 bool IsReturnStmt) {
7733 if (!InitExpr)
7734 return;
7735
7737 return;
7738
7739 QualType DestType = InitExpr->getType();
7740 if (!DestType->isRecordType())
7741 return;
7742
7743 unsigned DiagID = 0;
7744 if (IsReturnStmt) {
7745 const CXXConstructExpr *CCE =
7746 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7747 if (!CCE || CCE->getNumArgs() != 1)
7748 return;
7749
7751 return;
7752
7753 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7754 }
7755
7756 // Find the std::move call and get the argument.
7757 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7758 if (!CE || !CE->isCallToStdMove())
7759 return;
7760
7761 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7762
7763 if (IsReturnStmt) {
7764 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7765 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7766 return;
7767
7768 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7769 if (!VD || !VD->hasLocalStorage())
7770 return;
7771
7772 // __block variables are not moved implicitly.
7773 if (VD->hasAttr<BlocksAttr>())
7774 return;
7775
7776 QualType SourceType = VD->getType();
7777 if (!SourceType->isRecordType())
7778 return;
7779
7780 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7781 return;
7782 }
7783
7784 // If we're returning a function parameter, copy elision
7785 // is not possible.
7786 if (isa<ParmVarDecl>(VD))
7787 DiagID = diag::warn_redundant_move_on_return;
7788 else
7789 DiagID = diag::warn_pessimizing_move_on_return;
7790 } else {
7791 DiagID = diag::warn_pessimizing_move_on_initialization;
7792 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7793 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7794 return;
7795 }
7796
7797 S.Diag(CE->getBeginLoc(), DiagID);
7798
7799 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7800 // is within a macro.
7801 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7802 if (CallBegin.isMacroID())
7803 return;
7804 SourceLocation RParen = CE->getRParenLoc();
7805 if (RParen.isMacroID())
7806 return;
7807 SourceLocation LParen;
7808 SourceLocation ArgLoc = Arg->getBeginLoc();
7809
7810 // Special testing for the argument location. Since the fix-it needs the
7811 // location right before the argument, the argument location can be in a
7812 // macro only if it is at the beginning of the macro.
7813 while (ArgLoc.isMacroID() &&
7816 }
7817
7818 if (LParen.isMacroID())
7819 return;
7820
7821 LParen = ArgLoc.getLocWithOffset(-1);
7822
7823 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7824 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7825 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7826}
7827
7828static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7829 // Check to see if we are dereferencing a null pointer. If so, this is
7830 // undefined behavior, so warn about it. This only handles the pattern
7831 // "*null", which is a very syntactic check.
7832 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7833 if (UO->getOpcode() == UO_Deref &&
7834 UO->getSubExpr()->IgnoreParenCasts()->
7835 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7836 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7837 S.PDiag(diag::warn_binding_null_to_reference)
7838 << UO->getSubExpr()->getSourceRange());
7839 }
7840}
7841
7844 bool BoundToLvalueReference) {
7845 auto MTE = new (Context)
7846 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7847
7848 // Order an ExprWithCleanups for lifetime marks.
7849 //
7850 // TODO: It'll be good to have a single place to check the access of the
7851 // destructor and generate ExprWithCleanups for various uses. Currently these
7852 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7853 // but there may be a chance to merge them.
7854 Cleanup.setExprNeedsCleanups(false);
7857 return MTE;
7858}
7859
7861 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7862 // same rule, but C99 is broken without this behavior and so we treat the
7863 // change as applying to all C language modes.
7864 // FIXME: This means that AST consumers need to deal with "prvalues" that
7865 // denote materialized temporaries. Maybe we should add another ValueKind
7866 // for "xvalue pretending to be a prvalue" for C++98 support.
7867 if (!E->isPRValue() ||
7869 return E;
7870
7871 // C++1z [conv.rval]/1: T shall be a complete type.
7872 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7873 // If so, we should check for a non-abstract class type here too.
7874 QualType T = E->getType();
7875 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7876 return ExprError();
7877
7878 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7879}
7880
7884
7885 CastKind CK = CK_NoOp;
7886
7887 if (VK == VK_PRValue) {
7888 auto PointeeTy = Ty->getPointeeType();
7889 auto ExprPointeeTy = E->getType()->getPointeeType();
7890 if (!PointeeTy.isNull() &&
7891 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7892 CK = CK_AddressSpaceConversion;
7893 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7894 CK = CK_AddressSpaceConversion;
7895 }
7896
7897 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7898}
7899
7901 const InitializedEntity &Entity,
7902 const InitializationKind &Kind,
7903 MultiExprArg Args,
7904 QualType *ResultType) {
7905 if (Failed()) {
7906 Diagnose(S, Entity, Kind, Args);
7907 return ExprError();
7908 }
7909 if (!ZeroInitializationFixit.empty()) {
7910 const Decl *D = Entity.getDecl();
7911 const auto *VD = dyn_cast_or_null<VarDecl>(D);
7912 QualType DestType = Entity.getType();
7913
7914 // The initialization would have succeeded with this fixit. Since the fixit
7915 // is on the error, we need to build a valid AST in this case, so this isn't
7916 // handled in the Failed() branch above.
7917 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7918 // Use a more useful diagnostic for constexpr variables.
7919 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
7920 << VD
7921 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7922 ZeroInitializationFixit);
7923 } else {
7924 unsigned DiagID = diag::err_default_init_const;
7925 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7926 DiagID = diag::ext_default_init_const;
7927
7928 S.Diag(Kind.getLocation(), DiagID)
7929 << DestType << DestType->isRecordType()
7930 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7931 ZeroInitializationFixit);
7932 }
7933 }
7934
7935 if (getKind() == DependentSequence) {
7936 // If the declaration is a non-dependent, incomplete array type
7937 // that has an initializer, then its type will be completed once
7938 // the initializer is instantiated.
7939 if (ResultType && !Entity.getType()->isDependentType() &&
7940 Args.size() == 1) {
7941 QualType DeclType = Entity.getType();
7942 if (const IncompleteArrayType *ArrayT
7943 = S.Context.getAsIncompleteArrayType(DeclType)) {
7944 // FIXME: We don't currently have the ability to accurately
7945 // compute the length of an initializer list without
7946 // performing full type-checking of the initializer list
7947 // (since we have to determine where braces are implicitly
7948 // introduced and such). So, we fall back to making the array
7949 // type a dependently-sized array type with no specified
7950 // bound.
7951 if (isa<InitListExpr>((Expr *)Args[0]))
7952 *ResultType = S.Context.getDependentSizedArrayType(
7953 ArrayT->getElementType(),
7954 /*NumElts=*/nullptr, ArrayT->getSizeModifier(),
7955 ArrayT->getIndexTypeCVRQualifiers());
7956 }
7957 }
7958 if (Kind.getKind() == InitializationKind::IK_Direct &&
7959 !Kind.isExplicitCast()) {
7960 // Rebuild the ParenListExpr.
7961 SourceRange ParenRange = Kind.getParenOrBraceRange();
7962 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7963 Args);
7964 }
7965 assert(Kind.getKind() == InitializationKind::IK_Copy ||
7966 Kind.isExplicitCast() ||
7967 Kind.getKind() == InitializationKind::IK_DirectList);
7968 return ExprResult(Args[0]);
7969 }
7970
7971 // No steps means no initialization.
7972 if (Steps.empty())
7973 return ExprResult((Expr *)nullptr);
7974
7975 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7976 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7977 !Entity.isParamOrTemplateParamKind()) {
7978 // Produce a C++98 compatibility warning if we are initializing a reference
7979 // from an initializer list. For parameters, we produce a better warning
7980 // elsewhere.
7981 Expr *Init = Args[0];
7982 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7983 << Init->getSourceRange();
7984 }
7985
7986 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
7987 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
7988 // Produce a Microsoft compatibility warning when initializing from a
7989 // predefined expression since MSVC treats predefined expressions as string
7990 // literals.
7991 Expr *Init = Args[0];
7992 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
7993 }
7994
7995 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7996 QualType ETy = Entity.getType();
7997 bool HasGlobalAS = ETy.hasAddressSpace() &&
7999
8000 if (S.getLangOpts().OpenCLVersion >= 200 &&
8001 ETy->isAtomicType() && !HasGlobalAS &&
8002 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8003 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8004 << 1
8005 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8006 return ExprError();
8007 }
8008
8009 QualType DestType = Entity.getType().getNonReferenceType();
8010 // FIXME: Ugly hack around the fact that Entity.getType() is not
8011 // the same as Entity.getDecl()->getType() in cases involving type merging,
8012 // and we want latter when it makes sense.
8013 if (ResultType)
8014 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8015 Entity.getType();
8016
8017 ExprResult CurInit((Expr *)nullptr);
8018 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8019
8020 // HLSL allows vector/matrix initialization to function like list
8021 // initialization, but use the syntax of a C++-like constructor.
8022 bool IsHLSLVectorOrMatrixInit =
8023 S.getLangOpts().HLSL &&
8024 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8025 isa<InitListExpr>(Args[0]);
8026 (void)IsHLSLVectorOrMatrixInit;
8027
8028 // For initialization steps that start with a single initializer,
8029 // grab the only argument out the Args and place it into the "current"
8030 // initializer.
8031 switch (Steps.front().Kind) {
8036 case SK_BindReference:
8038 case SK_FinalCopy:
8040 case SK_UserConversion:
8049 case SK_UnwrapInitList:
8050 case SK_RewrapInitList:
8051 case SK_CAssignment:
8052 case SK_StringInit:
8054 case SK_ArrayLoopIndex:
8055 case SK_ArrayLoopInit:
8056 case SK_ArrayInit:
8057 case SK_GNUArrayInit:
8063 case SK_OCLSamplerInit:
8064 case SK_OCLZeroOpaqueType: {
8065 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8066 CurInit = Args[0];
8067 if (!CurInit.get()) return ExprError();
8068 break;
8069 }
8070
8076 break;
8077 }
8078
8079 // Promote from an unevaluated context to an unevaluated list context in
8080 // C++11 list-initialization; we need to instantiate entities usable in
8081 // constant expressions here in order to perform narrowing checks =(
8084 isa_and_nonnull<InitListExpr>(CurInit.get()));
8085
8086 // C++ [class.abstract]p2:
8087 // no objects of an abstract class can be created except as subobjects
8088 // of a class derived from it
8089 auto checkAbstractType = [&](QualType T) -> bool {
8090 if (Entity.getKind() == InitializedEntity::EK_Base ||
8092 return false;
8093 return S.RequireNonAbstractType(Kind.getLocation(), T,
8094 diag::err_allocation_of_abstract_type);
8095 };
8096
8097 // Walk through the computed steps for the initialization sequence,
8098 // performing the specified conversions along the way.
8099 bool ConstructorInitRequiresZeroInit = false;
8100 for (step_iterator Step = step_begin(), StepEnd = step_end();
8101 Step != StepEnd; ++Step) {
8102 if (CurInit.isInvalid())
8103 return ExprError();
8104
8105 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8106
8107 switch (Step->Kind) {
8109 // Overload resolution determined which function invoke; update the
8110 // initializer to reflect that choice.
8112 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8113 return ExprError();
8114 CurInit = S.FixOverloadedFunctionReference(CurInit,
8117 // We might get back another placeholder expression if we resolved to a
8118 // builtin.
8119 if (!CurInit.isInvalid())
8120 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8121 break;
8122
8126 // We have a derived-to-base cast that produces either an rvalue or an
8127 // lvalue. Perform that cast.
8128
8129 CXXCastPath BasePath;
8130
8131 // Casts to inaccessible base classes are allowed with C-style casts.
8132 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8134 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8135 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8136 return ExprError();
8137
8140 ? VK_LValue
8142 : VK_PRValue);
8144 CK_DerivedToBase, CurInit.get(),
8145 &BasePath, VK, FPOptionsOverride());
8146 break;
8147 }
8148
8149 case SK_BindReference:
8150 // Reference binding does not have any corresponding ASTs.
8151
8152 // Check exception specifications
8153 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8154 return ExprError();
8155
8156 // We don't check for e.g. function pointers here, since address
8157 // availability checks should only occur when the function first decays
8158 // into a pointer or reference.
8159 if (CurInit.get()->getType()->isFunctionProtoType()) {
8160 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8161 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8162 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8163 DRE->getBeginLoc()))
8164 return ExprError();
8165 }
8166 }
8167 }
8168
8169 CheckForNullPointerDereference(S, CurInit.get());
8170 break;
8171
8173 // Make sure the "temporary" is actually an rvalue.
8174 assert(CurInit.get()->isPRValue() && "not a temporary");
8175
8176 // Check exception specifications
8177 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8178 return ExprError();
8179
8180 QualType MTETy = Step->Type;
8181
8182 // When this is an incomplete array type (such as when this is
8183 // initializing an array of unknown bounds from an init list), use THAT
8184 // type instead so that we propagate the array bounds.
8185 if (MTETy->isIncompleteArrayType() &&
8186 !CurInit.get()->getType()->isIncompleteArrayType() &&
8189 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8190 MTETy = CurInit.get()->getType();
8191
8192 // Materialize the temporary into memory.
8194 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8195 CurInit = MTE;
8196
8197 // If we're extending this temporary to automatic storage duration -- we
8198 // need to register its cleanup during the full-expression's cleanups.
8199 if (MTE->getStorageDuration() == SD_Automatic &&
8200 MTE->getType().isDestructedType())
8202 break;
8203 }
8204
8205 case SK_FinalCopy:
8206 if (checkAbstractType(Step->Type))
8207 return ExprError();
8208
8209 // If the overall initialization is initializing a temporary, we already
8210 // bound our argument if it was necessary to do so. If not (if we're
8211 // ultimately initializing a non-temporary), our argument needs to be
8212 // bound since it's initializing a function parameter.
8213 // FIXME: This is a mess. Rationalize temporary destruction.
8214 if (!shouldBindAsTemporary(Entity))
8215 CurInit = S.MaybeBindToTemporary(CurInit.get());
8216 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8217 /*IsExtraneousCopy=*/false);
8218 break;
8219
8221 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8222 /*IsExtraneousCopy=*/true);
8223 break;
8224
8225 case SK_UserConversion: {
8226 // We have a user-defined conversion that invokes either a constructor
8227 // or a conversion function.
8231 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8232 bool CreatedObject = false;
8233 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8234 // Build a call to the selected constructor.
8235 SmallVector<Expr*, 8> ConstructorArgs;
8236 SourceLocation Loc = CurInit.get()->getBeginLoc();
8237
8238 // Determine the arguments required to actually perform the constructor
8239 // call.
8240 Expr *Arg = CurInit.get();
8242 MultiExprArg(&Arg, 1), Loc,
8243 ConstructorArgs))
8244 return ExprError();
8245
8246 // Build an expression that constructs a temporary.
8247 CurInit = S.BuildCXXConstructExpr(
8248 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8249 HadMultipleCandidates,
8250 /*ListInit*/ false,
8251 /*StdInitListInit*/ false,
8252 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8253 if (CurInit.isInvalid())
8254 return ExprError();
8255
8256 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8257 Entity);
8258 if (S.DiagnoseUseOfOverloadedDecl(Constructor, Kind.getLocation()))
8259 return ExprError();
8260
8261 CastKind = CK_ConstructorConversion;
8262 CreatedObject = true;
8263 } else {
8264 // Build a call to the conversion function.
8266 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8267 FoundFn);
8268 if (S.DiagnoseUseOfOverloadedDecl(Conversion, Kind.getLocation()))
8269 return ExprError();
8270
8271 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8272 HadMultipleCandidates);
8273 if (CurInit.isInvalid())
8274 return ExprError();
8275
8276 CastKind = CK_UserDefinedConversion;
8277 CreatedObject = Conversion->getReturnType()->isRecordType();
8278 }
8279
8280 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8281 return ExprError();
8282
8283 CurInit = ImplicitCastExpr::Create(
8284 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8285 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8286
8287 if (shouldBindAsTemporary(Entity))
8288 // The overall entity is temporary, so this expression should be
8289 // destroyed at the end of its full-expression.
8290 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8291 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8292 // The object outlasts the full-expression, but we need to prepare for
8293 // a destructor being run on it.
8294 // FIXME: It makes no sense to do this here. This should happen
8295 // regardless of how we initialized the entity.
8296 QualType T = CurInit.get()->getType();
8297 if (auto *Record = T->castAsCXXRecordDecl()) {
8300 S.PDiag(diag::err_access_dtor_temp) << T);
8302 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8303 return ExprError();
8304 }
8305 }
8306 break;
8307 }
8308
8312 // Perform a qualification conversion; these can never go wrong.
8315 ? VK_LValue
8317 : VK_PRValue);
8318 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8319 break;
8320 }
8321
8323 assert(CurInit.get()->isLValue() &&
8324 "function reference should be lvalue");
8325 CurInit =
8326 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8327 break;
8328
8329 case SK_AtomicConversion: {
8330 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8331 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8332 CK_NonAtomicToAtomic, VK_PRValue);
8333 break;
8334 }
8335
8338 if (const auto *FromPtrType =
8339 CurInit.get()->getType()->getAs<PointerType>()) {
8340 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8341 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8342 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8343 // Do not check static casts here because they are checked earlier
8344 // in Sema::ActOnCXXNamedCast()
8345 if (!Kind.isStaticCast()) {
8346 S.Diag(CurInit.get()->getExprLoc(),
8347 diag::warn_noderef_to_dereferenceable_pointer)
8348 << CurInit.get()->getSourceRange();
8349 }
8350 }
8351 }
8352 }
8353 Expr *Init = CurInit.get();
8355 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8356 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8357 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8359 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8360 Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);
8361 if (CurInitExprRes.isInvalid())
8362 return ExprError();
8363
8365
8366 CurInit = CurInitExprRes;
8367
8369 S.getLangOpts().CPlusPlus)
8370 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8371 CurInit.get());
8372
8373 break;
8374 }
8375
8376 case SK_ListInitialization: {
8377 if (checkAbstractType(Step->Type))
8378 return ExprError();
8379
8380 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8381 // If we're not initializing the top-level entity, we need to create an
8382 // InitializeTemporary entity for our target type.
8383 QualType Ty = Step->Type;
8384 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8385 InitializedEntity InitEntity =
8386 IsTemporary ? InitializedEntity::InitializeTemporary(Ty) : Entity;
8387 InitListChecker PerformInitList(S, InitEntity,
8388 InitList, Ty, /*VerifyOnly=*/false,
8389 /*TreatUnavailableAsInvalid=*/false);
8390 if (PerformInitList.HadError())
8391 return ExprError();
8392
8393 // Hack: We must update *ResultType if available in order to set the
8394 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8395 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8396 if (ResultType &&
8397 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8398 if ((*ResultType)->isRValueReferenceType())
8400 else if ((*ResultType)->isLValueReferenceType())
8402 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8403 *ResultType = Ty;
8404 }
8405
8406 InitListExpr *StructuredInitList =
8407 PerformInitList.getFullyStructuredList();
8408 CurInit = shouldBindAsTemporary(InitEntity)
8409 ? S.MaybeBindToTemporary(StructuredInitList)
8410 : StructuredInitList;
8411 break;
8412 }
8413
8415 if (checkAbstractType(Step->Type))
8416 return ExprError();
8417
8418 // When an initializer list is passed for a parameter of type "reference
8419 // to object", we don't get an EK_Temporary entity, but instead an
8420 // EK_Parameter entity with reference type.
8421 // FIXME: This is a hack. What we really should do is create a user
8422 // conversion step for this case, but this makes it considerably more
8423 // complicated. For now, this will do.
8425 Entity.getType().getNonReferenceType());
8426 bool UseTemporary = Entity.getType()->isReferenceType();
8427 assert(Args.size() == 1 && "expected a single argument for list init");
8428 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8429 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8430 << InitList->getSourceRange();
8431 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8432 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8433 Entity,
8434 Kind, Arg, *Step,
8435 ConstructorInitRequiresZeroInit,
8436 /*IsListInitialization*/true,
8437 /*IsStdInitListInit*/false,
8438 InitList->getLBraceLoc(),
8439 InitList->getRBraceLoc());
8440 break;
8441 }
8442
8443 case SK_UnwrapInitList:
8444 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8445 break;
8446
8447 case SK_RewrapInitList: {
8448 Expr *E = CurInit.get();
8450 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8451 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8452 ILE->setSyntacticForm(Syntactic);
8453 ILE->setType(E->getType());
8454 ILE->setValueKind(E->getValueKind());
8455 CurInit = ILE;
8456 break;
8457 }
8458
8461 if (checkAbstractType(Step->Type))
8462 return ExprError();
8463
8464 // When an initializer list is passed for a parameter of type "reference
8465 // to object", we don't get an EK_Temporary entity, but instead an
8466 // EK_Parameter entity with reference type.
8467 // FIXME: This is a hack. What we really should do is create a user
8468 // conversion step for this case, but this makes it considerably more
8469 // complicated. For now, this will do.
8471 Entity.getType().getNonReferenceType());
8472 bool UseTemporary = Entity.getType()->isReferenceType();
8473 bool IsStdInitListInit =
8475 Expr *Source = CurInit.get();
8476 SourceRange Range = Kind.hasParenOrBraceRange()
8477 ? Kind.getParenOrBraceRange()
8478 : SourceRange();
8480 S, UseTemporary ? TempEntity : Entity, Kind,
8481 Source ? MultiExprArg(Source) : Args, *Step,
8482 ConstructorInitRequiresZeroInit,
8483 /*IsListInitialization*/ IsStdInitListInit,
8484 /*IsStdInitListInitialization*/ IsStdInitListInit,
8485 /*LBraceLoc*/ Range.getBegin(),
8486 /*RBraceLoc*/ Range.getEnd());
8487 break;
8488 }
8489
8490 case SK_ZeroInitialization: {
8491 step_iterator NextStep = Step;
8492 ++NextStep;
8493 if (NextStep != StepEnd &&
8494 (NextStep->Kind == SK_ConstructorInitialization ||
8495 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8496 // The need for zero-initialization is recorded directly into
8497 // the call to the object's constructor within the next step.
8498 ConstructorInitRequiresZeroInit = true;
8499 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8500 S.getLangOpts().CPlusPlus &&
8501 !Kind.isImplicitValueInit()) {
8502 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8503 if (!TSInfo)
8505 Kind.getRange().getBegin());
8506
8507 CurInit = new (S.Context) CXXScalarValueInitExpr(
8508 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
8509 Kind.getRange().getEnd());
8510 } else {
8511 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8512 // Note the return value isn't used to return a ExprError() when
8513 // initialization fails . For struct initialization allows all field
8514 // assignments to be checked rather than bailing on the first error.
8515 S.BoundsSafetyCheckInitialization(Entity, Kind,
8517 Step->Type, CurInit.get());
8518 }
8519 break;
8520 }
8521
8522 case SK_CAssignment: {
8523 QualType SourceType = CurInit.get()->getType();
8524 Expr *Init = CurInit.get();
8525
8526 // Save off the initial CurInit in case we need to emit a diagnostic
8527 ExprResult InitialCurInit = Init;
8530 Step->Type, Result, true,
8532 if (Result.isInvalid())
8533 return ExprError();
8534 CurInit = Result;
8535
8536 // If this is a call, allow conversion to a transparent union.
8537 ExprResult CurInitExprRes = CurInit;
8538 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8540 Step->Type, CurInitExprRes) == AssignConvertType::Compatible)
8542 if (CurInitExprRes.isInvalid())
8543 return ExprError();
8544 CurInit = CurInitExprRes;
8545
8546 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8547 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
8548 CurInit.get());
8549
8550 // C23 6.7.1p6: If an object or subobject declared with storage-class
8551 // specifier constexpr has pointer, integer, or arithmetic type, any
8552 // explicit initializer value for it shall be null, an integer
8553 // constant expression, or an arithmetic constant expression,
8554 // respectively.
8556 if (Entity.getType()->getAs<PointerType>() &&
8557 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
8558 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8559 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
8560 return ExprError();
8561 }
8562 }
8563
8564 // Note the return value isn't used to return a ExprError() when
8565 // initialization fails. For struct initialization this allows all field
8566 // assignments to be checked rather than bailing on the first error.
8567 S.BoundsSafetyCheckInitialization(Entity, Kind,
8568 getAssignmentAction(Entity, true),
8569 Step->Type, InitialCurInit.get());
8570
8571 bool Complained;
8572 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
8573 Step->Type, SourceType,
8574 InitialCurInit.get(),
8575 getAssignmentAction(Entity, true),
8576 &Complained)) {
8577 PrintInitLocationNote(S, Entity);
8578 return ExprError();
8579 } else if (Complained)
8580 PrintInitLocationNote(S, Entity);
8581 break;
8582 }
8583
8584 case SK_StringInit: {
8585 QualType Ty = Step->Type;
8586 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8587 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
8588 S.Context.getAsArrayType(Ty), S, Entity,
8589 S.getLangOpts().C23 &&
8591 break;
8592 }
8593
8595 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8596 CK_ObjCObjectLValueCast,
8597 CurInit.get()->getValueKind());
8598 break;
8599
8600 case SK_ArrayLoopIndex: {
8601 Expr *Cur = CurInit.get();
8602 Expr *BaseExpr = new (S.Context)
8603 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8604 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8605 Expr *IndexExpr =
8608 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8609 ArrayLoopCommonExprs.push_back(BaseExpr);
8610 break;
8611 }
8612
8613 case SK_ArrayLoopInit: {
8614 assert(!ArrayLoopCommonExprs.empty() &&
8615 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8616 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8617 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8618 CurInit.get());
8619 break;
8620 }
8621
8622 case SK_GNUArrayInit:
8623 // Okay: we checked everything before creating this step. Note that
8624 // this is a GNU extension.
8625 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8626 << Step->Type << CurInit.get()->getType()
8627 << CurInit.get()->getSourceRange();
8629 [[fallthrough]];
8630 case SK_ArrayInit:
8631 // If the destination type is an incomplete array type, update the
8632 // type accordingly.
8633 if (ResultType) {
8634 if (const IncompleteArrayType *IncompleteDest
8636 if (const ConstantArrayType *ConstantSource
8637 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8638 *ResultType = S.Context.getConstantArrayType(
8639 IncompleteDest->getElementType(), ConstantSource->getSize(),
8640 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
8641 }
8642 }
8643 }
8644 break;
8645
8647 // Okay: we checked everything before creating this step. Note that
8648 // this is a GNU extension.
8649 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8650 << CurInit.get()->getSourceRange();
8651 break;
8652
8655 checkIndirectCopyRestoreSource(S, CurInit.get());
8656 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8657 CurInit.get(), Step->Type,
8659 break;
8660
8662 CurInit = ImplicitCastExpr::Create(
8663 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
8665 break;
8666
8667 case SK_StdInitializerList: {
8668 S.Diag(CurInit.get()->getExprLoc(),
8669 diag::warn_cxx98_compat_initializer_list_init)
8670 << CurInit.get()->getSourceRange();
8671
8672 // Materialize the temporary into memory.
8674 CurInit.get()->getType(), CurInit.get(),
8675 /*BoundToLvalueReference=*/false);
8676
8677 // Wrap it in a construction of a std::initializer_list<T>.
8678 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8679
8680 if (!Step->Type->isDependentType()) {
8681 QualType ElementType;
8682 [[maybe_unused]] bool IsStdInitializerList =
8683 S.isStdInitializerList(Step->Type, &ElementType);
8684 assert(IsStdInitializerList &&
8685 "StdInitializerList step to non-std::initializer_list");
8686 const auto *Record = Step->Type->castAsCXXRecordDecl();
8687 assert(Record->isCompleteDefinition() &&
8688 "std::initializer_list should have already be "
8689 "complete/instantiated by this point");
8690
8691 auto InvalidType = [&] {
8692 S.Diag(Record->getLocation(),
8693 diag::err_std_initializer_list_malformed)
8695 return ExprError();
8696 };
8697
8698 if (Record->isUnion() || Record->getNumBases() != 0 ||
8699 Record->isPolymorphic())
8700 return InvalidType();
8701
8702 RecordDecl::field_iterator Field = Record->field_begin();
8703 if (Field == Record->field_end())
8704 return InvalidType();
8705
8706 // Start pointer
8707 if (!Field->getType()->isPointerType() ||
8708 !S.Context.hasSameType(Field->getType()->getPointeeType(),
8709 ElementType.withConst()))
8710 return InvalidType();
8711
8712 if (++Field == Record->field_end())
8713 return InvalidType();
8714
8715 // Size or end pointer
8716 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8717 if (!S.Context.hasSameType(PT->getPointeeType(),
8718 ElementType.withConst()))
8719 return InvalidType();
8720 } else {
8721 if (Field->isBitField() ||
8722 !S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))
8723 return InvalidType();
8724 }
8725
8726 if (++Field != Record->field_end())
8727 return InvalidType();
8728 }
8729
8730 // Bind the result, in case the library has given initializer_list a
8731 // non-trivial destructor.
8732 if (shouldBindAsTemporary(Entity))
8733 CurInit = S.MaybeBindToTemporary(CurInit.get());
8734 break;
8735 }
8736
8737 case SK_OCLSamplerInit: {
8738 // Sampler initialization have 5 cases:
8739 // 1. function argument passing
8740 // 1a. argument is a file-scope variable
8741 // 1b. argument is a function-scope variable
8742 // 1c. argument is one of caller function's parameters
8743 // 2. variable initialization
8744 // 2a. initializing a file-scope variable
8745 // 2b. initializing a function-scope variable
8746 //
8747 // For file-scope variables, since they cannot be initialized by function
8748 // call of __translate_sampler_initializer in LLVM IR, their references
8749 // need to be replaced by a cast from their literal initializers to
8750 // sampler type. Since sampler variables can only be used in function
8751 // calls as arguments, we only need to replace them when handling the
8752 // argument passing.
8753 assert(Step->Type->isSamplerT() &&
8754 "Sampler initialization on non-sampler type.");
8755 Expr *Init = CurInit.get()->IgnoreParens();
8756 QualType SourceType = Init->getType();
8757 // Case 1
8758 if (Entity.isParameterKind()) {
8759 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8760 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8761 << SourceType;
8762 break;
8763 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8764 auto Var = cast<VarDecl>(DRE->getDecl());
8765 // Case 1b and 1c
8766 // No cast from integer to sampler is needed.
8767 if (!Var->hasGlobalStorage()) {
8768 CurInit = ImplicitCastExpr::Create(
8769 S.Context, Step->Type, CK_LValueToRValue, Init,
8770 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
8771 break;
8772 }
8773 // Case 1a
8774 // For function call with a file-scope sampler variable as argument,
8775 // get the integer literal.
8776 // Do not diagnose if the file-scope variable does not have initializer
8777 // since this has already been diagnosed when parsing the variable
8778 // declaration.
8779 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8780 break;
8781 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8782 Var->getInit()))->getSubExpr();
8783 SourceType = Init->getType();
8784 }
8785 } else {
8786 // Case 2
8787 // Check initializer is 32 bit integer constant.
8788 // If the initializer is taken from global variable, do not diagnose since
8789 // this has already been done when parsing the variable declaration.
8790 if (!Init->isConstantInitializer(S.Context))
8791 break;
8792
8793 if (!SourceType->isIntegerType() ||
8794 32 != S.Context.getIntWidth(SourceType)) {
8795 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8796 << SourceType;
8797 break;
8798 }
8799
8800 Expr::EvalResult EVResult;
8801 Init->EvaluateAsInt(EVResult, S.Context);
8802 llvm::APSInt Result = EVResult.Val.getInt();
8803 const uint64_t SamplerValue = Result.getLimitedValue();
8804 // 32-bit value of sampler's initializer is interpreted as
8805 // bit-field with the following structure:
8806 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8807 // |31 6|5 4|3 1| 0|
8808 // This structure corresponds to enum values of sampler properties
8809 // defined in SPIR spec v1.2 and also opencl-c.h
8810 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8811 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8812 if (FilterMode != 1 && FilterMode != 2 &&
8814 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
8815 S.Diag(Kind.getLocation(),
8816 diag::warn_sampler_initializer_invalid_bits)
8817 << "Filter Mode";
8818 if (AddressingMode > 4)
8819 S.Diag(Kind.getLocation(),
8820 diag::warn_sampler_initializer_invalid_bits)
8821 << "Addressing Mode";
8822 }
8823
8824 // Cases 1a, 2a and 2b
8825 // Insert cast from integer to sampler.
8827 CK_IntToOCLSampler);
8828 break;
8829 }
8830 case SK_OCLZeroOpaqueType: {
8831 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8833 "Wrong type for initialization of OpenCL opaque type.");
8834
8835 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8836 CK_ZeroToOCLOpaqueType,
8837 CurInit.get()->getValueKind());
8838 break;
8839 }
8841 CurInit = nullptr;
8842 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
8843 /*VerifyOnly=*/false, &CurInit);
8844 if (CurInit.get() && ResultType)
8845 *ResultType = CurInit.get()->getType();
8846 if (shouldBindAsTemporary(Entity))
8847 CurInit = S.MaybeBindToTemporary(CurInit.get());
8848 break;
8849 }
8850 }
8851 }
8852
8853 Expr *Init = CurInit.get();
8854 if (!Init)
8855 return ExprError();
8856
8857 // Check whether the initializer has a shorter lifetime than the initialized
8858 // entity, and if not, either lifetime-extend or warn as appropriate.
8859 S.checkInitializerLifetime(Entity, Init);
8860
8861 // Diagnose non-fatal problems with the completed initialization.
8862 if (InitializedEntity::EntityKind EK = Entity.getKind();
8865 cast<FieldDecl>(Entity.getDecl())->isBitField())
8866 S.CheckBitFieldInitialization(Kind.getLocation(),
8867 cast<FieldDecl>(Entity.getDecl()), Init);
8868
8869 // Check for std::move on construction.
8872
8873 return Init;
8874}
8875
8876/// Somewhere within T there is an uninitialized reference subobject.
8877/// Dig it out and diagnose it.
8879 QualType T) {
8880 if (T->isReferenceType()) {
8881 S.Diag(Loc, diag::err_reference_without_init)
8882 << T.getNonReferenceType();
8883 return true;
8884 }
8885
8886 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8887 if (!RD || !RD->hasUninitializedReferenceMember())
8888 return false;
8889
8890 for (const auto *FI : RD->fields()) {
8891 if (FI->isUnnamedBitField())
8892 continue;
8893
8894 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8895 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8896 return true;
8897 }
8898 }
8899
8900 for (const auto &BI : RD->bases()) {
8901 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8902 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8903 return true;
8904 }
8905 }
8906
8907 return false;
8908}
8909
8910
8911//===----------------------------------------------------------------------===//
8912// Diagnose initialization failures
8913//===----------------------------------------------------------------------===//
8914
8915/// Emit notes associated with an initialization that failed due to a
8916/// "simple" conversion failure.
8917static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8918 Expr *op) {
8919 QualType destType = entity.getType();
8920 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8922
8923 // Emit a possible note about the conversion failing because the
8924 // operand is a message send with a related result type.
8926
8927 // Emit a possible note about a return failing because we're
8928 // expecting a related result type.
8929 if (entity.getKind() == InitializedEntity::EK_Result)
8931 }
8932 QualType fromType = op->getType();
8933 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8934 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8935 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8936 auto *destDecl = destType->getPointeeCXXRecordDecl();
8937 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8938 destDecl->getDeclKind() == Decl::CXXRecord &&
8939 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8940 !fromDecl->hasDefinition() &&
8941 destPointeeType.getQualifiers().compatiblyIncludes(
8942 fromPointeeType.getQualifiers(), S.getASTContext()))
8943 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
8944 << S.getASTContext().getCanonicalTagType(fromDecl)
8945 << S.getASTContext().getCanonicalTagType(destDecl);
8946}
8947
8948static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8949 InitListExpr *InitList) {
8950 QualType DestType = Entity.getType();
8951
8952 QualType E;
8953 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8955 E.withConst(),
8956 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8957 InitList->getNumInits()),
8959 InitializedEntity HiddenArray =
8961 return diagnoseListInit(S, HiddenArray, InitList);
8962 }
8963
8964 if (DestType->isReferenceType()) {
8965 // A list-initialization failure for a reference means that we tried to
8966 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8967 // inner initialization failed.
8968 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8970 SourceLocation Loc = InitList->getBeginLoc();
8971 if (auto *D = Entity.getDecl())
8972 Loc = D->getLocation();
8973 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8974 return;
8975 }
8976
8977 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8978 /*VerifyOnly=*/false,
8979 /*TreatUnavailableAsInvalid=*/false);
8980 assert(DiagnoseInitList.HadError() &&
8981 "Inconsistent init list check result.");
8982}
8983
8985 const InitializedEntity &Entity,
8986 const InitializationKind &Kind,
8987 ArrayRef<Expr *> Args) {
8988 if (!Failed())
8989 return false;
8990
8991 QualType DestType = Entity.getType();
8992
8993 // When we want to diagnose only one element of a braced-init-list,
8994 // we need to factor it out.
8995 Expr *OnlyArg;
8996 if (Args.size() == 1) {
8997 auto *List = dyn_cast<InitListExpr>(Args[0]);
8998 if (List && List->getNumInits() == 1)
8999 OnlyArg = List->getInit(0);
9000 else
9001 OnlyArg = Args[0];
9002
9003 if (OnlyArg->getType() == S.Context.OverloadTy) {
9006 OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,
9007 Found)) {
9008 if (Expr *Resolved =
9009 S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())
9010 OnlyArg = Resolved;
9011 }
9012 }
9013 }
9014 else
9015 OnlyArg = nullptr;
9016
9017 switch (Failure) {
9019 // FIXME: Customize for the initialized entity?
9020 if (Args.empty()) {
9021 // Dig out the reference subobject which is uninitialized and diagnose it.
9022 // If this is value-initialization, this could be nested some way within
9023 // the target type.
9024 assert(Kind.getKind() == InitializationKind::IK_Value ||
9025 DestType->isReferenceType());
9026 bool Diagnosed =
9027 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9028 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9029 (void)Diagnosed;
9030 } else // FIXME: diagnostic below could be better!
9031 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9032 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9033 break;
9035 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9036 << 1 << Entity.getType() << Args[0]->getSourceRange();
9037 break;
9038
9040 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9041 break;
9043 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9044 break;
9046 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9047 break;
9049 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9050 break;
9052 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9053 break;
9055 S.Diag(Kind.getLocation(),
9056 diag::err_array_init_incompat_wide_string_into_wchar);
9057 break;
9059 S.Diag(Kind.getLocation(),
9060 diag::err_array_init_plain_string_into_char8_t);
9061 S.Diag(Args.front()->getBeginLoc(),
9062 diag::note_array_init_plain_string_into_char8_t)
9063 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9064 break;
9066 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9067 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9068 break;
9071 S.Diag(Kind.getLocation(),
9072 (Failure == FK_ArrayTypeMismatch
9073 ? diag::err_array_init_different_type
9074 : diag::err_array_init_non_constant_array))
9075 << DestType.getNonReferenceType()
9076 << OnlyArg->getType()
9077 << Args[0]->getSourceRange();
9078 break;
9079
9081 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9082 << Args[0]->getSourceRange();
9083 break;
9084
9088 DestType.getNonReferenceType(),
9089 true,
9090 Found);
9091 break;
9092 }
9093
9095 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9096 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9097 OnlyArg->getBeginLoc());
9098 break;
9099 }
9100
9103 switch (FailedOverloadResult) {
9104 case OR_Ambiguous:
9105
9106 FailedCandidateSet.NoteCandidates(
9108 Kind.getLocation(),
9110 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9111 << OnlyArg->getType() << DestType
9112 << Args[0]->getSourceRange())
9113 : (S.PDiag(diag::err_ref_init_ambiguous)
9114 << DestType << OnlyArg->getType()
9115 << Args[0]->getSourceRange())),
9116 S, OCD_AmbiguousCandidates, Args);
9117 break;
9118
9119 case OR_No_Viable_Function: {
9120 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9121 if (!S.RequireCompleteType(Kind.getLocation(),
9122 DestType.getNonReferenceType(),
9123 diag::err_typecheck_nonviable_condition_incomplete,
9124 OnlyArg->getType(), Args[0]->getSourceRange()))
9125 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9126 << (Entity.getKind() == InitializedEntity::EK_Result)
9127 << OnlyArg->getType() << Args[0]->getSourceRange()
9128 << DestType.getNonReferenceType();
9129
9130 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9131 break;
9132 }
9133 case OR_Deleted: {
9136 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9137
9138 StringLiteral *Msg = Best->Function->getDeletedMessage();
9139 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9140 << OnlyArg->getType() << DestType.getNonReferenceType()
9141 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9142 << Args[0]->getSourceRange();
9143 if (Ovl == OR_Deleted) {
9144 S.NoteDeletedFunction(Best->Function);
9145 } else {
9146 llvm_unreachable("Inconsistent overload resolution?");
9147 }
9148 break;
9149 }
9150
9151 case OR_Success:
9152 llvm_unreachable("Conversion did not fail!");
9153 }
9154 break;
9155
9157 if (isa<InitListExpr>(Args[0])) {
9158 S.Diag(Kind.getLocation(),
9159 diag::err_lvalue_reference_bind_to_initlist)
9161 << DestType.getNonReferenceType()
9162 << Args[0]->getSourceRange();
9163 break;
9164 }
9165 [[fallthrough]];
9166
9168 S.Diag(Kind.getLocation(),
9170 ? diag::err_lvalue_reference_bind_to_temporary
9171 : diag::err_lvalue_reference_bind_to_unrelated)
9173 << DestType.getNonReferenceType()
9174 << OnlyArg->getType()
9175 << Args[0]->getSourceRange();
9176 break;
9177
9179 // We don't necessarily have an unambiguous source bit-field.
9180 FieldDecl *BitField = Args[0]->getSourceBitField();
9181 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9182 << DestType.isVolatileQualified()
9183 << (BitField ? BitField->getDeclName() : DeclarationName())
9184 << (BitField != nullptr)
9185 << Args[0]->getSourceRange();
9186 if (BitField)
9187 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9188 break;
9189 }
9190
9192 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9193 << DestType.isVolatileQualified()
9194 << Args[0]->getSourceRange();
9195 break;
9196
9198 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9199 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9200 break;
9201
9203 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9204 << DestType.getNonReferenceType() << OnlyArg->getType()
9205 << Args[0]->getSourceRange();
9206 break;
9207
9209 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9210 << DestType << Args[0]->getSourceRange();
9211 break;
9212
9214 QualType SourceType = OnlyArg->getType();
9215 QualType NonRefType = DestType.getNonReferenceType();
9216 Qualifiers DroppedQualifiers =
9217 SourceType.getQualifiers() - NonRefType.getQualifiers();
9218
9219 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9220 SourceType.getQualifiers(), S.getASTContext()))
9221 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9222 << NonRefType << SourceType << 1 /*addr space*/
9223 << Args[0]->getSourceRange();
9224 else if (DroppedQualifiers.hasQualifiers())
9225 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9226 << NonRefType << SourceType << 0 /*cv quals*/
9227 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9228 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9229 else
9230 // FIXME: Consider decomposing the type and explaining which qualifiers
9231 // were dropped where, or on which level a 'const' is missing, etc.
9232 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9233 << NonRefType << SourceType << 2 /*incompatible quals*/
9234 << Args[0]->getSourceRange();
9235 break;
9236 }
9237
9239 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9240 << DestType.getNonReferenceType()
9241 << DestType.getNonReferenceType()->isIncompleteType()
9242 << OnlyArg->isLValue()
9243 << OnlyArg->getType()
9244 << Args[0]->getSourceRange();
9245 emitBadConversionNotes(S, Entity, Args[0]);
9246 break;
9247
9248 case FK_ConversionFailed: {
9249 QualType FromType = OnlyArg->getType();
9250 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9251 // type, although this is almost always an error and we advise against it.
9252 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9253 DestType == S.Context.getLogicalOperationType()) {
9254 S.Diag(OnlyArg->getExprLoc(),
9255 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9256 << OnlyArg << DestType;
9257 break;
9258 }
9259 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9260 << (int)Entity.getKind()
9261 << DestType
9262 << OnlyArg->isLValue()
9263 << FromType
9264 << Args[0]->getSourceRange();
9265 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9266 S.Diag(Kind.getLocation(), PDiag);
9267 emitBadConversionNotes(S, Entity, Args[0]);
9268 break;
9269 }
9270
9272 // No-op. This error has already been reported.
9273 break;
9274
9276 SourceRange R;
9277
9278 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9279 if (InitList && InitList->getNumInits() >= 1) {
9280 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9281 } else {
9282 assert(Args.size() > 1 && "Expected multiple initializers!");
9283 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9284 }
9285
9286 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9287 if (Kind.isCStyleOrFunctionalCast())
9288 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9289 << R;
9290 else
9291 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9292 << /*scalar=*/3 << R;
9293 break;
9294 }
9295
9297 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9298 << 0 << Entity.getType() << Args[0]->getSourceRange();
9299 break;
9300
9302 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9303 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9304 break;
9305
9307 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9308 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9309 break;
9310
9313 SourceRange ArgsRange;
9314 if (Args.size())
9315 ArgsRange =
9316 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9317
9318 if (Failure == FK_ListConstructorOverloadFailed) {
9319 assert(Args.size() == 1 &&
9320 "List construction from other than 1 argument.");
9321 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9322 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9323 }
9324
9325 // FIXME: Using "DestType" for the entity we're printing is probably
9326 // bad.
9327 switch (FailedOverloadResult) {
9328 case OR_Ambiguous:
9329 FailedCandidateSet.NoteCandidates(
9330 PartialDiagnosticAt(Kind.getLocation(),
9331 S.PDiag(diag::err_ovl_ambiguous_init)
9332 << DestType << ArgsRange),
9333 S, OCD_AmbiguousCandidates, Args);
9334 break;
9335
9337 if (Kind.getKind() == InitializationKind::IK_Default &&
9338 (Entity.getKind() == InitializedEntity::EK_Base ||
9342 // This is implicit default initialization of a member or
9343 // base within a constructor. If no viable function was
9344 // found, notify the user that they need to explicitly
9345 // initialize this base/member.
9348 const CXXRecordDecl *InheritedFrom = nullptr;
9349 if (auto Inherited = Constructor->getInheritedConstructor())
9350 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9351 if (Entity.getKind() == InitializedEntity::EK_Base) {
9352 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9353 << (InheritedFrom ? 2
9354 : Constructor->isImplicit() ? 1
9355 : 0)
9356 << S.Context.getCanonicalTagType(Constructor->getParent())
9357 << /*base=*/0 << Entity.getType() << InheritedFrom;
9358
9359 auto *BaseDecl =
9361 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9362 << S.Context.getCanonicalTagType(BaseDecl);
9363 } else {
9364 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9365 << (InheritedFrom ? 2
9366 : Constructor->isImplicit() ? 1
9367 : 0)
9368 << S.Context.getCanonicalTagType(Constructor->getParent())
9369 << /*member=*/1 << Entity.getName() << InheritedFrom;
9370 S.Diag(Entity.getDecl()->getLocation(),
9371 diag::note_member_declared_at);
9372
9373 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9374 S.Diag(Record->getDecl()->getLocation(), diag::note_previous_decl)
9375 << S.Context.getCanonicalTagType(Record->getDecl());
9376 }
9377 break;
9378 }
9379
9380 FailedCandidateSet.NoteCandidates(
9382 Kind.getLocation(),
9383 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9384 << DestType << ArgsRange),
9385 S, OCD_AllCandidates, Args);
9386 break;
9387
9388 case OR_Deleted: {
9391 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9392 if (Ovl != OR_Deleted) {
9393 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9394 << DestType << ArgsRange;
9395 llvm_unreachable("Inconsistent overload resolution?");
9396 break;
9397 }
9398
9399 // If this is a defaulted or implicitly-declared function, then
9400 // it was implicitly deleted. Make it clear that the deletion was
9401 // implicit.
9402 if (S.isImplicitlyDeleted(Best->Function))
9403 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9404 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9405 << DestType << ArgsRange;
9406 else {
9407 StringLiteral *Msg = Best->Function->getDeletedMessage();
9408 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9409 << DestType << (Msg != nullptr)
9410 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9411 }
9412
9413 // If it's a default constructed member, but it's not in the
9414 // constructor's initializer list, explicitly note where the member is
9415 // declared so the user can see which member is erroneously initialized
9416 // with a deleted default constructor.
9417 if (Kind.getKind() == InitializationKind::IK_Default &&
9420 S.Diag(Entity.getDecl()->getLocation(),
9421 diag::note_default_constructed_field)
9422 << Entity.getDecl();
9423 }
9424 S.NoteDeletedFunction(Best->Function);
9425 break;
9426 }
9427
9428 case OR_Success:
9429 llvm_unreachable("Conversion did not fail!");
9430 }
9431 }
9432 break;
9433
9435 if (Entity.getKind() == InitializedEntity::EK_Member &&
9437 // This is implicit default-initialization of a const member in
9438 // a constructor. Complain that it needs to be explicitly
9439 // initialized.
9441 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9442 << (Constructor->getInheritedConstructor() ? 2
9443 : Constructor->isImplicit() ? 1
9444 : 0)
9445 << S.Context.getCanonicalTagType(Constructor->getParent())
9446 << /*const=*/1 << Entity.getName();
9447 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9448 << Entity.getName();
9449 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9450 VD && VD->isConstexpr()) {
9451 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9452 << VD;
9453 } else {
9454 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9455 << DestType << DestType->isRecordType();
9456 }
9457 break;
9458
9459 case FK_Incomplete:
9460 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9461 diag::err_init_incomplete_type);
9462 break;
9463
9465 // Run the init list checker again to emit diagnostics.
9466 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9467 diagnoseListInit(S, Entity, InitList);
9468 break;
9469 }
9470
9471 case FK_PlaceholderType: {
9472 // FIXME: Already diagnosed!
9473 break;
9474 }
9475
9477 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9478 // allows us to diagnose the failure when it happens in the
9479 // TryListInitialization call instead of delaying the diagnosis, which is
9480 // beneficial because the flattening is also expensive.
9481 break;
9482 }
9483
9485 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9486 << Args[0]->getSourceRange();
9489 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9490 (void)Ovl;
9491 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9492 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9493 S.Diag(CtorDecl->getLocation(),
9494 diag::note_explicit_ctor_deduction_guide_here) << false;
9495 break;
9496 }
9497
9499 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9500 /*VerifyOnly=*/false);
9501 break;
9502
9504 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9505 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9506 << Entity.getType() << InitList->getSourceRange();
9507 break;
9508 }
9509
9510 PrintInitLocationNote(S, Entity);
9511 return true;
9512}
9513
9514void InitializationSequence::dump(raw_ostream &OS) const {
9515 switch (SequenceKind) {
9516 case FailedSequence: {
9517 OS << "Failed sequence: ";
9518 switch (Failure) {
9520 OS << "too many initializers for reference";
9521 break;
9522
9524 OS << "parenthesized list init for reference";
9525 break;
9526
9528 OS << "array requires initializer list";
9529 break;
9530
9532 OS << "address of unaddressable function was taken";
9533 break;
9534
9536 OS << "array requires initializer list or string literal";
9537 break;
9538
9540 OS << "array requires initializer list or wide string literal";
9541 break;
9542
9544 OS << "narrow string into wide char array";
9545 break;
9546
9548 OS << "wide string into char array";
9549 break;
9550
9552 OS << "incompatible wide string into wide char array";
9553 break;
9554
9556 OS << "plain string literal into char8_t array";
9557 break;
9558
9560 OS << "u8 string literal into char array";
9561 break;
9562
9564 OS << "array type mismatch";
9565 break;
9566
9568 OS << "non-constant array initializer";
9569 break;
9570
9572 OS << "address of overloaded function failed";
9573 break;
9574
9576 OS << "overload resolution for reference initialization failed";
9577 break;
9578
9580 OS << "non-const lvalue reference bound to temporary";
9581 break;
9582
9584 OS << "non-const lvalue reference bound to bit-field";
9585 break;
9586
9588 OS << "non-const lvalue reference bound to vector element";
9589 break;
9590
9592 OS << "non-const lvalue reference bound to matrix element";
9593 break;
9594
9596 OS << "non-const lvalue reference bound to unrelated type";
9597 break;
9598
9600 OS << "rvalue reference bound to an lvalue";
9601 break;
9602
9604 OS << "reference initialization drops qualifiers";
9605 break;
9606
9608 OS << "reference with mismatching address space bound to temporary";
9609 break;
9610
9612 OS << "reference initialization failed";
9613 break;
9614
9616 OS << "conversion failed";
9617 break;
9618
9620 OS << "conversion from property failed";
9621 break;
9622
9624 OS << "too many initializers for scalar";
9625 break;
9626
9628 OS << "parenthesized list init for reference";
9629 break;
9630
9632 OS << "referencing binding to initializer list";
9633 break;
9634
9636 OS << "initializer list for non-aggregate, non-scalar type";
9637 break;
9638
9640 OS << "overloading failed for user-defined conversion";
9641 break;
9642
9644 OS << "constructor overloading failed";
9645 break;
9646
9648 OS << "default initialization of a const variable";
9649 break;
9650
9651 case FK_Incomplete:
9652 OS << "initialization of incomplete type";
9653 break;
9654
9656 OS << "list initialization checker failure";
9657 break;
9658
9660 OS << "variable length array has an initializer";
9661 break;
9662
9663 case FK_PlaceholderType:
9664 OS << "initializer expression isn't contextually valid";
9665 break;
9666
9668 OS << "list constructor overloading failed";
9669 break;
9670
9672 OS << "list copy initialization chose explicit constructor";
9673 break;
9674
9676 OS << "parenthesized list initialization failed";
9677 break;
9678
9680 OS << "designated initializer for non-aggregate type";
9681 break;
9682
9684 OS << "HLSL initialization list flattening failed";
9685 break;
9686 }
9687 OS << '\n';
9688 return;
9689 }
9690
9691 case DependentSequence:
9692 OS << "Dependent sequence\n";
9693 return;
9694
9695 case NormalSequence:
9696 OS << "Normal sequence: ";
9697 break;
9698 }
9699
9700 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9701 if (S != step_begin()) {
9702 OS << " -> ";
9703 }
9704
9705 switch (S->Kind) {
9707 OS << "resolve address of overloaded function";
9708 break;
9709
9711 OS << "derived-to-base (prvalue)";
9712 break;
9713
9715 OS << "derived-to-base (xvalue)";
9716 break;
9717
9719 OS << "derived-to-base (lvalue)";
9720 break;
9721
9722 case SK_BindReference:
9723 OS << "bind reference to lvalue";
9724 break;
9725
9727 OS << "bind reference to a temporary";
9728 break;
9729
9730 case SK_FinalCopy:
9731 OS << "final copy in class direct-initialization";
9732 break;
9733
9735 OS << "extraneous C++03 copy to temporary";
9736 break;
9737
9738 case SK_UserConversion:
9739 OS << "user-defined conversion via " << *S->Function.Function;
9740 break;
9741
9743 OS << "qualification conversion (prvalue)";
9744 break;
9745
9747 OS << "qualification conversion (xvalue)";
9748 break;
9749
9751 OS << "qualification conversion (lvalue)";
9752 break;
9753
9755 OS << "function reference conversion";
9756 break;
9757
9759 OS << "non-atomic-to-atomic conversion";
9760 break;
9761
9763 OS << "implicit conversion sequence (";
9764 S->ICS->dump(); // FIXME: use OS
9765 OS << ")";
9766 break;
9767
9769 OS << "implicit conversion sequence with narrowing prohibited (";
9770 S->ICS->dump(); // FIXME: use OS
9771 OS << ")";
9772 break;
9773
9775 OS << "list aggregate initialization";
9776 break;
9777
9778 case SK_UnwrapInitList:
9779 OS << "unwrap reference initializer list";
9780 break;
9781
9782 case SK_RewrapInitList:
9783 OS << "rewrap reference initializer list";
9784 break;
9785
9787 OS << "constructor initialization";
9788 break;
9789
9791 OS << "list initialization via constructor";
9792 break;
9793
9795 OS << "zero initialization";
9796 break;
9797
9798 case SK_CAssignment:
9799 OS << "C assignment";
9800 break;
9801
9802 case SK_StringInit:
9803 OS << "string initialization";
9804 break;
9805
9807 OS << "Objective-C object conversion";
9808 break;
9809
9810 case SK_ArrayLoopIndex:
9811 OS << "indexing for array initialization loop";
9812 break;
9813
9814 case SK_ArrayLoopInit:
9815 OS << "array initialization loop";
9816 break;
9817
9818 case SK_ArrayInit:
9819 OS << "array initialization";
9820 break;
9821
9822 case SK_GNUArrayInit:
9823 OS << "array initialization (GNU extension)";
9824 break;
9825
9827 OS << "parenthesized array initialization";
9828 break;
9829
9831 OS << "pass by indirect copy and restore";
9832 break;
9833
9835 OS << "pass by indirect restore";
9836 break;
9837
9839 OS << "Objective-C object retension";
9840 break;
9841
9843 OS << "std::initializer_list from initializer list";
9844 break;
9845
9847 OS << "list initialization from std::initializer_list";
9848 break;
9849
9850 case SK_OCLSamplerInit:
9851 OS << "OpenCL sampler_t from integer constant";
9852 break;
9853
9855 OS << "OpenCL opaque type from zero";
9856 break;
9858 OS << "initialization from a parenthesized list of values";
9859 break;
9860 }
9861
9862 OS << " [" << S->Type << ']';
9863 }
9864
9865 OS << '\n';
9866}
9867
9869 dump(llvm::errs());
9870}
9871
9873 const ImplicitConversionSequence &ICS,
9874 QualType PreNarrowingType,
9875 QualType EntityType,
9876 const Expr *PostInit) {
9877 const StandardConversionSequence *SCS = nullptr;
9878 switch (ICS.getKind()) {
9880 SCS = &ICS.Standard;
9881 break;
9883 SCS = &ICS.UserDefined.After;
9884 break;
9889 return;
9890 }
9891
9892 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9893 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9894 unsigned DiagID;
9895 auto &L = S.getLangOpts();
9896 if (L.CPlusPlus11 && !L.HLSL &&
9897 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
9898 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9899 else
9900 DiagID = WarnDiagID;
9901 return S.Diag(PostInit->getBeginLoc(), DiagID)
9902 << PostInit->getSourceRange();
9903 };
9904
9905 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9906 APValue ConstantValue;
9907 QualType ConstantType;
9908 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9909 ConstantType)) {
9910 case NK_Not_Narrowing:
9912 // No narrowing occurred.
9913 return;
9914
9915 case NK_Type_Narrowing: {
9916 // This was a floating-to-integer conversion, which is always considered a
9917 // narrowing conversion even if the value is a constant and can be
9918 // represented exactly as an integer.
9919 QualType T = EntityType.getNonReferenceType();
9920 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9921 diag::ext_init_list_type_narrowing_const_reference,
9922 diag::warn_init_list_type_narrowing)
9923 << PreNarrowingType.getLocalUnqualifiedType()
9925 break;
9926 }
9927
9928 case NK_Constant_Narrowing: {
9929 // A constant value was narrowed.
9930 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9931 diag::ext_init_list_constant_narrowing,
9932 diag::ext_init_list_constant_narrowing_const_reference,
9933 diag::warn_init_list_constant_narrowing)
9934 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9936 break;
9937 }
9938
9939 case NK_Variable_Narrowing: {
9940 // A variable's value may have been narrowed.
9941 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9942 diag::ext_init_list_variable_narrowing,
9943 diag::ext_init_list_variable_narrowing_const_reference,
9944 diag::warn_init_list_variable_narrowing)
9945 << PreNarrowingType.getLocalUnqualifiedType()
9947 break;
9948 }
9949 }
9950
9951 SmallString<128> StaticCast;
9952 llvm::raw_svector_ostream OS(StaticCast);
9953 OS << "static_cast<";
9954 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9955 // It's important to use the typedef's name if there is one so that the
9956 // fixit doesn't break code using types like int64_t.
9957 //
9958 // FIXME: This will break if the typedef requires qualification. But
9959 // getQualifiedNameAsString() includes non-machine-parsable components.
9960 OS << *TT->getDecl();
9961 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9962 OS << BT->getName(S.getLangOpts());
9963 else {
9964 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9965 // with a broken cast.
9966 return;
9967 }
9968 OS << ">(";
9969 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9970 << PostInit->getSourceRange()
9971 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9973 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9974}
9975
9977 QualType ToType, Expr *Init) {
9978 assert(S.getLangOpts().C23);
9980 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
9981 Sema::AllowedExplicit::None,
9982 /*InOverloadResolution*/ false,
9983 /*CStyle*/ false,
9984 /*AllowObjCWritebackConversion=*/false);
9985
9986 if (!ICS.isStandard())
9987 return;
9988
9989 APValue Value;
9990 QualType PreNarrowingType;
9991 // Reuse C++ narrowing check.
9992 switch (ICS.Standard.getNarrowingKind(
9993 S.Context, Init, Value, PreNarrowingType,
9994 /*IgnoreFloatToIntegralConversion*/ false)) {
9995 // The value doesn't fit.
9997 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
9998 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
9999 return;
10000
10001 // Conversion to a narrower type.
10002 case NK_Type_Narrowing:
10003 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10004 << ToType << FromType;
10005 return;
10006
10007 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10008 // not really interested in these cases.
10011 case NK_Not_Narrowing:
10012 return;
10013 }
10014 llvm_unreachable("unhandled case in switch");
10015}
10016
10018 Sema &SemaRef, QualType &TT) {
10019 assert(SemaRef.getLangOpts().C23);
10020 // character that string literal contains fits into TT - target type.
10021 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10022 QualType CharType = AT->getElementType();
10023 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10024 bool isUnsigned = CharType->isUnsignedIntegerType();
10025 llvm::APSInt Value(BitWidth, isUnsigned);
10026 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10027 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10028 Value = C;
10029 if (Value != C) {
10030 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10031 diag::err_c23_constexpr_init_not_representable)
10032 << C << CharType;
10033 return;
10034 }
10035 }
10036}
10037
10038//===----------------------------------------------------------------------===//
10039// Initialization helper functions
10040//===----------------------------------------------------------------------===//
10041bool
10043 ExprResult Init) {
10044 if (Init.isInvalid())
10045 return false;
10046
10047 Expr *InitE = Init.get();
10048 assert(InitE && "No initialization expression");
10049
10050 InitializationKind Kind =
10052 InitializationSequence Seq(*this, Entity, Kind, InitE);
10053 return !Seq.Failed();
10054}
10055
10058 SourceLocation EqualLoc,
10060 bool TopLevelOfInitList,
10061 bool AllowExplicit) {
10062 if (Init.isInvalid())
10063 return ExprError();
10064
10065 Expr *InitE = Init.get();
10066 assert(InitE && "No initialization expression?");
10067
10068 if (EqualLoc.isInvalid())
10069 EqualLoc = InitE->getBeginLoc();
10070
10071 if (Entity.getType().getDesugaredType(Context) ==
10072 Context.AMDGPUFeaturePredicateTy &&
10073 Entity.getDecl()) {
10074 Diag(EqualLoc, diag::err_amdgcn_predicate_type_is_not_constructible)
10075 << Entity.getDecl();
10076 return ExprError();
10077 }
10078
10080 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10081 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10082
10083 // Prevent infinite recursion when performing parameter copy-initialization.
10084 const bool ShouldTrackCopy =
10085 Entity.isParameterKind() && Seq.isConstructorInitialization();
10086 if (ShouldTrackCopy) {
10087 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10088 Seq.SetOverloadFailure(
10091
10092 // Try to give a meaningful diagnostic note for the problematic
10093 // constructor.
10094 const auto LastStep = Seq.step_end() - 1;
10095 assert(LastStep->Kind ==
10097 const FunctionDecl *Function = LastStep->Function.Function;
10098 auto Candidate =
10099 llvm::find_if(Seq.getFailedCandidateSet(),
10100 [Function](const OverloadCandidate &Candidate) -> bool {
10101 return Candidate.Viable &&
10102 Candidate.Function == Function &&
10103 Candidate.Conversions.size() > 0;
10104 });
10105 if (Candidate != Seq.getFailedCandidateSet().end() &&
10106 Function->getNumParams() > 0) {
10107 Candidate->Viable = false;
10110 InitE,
10111 Function->getParamDecl(0)->getType());
10112 }
10113 }
10114 CurrentParameterCopyTypes.push_back(Entity.getType());
10115 }
10116
10117 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10118
10119 if (ShouldTrackCopy)
10120 CurrentParameterCopyTypes.pop_back();
10121
10122 return Result;
10123}
10124
10125/// Determine whether RD is, or is derived from, a specialization of CTD.
10127 ClassTemplateDecl *CTD) {
10128 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10129 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10130 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10131 };
10132 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10133}
10134
10136 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10137 const InitializationKind &Kind, MultiExprArg Inits) {
10138 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10139 TSInfo->getType()->getContainedDeducedType());
10140 assert(DeducedTST && "not a deduced template specialization type");
10141
10142 auto TemplateName = DeducedTST->getTemplateName();
10144 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10145
10146 // We can only perform deduction for class templates or alias templates.
10147 auto *Template =
10148 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10149 TemplateDecl *LookupTemplateDecl = Template;
10150 if (!Template) {
10151 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10153 DiagCompat(Kind.getLocation(), diag_compat::ctad_for_alias_templates);
10154 LookupTemplateDecl = AliasTemplate;
10155 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10156 ->getUnderlyingType()
10157 .getCanonicalType();
10158 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10159 // of the form
10160 // [typename] [nested-name-specifier] [template] simple-template-id
10161 if (const auto *TST =
10162 UnderlyingType->getAs<TemplateSpecializationType>()) {
10163 Template = dyn_cast_or_null<ClassTemplateDecl>(
10164 TST->getTemplateName().getAsTemplateDecl());
10165 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10166 // Cases where template arguments in the RHS of the alias are not
10167 // dependent. e.g.
10168 // using AliasFoo = Foo<bool>;
10169 if (const auto *CTSD =
10170 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
10171 Template = CTSD->getSpecializedTemplate();
10172 }
10173 }
10174 }
10175 if (!Template) {
10176 Diag(Kind.getLocation(),
10177 diag::err_deduced_non_class_or_alias_template_specialization_type)
10179 if (auto *TD = TemplateName.getAsTemplateDecl())
10181 return QualType();
10182 }
10183
10184 // Can't deduce from dependent arguments.
10186 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10187 diag::warn_cxx14_compat_class_template_argument_deduction)
10188 << TSInfo->getTypeLoc().getSourceRange() << 0;
10189 return SubstAutoTypeSourceInfoDependent(TSInfo)->getType();
10190 }
10191
10192 // FIXME: Perform "exact type" matching first, per CWG discussion?
10193 // Or implement this via an implied 'T(T) -> T' deduction guide?
10194
10195 // Look up deduction guides, including those synthesized from constructors.
10196 //
10197 // C++1z [over.match.class.deduct]p1:
10198 // A set of functions and function templates is formed comprising:
10199 // - For each constructor of the class template designated by the
10200 // template-name, a function template [...]
10201 // - For each deduction-guide, a function or function template [...]
10202 DeclarationNameInfo NameInfo(
10203 Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),
10204 TSInfo->getTypeLoc().getEndLoc());
10205 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10206 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10207
10208 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10209 // clear on this, but they're not found by name so access does not apply.
10210 Guides.suppressDiagnostics();
10211
10212 // Figure out if this is list-initialization.
10214 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10215 ? dyn_cast<InitListExpr>(Inits[0])
10216 : nullptr;
10217
10218 // C++1z [over.match.class.deduct]p1:
10219 // Initialization and overload resolution are performed as described in
10220 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10221 // (as appropriate for the type of initialization performed) for an object
10222 // of a hypothetical class type, where the selected functions and function
10223 // templates are considered to be the constructors of that class type
10224 //
10225 // Since we know we're initializing a class type of a type unrelated to that
10226 // of the initializer, this reduces to something fairly reasonable.
10227 OverloadCandidateSet Candidates(Kind.getLocation(),
10230
10231 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10232
10233 // Return true if the candidate is added successfully, false otherwise.
10234 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10236 DeclAccessPair FoundDecl,
10237 bool OnlyListConstructors,
10238 bool AllowAggregateDeductionCandidate) {
10239 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10240 // For copy-initialization, the candidate functions are all the
10241 // converting constructors (12.3.1) of that class.
10242 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10243 // The converting constructors of T are candidate functions.
10244 if (!AllowExplicit) {
10245 // Overload resolution checks whether the deduction guide is declared
10246 // explicit for us.
10247
10248 // When looking for a converting constructor, deduction guides that
10249 // could never be called with one argument are not interesting to
10250 // check or note.
10251 if (GD->getMinRequiredArguments() > 1 ||
10252 (GD->getNumParams() == 0 && !GD->isVariadic()))
10253 return;
10254 }
10255
10256 // C++ [over.match.list]p1.1: (first phase list initialization)
10257 // Initially, the candidate functions are the initializer-list
10258 // constructors of the class T
10259 if (OnlyListConstructors && !isInitListConstructor(GD))
10260 return;
10261
10262 if (!AllowAggregateDeductionCandidate &&
10263 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10264 return;
10265
10266 // C++ [over.match.list]p1.2: (second phase list initialization)
10267 // the candidate functions are all the constructors of the class T
10268 // C++ [over.match.ctor]p1: (all other cases)
10269 // the candidate functions are all the constructors of the class of
10270 // the object being initialized
10271
10272 // C++ [over.best.ics]p4:
10273 // When [...] the constructor [...] is a candidate by
10274 // - [over.match.copy] (in all cases)
10275 if (TD) {
10276
10277 // As template candidates are not deduced immediately,
10278 // persist the array in the overload set.
10279 MutableArrayRef<Expr *> TmpInits =
10280 Candidates.getPersistentArgsArray(Inits.size());
10281
10282 for (auto [I, E] : llvm::enumerate(Inits)) {
10283 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10284 TmpInits[I] = DI->getInit();
10285 else
10286 TmpInits[I] = E;
10287 }
10288
10290 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10291 /*SuppressUserConversions=*/false,
10292 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10293 /*PO=*/{}, AllowAggregateDeductionCandidate);
10294 } else {
10295 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10296 /*SuppressUserConversions=*/false,
10297 /*PartialOverloading=*/false, AllowExplicit);
10298 }
10299 };
10300
10301 bool FoundDeductionGuide = false;
10302
10303 auto TryToResolveOverload =
10304 [&](bool OnlyListConstructors) -> OverloadingResult {
10306 bool HasAnyDeductionGuide = false;
10307
10308 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10309 auto *Pattern = Template;
10310 while (Pattern->getInstantiatedFromMemberTemplate()) {
10311 if (Pattern->isMemberSpecialization())
10312 break;
10313 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10314 }
10315
10316 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10317 if (!(RD->getDefinition() && RD->isAggregate()))
10318 return;
10319 QualType Ty = Context.getCanonicalTagType(RD);
10320 SmallVector<QualType, 8> ElementTypes;
10321
10322 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10323 if (!CheckInitList.HadError()) {
10324 // C++ [over.match.class.deduct]p1.8:
10325 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10326 // rvalue reference to the declared type of e_i and
10327 // C++ [over.match.class.deduct]p1.9:
10328 // if e_i is of array type and x_i is a string-literal, T_i is an
10329 // lvalue reference to the const-qualified declared type of e_i and
10330 // C++ [over.match.class.deduct]p1.10:
10331 // otherwise, T_i is the declared type of e_i
10332 for (int I = 0, E = ListInit->getNumInits();
10333 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10334 if (ElementTypes[I]->isArrayType()) {
10336 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10337 else if (isa<StringLiteral>(
10338 ListInit->getInit(I)->IgnoreParenImpCasts()))
10339 ElementTypes[I] =
10340 Context.getLValueReferenceType(ElementTypes[I].withConst());
10341 }
10342
10343 if (CXXDeductionGuideDecl *GD =
10345 LookupTemplateDecl, ElementTypes,
10346 TSInfo->getTypeLoc().getEndLoc())) {
10347 auto *TD = GD->getDescribedFunctionTemplate();
10348 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10349 OnlyListConstructors,
10350 /*AllowAggregateDeductionCandidate=*/true);
10351 HasAnyDeductionGuide = true;
10352 }
10353 }
10354 };
10355
10356 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10357 NamedDecl *D = (*I)->getUnderlyingDecl();
10358 if (D->isInvalidDecl())
10359 continue;
10360
10361 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10362 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10363 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10364 if (!GD)
10365 continue;
10366
10367 if (!GD->isImplicit())
10368 HasAnyDeductionGuide = true;
10369
10370 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10371 /*AllowAggregateDeductionCandidate=*/false);
10372 }
10373
10374 // C++ [over.match.class.deduct]p1.4:
10375 // if C is defined and its definition satisfies the conditions for an
10376 // aggregate class ([dcl.init.aggr]) with the assumption that any
10377 // dependent base class has no virtual functions and no virtual base
10378 // classes, and the initializer is a non-empty braced-init-list or
10379 // parenthesized expression-list, and there are no deduction-guides for
10380 // C, the set contains an additional function template, called the
10381 // aggregate deduction candidate, defined as follows.
10382 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10383 if (ListInit && ListInit->getNumInits()) {
10384 SynthesizeAggrGuide(ListInit);
10385 } else if (Inits.size()) { // parenthesized expression-list
10386 // Inits are expressions inside the parentheses. We don't have
10387 // the parentheses source locations, use the begin/end of Inits as the
10388 // best heuristic.
10389 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10390 Inits, Inits.back()->getEndLoc());
10391 SynthesizeAggrGuide(&TempListInit);
10392 }
10393 }
10394
10395 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10396
10397 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10398 };
10399
10401
10402 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10403 // try initializer-list constructors.
10404 if (ListInit) {
10405 bool TryListConstructors = true;
10406
10407 // Try list constructors unless the list is empty and the class has one or
10408 // more default constructors, in which case those constructors win.
10409 if (!ListInit->getNumInits()) {
10410 for (NamedDecl *D : Guides) {
10411 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10412 if (FD && FD->getMinRequiredArguments() == 0) {
10413 TryListConstructors = false;
10414 break;
10415 }
10416 }
10417 } else if (ListInit->getNumInits() == 1) {
10418 // C++ [over.match.class.deduct]:
10419 // As an exception, the first phase in [over.match.list] (considering
10420 // initializer-list constructors) is omitted if the initializer list
10421 // consists of a single expression of type cv U, where U is a
10422 // specialization of C or a class derived from a specialization of C.
10423 Expr *E = ListInit->getInit(0);
10424 auto *RD = E->getType()->getAsCXXRecordDecl();
10425 if (!isa<InitListExpr>(E) && RD &&
10426 isCompleteType(Kind.getLocation(), E->getType()) &&
10428 TryListConstructors = false;
10429 }
10430
10431 if (TryListConstructors)
10432 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10433 // Then unwrap the initializer list and try again considering all
10434 // constructors.
10435 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10436 }
10437
10438 // If list-initialization fails, or if we're doing any other kind of
10439 // initialization, we (eventually) consider constructors.
10441 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10442
10443 switch (Result) {
10444 case OR_Ambiguous:
10445 // FIXME: For list-initialization candidates, it'd usually be better to
10446 // list why they were not viable when given the initializer list itself as
10447 // an argument.
10448 Candidates.NoteCandidates(
10450 Kind.getLocation(),
10451 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10452 << TemplateName),
10454 return QualType();
10455
10456 case OR_No_Viable_Function: {
10457 CXXRecordDecl *Primary =
10458 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10459 bool Complete = isCompleteType(Kind.getLocation(),
10460 Context.getCanonicalTagType(Primary));
10461 Candidates.NoteCandidates(
10463 Kind.getLocation(),
10464 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10465 : diag::err_deduced_class_template_incomplete)
10466 << TemplateName << !Guides.empty()),
10467 *this, OCD_AllCandidates, Inits);
10468 return QualType();
10469 }
10470
10471 case OR_Deleted: {
10472 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10473 // like we ever get here; attempts to trigger this seem to yield a
10474 // generic c'all to deleted function' diagnostic instead.
10475 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10476 << TemplateName;
10477 NoteDeletedFunction(Best->Function);
10478 return QualType();
10479 }
10480
10481 case OR_Success:
10482 // C++ [over.match.list]p1:
10483 // In copy-list-initialization, if an explicit constructor is chosen, the
10484 // initialization is ill-formed.
10485 if (Kind.isCopyInit() && ListInit &&
10486 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10487 bool IsDeductionGuide = !Best->Function->isImplicit();
10488 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10489 << TemplateName << IsDeductionGuide;
10490 Diag(Best->Function->getLocation(),
10491 diag::note_explicit_ctor_deduction_guide_here)
10492 << IsDeductionGuide;
10493 return QualType();
10494 }
10495
10496 // Make sure we didn't select an unusable deduction guide, and mark it
10497 // as referenced.
10498 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
10499 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10500 break;
10501 }
10502
10503 // C++ [dcl.type.class.deduct]p1:
10504 // The placeholder is replaced by the return type of the function selected
10505 // by overload resolution for class template deduction.
10506 QualType DeducedType =
10507 SubstAutoTypeSourceInfo(TSInfo, Best->Function->getReturnType())
10508 ->getType();
10509 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10510 diag::warn_cxx14_compat_class_template_argument_deduction)
10511 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10512
10513 // Warn if CTAD was used on a type that does not have any user-defined
10514 // deduction guides.
10515 if (!FoundDeductionGuide) {
10516 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10517 diag::warn_ctad_maybe_unsupported)
10518 << TemplateName;
10519 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10520 }
10521
10522 return DeducedType;
10523}
Defines the clang::ASTContext interface.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
static bool isRValueRef(QualType ParamType)
Definition Consumed.cpp:178
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
#define SM(sm)
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:562
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:508
bool isLValue() const
Definition APValue.h:490
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
bool isNullPointer() const
Definition APValue.cpp:1051
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
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:959
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType OverloadTy
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType OCLSamplerTy
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:924
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6022
Represents a loop initializing the elements of an array.
Definition Expr.h:5969
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3777
QualType getElementType() const
Definition TypeBase.h:3789
This class is used for builtin types like 'int'.
Definition TypeBase.h:3219
Kind getKind() const
Definition TypeBase.h:3267
Represents a base class of a C++ class.
Definition DeclCXX.h:146
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2860
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2697
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3071
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2952
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2988
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:1983
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2005
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:1397
CXXBaseSpecifier * base_class_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:517
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition DeclCXX.h:605
base_class_range bases()
Definition DeclCXX.h:608
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
llvm::iterator_range< base_class_iterator > base_class_range
Definition DeclCXX.h:604
bool forallBases(ForallBasesCallback BaseMatches) const
Determines if the given callback holds for all the direct or indirect base classes of this type.
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
static CXXTemporaryObjectExpr * Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef< Expr * > Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization)
Definition ExprCXX.cpp:1148
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
bool isCallToStdMove() const
Definition Expr.cpp:3642
Expr * getCallee()
Definition Expr.h:3093
SourceLocation getRParenLoc() const
Definition Expr.h:3277
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
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:4394
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3815
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3891
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4464
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:2251
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
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:2386
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
ValueDecl * getDecl()
Definition Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:460
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
Represents a single C99 designator.
Definition Expr.h:5595
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:5757
void setFieldDecl(FieldDecl *FD)
Definition Expr.h:5693
FieldDecl * getFieldDecl() const
Definition Expr.h:5686
SourceLocation getFieldLoc() const
Definition Expr.h:5703
const IdentifierInfo * getFieldName() const
Definition Expr.cpp:4786
SourceLocation getDotLoc() const
Definition Expr.h:5698
SourceLocation getLBracketLoc() const
Definition Expr.h:5739
Represents a C99 designated initializer expression.
Definition Expr.h:5552
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition Expr.h:5812
Expr * getArrayRangeEnd(const Designator &D) const
Definition Expr.cpp:4895
Expr * getSubExpr(unsigned Idx) const
Definition Expr.h:5834
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition Expr.h:5816
Expr * getArrayRangeStart(const Designator &D) const
Definition Expr.cpp:4890
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:4902
MutableArrayRef< Designator > designators()
Definition Expr.h:5785
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4885
Designator * getDesignator(unsigned Idx)
Definition Expr.h:5793
Expr * getInit() const
Retrieve the initializer value.
Definition Expr.h:5820
unsigned size() const
Returns the number of designators in this initializer.
Definition Expr.h:5782
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4864
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4881
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition Expr.h:5807
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition Expr.h:5832
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition Expr.cpp:4827
InitListExpr * getUpdater() const
Definition Expr.h:5937
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:960
Represents a reference to emded data.
Definition Expr.h:5129
StringLiteral * getDataStringLiteral() const
Definition Expr.h:5146
EmbedDataStorage * getData() const
Definition Expr.h:5148
SourceLocation getLocation() const
Definition Expr.h:5142
size_t getDataElementCount() const
Definition Expr.h:5151
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:4256
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4283
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:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
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:3339
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3688
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3070
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:3253
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:4068
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
bool refersToMatrixElement() const
Returns whether this expression refers to a matrix element.
Definition Expr.h:517
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3178
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3358
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4821
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3263
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition Decl.h:3284
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
Represents a function declaration or definition.
Definition Decl.h:2018
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3842
QualType getReturnType() const
Definition Decl.h:2863
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3821
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:2073
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:827
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6058
Represents a C array with an unspecified size.
Definition TypeBase.h:3964
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3485
chain_iterator chain_end() const
Definition Decl.h:3508
chain_iterator chain_begin() const
Definition Decl.h:3507
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition Decl.h:3504
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition Expr.h:5412
void setSyntacticForm(InitListExpr *Init)
Definition Expr.h:5477
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition Expr.h:5374
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5415
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2462
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2422
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5426
unsigned getNumInits() const
Definition Expr.h:5332
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2496
void setInit(unsigned Init, Expr *expr)
Definition Expr.h:5364
SourceLocation getLBraceLoc() const
Definition Expr.h:5461
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:2426
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2438
InitListExpr * getSyntacticForm() const
Definition Expr.h:5473
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5402
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5336
SourceLocation getRBraceLoc() const
Definition Expr.h:5463
InitListExpr * getSemanticForm() const
Definition Expr.h:5467
const Expr * getInit(unsigned Init) const
Definition Expr.h:5354
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition Expr.cpp:2485
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2514
void setInitializedFieldInUnion(FieldDecl *FD)
Definition Expr.h:5432
bool isSyntacticForm() const
Definition Expr.h:5470
void setRBraceLoc(SourceLocation Loc)
Definition Expr.h:5464
ArrayRef< Expr * > inits() const
Definition Expr.h:5352
void sawArrayRangeDesignator(bool ARD=true)
Definition Expr.h:5487
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5345
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 initialization list flattening failed.
@ FK_PlaceholderType
Initializer has a placeholder type which cannot be resolved by initialization.
@ FK_IncompatWideStringIntoWideChar
Initializing wide char array with incompatible wide string literal.
@ FK_NonConstLValueReferenceBindingToMatrixElement
Non-const lvalue reference binding to a matrix element.
@ FK_TooManyInitsForReference
Too many initializers provided for a reference.
@ FK_NonConstLValueReferenceBindingToBitfield
Non-const lvalue reference binding to a bit-field.
@ FK_ReferenceAddrspaceMismatchTemporary
Reference with mismatching address space binding to temporary.
@ FK_ListInitializationFailed
List initialization failed at some point.
@ FK_TooManyInitsForScalar
Too many initializers for scalar.
@ FK_AddressOfOverloadFailed
Cannot resolve the address of an overloaded function.
@ FK_VariableLengthArrayHasInitializer
Variable-length array must not have an initializer.
@ FK_ArrayNeedsInitListOrWideStringLiteral
Array must be initialized with an initializer list or a wide string literal.
@ FK_RValueReferenceBindingToLValue
Rvalue reference binding to an lvalue.
@ FK_Incomplete
Initialization of an incomplete type.
@ FK_WideStringIntoCharArray
Initializing char array with wide string literal.
@ FK_ExplicitConstructor
List-copy-initialization chose an explicit constructor.
@ FK_ReferenceInitOverloadFailed
Overloading due to reference initialization failed.
@ FK_ConstructorOverloadFailed
Overloading for initialization by constructor failed.
@ FK_ReferenceBindingToInitList
Reference initialization from an initializer list.
@ FK_DefaultInitOfConst
Default-initialization of a 'const' object.
@ FK_ParenthesizedListInitFailed
Parenthesized list initialization failed at some point.
@ FK_AddressOfUnaddressableFunction
Trying to take the address of a function that doesn't support having its address taken.
@ FK_UTF8StringIntoPlainChar
Initializing char array with UTF-8 string literal.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
void AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates)
Add a new step in the initialization that resolves the address of an overloaded function to a specifi...
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
SmallVectorImpl< Step >::const_iterator step_iterator
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
VD Variable
When Kind == EK_Variable, EK_Member, EK_Binding, or EK_TemplateParameter, the variable,...
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a member subobject.
EntityKind getKind() const
Determine the kind of initialization.
DeclarationName getName() const
Retrieve the name of the entity being initialized.
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
bool isImplicitMemberInitializer() const
Is this the implicit initialization of a member of a class from a defaulted constructor?
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index.
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda.
bool isParamOrTemplateParamKind() const
llvm::PointerIntPair< const CXXBaseSpecifier *, 1 > Base
When Kind == EK_Base, the base specifier that provides the base class.
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
EntityKind
Specifies the kind of entity being initialized.
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_MatrixElement
The entity being initialized is an element of a matrix.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
static InitializedEntity InitializeMemberFromParenAggInit(FieldDecl *Member)
Create the initialization entity for a member subobject initialized via parenthesized aggregate init.
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, EK_MatrixElement, or EK_ComplexElement,...
bool isVariableLengthArrayNew() const
Determine whether this is an array new with an unknown bound.
llvm::PointerIntPair< ParmVarDecl *, 1 > Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the integer indicating whether the parameter is "con...
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call.
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3672
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:1052
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:4392
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4406
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represent a C++ namespace.
Definition Decl.h:592
Represents a place-holder for an object not to be initialized by anything.
Definition Expr.h:5878
QualType getEncodedType() const
Definition ExprObjC.h:460
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition ExprObjC.h:1613
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition Overload.h:1486
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CandidateSetKind getKind() const
Definition Overload.h:1349
Represents a parameter to a function.
Definition Decl.h:1808
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3383
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:8520
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8525
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3677
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1307
QualType withConst() const
Definition TypeBase.h:1170
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1236
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:8436
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8562
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8476
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1449
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:8621
QualType getCanonicalType() const
Definition TypeBase.h:8488
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8530
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8509
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8557
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1556
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
bool hasConst() const
Definition TypeBase.h:457
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition TypeBase.h:646
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasAddressSpace() const
Definition TypeBase.h:570
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
Qualifiers withoutAddressSpace() const
Definition TypeBase.h:538
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:435
bool hasVolatile() const
Definition TypeBase.h:467
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3690
Represents a struct/union/class.
Definition Decl.h:4343
field_iterator field_end() const
Definition Decl.h:4549
field_range fields() const
Definition Decl.h:4546
bool isRandomized() const
Definition Decl.h:4501
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4527
bool hasUninitializedExplicitInitFields() const
Definition Decl.h:4469
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4543
bool field_empty() const
Definition Decl.h:4554
field_iterator field_begin() const
Definition Decl.cpp:5270
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3628
bool isSpelledAsLValue() const
Definition TypeBase.h:3641
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:868
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6387
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10487
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10490
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10496
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10494
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
Preprocessor & getPreprocessor() const
Definition Sema.h:938
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7010
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:2077
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:7022
ASTContext & Context
Definition Sema.h:1308
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:686
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
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:1518
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:759
ASTContext & getASTContext() const
Definition Sema.h:939
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition Sema.h:9097
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1483
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:77
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7046
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10515
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8269
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8136
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7058
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
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:8261
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:14063
SourceManager & getSourceManager() const
Definition Sema.h:937
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:13796
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15580
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:125
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:6821
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:1311
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
DiagnosticsEngine & Diags
Definition Sema.h:1310
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
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:1588
CXXDeductionGuideDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the beginning of the immediate macro expansion.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
QualType getToType(unsigned Idx) const
Definition Overload.h:411
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
unsigned getLength() const
Definition Expr.h:1912
StringLiteralKind getKind() const
Definition Expr.h:1915
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition Expr.h:1899
StringRef getString() const
Definition Expr.h:1870
bool isUnion() const
Definition Decl.h:3946
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:8407
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:8418
The base class of the type hierarchy.
Definition TypeBase.h:1871
bool isVoidType() const
Definition TypeBase.h:9039
bool isBooleanType() const
Definition TypeBase.h:9176
bool isMFloat8Type() const
Definition TypeBase.h:9064
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9226
bool isIncompleteArrayType() const
Definition TypeBase.h:8780
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
bool isRValueReferenceType() const
Definition TypeBase.h:8705
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:8772
bool isCharType() const
Definition Type.cpp:2193
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:8840
bool isArrayParameterType() const
Definition TypeBase.h:8788
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9083
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9333
bool isReferenceType() const
Definition TypeBase.h:8697
bool isEnumeralType() const
Definition TypeBase.h:8804
bool isScalarType() const
Definition TypeBase.h:9145
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1958
bool isChar8Type() const
Definition Type.cpp:2209
bool isSizelessBuiltinType() const
Definition Type.cpp:2623
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8816
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:8958
bool isLValueReferenceType() const
Definition TypeBase.h:8701
bool isOpenCLSpecificType() const
Definition TypeBase.h:8973
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2503
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8808
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2109
bool isQueueT() const
Definition TypeBase.h:8929
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9219
bool isAtomicType() const
Definition TypeBase.h:8865
bool isFunctionProtoType() const
Definition TypeBase.h:2654
bool isMatrixType() const
Definition TypeBase.h:8836
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isObjCObjectType() const
Definition TypeBase.h:8856
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9319
bool isEventT() const
Definition TypeBase.h:8921
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8669
bool isObjCObjectPointerType() const
Definition TypeBase.h:8852
bool isVectorType() const
Definition TypeBase.h:8812
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2976
bool isFloatingType() const
Definition Type.cpp:2389
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:2332
bool isSamplerT() const
Definition TypeBase.h:8917
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9266
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9076
bool isRecordType() const
Definition TypeBase.h:8800
bool isObjCRetainableType() const
Definition Type.cpp:5416
bool isUnionType() const
Definition Type.cpp:755
DeclClass * getCorrectionDeclAs() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
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:924
const Expr * getInit() const
Definition Decl.h:1381
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition Decl.h:1242
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4021
Represents a GCC generic vector type.
Definition TypeBase.h:4230
unsigned getNumElements() const
Definition TypeBase.h:4245
VectorKind getVectorKind() const
Definition TypeBase.h:4250
QualType getElementType() const
Definition TypeBase.h:4244
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
CXXConstructionKind
Definition ExprCXX.h:1544
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:343
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:342
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ Template
We are parsing a template declaration.
Definition Parser.h:81
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
ExprResult ExprError()
Definition Ownership.h:265
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
Expr * IgnoreParensSingleStep(Expr *E)
Definition IgnoreExpr.h:157
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:151
@ 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:1301
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2252
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:438
@ Implicit
An implicit conversion.
Definition Sema.h:440
@ CStyleCast
A C-style cast.
Definition Sema.h:442
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:446
@ FunctionalCast
A functional-style cast.
Definition Sema.h:444
unsigned long uint64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
CXXConstructorDecl * Constructor
Definition Overload.h:1511
DeclAccessPair FoundDecl
Definition Overload.h:1510
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6932
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6900
bool RebuildDefaultArgOrDefaultInit
Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
Definition Sema.h:6938
std::optional< InitializationContext > DelayedDefaultInitializationContext
Definition Sema.h:6955
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506