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