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