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