clang 19.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
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeLoc.h"
28#include "clang/Sema/Lookup.h"
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/PointerIntPair.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// Sema Initialization Checking
44//===----------------------------------------------------------------------===//
45
46/// Check whether T is compatible with a wide character type (wchar_t,
47/// char16_t or char32_t).
48static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
49 if (Context.typesAreCompatible(Context.getWideCharType(), T))
50 return true;
51 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
52 return Context.typesAreCompatible(Context.Char16Ty, T) ||
53 Context.typesAreCompatible(Context.Char32Ty, T);
54 }
55 return false;
56}
57
66};
67
68/// Check whether the array of type AT can be initialized by the Init
69/// expression by means of string initialization. Returns SIF_None if so,
70/// otherwise returns a StringInitFailureKind that describes why the
71/// initialization would not work.
73 ASTContext &Context) {
74 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
75 return SIF_Other;
76
77 // See if this is a string literal or @encode.
78 Init = Init->IgnoreParens();
79
80 // Handle @encode, which is a narrow string.
81 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
82 return SIF_None;
83
84 // Otherwise we can only handle string literals.
85 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
86 if (!SL)
87 return SIF_Other;
88
89 const QualType ElemTy =
91
92 auto IsCharOrUnsignedChar = [](const QualType &T) {
93 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
94 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
95 };
96
97 switch (SL->getKind()) {
98 case StringLiteralKind::UTF8:
99 // char8_t array can be initialized with a UTF-8 string.
100 // - C++20 [dcl.init.string] (DR)
101 // Additionally, an array of char or unsigned char may be initialized
102 // by a UTF-8 string literal.
103 if (ElemTy->isChar8Type() ||
104 (Context.getLangOpts().Char8 &&
105 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
106 return SIF_None;
107 [[fallthrough]];
108 case StringLiteralKind::Ordinary:
109 // char array can be initialized with a narrow string.
110 // Only allow char x[] = "foo"; not char x[] = L"foo";
111 if (ElemTy->isCharType())
112 return (SL->getKind() == StringLiteralKind::UTF8 &&
113 Context.getLangOpts().Char8)
115 : SIF_None;
116 if (ElemTy->isChar8Type())
118 if (IsWideCharCompatible(ElemTy, Context))
120 return SIF_Other;
121 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
122 // "An array with element type compatible with a qualified or unqualified
123 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
124 // string literal with the corresponding encoding prefix (L, u, or U,
125 // respectively), optionally enclosed in braces.
126 case StringLiteralKind::UTF16:
127 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
128 return SIF_None;
129 if (ElemTy->isCharType() || ElemTy->isChar8Type())
131 if (IsWideCharCompatible(ElemTy, Context))
133 return SIF_Other;
134 case StringLiteralKind::UTF32:
135 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
136 return SIF_None;
137 if (ElemTy->isCharType() || ElemTy->isChar8Type())
139 if (IsWideCharCompatible(ElemTy, Context))
141 return SIF_Other;
142 case StringLiteralKind::Wide:
143 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
144 return SIF_None;
145 if (ElemTy->isCharType() || ElemTy->isChar8Type())
147 if (IsWideCharCompatible(ElemTy, Context))
149 return SIF_Other;
150 case StringLiteralKind::Unevaluated:
151 assert(false && "Unevaluated string literal in initialization");
152 break;
153 }
154
155 llvm_unreachable("missed a StringLiteral kind?");
156}
157
159 ASTContext &Context) {
160 const ArrayType *arrayType = Context.getAsArrayType(declType);
161 if (!arrayType)
162 return SIF_Other;
163 return IsStringInit(init, arrayType, Context);
164}
165
167 return ::IsStringInit(Init, AT, Context) == SIF_None;
168}
169
170/// Update the type of a string literal, including any surrounding parentheses,
171/// to match the type of the object which it is initializing.
173 while (true) {
174 E->setType(Ty);
176 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
177 break;
179 }
180}
181
182/// Fix a compound literal initializing an array so it's correctly marked
183/// as an rvalue.
185 while (true) {
187 if (isa<CompoundLiteralExpr>(E))
188 break;
190 }
191}
192
194 Decl *D = Entity.getDecl();
195 const InitializedEntity *Parent = &Entity;
196
197 while (Parent) {
198 D = Parent->getDecl();
199 Parent = Parent->getParent();
200 }
201
202 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
203 return true;
204
205 return false;
206}
207
209 Sema &SemaRef, QualType &TT);
210
211static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
212 Sema &S, bool CheckC23ConstexprInit = false) {
213 // Get the length of the string as parsed.
214 auto *ConstantArrayTy =
215 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
216 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
217
218 if (CheckC23ConstexprInit)
219 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
221
222 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
223 // C99 6.7.8p14. We have an array of character type with unknown size
224 // being initialized to a string literal.
225 llvm::APInt ConstVal(32, StrLength);
226 // Return a new array type (C99 6.7.8p22).
228 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
229 updateStringLiteralType(Str, DeclT);
230 return;
231 }
232
233 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
234
235 // We have an array of character type with known size. However,
236 // the size may be smaller or larger than the string we are initializing.
237 // FIXME: Avoid truncation for 64-bit length strings.
238 if (S.getLangOpts().CPlusPlus) {
239 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
240 // For Pascal strings it's OK to strip off the terminating null character,
241 // so the example below is valid:
242 //
243 // unsigned char a[2] = "\pa";
244 if (SL->isPascal())
245 StrLength--;
246 }
247
248 // [dcl.init.string]p2
249 if (StrLength > CAT->getSize().getZExtValue())
250 S.Diag(Str->getBeginLoc(),
251 diag::err_initializer_string_for_char_array_too_long)
252 << CAT->getSize().getZExtValue() << StrLength
253 << Str->getSourceRange();
254 } else {
255 // C99 6.7.8p14.
256 if (StrLength-1 > CAT->getSize().getZExtValue())
257 S.Diag(Str->getBeginLoc(),
258 diag::ext_initializer_string_for_char_array_too_long)
259 << Str->getSourceRange();
260 }
261
262 // Set the type to the actual size that we are initializing. If we have
263 // something like:
264 // char x[1] = "foo";
265 // then this will set the string literal's type to char[1].
266 updateStringLiteralType(Str, DeclT);
267}
268
269//===----------------------------------------------------------------------===//
270// Semantic checking for initializer lists.
271//===----------------------------------------------------------------------===//
272
273namespace {
274
275/// Semantic checking for initializer lists.
276///
277/// The InitListChecker class contains a set of routines that each
278/// handle the initialization of a certain kind of entity, e.g.,
279/// arrays, vectors, struct/union types, scalars, etc. The
280/// InitListChecker itself performs a recursive walk of the subobject
281/// structure of the type to be initialized, while stepping through
282/// the initializer list one element at a time. The IList and Index
283/// parameters to each of the Check* routines contain the active
284/// (syntactic) initializer list and the index into that initializer
285/// list that represents the current initializer. Each routine is
286/// responsible for moving that Index forward as it consumes elements.
287///
288/// Each Check* routine also has a StructuredList/StructuredIndex
289/// arguments, which contains the current "structured" (semantic)
290/// initializer list and the index into that initializer list where we
291/// are copying initializers as we map them over to the semantic
292/// list. Once we have completed our recursive walk of the subobject
293/// structure, we will have constructed a full semantic initializer
294/// list.
295///
296/// C99 designators cause changes in the initializer list traversal,
297/// because they make the initialization "jump" into a specific
298/// subobject and then continue the initialization from that
299/// point. CheckDesignatedInitializer() recursively steps into the
300/// designated subobject and manages backing out the recursion to
301/// initialize the subobjects after the one designated.
302///
303/// If an initializer list contains any designators, we build a placeholder
304/// structured list even in 'verify only' mode, so that we can track which
305/// elements need 'empty' initializtion.
306class InitListChecker {
307 Sema &SemaRef;
308 bool hadError = false;
309 bool VerifyOnly; // No diagnostics.
310 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
311 bool InOverloadResolution;
312 InitListExpr *FullyStructuredList = nullptr;
313 NoInitExpr *DummyExpr = nullptr;
314 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
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,
501 SourceLocation Loc);
502
503public:
504 InitListChecker(
505 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
506 bool VerifyOnly, bool TreatUnavailableAsInvalid,
507 bool InOverloadResolution = false,
508 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
509 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
510 QualType &T,
511 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
512 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
513 /*TreatUnavailableAsInvalid=*/false,
514 /*InOverloadResolution=*/false,
515 &AggrDeductionCandidateParamTypes){};
516
517 bool HadError() { return hadError; }
518
519 // Retrieves the fully-structured initializer list used for
520 // semantic analysis and code generation.
521 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
522};
523
524} // end anonymous namespace
525
526ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
527 const InitializedEntity &Entity) {
529 true);
530 MultiExprArg SubInit;
531 Expr *InitExpr;
532 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
533
534 // C++ [dcl.init.aggr]p7:
535 // If there are fewer initializer-clauses in the list than there are
536 // members in the aggregate, then each member not explicitly initialized
537 // ...
538 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
540 if (EmptyInitList) {
541 // C++1y / DR1070:
542 // shall be initialized [...] from an empty initializer list.
543 //
544 // We apply the resolution of this DR to C++11 but not C++98, since C++98
545 // does not have useful semantics for initialization from an init list.
546 // We treat this as copy-initialization, because aggregate initialization
547 // always performs copy-initialization on its elements.
548 //
549 // Only do this if we're initializing a class type, to avoid filling in
550 // the initializer list where possible.
551 InitExpr = VerifyOnly
552 ? &DummyInitList
553 : new (SemaRef.Context)
554 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
555 InitExpr->setType(SemaRef.Context.VoidTy);
556 SubInit = InitExpr;
558 } else {
559 // C++03:
560 // shall be value-initialized.
561 }
562
563 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
564 // libstdc++4.6 marks the vector default constructor as explicit in
565 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
566 // stlport does so too. Look for std::__debug for libstdc++, and for
567 // std:: for stlport. This is effectively a compiler-side implementation of
568 // LWG2193.
569 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
573 InitSeq.getFailedCandidateSet()
574 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
575 (void)O;
576 assert(O == OR_Success && "Inconsistent overload resolution");
577 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
578 CXXRecordDecl *R = CtorDecl->getParent();
579
580 if (CtorDecl->getMinRequiredArguments() == 0 &&
581 CtorDecl->isExplicit() && R->getDeclName() &&
582 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
583 bool IsInStd = false;
584 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
585 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
587 IsInStd = true;
588 }
589
590 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
591 .Cases("basic_string", "deque", "forward_list", true)
592 .Cases("list", "map", "multimap", "multiset", true)
593 .Cases("priority_queue", "queue", "set", "stack", true)
594 .Cases("unordered_map", "unordered_set", "vector", true)
595 .Default(false)) {
596 InitSeq.InitializeFrom(
597 SemaRef, Entity,
598 InitializationKind::CreateValue(Loc, Loc, Loc, true),
599 MultiExprArg(), /*TopLevelOfInitList=*/false,
600 TreatUnavailableAsInvalid);
601 // Emit a warning for this. System header warnings aren't shown
602 // by default, but people working on system headers should see it.
603 if (!VerifyOnly) {
604 SemaRef.Diag(CtorDecl->getLocation(),
605 diag::warn_invalid_initializer_from_system_header);
607 SemaRef.Diag(Entity.getDecl()->getLocation(),
608 diag::note_used_in_initialization_here);
609 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
610 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
611 }
612 }
613 }
614 }
615 if (!InitSeq) {
616 if (!VerifyOnly) {
617 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
619 SemaRef.Diag(Entity.getDecl()->getLocation(),
620 diag::note_in_omitted_aggregate_initializer)
621 << /*field*/1 << Entity.getDecl();
622 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
623 bool IsTrailingArrayNewMember =
624 Entity.getParent() &&
626 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
627 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
628 << Entity.getElementIndex();
629 }
630 }
631 hadError = true;
632 return ExprError();
633 }
634
635 return VerifyOnly ? ExprResult()
636 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
637}
638
639void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
640 SourceLocation Loc) {
641 // If we're building a fully-structured list, we'll check this at the end
642 // once we know which elements are actually initialized. Otherwise, we know
643 // that there are no designators so we can just check now.
644 if (FullyStructuredList)
645 return;
646 PerformEmptyInit(Loc, Entity);
647}
648
649void InitListChecker::FillInEmptyInitForBase(
650 unsigned Init, const CXXBaseSpecifier &Base,
651 const InitializedEntity &ParentEntity, InitListExpr *ILE,
652 bool &RequiresSecondPass, bool FillWithNoInit) {
654 SemaRef.Context, &Base, false, &ParentEntity);
655
656 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
657 ExprResult BaseInit = FillWithNoInit
658 ? new (SemaRef.Context) NoInitExpr(Base.getType())
659 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
660 if (BaseInit.isInvalid()) {
661 hadError = true;
662 return;
663 }
664
665 if (!VerifyOnly) {
666 assert(Init < ILE->getNumInits() && "should have been expanded");
667 ILE->setInit(Init, BaseInit.getAs<Expr>());
668 }
669 } else if (InitListExpr *InnerILE =
670 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
671 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
672 ILE, Init, FillWithNoInit);
673 } else if (DesignatedInitUpdateExpr *InnerDIUE =
674 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
675 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
676 RequiresSecondPass, ILE, Init,
677 /*FillWithNoInit =*/true);
678 }
679}
680
681void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
682 const InitializedEntity &ParentEntity,
683 InitListExpr *ILE,
684 bool &RequiresSecondPass,
685 bool FillWithNoInit) {
686 SourceLocation Loc = ILE->getEndLoc();
687 unsigned NumInits = ILE->getNumInits();
688 InitializedEntity MemberEntity
689 = InitializedEntity::InitializeMember(Field, &ParentEntity);
690
691 if (Init >= NumInits || !ILE->getInit(Init)) {
692 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
693 if (!RType->getDecl()->isUnion())
694 assert((Init < NumInits || VerifyOnly) &&
695 "This ILE should have been expanded");
696
697 if (FillWithNoInit) {
698 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
699 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
700 if (Init < NumInits)
701 ILE->setInit(Init, Filler);
702 else
703 ILE->updateInit(SemaRef.Context, Init, Filler);
704 return;
705 }
706 // C++1y [dcl.init.aggr]p7:
707 // If there are fewer initializer-clauses in the list than there are
708 // members in the aggregate, then each member not explicitly initialized
709 // shall be initialized from its brace-or-equal-initializer [...]
710 if (Field->hasInClassInitializer()) {
711 if (VerifyOnly)
712 return;
713
714 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
715 if (DIE.isInvalid()) {
716 hadError = true;
717 return;
718 }
719 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
720 if (Init < NumInits)
721 ILE->setInit(Init, DIE.get());
722 else {
723 ILE->updateInit(SemaRef.Context, Init, DIE.get());
724 RequiresSecondPass = true;
725 }
726 return;
727 }
728
729 if (Field->getType()->isReferenceType()) {
730 if (!VerifyOnly) {
731 // C++ [dcl.init.aggr]p9:
732 // If an incomplete or empty initializer-list leaves a
733 // member of reference type uninitialized, the program is
734 // ill-formed.
735 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
736 << Field->getType()
737 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
738 ->getSourceRange();
739 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
740 }
741 hadError = true;
742 return;
743 }
744
745 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
746 if (MemberInit.isInvalid()) {
747 hadError = true;
748 return;
749 }
750
751 if (hadError || VerifyOnly) {
752 // Do nothing
753 } else if (Init < NumInits) {
754 ILE->setInit(Init, MemberInit.getAs<Expr>());
755 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
756 // Empty initialization requires a constructor call, so
757 // extend the initializer list to include the constructor
758 // call and make a note that we'll need to take another pass
759 // through the initializer list.
760 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
761 RequiresSecondPass = true;
762 }
763 } else if (InitListExpr *InnerILE
764 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
765 FillInEmptyInitializations(MemberEntity, InnerILE,
766 RequiresSecondPass, ILE, Init, FillWithNoInit);
767 } else if (DesignatedInitUpdateExpr *InnerDIUE =
768 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
769 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
770 RequiresSecondPass, ILE, Init,
771 /*FillWithNoInit =*/true);
772 }
773}
774
775/// Recursively replaces NULL values within the given initializer list
776/// with expressions that perform value-initialization of the
777/// appropriate type, and finish off the InitListExpr formation.
778void
779InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
780 InitListExpr *ILE,
781 bool &RequiresSecondPass,
782 InitListExpr *OuterILE,
783 unsigned OuterIndex,
784 bool FillWithNoInit) {
785 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
786 "Should not have void type");
787
788 // We don't need to do any checks when just filling NoInitExprs; that can't
789 // fail.
790 if (FillWithNoInit && VerifyOnly)
791 return;
792
793 // If this is a nested initializer list, we might have changed its contents
794 // (and therefore some of its properties, such as instantiation-dependence)
795 // while filling it in. Inform the outer initializer list so that its state
796 // can be updated to match.
797 // FIXME: We should fully build the inner initializers before constructing
798 // the outer InitListExpr instead of mutating AST nodes after they have
799 // been used as subexpressions of other nodes.
800 struct UpdateOuterILEWithUpdatedInit {
801 InitListExpr *Outer;
802 unsigned OuterIndex;
803 ~UpdateOuterILEWithUpdatedInit() {
804 if (Outer)
805 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
806 }
807 } UpdateOuterRAII = {OuterILE, OuterIndex};
808
809 // A transparent ILE is not performing aggregate initialization and should
810 // not be filled in.
811 if (ILE->isTransparent())
812 return;
813
814 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
815 const RecordDecl *RDecl = RType->getDecl();
816 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
817 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
818 Entity, ILE, RequiresSecondPass, FillWithNoInit);
819 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
820 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
821 for (auto *Field : RDecl->fields()) {
822 if (Field->hasInClassInitializer()) {
823 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
824 FillWithNoInit);
825 break;
826 }
827 }
828 } else {
829 // The fields beyond ILE->getNumInits() are default initialized, so in
830 // order to leave them uninitialized, the ILE is expanded and the extra
831 // fields are then filled with NoInitExpr.
832 unsigned NumElems = numStructUnionElements(ILE->getType());
833 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
834 ++NumElems;
835 if (!VerifyOnly && ILE->getNumInits() < NumElems)
836 ILE->resizeInits(SemaRef.Context, NumElems);
837
838 unsigned Init = 0;
839
840 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
841 for (auto &Base : CXXRD->bases()) {
842 if (hadError)
843 return;
844
845 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
846 FillWithNoInit);
847 ++Init;
848 }
849 }
850
851 for (auto *Field : RDecl->fields()) {
852 if (Field->isUnnamedBitfield())
853 continue;
854
855 if (hadError)
856 return;
857
858 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
859 FillWithNoInit);
860 if (hadError)
861 return;
862
863 ++Init;
864
865 // Only look at the first initialization of a union.
866 if (RDecl->isUnion())
867 break;
868 }
869 }
870
871 return;
872 }
873
874 QualType ElementType;
875
876 InitializedEntity ElementEntity = Entity;
877 unsigned NumInits = ILE->getNumInits();
878 unsigned NumElements = NumInits;
879 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
880 ElementType = AType->getElementType();
881 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
882 NumElements = CAType->getSize().getZExtValue();
883 // For an array new with an unknown bound, ask for one additional element
884 // in order to populate the array filler.
885 if (Entity.isVariableLengthArrayNew())
886 ++NumElements;
887 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
888 0, Entity);
889 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
890 ElementType = VType->getElementType();
891 NumElements = VType->getNumElements();
892 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
893 0, Entity);
894 } else
895 ElementType = ILE->getType();
896
897 bool SkipEmptyInitChecks = false;
898 for (unsigned Init = 0; Init != NumElements; ++Init) {
899 if (hadError)
900 return;
901
902 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
904 ElementEntity.setElementIndex(Init);
905
906 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
907 return;
908
909 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
910 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
911 ILE->setInit(Init, ILE->getArrayFiller());
912 else if (!InitExpr && !ILE->hasArrayFiller()) {
913 // In VerifyOnly mode, there's no point performing empty initialization
914 // more than once.
915 if (SkipEmptyInitChecks)
916 continue;
917
918 Expr *Filler = nullptr;
919
920 if (FillWithNoInit)
921 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
922 else {
923 ExprResult ElementInit =
924 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
925 if (ElementInit.isInvalid()) {
926 hadError = true;
927 return;
928 }
929
930 Filler = ElementInit.getAs<Expr>();
931 }
932
933 if (hadError) {
934 // Do nothing
935 } else if (VerifyOnly) {
936 SkipEmptyInitChecks = true;
937 } else if (Init < NumInits) {
938 // For arrays, just set the expression used for value-initialization
939 // of the "holes" in the array.
940 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
941 ILE->setArrayFiller(Filler);
942 else
943 ILE->setInit(Init, Filler);
944 } else {
945 // For arrays, just set the expression used for value-initialization
946 // of the rest of elements and exit.
947 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
948 ILE->setArrayFiller(Filler);
949 return;
950 }
951
952 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
953 // Empty initialization requires a constructor call, so
954 // extend the initializer list to include the constructor
955 // call and make a note that we'll need to take another pass
956 // through the initializer list.
957 ILE->updateInit(SemaRef.Context, Init, Filler);
958 RequiresSecondPass = true;
959 }
960 }
961 } else if (InitListExpr *InnerILE
962 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
963 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
964 ILE, Init, FillWithNoInit);
965 } else if (DesignatedInitUpdateExpr *InnerDIUE =
966 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
967 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
968 RequiresSecondPass, ILE, Init,
969 /*FillWithNoInit =*/true);
970 }
971 }
972}
973
974static bool hasAnyDesignatedInits(const InitListExpr *IL) {
975 for (const Stmt *Init : *IL)
976 if (isa_and_nonnull<DesignatedInitExpr>(Init))
977 return true;
978 return false;
979}
980
981InitListChecker::InitListChecker(
982 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
983 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
984 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
985 : SemaRef(S), VerifyOnly(VerifyOnly),
986 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
987 InOverloadResolution(InOverloadResolution),
988 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
989 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
990 FullyStructuredList =
991 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
992
993 // FIXME: Check that IL isn't already the semantic form of some other
994 // InitListExpr. If it is, we'd create a broken AST.
995 if (!VerifyOnly)
996 FullyStructuredList->setSyntacticForm(IL);
997 }
998
999 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1000 /*TopLevelObject=*/true);
1001
1002 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1003 bool RequiresSecondPass = false;
1004 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1005 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1006 if (RequiresSecondPass && !hadError)
1007 FillInEmptyInitializations(Entity, FullyStructuredList,
1008 RequiresSecondPass, nullptr, 0);
1009 }
1010 if (hadError && FullyStructuredList)
1011 FullyStructuredList->markError();
1012}
1013
1014int InitListChecker::numArrayElements(QualType DeclType) {
1015 // FIXME: use a proper constant
1016 int maxElements = 0x7FFFFFFF;
1017 if (const ConstantArrayType *CAT =
1018 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1019 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
1020 }
1021 return maxElements;
1022}
1023
1024int InitListChecker::numStructUnionElements(QualType DeclType) {
1025 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1026 int InitializableMembers = 0;
1027 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1028 InitializableMembers += CXXRD->getNumBases();
1029 for (const auto *Field : structDecl->fields())
1030 if (!Field->isUnnamedBitfield())
1031 ++InitializableMembers;
1032
1033 if (structDecl->isUnion())
1034 return std::min(InitializableMembers, 1);
1035 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1036}
1037
1038RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1039 if (const auto *RT = DeclType->getAs<RecordType>())
1040 return RT->getDecl();
1041 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1042 return Inject->getDecl();
1043 return nullptr;
1044}
1045
1046/// Determine whether Entity is an entity for which it is idiomatic to elide
1047/// the braces in aggregate initialization.
1049 // Recursive initialization of the one and only field within an aggregate
1050 // class is considered idiomatic. This case arises in particular for
1051 // initialization of std::array, where the C++ standard suggests the idiom of
1052 //
1053 // std::array<T, N> arr = {1, 2, 3};
1054 //
1055 // (where std::array is an aggregate struct containing a single array field.
1056
1057 if (!Entity.getParent())
1058 return false;
1059
1060 // Allows elide brace initialization for aggregates with empty base.
1061 if (Entity.getKind() == InitializedEntity::EK_Base) {
1062 auto *ParentRD =
1063 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1064 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1065 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1066 }
1067
1068 // Allow brace elision if the only subobject is a field.
1069 if (Entity.getKind() == InitializedEntity::EK_Member) {
1070 auto *ParentRD =
1071 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1072 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1073 if (CXXRD->getNumBases()) {
1074 return false;
1075 }
1076 }
1077 auto FieldIt = ParentRD->field_begin();
1078 assert(FieldIt != ParentRD->field_end() &&
1079 "no fields but have initializer for member?");
1080 return ++FieldIt == ParentRD->field_end();
1081 }
1082
1083 return false;
1084}
1085
1086/// Check whether the range of the initializer \p ParentIList from element
1087/// \p Index onwards can be used to initialize an object of type \p T. Update
1088/// \p Index to indicate how many elements of the list were consumed.
1089///
1090/// This also fills in \p StructuredList, from element \p StructuredIndex
1091/// onwards, with the fully-braced, desugared form of the initialization.
1092void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1093 InitListExpr *ParentIList,
1094 QualType T, unsigned &Index,
1095 InitListExpr *StructuredList,
1096 unsigned &StructuredIndex) {
1097 int maxElements = 0;
1098
1099 if (T->isArrayType())
1100 maxElements = numArrayElements(T);
1101 else if (T->isRecordType())
1102 maxElements = numStructUnionElements(T);
1103 else if (T->isVectorType())
1104 maxElements = T->castAs<VectorType>()->getNumElements();
1105 else
1106 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1107
1108 if (maxElements == 0) {
1109 if (!VerifyOnly)
1110 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1111 diag::err_implicit_empty_initializer);
1112 ++Index;
1113 hadError = true;
1114 return;
1115 }
1116
1117 // Build a structured initializer list corresponding to this subobject.
1118 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1119 ParentIList, Index, T, StructuredList, StructuredIndex,
1120 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1121 ParentIList->getSourceRange().getEnd()));
1122 unsigned StructuredSubobjectInitIndex = 0;
1123
1124 // Check the element types and build the structural subobject.
1125 unsigned StartIndex = Index;
1126 CheckListElementTypes(Entity, ParentIList, T,
1127 /*SubobjectIsDesignatorContext=*/false, Index,
1128 StructuredSubobjectInitList,
1129 StructuredSubobjectInitIndex);
1130
1131 if (StructuredSubobjectInitList) {
1132 StructuredSubobjectInitList->setType(T);
1133
1134 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1135 // Update the structured sub-object initializer so that it's ending
1136 // range corresponds with the end of the last initializer it used.
1137 if (EndIndex < ParentIList->getNumInits() &&
1138 ParentIList->getInit(EndIndex)) {
1139 SourceLocation EndLoc
1140 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1141 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1142 }
1143
1144 // Complain about missing braces.
1145 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1146 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1148 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1149 diag::warn_missing_braces)
1150 << StructuredSubobjectInitList->getSourceRange()
1152 StructuredSubobjectInitList->getBeginLoc(), "{")
1154 SemaRef.getLocForEndOfToken(
1155 StructuredSubobjectInitList->getEndLoc()),
1156 "}");
1157 }
1158
1159 // Warn if this type won't be an aggregate in future versions of C++.
1160 auto *CXXRD = T->getAsCXXRecordDecl();
1161 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1162 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1163 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1164 << StructuredSubobjectInitList->getSourceRange() << T;
1165 }
1166 }
1167}
1168
1169/// Warn that \p Entity was of scalar type and was initialized by a
1170/// single-element braced initializer list.
1171static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1173 // Don't warn during template instantiation. If the initialization was
1174 // non-dependent, we warned during the initial parse; otherwise, the
1175 // type might not be scalar in some uses of the template.
1177 return;
1178
1179 unsigned DiagID = 0;
1180
1181 switch (Entity.getKind()) {
1190 // Extra braces here are suspicious.
1191 DiagID = diag::warn_braces_around_init;
1192 break;
1193
1195 // Warn on aggregate initialization but not on ctor init list or
1196 // default member initializer.
1197 if (Entity.getParent())
1198 DiagID = diag::warn_braces_around_init;
1199 break;
1200
1203 // No warning, might be direct-list-initialization.
1204 // FIXME: Should we warn for copy-list-initialization in these cases?
1205 break;
1206
1210 // No warning, braces are part of the syntax of the underlying construct.
1211 break;
1212
1214 // No warning, we already warned when initializing the result.
1215 break;
1216
1224 llvm_unreachable("unexpected braced scalar init");
1225 }
1226
1227 if (DiagID) {
1228 S.Diag(Braces.getBegin(), DiagID)
1229 << Entity.getType()->isSizelessBuiltinType() << Braces
1230 << FixItHint::CreateRemoval(Braces.getBegin())
1231 << FixItHint::CreateRemoval(Braces.getEnd());
1232 }
1233}
1234
1235/// Check whether the initializer \p IList (that was written with explicit
1236/// braces) can be used to initialize an object of type \p T.
1237///
1238/// This also fills in \p StructuredList with the fully-braced, desugared
1239/// form of the initialization.
1240void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1241 InitListExpr *IList, QualType &T,
1242 InitListExpr *StructuredList,
1243 bool TopLevelObject) {
1244 unsigned Index = 0, StructuredIndex = 0;
1245 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1246 Index, StructuredList, StructuredIndex, TopLevelObject);
1247 if (StructuredList) {
1248 QualType ExprTy = T;
1249 if (!ExprTy->isArrayType())
1250 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1251 if (!VerifyOnly)
1252 IList->setType(ExprTy);
1253 StructuredList->setType(ExprTy);
1254 }
1255 if (hadError)
1256 return;
1257
1258 // Don't complain for incomplete types, since we'll get an error elsewhere.
1259 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1260 // We have leftover initializers
1261 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1262 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1263 hadError = ExtraInitsIsError;
1264 if (VerifyOnly) {
1265 return;
1266 } else if (StructuredIndex == 1 &&
1267 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1268 SIF_None) {
1269 unsigned DK =
1270 ExtraInitsIsError
1271 ? diag::err_excess_initializers_in_char_array_initializer
1272 : diag::ext_excess_initializers_in_char_array_initializer;
1273 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1274 << IList->getInit(Index)->getSourceRange();
1275 } else if (T->isSizelessBuiltinType()) {
1276 unsigned DK = ExtraInitsIsError
1277 ? diag::err_excess_initializers_for_sizeless_type
1278 : diag::ext_excess_initializers_for_sizeless_type;
1279 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1280 << T << IList->getInit(Index)->getSourceRange();
1281 } else {
1282 int initKind = T->isArrayType() ? 0 :
1283 T->isVectorType() ? 1 :
1284 T->isScalarType() ? 2 :
1285 T->isUnionType() ? 3 :
1286 4;
1287
1288 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1289 : diag::ext_excess_initializers;
1290 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1291 << initKind << IList->getInit(Index)->getSourceRange();
1292 }
1293 }
1294
1295 if (!VerifyOnly) {
1296 if (T->isScalarType() && IList->getNumInits() == 1 &&
1297 !isa<InitListExpr>(IList->getInit(0)))
1298 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1299
1300 // Warn if this is a class type that won't be an aggregate in future
1301 // versions of C++.
1302 auto *CXXRD = T->getAsCXXRecordDecl();
1303 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1304 // Don't warn if there's an equivalent default constructor that would be
1305 // used instead.
1306 bool HasEquivCtor = false;
1307 if (IList->getNumInits() == 0) {
1308 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1309 HasEquivCtor = CD && !CD->isDeleted();
1310 }
1311
1312 if (!HasEquivCtor) {
1313 SemaRef.Diag(IList->getBeginLoc(),
1314 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1315 << IList->getSourceRange() << T;
1316 }
1317 }
1318 }
1319}
1320
1321void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1322 InitListExpr *IList,
1323 QualType &DeclType,
1324 bool SubobjectIsDesignatorContext,
1325 unsigned &Index,
1326 InitListExpr *StructuredList,
1327 unsigned &StructuredIndex,
1328 bool TopLevelObject) {
1329 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1330 // Explicitly braced initializer for complex type can be real+imaginary
1331 // parts.
1332 CheckComplexType(Entity, IList, DeclType, Index,
1333 StructuredList, StructuredIndex);
1334 } else if (DeclType->isScalarType()) {
1335 CheckScalarType(Entity, IList, DeclType, Index,
1336 StructuredList, StructuredIndex);
1337 } else if (DeclType->isVectorType()) {
1338 CheckVectorType(Entity, IList, DeclType, Index,
1339 StructuredList, StructuredIndex);
1340 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1341 auto Bases =
1344 if (DeclType->isRecordType()) {
1345 assert(DeclType->isAggregateType() &&
1346 "non-aggregate records should be handed in CheckSubElementType");
1347 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1348 Bases = CXXRD->bases();
1349 } else {
1350 Bases = cast<CXXRecordDecl>(RD)->bases();
1351 }
1352 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1353 SubobjectIsDesignatorContext, Index, StructuredList,
1354 StructuredIndex, TopLevelObject);
1355 } else if (DeclType->isArrayType()) {
1356 llvm::APSInt Zero(
1357 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1358 false);
1359 CheckArrayType(Entity, IList, DeclType, Zero,
1360 SubobjectIsDesignatorContext, Index,
1361 StructuredList, StructuredIndex);
1362 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1363 // This type is invalid, issue a diagnostic.
1364 ++Index;
1365 if (!VerifyOnly)
1366 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1367 << DeclType;
1368 hadError = true;
1369 } else if (DeclType->isReferenceType()) {
1370 CheckReferenceType(Entity, IList, DeclType, Index,
1371 StructuredList, StructuredIndex);
1372 } else if (DeclType->isObjCObjectType()) {
1373 if (!VerifyOnly)
1374 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1375 hadError = true;
1376 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1377 DeclType->isSizelessBuiltinType()) {
1378 // Checks for scalar type are sufficient for these types too.
1379 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1380 StructuredIndex);
1381 } else if (DeclType->isDependentType()) {
1382 // C++ [over.match.class.deduct]p1.5:
1383 // brace elision is not considered for any aggregate element that has a
1384 // dependent non-array type or an array type with a value-dependent bound
1385 ++Index;
1386 assert(AggrDeductionCandidateParamTypes);
1387 AggrDeductionCandidateParamTypes->push_back(DeclType);
1388 } else {
1389 if (!VerifyOnly)
1390 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1391 << DeclType;
1392 hadError = true;
1393 }
1394}
1395
1396void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1397 InitListExpr *IList,
1398 QualType ElemType,
1399 unsigned &Index,
1400 InitListExpr *StructuredList,
1401 unsigned &StructuredIndex,
1402 bool DirectlyDesignated) {
1403 Expr *expr = IList->getInit(Index);
1404
1405 if (ElemType->isReferenceType())
1406 return CheckReferenceType(Entity, IList, ElemType, Index,
1407 StructuredList, StructuredIndex);
1408
1409 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1410 if (SubInitList->getNumInits() == 1 &&
1411 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1412 SIF_None) {
1413 // FIXME: It would be more faithful and no less correct to include an
1414 // InitListExpr in the semantic form of the initializer list in this case.
1415 expr = SubInitList->getInit(0);
1416 }
1417 // Nested aggregate initialization and C++ initialization are handled later.
1418 } else if (isa<ImplicitValueInitExpr>(expr)) {
1419 // This happens during template instantiation when we see an InitListExpr
1420 // that we've already checked once.
1421 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1422 "found implicit initialization for the wrong type");
1423 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1424 ++Index;
1425 return;
1426 }
1427
1428 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1429 // C++ [dcl.init.aggr]p2:
1430 // Each member is copy-initialized from the corresponding
1431 // initializer-clause.
1432
1433 // FIXME: Better EqualLoc?
1436
1437 // Vector elements can be initialized from other vectors in which case
1438 // we need initialization entity with a type of a vector (and not a vector
1439 // element!) initializing multiple vector elements.
1440 auto TmpEntity =
1441 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1443 : Entity;
1444
1445 if (TmpEntity.getType()->isDependentType()) {
1446 // C++ [over.match.class.deduct]p1.5:
1447 // brace elision is not considered for any aggregate element that has a
1448 // dependent non-array type or an array type with a value-dependent
1449 // bound
1450 assert(AggrDeductionCandidateParamTypes);
1451 if (!isa_and_nonnull<ConstantArrayType>(
1452 SemaRef.Context.getAsArrayType(ElemType))) {
1453 ++Index;
1454 AggrDeductionCandidateParamTypes->push_back(ElemType);
1455 return;
1456 }
1457 } else {
1458 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1459 /*TopLevelOfInitList*/ true);
1460 // C++14 [dcl.init.aggr]p13:
1461 // If the assignment-expression can initialize a member, the member is
1462 // initialized. Otherwise [...] brace elision is assumed
1463 //
1464 // Brace elision is never performed if the element is not an
1465 // assignment-expression.
1466 if (Seq || isa<InitListExpr>(expr)) {
1467 if (!VerifyOnly) {
1468 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1469 if (Result.isInvalid())
1470 hadError = true;
1471
1472 UpdateStructuredListElement(StructuredList, StructuredIndex,
1473 Result.getAs<Expr>());
1474 } else if (!Seq) {
1475 hadError = true;
1476 } else if (StructuredList) {
1477 UpdateStructuredListElement(StructuredList, StructuredIndex,
1478 getDummyInit());
1479 }
1480 ++Index;
1481 if (AggrDeductionCandidateParamTypes)
1482 AggrDeductionCandidateParamTypes->push_back(ElemType);
1483 return;
1484 }
1485 }
1486
1487 // Fall through for subaggregate initialization
1488 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1489 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1490 return CheckScalarType(Entity, IList, ElemType, Index,
1491 StructuredList, StructuredIndex);
1492 } else if (const ArrayType *arrayType =
1493 SemaRef.Context.getAsArrayType(ElemType)) {
1494 // arrayType can be incomplete if we're initializing a flexible
1495 // array member. There's nothing we can do with the completed
1496 // type here, though.
1497
1498 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1499 // FIXME: Should we do this checking in verify-only mode?
1500 if (!VerifyOnly)
1501 CheckStringInit(expr, ElemType, arrayType, SemaRef,
1502 SemaRef.getLangOpts().C23 &&
1504 if (StructuredList)
1505 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1506 ++Index;
1507 return;
1508 }
1509
1510 // Fall through for subaggregate initialization.
1511
1512 } else {
1513 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1514 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1515
1516 // C99 6.7.8p13:
1517 //
1518 // The initializer for a structure or union object that has
1519 // automatic storage duration shall be either an initializer
1520 // list as described below, or a single expression that has
1521 // compatible structure or union type. In the latter case, the
1522 // initial value of the object, including unnamed members, is
1523 // that of the expression.
1524 ExprResult ExprRes = expr;
1526 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1527 if (ExprRes.isInvalid())
1528 hadError = true;
1529 else {
1530 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1531 if (ExprRes.isInvalid())
1532 hadError = true;
1533 }
1534 UpdateStructuredListElement(StructuredList, StructuredIndex,
1535 ExprRes.getAs<Expr>());
1536 ++Index;
1537 return;
1538 }
1539 ExprRes.get();
1540 // Fall through for subaggregate initialization
1541 }
1542
1543 // C++ [dcl.init.aggr]p12:
1544 //
1545 // [...] Otherwise, if the member is itself a non-empty
1546 // subaggregate, brace elision is assumed and the initializer is
1547 // considered for the initialization of the first member of
1548 // the subaggregate.
1549 // OpenCL vector initializer is handled elsewhere.
1550 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1551 ElemType->isAggregateType()) {
1552 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1553 StructuredIndex);
1554 ++StructuredIndex;
1555
1556 // In C++20, brace elision is not permitted for a designated initializer.
1557 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1558 if (InOverloadResolution)
1559 hadError = true;
1560 if (!VerifyOnly) {
1561 SemaRef.Diag(expr->getBeginLoc(),
1562 diag::ext_designated_init_brace_elision)
1563 << expr->getSourceRange()
1564 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1566 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1567 }
1568 }
1569 } else {
1570 if (!VerifyOnly) {
1571 // We cannot initialize this element, so let PerformCopyInitialization
1572 // produce the appropriate diagnostic. We already checked that this
1573 // initialization will fail.
1576 /*TopLevelOfInitList=*/true);
1577 (void)Copy;
1578 assert(Copy.isInvalid() &&
1579 "expected non-aggregate initialization to fail");
1580 }
1581 hadError = true;
1582 ++Index;
1583 ++StructuredIndex;
1584 }
1585}
1586
1587void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1588 InitListExpr *IList, QualType DeclType,
1589 unsigned &Index,
1590 InitListExpr *StructuredList,
1591 unsigned &StructuredIndex) {
1592 assert(Index == 0 && "Index in explicit init list must be zero");
1593
1594 // As an extension, clang supports complex initializers, which initialize
1595 // a complex number component-wise. When an explicit initializer list for
1596 // a complex number contains two initializers, this extension kicks in:
1597 // it expects the initializer list to contain two elements convertible to
1598 // the element type of the complex type. The first element initializes
1599 // the real part, and the second element intitializes the imaginary part.
1600
1601 if (IList->getNumInits() < 2)
1602 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1603 StructuredIndex);
1604
1605 // This is an extension in C. (The builtin _Complex type does not exist
1606 // in the C++ standard.)
1607 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1608 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1609 << IList->getSourceRange();
1610
1611 // Initialize the complex number.
1612 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1613 InitializedEntity ElementEntity =
1615
1616 for (unsigned i = 0; i < 2; ++i) {
1617 ElementEntity.setElementIndex(Index);
1618 CheckSubElementType(ElementEntity, IList, elementType, Index,
1619 StructuredList, StructuredIndex);
1620 }
1621}
1622
1623void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1624 InitListExpr *IList, QualType DeclType,
1625 unsigned &Index,
1626 InitListExpr *StructuredList,
1627 unsigned &StructuredIndex) {
1628 if (Index >= IList->getNumInits()) {
1629 if (!VerifyOnly) {
1630 if (SemaRef.getLangOpts().CPlusPlus) {
1631 if (DeclType->isSizelessBuiltinType())
1632 SemaRef.Diag(IList->getBeginLoc(),
1633 SemaRef.getLangOpts().CPlusPlus11
1634 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1635 : diag::err_empty_sizeless_initializer)
1636 << DeclType << IList->getSourceRange();
1637 else
1638 SemaRef.Diag(IList->getBeginLoc(),
1639 SemaRef.getLangOpts().CPlusPlus11
1640 ? diag::warn_cxx98_compat_empty_scalar_initializer
1641 : diag::err_empty_scalar_initializer)
1642 << IList->getSourceRange();
1643 }
1644 }
1645 hadError =
1646 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1647 ++Index;
1648 ++StructuredIndex;
1649 return;
1650 }
1651
1652 Expr *expr = IList->getInit(Index);
1653 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1654 // FIXME: This is invalid, and accepting it causes overload resolution
1655 // to pick the wrong overload in some corner cases.
1656 if (!VerifyOnly)
1657 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1658 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1659
1660 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1661 StructuredIndex);
1662 return;
1663 } else if (isa<DesignatedInitExpr>(expr)) {
1664 if (!VerifyOnly)
1665 SemaRef.Diag(expr->getBeginLoc(),
1666 diag::err_designator_for_scalar_or_sizeless_init)
1667 << DeclType->isSizelessBuiltinType() << DeclType
1668 << expr->getSourceRange();
1669 hadError = true;
1670 ++Index;
1671 ++StructuredIndex;
1672 return;
1673 }
1674
1675 ExprResult Result;
1676 if (VerifyOnly) {
1677 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1678 Result = getDummyInit();
1679 else
1680 Result = ExprError();
1681 } else {
1682 Result =
1683 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1684 /*TopLevelOfInitList=*/true);
1685 }
1686
1687 Expr *ResultExpr = nullptr;
1688
1689 if (Result.isInvalid())
1690 hadError = true; // types weren't compatible.
1691 else {
1692 ResultExpr = Result.getAs<Expr>();
1693
1694 if (ResultExpr != expr && !VerifyOnly) {
1695 // The type was promoted, update initializer list.
1696 // FIXME: Why are we updating the syntactic init list?
1697 IList->setInit(Index, ResultExpr);
1698 }
1699 }
1700 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1701 ++Index;
1702 if (AggrDeductionCandidateParamTypes)
1703 AggrDeductionCandidateParamTypes->push_back(DeclType);
1704}
1705
1706void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1707 InitListExpr *IList, QualType DeclType,
1708 unsigned &Index,
1709 InitListExpr *StructuredList,
1710 unsigned &StructuredIndex) {
1711 if (Index >= IList->getNumInits()) {
1712 // FIXME: It would be wonderful if we could point at the actual member. In
1713 // general, it would be useful to pass location information down the stack,
1714 // so that we know the location (or decl) of the "current object" being
1715 // initialized.
1716 if (!VerifyOnly)
1717 SemaRef.Diag(IList->getBeginLoc(),
1718 diag::err_init_reference_member_uninitialized)
1719 << DeclType << IList->getSourceRange();
1720 hadError = true;
1721 ++Index;
1722 ++StructuredIndex;
1723 return;
1724 }
1725
1726 Expr *expr = IList->getInit(Index);
1727 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1728 if (!VerifyOnly)
1729 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1730 << DeclType << IList->getSourceRange();
1731 hadError = true;
1732 ++Index;
1733 ++StructuredIndex;
1734 return;
1735 }
1736
1737 ExprResult Result;
1738 if (VerifyOnly) {
1739 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1740 Result = getDummyInit();
1741 else
1742 Result = ExprError();
1743 } else {
1744 Result =
1745 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1746 /*TopLevelOfInitList=*/true);
1747 }
1748
1749 if (Result.isInvalid())
1750 hadError = true;
1751
1752 expr = Result.getAs<Expr>();
1753 // FIXME: Why are we updating the syntactic init list?
1754 if (!VerifyOnly && expr)
1755 IList->setInit(Index, expr);
1756
1757 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1758 ++Index;
1759 if (AggrDeductionCandidateParamTypes)
1760 AggrDeductionCandidateParamTypes->push_back(DeclType);
1761}
1762
1763void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1764 InitListExpr *IList, QualType DeclType,
1765 unsigned &Index,
1766 InitListExpr *StructuredList,
1767 unsigned &StructuredIndex) {
1768 const VectorType *VT = DeclType->castAs<VectorType>();
1769 unsigned maxElements = VT->getNumElements();
1770 unsigned numEltsInit = 0;
1771 QualType elementType = VT->getElementType();
1772
1773 if (Index >= IList->getNumInits()) {
1774 // Make sure the element type can be value-initialized.
1775 CheckEmptyInitializable(
1777 IList->getEndLoc());
1778 return;
1779 }
1780
1781 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1782 // If the initializing element is a vector, try to copy-initialize
1783 // instead of breaking it apart (which is doomed to failure anyway).
1784 Expr *Init = IList->getInit(Index);
1785 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1786 ExprResult Result;
1787 if (VerifyOnly) {
1788 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1789 Result = getDummyInit();
1790 else
1791 Result = ExprError();
1792 } else {
1793 Result =
1794 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1795 /*TopLevelOfInitList=*/true);
1796 }
1797
1798 Expr *ResultExpr = nullptr;
1799 if (Result.isInvalid())
1800 hadError = true; // types weren't compatible.
1801 else {
1802 ResultExpr = Result.getAs<Expr>();
1803
1804 if (ResultExpr != Init && !VerifyOnly) {
1805 // The type was promoted, update initializer list.
1806 // FIXME: Why are we updating the syntactic init list?
1807 IList->setInit(Index, ResultExpr);
1808 }
1809 }
1810 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1811 ++Index;
1812 if (AggrDeductionCandidateParamTypes)
1813 AggrDeductionCandidateParamTypes->push_back(elementType);
1814 return;
1815 }
1816
1817 InitializedEntity ElementEntity =
1819
1820 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1821 // Don't attempt to go past the end of the init list
1822 if (Index >= IList->getNumInits()) {
1823 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1824 break;
1825 }
1826
1827 ElementEntity.setElementIndex(Index);
1828 CheckSubElementType(ElementEntity, IList, elementType, Index,
1829 StructuredList, StructuredIndex);
1830 }
1831
1832 if (VerifyOnly)
1833 return;
1834
1835 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1836 const VectorType *T = Entity.getType()->castAs<VectorType>();
1837 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1838 T->getVectorKind() == VectorKind::NeonPoly)) {
1839 // The ability to use vector initializer lists is a GNU vector extension
1840 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1841 // endian machines it works fine, however on big endian machines it
1842 // exhibits surprising behaviour:
1843 //
1844 // uint32x2_t x = {42, 64};
1845 // return vget_lane_u32(x, 0); // Will return 64.
1846 //
1847 // Because of this, explicitly call out that it is non-portable.
1848 //
1849 SemaRef.Diag(IList->getBeginLoc(),
1850 diag::warn_neon_vector_initializer_non_portable);
1851
1852 const char *typeCode;
1853 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1854
1855 if (elementType->isFloatingType())
1856 typeCode = "f";
1857 else if (elementType->isSignedIntegerType())
1858 typeCode = "s";
1859 else if (elementType->isUnsignedIntegerType())
1860 typeCode = "u";
1861 else
1862 llvm_unreachable("Invalid element type!");
1863
1864 SemaRef.Diag(IList->getBeginLoc(),
1865 SemaRef.Context.getTypeSize(VT) > 64
1866 ? diag::note_neon_vector_initializer_non_portable_q
1867 : diag::note_neon_vector_initializer_non_portable)
1868 << typeCode << typeSize;
1869 }
1870
1871 return;
1872 }
1873
1874 InitializedEntity ElementEntity =
1876
1877 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1878 for (unsigned i = 0; i < maxElements; ++i) {
1879 // Don't attempt to go past the end of the init list
1880 if (Index >= IList->getNumInits())
1881 break;
1882
1883 ElementEntity.setElementIndex(Index);
1884
1885 QualType IType = IList->getInit(Index)->getType();
1886 if (!IType->isVectorType()) {
1887 CheckSubElementType(ElementEntity, IList, elementType, Index,
1888 StructuredList, StructuredIndex);
1889 ++numEltsInit;
1890 } else {
1891 QualType VecType;
1892 const VectorType *IVT = IType->castAs<VectorType>();
1893 unsigned numIElts = IVT->getNumElements();
1894
1895 if (IType->isExtVectorType())
1896 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1897 else
1898 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1899 IVT->getVectorKind());
1900 CheckSubElementType(ElementEntity, IList, VecType, Index,
1901 StructuredList, StructuredIndex);
1902 numEltsInit += numIElts;
1903 }
1904 }
1905
1906 // OpenCL and HLSL require all elements to be initialized.
1907 if (numEltsInit != maxElements) {
1908 if (!VerifyOnly)
1909 SemaRef.Diag(IList->getBeginLoc(),
1910 diag::err_vector_incorrect_num_initializers)
1911 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1912 hadError = true;
1913 }
1914}
1915
1916/// Check if the type of a class element has an accessible destructor, and marks
1917/// it referenced. Returns true if we shouldn't form a reference to the
1918/// destructor.
1919///
1920/// Aggregate initialization requires a class element's destructor be
1921/// accessible per 11.6.1 [dcl.init.aggr]:
1922///
1923/// The destructor for each element of class type is potentially invoked
1924/// (15.4 [class.dtor]) from the context where the aggregate initialization
1925/// occurs.
1927 Sema &SemaRef) {
1928 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1929 if (!CXXRD)
1930 return false;
1931
1932 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1933 SemaRef.CheckDestructorAccess(Loc, Destructor,
1934 SemaRef.PDiag(diag::err_access_dtor_temp)
1935 << ElementType);
1936 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1937 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1938}
1939
1940void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1941 InitListExpr *IList, QualType &DeclType,
1942 llvm::APSInt elementIndex,
1943 bool SubobjectIsDesignatorContext,
1944 unsigned &Index,
1945 InitListExpr *StructuredList,
1946 unsigned &StructuredIndex) {
1947 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1948
1949 if (!VerifyOnly) {
1950 if (checkDestructorReference(arrayType->getElementType(),
1951 IList->getEndLoc(), SemaRef)) {
1952 hadError = true;
1953 return;
1954 }
1955 }
1956
1957 // Check for the special-case of initializing an array with a string.
1958 if (Index < IList->getNumInits()) {
1959 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1960 SIF_None) {
1961 // We place the string literal directly into the resulting
1962 // initializer list. This is the only place where the structure
1963 // of the structured initializer list doesn't match exactly,
1964 // because doing so would involve allocating one character
1965 // constant for each string.
1966 // FIXME: Should we do these checks in verify-only mode too?
1967 if (!VerifyOnly)
1968 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
1969 SemaRef.getLangOpts().C23 &&
1971 if (StructuredList) {
1972 UpdateStructuredListElement(StructuredList, StructuredIndex,
1973 IList->getInit(Index));
1974 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1975 }
1976 ++Index;
1977 if (AggrDeductionCandidateParamTypes)
1978 AggrDeductionCandidateParamTypes->push_back(DeclType);
1979 return;
1980 }
1981 }
1982 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1983 // Check for VLAs; in standard C it would be possible to check this
1984 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1985 // them in all sorts of strange places).
1986 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1987 if (!VerifyOnly) {
1988 // C23 6.7.10p4: An entity of variable length array type shall not be
1989 // initialized except by an empty initializer.
1990 //
1991 // The C extension warnings are issued from ParseBraceInitializer() and
1992 // do not need to be issued here. However, we continue to issue an error
1993 // in the case there are initializers or we are compiling C++. We allow
1994 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1995 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1996 // FIXME: should we allow this construct in C++ when it makes sense to do
1997 // so?
1998 if (HasErr)
1999 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2000 diag::err_variable_object_no_init)
2001 << VAT->getSizeExpr()->getSourceRange();
2002 }
2003 hadError = HasErr;
2004 ++Index;
2005 ++StructuredIndex;
2006 return;
2007 }
2008
2009 // We might know the maximum number of elements in advance.
2010 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2011 elementIndex.isUnsigned());
2012 bool maxElementsKnown = false;
2013 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2014 maxElements = CAT->getSize();
2015 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2016 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2017 maxElementsKnown = true;
2018 }
2019
2020 QualType elementType = arrayType->getElementType();
2021 while (Index < IList->getNumInits()) {
2022 Expr *Init = IList->getInit(Index);
2023 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2024 // If we're not the subobject that matches up with the '{' for
2025 // the designator, we shouldn't be handling the
2026 // designator. Return immediately.
2027 if (!SubobjectIsDesignatorContext)
2028 return;
2029
2030 // Handle this designated initializer. elementIndex will be
2031 // updated to be the next array element we'll initialize.
2032 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2033 DeclType, nullptr, &elementIndex, Index,
2034 StructuredList, StructuredIndex, true,
2035 false)) {
2036 hadError = true;
2037 continue;
2038 }
2039
2040 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2041 maxElements = maxElements.extend(elementIndex.getBitWidth());
2042 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2043 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2044 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2045
2046 // If the array is of incomplete type, keep track of the number of
2047 // elements in the initializer.
2048 if (!maxElementsKnown && elementIndex > maxElements)
2049 maxElements = elementIndex;
2050
2051 continue;
2052 }
2053
2054 // If we know the maximum number of elements, and we've already
2055 // hit it, stop consuming elements in the initializer list.
2056 if (maxElementsKnown && elementIndex == maxElements)
2057 break;
2058
2059 InitializedEntity ElementEntity =
2060 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
2061 Entity);
2062 // Check this element.
2063 CheckSubElementType(ElementEntity, IList, elementType, Index,
2064 StructuredList, StructuredIndex);
2065 ++elementIndex;
2066
2067 // If the array is of incomplete type, keep track of the number of
2068 // elements in the initializer.
2069 if (!maxElementsKnown && elementIndex > maxElements)
2070 maxElements = elementIndex;
2071 }
2072 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2073 // If this is an incomplete array type, the actual type needs to
2074 // be calculated here.
2075 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2076 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2077 // Sizing an array implicitly to zero is not allowed by ISO C,
2078 // but is supported by GNU.
2079 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2080 }
2081
2082 DeclType = SemaRef.Context.getConstantArrayType(
2083 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2084 }
2085 if (!hadError) {
2086 // If there are any members of the array that get value-initialized, check
2087 // that is possible. That happens if we know the bound and don't have
2088 // enough elements, or if we're performing an array new with an unknown
2089 // bound.
2090 if ((maxElementsKnown && elementIndex < maxElements) ||
2091 Entity.isVariableLengthArrayNew())
2092 CheckEmptyInitializable(
2094 IList->getEndLoc());
2095 }
2096}
2097
2098bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2099 Expr *InitExpr,
2100 FieldDecl *Field,
2101 bool TopLevelObject) {
2102 // Handle GNU flexible array initializers.
2103 unsigned FlexArrayDiag;
2104 if (isa<InitListExpr>(InitExpr) &&
2105 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2106 // Empty flexible array init always allowed as an extension
2107 FlexArrayDiag = diag::ext_flexible_array_init;
2108 } else if (!TopLevelObject) {
2109 // Disallow flexible array init on non-top-level object
2110 FlexArrayDiag = diag::err_flexible_array_init;
2111 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2112 // Disallow flexible array init on anything which is not a variable.
2113 FlexArrayDiag = diag::err_flexible_array_init;
2114 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2115 // Disallow flexible array init on local variables.
2116 FlexArrayDiag = diag::err_flexible_array_init;
2117 } else {
2118 // Allow other cases.
2119 FlexArrayDiag = diag::ext_flexible_array_init;
2120 }
2121
2122 if (!VerifyOnly) {
2123 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2124 << InitExpr->getBeginLoc();
2125 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2126 << Field;
2127 }
2128
2129 return FlexArrayDiag != diag::ext_flexible_array_init;
2130}
2131
2132void InitListChecker::CheckStructUnionTypes(
2133 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2135 bool SubobjectIsDesignatorContext, unsigned &Index,
2136 InitListExpr *StructuredList, unsigned &StructuredIndex,
2137 bool TopLevelObject) {
2138 const RecordDecl *RD = getRecordDecl(DeclType);
2139
2140 // If the record is invalid, some of it's members are invalid. To avoid
2141 // confusion, we forgo checking the initializer for the entire record.
2142 if (RD->isInvalidDecl()) {
2143 // Assume it was supposed to consume a single initializer.
2144 ++Index;
2145 hadError = true;
2146 return;
2147 }
2148
2149 if (RD->isUnion() && IList->getNumInits() == 0) {
2150 if (!VerifyOnly)
2151 for (FieldDecl *FD : RD->fields()) {
2152 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2153 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2154 hadError = true;
2155 return;
2156 }
2157 }
2158
2159 // If there's a default initializer, use it.
2160 if (isa<CXXRecordDecl>(RD) &&
2161 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2162 if (!StructuredList)
2163 return;
2164 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2165 Field != FieldEnd; ++Field) {
2166 if (Field->hasInClassInitializer()) {
2167 StructuredList->setInitializedFieldInUnion(*Field);
2168 // FIXME: Actually build a CXXDefaultInitExpr?
2169 return;
2170 }
2171 }
2172 }
2173
2174 // Value-initialize the first member of the union that isn't an unnamed
2175 // bitfield.
2176 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2177 Field != FieldEnd; ++Field) {
2178 if (!Field->isUnnamedBitfield()) {
2179 CheckEmptyInitializable(
2180 InitializedEntity::InitializeMember(*Field, &Entity),
2181 IList->getEndLoc());
2182 if (StructuredList)
2183 StructuredList->setInitializedFieldInUnion(*Field);
2184 break;
2185 }
2186 }
2187 return;
2188 }
2189
2190 bool InitializedSomething = false;
2191
2192 // If we have any base classes, they are initialized prior to the fields.
2193 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2194 auto &Base = *I;
2195 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2196
2197 // Designated inits always initialize fields, so if we see one, all
2198 // remaining base classes have no explicit initializer.
2199 if (Init && isa<DesignatedInitExpr>(Init))
2200 Init = nullptr;
2201
2202 // C++ [over.match.class.deduct]p1.6:
2203 // each non-trailing aggregate element that is a pack expansion is assumed
2204 // to correspond to no elements of the initializer list, and (1.7) a
2205 // trailing aggregate element that is a pack expansion is assumed to
2206 // correspond to all remaining elements of the initializer list (if any).
2207
2208 // C++ [over.match.class.deduct]p1.9:
2209 // ... except that additional parameter packs of the form P_j... are
2210 // inserted into the parameter list in their original aggregate element
2211 // position corresponding to each non-trailing aggregate element of
2212 // type P_j that was skipped because it was a parameter pack, and the
2213 // trailing sequence of parameters corresponding to a trailing
2214 // aggregate element that is a pack expansion (if any) is replaced
2215 // by a single parameter of the form T_n....
2216 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2217 AggrDeductionCandidateParamTypes->push_back(
2218 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2219
2220 // Trailing pack expansion
2221 if (I + 1 == E && RD->field_empty()) {
2222 if (Index < IList->getNumInits())
2223 Index = IList->getNumInits();
2224 return;
2225 }
2226
2227 continue;
2228 }
2229
2230 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2232 SemaRef.Context, &Base, false, &Entity);
2233 if (Init) {
2234 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2235 StructuredList, StructuredIndex);
2236 InitializedSomething = true;
2237 } else {
2238 CheckEmptyInitializable(BaseEntity, InitLoc);
2239 }
2240
2241 if (!VerifyOnly)
2242 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2243 hadError = true;
2244 return;
2245 }
2246 }
2247
2248 // If structDecl is a forward declaration, this loop won't do
2249 // anything except look at designated initializers; That's okay,
2250 // because an error should get printed out elsewhere. It might be
2251 // worthwhile to skip over the rest of the initializer, though.
2252 RecordDecl::field_iterator FieldEnd = RD->field_end();
2253 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2254 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2255 });
2256 bool HasDesignatedInit = false;
2257
2258 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2259
2260 while (Index < IList->getNumInits()) {
2261 Expr *Init = IList->getInit(Index);
2262 SourceLocation InitLoc = Init->getBeginLoc();
2263
2264 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2265 // If we're not the subobject that matches up with the '{' for
2266 // the designator, we shouldn't be handling the
2267 // designator. Return immediately.
2268 if (!SubobjectIsDesignatorContext)
2269 return;
2270
2271 HasDesignatedInit = true;
2272
2273 // Handle this designated initializer. Field will be updated to
2274 // the next field that we'll be initializing.
2275 bool DesignatedInitFailed = CheckDesignatedInitializer(
2276 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2277 StructuredList, StructuredIndex, true, TopLevelObject);
2278 if (DesignatedInitFailed)
2279 hadError = true;
2280
2281 // Find the field named by the designated initializer.
2282 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2283 if (!VerifyOnly && D->isFieldDesignator()) {
2284 FieldDecl *F = D->getFieldDecl();
2285 InitializedFields.insert(F);
2286 if (!DesignatedInitFailed) {
2287 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2288 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2289 hadError = true;
2290 return;
2291 }
2292 }
2293 }
2294
2295 InitializedSomething = true;
2296 continue;
2297 }
2298
2299 // Check if this is an initializer of forms:
2300 //
2301 // struct foo f = {};
2302 // struct foo g = {0};
2303 //
2304 // These are okay for randomized structures. [C99 6.7.8p19]
2305 //
2306 // Also, if there is only one element in the structure, we allow something
2307 // like this, because it's really not randomized in the traditional sense.
2308 //
2309 // struct foo h = {bar};
2310 auto IsZeroInitializer = [&](const Expr *I) {
2311 if (IList->getNumInits() == 1) {
2312 if (NumRecordDecls == 1)
2313 return true;
2314 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2315 return IL->getValue().isZero();
2316 }
2317 return false;
2318 };
2319
2320 // Don't allow non-designated initializers on randomized structures.
2321 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2322 if (!VerifyOnly)
2323 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2324 hadError = true;
2325 break;
2326 }
2327
2328 if (Field == FieldEnd) {
2329 // We've run out of fields. We're done.
2330 break;
2331 }
2332
2333 // We've already initialized a member of a union. We're done.
2334 if (InitializedSomething && RD->isUnion())
2335 break;
2336
2337 // If we've hit the flexible array member at the end, we're done.
2338 if (Field->getType()->isIncompleteArrayType())
2339 break;
2340
2341 if (Field->isUnnamedBitfield()) {
2342 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2343 ++Field;
2344 continue;
2345 }
2346
2347 // Make sure we can use this declaration.
2348 bool InvalidUse;
2349 if (VerifyOnly)
2350 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2351 else
2352 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2353 *Field, IList->getInit(Index)->getBeginLoc());
2354 if (InvalidUse) {
2355 ++Index;
2356 ++Field;
2357 hadError = true;
2358 continue;
2359 }
2360
2361 if (!VerifyOnly) {
2362 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2363 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2364 hadError = true;
2365 return;
2366 }
2367 }
2368
2369 InitializedEntity MemberEntity =
2370 InitializedEntity::InitializeMember(*Field, &Entity);
2371 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2372 StructuredList, StructuredIndex);
2373 InitializedSomething = true;
2374 InitializedFields.insert(*Field);
2375
2376 if (RD->isUnion() && StructuredList) {
2377 // Initialize the first field within the union.
2378 StructuredList->setInitializedFieldInUnion(*Field);
2379 }
2380
2381 ++Field;
2382 }
2383
2384 // Emit warnings for missing struct field initializers.
2385 // This check is disabled for designated initializers in C.
2386 // This matches gcc behaviour.
2387 bool IsCDesignatedInitializer =
2388 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2389 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2390 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2391 !IsCDesignatedInitializer) {
2392 // It is possible we have one or more unnamed bitfields remaining.
2393 // Find first (if any) named field and emit warning.
2394 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2395 : Field,
2396 end = RD->field_end();
2397 it != end; ++it) {
2398 if (HasDesignatedInit && InitializedFields.count(*it))
2399 continue;
2400
2401 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&
2402 !it->getType()->isIncompleteArrayType()) {
2403 auto Diag = HasDesignatedInit
2404 ? diag::warn_missing_designated_field_initializers
2405 : diag::warn_missing_field_initializers;
2406 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2407 break;
2408 }
2409 }
2410 }
2411
2412 // Check that any remaining fields can be value-initialized if we're not
2413 // building a structured list. (If we are, we'll check this later.)
2414 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2415 !Field->getType()->isIncompleteArrayType()) {
2416 for (; Field != FieldEnd && !hadError; ++Field) {
2417 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2418 CheckEmptyInitializable(
2419 InitializedEntity::InitializeMember(*Field, &Entity),
2420 IList->getEndLoc());
2421 }
2422 }
2423
2424 // Check that the types of the remaining fields have accessible destructors.
2425 if (!VerifyOnly) {
2426 // If the initializer expression has a designated initializer, check the
2427 // elements for which a designated initializer is not provided too.
2428 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2429 : Field;
2430 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2431 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2432 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2433 hadError = true;
2434 return;
2435 }
2436 }
2437 }
2438
2439 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2440 Index >= IList->getNumInits())
2441 return;
2442
2443 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2444 TopLevelObject)) {
2445 hadError = true;
2446 ++Index;
2447 return;
2448 }
2449
2450 InitializedEntity MemberEntity =
2451 InitializedEntity::InitializeMember(*Field, &Entity);
2452
2453 if (isa<InitListExpr>(IList->getInit(Index)) ||
2454 AggrDeductionCandidateParamTypes)
2455 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2456 StructuredList, StructuredIndex);
2457 else
2458 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2459 StructuredList, StructuredIndex);
2460}
2461
2462/// Expand a field designator that refers to a member of an
2463/// anonymous struct or union into a series of field designators that
2464/// refers to the field within the appropriate subobject.
2465///
2467 DesignatedInitExpr *DIE,
2468 unsigned DesigIdx,
2469 IndirectFieldDecl *IndirectField) {
2471
2472 // Build the replacement designators.
2473 SmallVector<Designator, 4> Replacements;
2474 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2475 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2476 if (PI + 1 == PE)
2477 Replacements.push_back(Designator::CreateFieldDesignator(
2478 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2479 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2480 else
2481 Replacements.push_back(Designator::CreateFieldDesignator(
2482 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2483 assert(isa<FieldDecl>(*PI));
2484 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2485 }
2486
2487 // Expand the current designator into the set of replacement
2488 // designators, so we have a full subobject path down to where the
2489 // member of the anonymous struct/union is actually stored.
2490 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2491 &Replacements[0] + Replacements.size());
2492}
2493
2495 DesignatedInitExpr *DIE) {
2496 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2497 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2498 for (unsigned I = 0; I < NumIndexExprs; ++I)
2499 IndexExprs[I] = DIE->getSubExpr(I + 1);
2500 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2501 IndexExprs,
2502 DIE->getEqualOrColonLoc(),
2503 DIE->usesGNUSyntax(), DIE->getInit());
2504}
2505
2506namespace {
2507
2508// Callback to only accept typo corrections that are for field members of
2509// the given struct or union.
2510class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2511 public:
2512 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2513 : Record(RD) {}
2514
2515 bool ValidateCandidate(const TypoCorrection &candidate) override {
2516 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2517 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2518 }
2519
2520 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2521 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2522 }
2523
2524 private:
2525 const RecordDecl *Record;
2526};
2527
2528} // end anonymous namespace
2529
2530/// Check the well-formedness of a C99 designated initializer.
2531///
2532/// Determines whether the designated initializer @p DIE, which
2533/// resides at the given @p Index within the initializer list @p
2534/// IList, is well-formed for a current object of type @p DeclType
2535/// (C99 6.7.8). The actual subobject that this designator refers to
2536/// within the current subobject is returned in either
2537/// @p NextField or @p NextElementIndex (whichever is appropriate).
2538///
2539/// @param IList The initializer list in which this designated
2540/// initializer occurs.
2541///
2542/// @param DIE The designated initializer expression.
2543///
2544/// @param DesigIdx The index of the current designator.
2545///
2546/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2547/// into which the designation in @p DIE should refer.
2548///
2549/// @param NextField If non-NULL and the first designator in @p DIE is
2550/// a field, this will be set to the field declaration corresponding
2551/// to the field named by the designator. On input, this is expected to be
2552/// the next field that would be initialized in the absence of designation,
2553/// if the complete object being initialized is a struct.
2554///
2555/// @param NextElementIndex If non-NULL and the first designator in @p
2556/// DIE is an array designator or GNU array-range designator, this
2557/// will be set to the last index initialized by this designator.
2558///
2559/// @param Index Index into @p IList where the designated initializer
2560/// @p DIE occurs.
2561///
2562/// @param StructuredList The initializer list expression that
2563/// describes all of the subobject initializers in the order they'll
2564/// actually be initialized.
2565///
2566/// @returns true if there was an error, false otherwise.
2567bool
2568InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2569 InitListExpr *IList,
2570 DesignatedInitExpr *DIE,
2571 unsigned DesigIdx,
2572 QualType &CurrentObjectType,
2573 RecordDecl::field_iterator *NextField,
2574 llvm::APSInt *NextElementIndex,
2575 unsigned &Index,
2576 InitListExpr *StructuredList,
2577 unsigned &StructuredIndex,
2578 bool FinishSubobjectInit,
2579 bool TopLevelObject) {
2580 if (DesigIdx == DIE->size()) {
2581 // C++20 designated initialization can result in direct-list-initialization
2582 // of the designated subobject. This is the only way that we can end up
2583 // performing direct initialization as part of aggregate initialization, so
2584 // it needs special handling.
2585 if (DIE->isDirectInit()) {
2586 Expr *Init = DIE->getInit();
2587 assert(isa<InitListExpr>(Init) &&
2588 "designator result in direct non-list initialization?");
2590 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2591 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2592 /*TopLevelOfInitList*/ true);
2593 if (StructuredList) {
2594 ExprResult Result = VerifyOnly
2595 ? getDummyInit()
2596 : Seq.Perform(SemaRef, Entity, Kind, Init);
2597 UpdateStructuredListElement(StructuredList, StructuredIndex,
2598 Result.get());
2599 }
2600 ++Index;
2601 if (AggrDeductionCandidateParamTypes)
2602 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2603 return !Seq;
2604 }
2605
2606 // Check the actual initialization for the designated object type.
2607 bool prevHadError = hadError;
2608
2609 // Temporarily remove the designator expression from the
2610 // initializer list that the child calls see, so that we don't try
2611 // to re-process the designator.
2612 unsigned OldIndex = Index;
2613 IList->setInit(OldIndex, DIE->getInit());
2614
2615 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2616 StructuredIndex, /*DirectlyDesignated=*/true);
2617
2618 // Restore the designated initializer expression in the syntactic
2619 // form of the initializer list.
2620 if (IList->getInit(OldIndex) != DIE->getInit())
2621 DIE->setInit(IList->getInit(OldIndex));
2622 IList->setInit(OldIndex, DIE);
2623
2624 return hadError && !prevHadError;
2625 }
2626
2628 bool IsFirstDesignator = (DesigIdx == 0);
2629 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2630 // Determine the structural initializer list that corresponds to the
2631 // current subobject.
2632 if (IsFirstDesignator)
2633 StructuredList = FullyStructuredList;
2634 else {
2635 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2636 StructuredList->getInit(StructuredIndex) : nullptr;
2637 if (!ExistingInit && StructuredList->hasArrayFiller())
2638 ExistingInit = StructuredList->getArrayFiller();
2639
2640 if (!ExistingInit)
2641 StructuredList = getStructuredSubobjectInit(
2642 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2643 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2644 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2645 StructuredList = Result;
2646 else {
2647 // We are creating an initializer list that initializes the
2648 // subobjects of the current object, but there was already an
2649 // initialization that completely initialized the current
2650 // subobject, e.g., by a compound literal:
2651 //
2652 // struct X { int a, b; };
2653 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2654 //
2655 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2656 // designated initializer re-initializes only its current object
2657 // subobject [0].b.
2658 diagnoseInitOverride(ExistingInit,
2659 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2660 /*UnionOverride=*/false,
2661 /*FullyOverwritten=*/false);
2662
2663 if (!VerifyOnly) {
2665 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2666 StructuredList = E->getUpdater();
2667 else {
2668 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2670 ExistingInit, DIE->getEndLoc());
2671 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2672 StructuredList = DIUE->getUpdater();
2673 }
2674 } else {
2675 // We don't need to track the structured representation of a
2676 // designated init update of an already-fully-initialized object in
2677 // verify-only mode. The only reason we would need the structure is
2678 // to determine where the uninitialized "holes" are, and in this
2679 // case, we know there aren't any and we can't introduce any.
2680 StructuredList = nullptr;
2681 }
2682 }
2683 }
2684 }
2685
2686 if (D->isFieldDesignator()) {
2687 // C99 6.7.8p7:
2688 //
2689 // If a designator has the form
2690 //
2691 // . identifier
2692 //
2693 // then the current object (defined below) shall have
2694 // structure or union type and the identifier shall be the
2695 // name of a member of that type.
2696 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2697 if (!RD) {
2698 SourceLocation Loc = D->getDotLoc();
2699 if (Loc.isInvalid())
2700 Loc = D->getFieldLoc();
2701 if (!VerifyOnly)
2702 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2703 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2704 ++Index;
2705 return true;
2706 }
2707
2708 FieldDecl *KnownField = D->getFieldDecl();
2709 if (!KnownField) {
2710 const IdentifierInfo *FieldName = D->getFieldName();
2711 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2712 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2713 KnownField = FD;
2714 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2715 // In verify mode, don't modify the original.
2716 if (VerifyOnly)
2717 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2718 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2719 D = DIE->getDesignator(DesigIdx);
2720 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2721 }
2722 if (!KnownField) {
2723 if (VerifyOnly) {
2724 ++Index;
2725 return true; // No typo correction when just trying this out.
2726 }
2727
2728 // We found a placeholder variable
2729 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2730 FieldName)) {
2731 ++Index;
2732 return true;
2733 }
2734 // Name lookup found something, but it wasn't a field.
2735 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2736 !Lookup.empty()) {
2737 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2738 << FieldName;
2739 SemaRef.Diag(Lookup.front()->getLocation(),
2740 diag::note_field_designator_found);
2741 ++Index;
2742 return true;
2743 }
2744
2745 // Name lookup didn't find anything.
2746 // Determine whether this was a typo for another field name.
2747 FieldInitializerValidatorCCC CCC(RD);
2748 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2749 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2750 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2752 SemaRef.diagnoseTypo(
2753 Corrected,
2754 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2755 << FieldName << CurrentObjectType);
2756 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2757 hadError = true;
2758 } else {
2759 // Typo correction didn't find anything.
2760 SourceLocation Loc = D->getFieldLoc();
2761
2762 // The loc can be invalid with a "null" designator (i.e. an anonymous
2763 // union/struct). Do our best to approximate the location.
2764 if (Loc.isInvalid())
2765 Loc = IList->getBeginLoc();
2766
2767 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2768 << FieldName << CurrentObjectType << DIE->getSourceRange();
2769 ++Index;
2770 return true;
2771 }
2772 }
2773 }
2774
2775 unsigned NumBases = 0;
2776 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2777 NumBases = CXXRD->getNumBases();
2778
2779 unsigned FieldIndex = NumBases;
2780
2781 for (auto *FI : RD->fields()) {
2782 if (FI->isUnnamedBitfield())
2783 continue;
2784 if (declaresSameEntity(KnownField, FI)) {
2785 KnownField = FI;
2786 break;
2787 }
2788 ++FieldIndex;
2789 }
2790
2793
2794 // All of the fields of a union are located at the same place in
2795 // the initializer list.
2796 if (RD->isUnion()) {
2797 FieldIndex = 0;
2798 if (StructuredList) {
2799 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2800 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2801 assert(StructuredList->getNumInits() == 1
2802 && "A union should never have more than one initializer!");
2803
2804 Expr *ExistingInit = StructuredList->getInit(0);
2805 if (ExistingInit) {
2806 // We're about to throw away an initializer, emit warning.
2807 diagnoseInitOverride(
2808 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2809 /*UnionOverride=*/true,
2810 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2811 : true);
2812 }
2813
2814 // remove existing initializer
2815 StructuredList->resizeInits(SemaRef.Context, 0);
2816 StructuredList->setInitializedFieldInUnion(nullptr);
2817 }
2818
2819 StructuredList->setInitializedFieldInUnion(*Field);
2820 }
2821 }
2822
2823 // Make sure we can use this declaration.
2824 bool InvalidUse;
2825 if (VerifyOnly)
2826 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2827 else
2828 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2829 if (InvalidUse) {
2830 ++Index;
2831 return true;
2832 }
2833
2834 // C++20 [dcl.init.list]p3:
2835 // The ordered identifiers in the designators of the designated-
2836 // initializer-list shall form a subsequence of the ordered identifiers
2837 // in the direct non-static data members of T.
2838 //
2839 // Note that this is not a condition on forming the aggregate
2840 // initialization, only on actually performing initialization,
2841 // so it is not checked in VerifyOnly mode.
2842 //
2843 // FIXME: This is the only reordering diagnostic we produce, and it only
2844 // catches cases where we have a top-level field designator that jumps
2845 // backwards. This is the only such case that is reachable in an
2846 // otherwise-valid C++20 program, so is the only case that's required for
2847 // conformance, but for consistency, we should diagnose all the other
2848 // cases where a designator takes us backwards too.
2849 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2850 NextField &&
2851 (*NextField == RD->field_end() ||
2852 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2853 // Find the field that we just initialized.
2854 FieldDecl *PrevField = nullptr;
2855 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2856 if (FI->isUnnamedBitfield())
2857 continue;
2858 if (*NextField != RD->field_end() &&
2859 declaresSameEntity(*FI, **NextField))
2860 break;
2861 PrevField = *FI;
2862 }
2863
2864 if (PrevField &&
2865 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2866 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2867 diag::ext_designated_init_reordered)
2868 << KnownField << PrevField << DIE->getSourceRange();
2869
2870 unsigned OldIndex = StructuredIndex - 1;
2871 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2872 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2873 SemaRef.Diag(PrevInit->getBeginLoc(),
2874 diag::note_previous_field_init)
2875 << PrevField << PrevInit->getSourceRange();
2876 }
2877 }
2878 }
2879 }
2880
2881
2882 // Update the designator with the field declaration.
2883 if (!VerifyOnly)
2884 D->setFieldDecl(*Field);
2885
2886 // Make sure that our non-designated initializer list has space
2887 // for a subobject corresponding to this field.
2888 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2889 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2890
2891 // This designator names a flexible array member.
2892 if (Field->getType()->isIncompleteArrayType()) {
2893 bool Invalid = false;
2894 if ((DesigIdx + 1) != DIE->size()) {
2895 // We can't designate an object within the flexible array
2896 // member (because GCC doesn't allow it).
2897 if (!VerifyOnly) {
2899 = DIE->getDesignator(DesigIdx + 1);
2900 SemaRef.Diag(NextD->getBeginLoc(),
2901 diag::err_designator_into_flexible_array_member)
2902 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2903 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2904 << *Field;
2905 }
2906 Invalid = true;
2907 }
2908
2909 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2910 !isa<StringLiteral>(DIE->getInit())) {
2911 // The initializer is not an initializer list.
2912 if (!VerifyOnly) {
2913 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2914 diag::err_flexible_array_init_needs_braces)
2915 << DIE->getInit()->getSourceRange();
2916 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2917 << *Field;
2918 }
2919 Invalid = true;
2920 }
2921
2922 // Check GNU flexible array initializer.
2923 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2924 TopLevelObject))
2925 Invalid = true;
2926
2927 if (Invalid) {
2928 ++Index;
2929 return true;
2930 }
2931
2932 // Initialize the array.
2933 bool prevHadError = hadError;
2934 unsigned newStructuredIndex = FieldIndex;
2935 unsigned OldIndex = Index;
2936 IList->setInit(Index, DIE->getInit());
2937
2938 InitializedEntity MemberEntity =
2939 InitializedEntity::InitializeMember(*Field, &Entity);
2940 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2941 StructuredList, newStructuredIndex);
2942
2943 IList->setInit(OldIndex, DIE);
2944 if (hadError && !prevHadError) {
2945 ++Field;
2946 ++FieldIndex;
2947 if (NextField)
2948 *NextField = Field;
2949 StructuredIndex = FieldIndex;
2950 return true;
2951 }
2952 } else {
2953 // Recurse to check later designated subobjects.
2954 QualType FieldType = Field->getType();
2955 unsigned newStructuredIndex = FieldIndex;
2956
2957 InitializedEntity MemberEntity =
2958 InitializedEntity::InitializeMember(*Field, &Entity);
2959 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2960 FieldType, nullptr, nullptr, Index,
2961 StructuredList, newStructuredIndex,
2962 FinishSubobjectInit, false))
2963 return true;
2964 }
2965
2966 // Find the position of the next field to be initialized in this
2967 // subobject.
2968 ++Field;
2969 ++FieldIndex;
2970
2971 // If this the first designator, our caller will continue checking
2972 // the rest of this struct/class/union subobject.
2973 if (IsFirstDesignator) {
2974 if (Field != RD->field_end() && Field->isUnnamedBitfield())
2975 ++Field;
2976
2977 if (NextField)
2978 *NextField = Field;
2979
2980 StructuredIndex = FieldIndex;
2981 return false;
2982 }
2983
2984 if (!FinishSubobjectInit)
2985 return false;
2986
2987 // We've already initialized something in the union; we're done.
2988 if (RD->isUnion())
2989 return hadError;
2990
2991 // Check the remaining fields within this class/struct/union subobject.
2992 bool prevHadError = hadError;
2993
2994 auto NoBases =
2997 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2998 false, Index, StructuredList, FieldIndex);
2999 return hadError && !prevHadError;
3000 }
3001
3002 // C99 6.7.8p6:
3003 //
3004 // If a designator has the form
3005 //
3006 // [ constant-expression ]
3007 //
3008 // then the current object (defined below) shall have array
3009 // type and the expression shall be an integer constant
3010 // expression. If the array is of unknown size, any
3011 // nonnegative value is valid.
3012 //
3013 // Additionally, cope with the GNU extension that permits
3014 // designators of the form
3015 //
3016 // [ constant-expression ... constant-expression ]
3017 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3018 if (!AT) {
3019 if (!VerifyOnly)
3020 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3021 << CurrentObjectType;
3022 ++Index;
3023 return true;
3024 }
3025
3026 Expr *IndexExpr = nullptr;
3027 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3028 if (D->isArrayDesignator()) {
3029 IndexExpr = DIE->getArrayIndex(*D);
3030 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3031 DesignatedEndIndex = DesignatedStartIndex;
3032 } else {
3033 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3034
3035 DesignatedStartIndex =
3037 DesignatedEndIndex =
3039 IndexExpr = DIE->getArrayRangeEnd(*D);
3040
3041 // Codegen can't handle evaluating array range designators that have side
3042 // effects, because we replicate the AST value for each initialized element.
3043 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3044 // elements with something that has a side effect, so codegen can emit an
3045 // "error unsupported" error instead of miscompiling the app.
3046 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3047 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3048 FullyStructuredList->sawArrayRangeDesignator();
3049 }
3050
3051 if (isa<ConstantArrayType>(AT)) {
3052 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3053 DesignatedStartIndex
3054 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3055 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3056 DesignatedEndIndex
3057 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3058 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3059 if (DesignatedEndIndex >= MaxElements) {
3060 if (!VerifyOnly)
3061 SemaRef.Diag(IndexExpr->getBeginLoc(),
3062 diag::err_array_designator_too_large)
3063 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3064 << IndexExpr->getSourceRange();
3065 ++Index;
3066 return true;
3067 }
3068 } else {
3069 unsigned DesignatedIndexBitWidth =
3071 DesignatedStartIndex =
3072 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3073 DesignatedEndIndex =
3074 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3075 DesignatedStartIndex.setIsUnsigned(true);
3076 DesignatedEndIndex.setIsUnsigned(true);
3077 }
3078
3079 bool IsStringLiteralInitUpdate =
3080 StructuredList && StructuredList->isStringLiteralInit();
3081 if (IsStringLiteralInitUpdate && VerifyOnly) {
3082 // We're just verifying an update to a string literal init. We don't need
3083 // to split the string up into individual characters to do that.
3084 StructuredList = nullptr;
3085 } else if (IsStringLiteralInitUpdate) {
3086 // We're modifying a string literal init; we have to decompose the string
3087 // so we can modify the individual characters.
3088 ASTContext &Context = SemaRef.Context;
3089 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3090
3091 // Compute the character type
3092 QualType CharTy = AT->getElementType();
3093
3094 // Compute the type of the integer literals.
3095 QualType PromotedCharTy = CharTy;
3096 if (Context.isPromotableIntegerType(CharTy))
3097 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3098 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3099
3100 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3101 // Get the length of the string.
3102 uint64_t StrLen = SL->getLength();
3103 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3104 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3105 StructuredList->resizeInits(Context, StrLen);
3106
3107 // Build a literal for each character in the string, and put them into
3108 // the init list.
3109 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3110 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3111 Expr *Init = new (Context) IntegerLiteral(
3112 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3113 if (CharTy != PromotedCharTy)
3114 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3115 Init, nullptr, VK_PRValue,
3117 StructuredList->updateInit(Context, i, Init);
3118 }
3119 } else {
3120 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3121 std::string Str;
3122 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3123
3124 // Get the length of the string.
3125 uint64_t StrLen = Str.size();
3126 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3127 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3128 StructuredList->resizeInits(Context, StrLen);
3129
3130 // Build a literal for each character in the string, and put them into
3131 // the init list.
3132 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3133 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3134 Expr *Init = new (Context) IntegerLiteral(
3135 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3136 if (CharTy != PromotedCharTy)
3137 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3138 Init, nullptr, VK_PRValue,
3140 StructuredList->updateInit(Context, i, Init);
3141 }
3142 }
3143 }
3144
3145 // Make sure that our non-designated initializer list has space
3146 // for a subobject corresponding to this array element.
3147 if (StructuredList &&
3148 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3149 StructuredList->resizeInits(SemaRef.Context,
3150 DesignatedEndIndex.getZExtValue() + 1);
3151
3152 // Repeatedly perform subobject initializations in the range
3153 // [DesignatedStartIndex, DesignatedEndIndex].
3154
3155 // Move to the next designator
3156 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3157 unsigned OldIndex = Index;
3158
3159 InitializedEntity ElementEntity =
3161
3162 while (DesignatedStartIndex <= DesignatedEndIndex) {
3163 // Recurse to check later designated subobjects.
3164 QualType ElementType = AT->getElementType();
3165 Index = OldIndex;
3166
3167 ElementEntity.setElementIndex(ElementIndex);
3168 if (CheckDesignatedInitializer(
3169 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3170 nullptr, Index, StructuredList, ElementIndex,
3171 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3172 false))
3173 return true;
3174
3175 // Move to the next index in the array that we'll be initializing.
3176 ++DesignatedStartIndex;
3177 ElementIndex = DesignatedStartIndex.getZExtValue();
3178 }
3179
3180 // If this the first designator, our caller will continue checking
3181 // the rest of this array subobject.
3182 if (IsFirstDesignator) {
3183 if (NextElementIndex)
3184 *NextElementIndex = DesignatedStartIndex;
3185 StructuredIndex = ElementIndex;
3186 return false;
3187 }
3188
3189 if (!FinishSubobjectInit)
3190 return false;
3191
3192 // Check the remaining elements within this array subobject.
3193 bool prevHadError = hadError;
3194 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3195 /*SubobjectIsDesignatorContext=*/false, Index,
3196 StructuredList, ElementIndex);
3197 return hadError && !prevHadError;
3198}
3199
3200// Get the structured initializer list for a subobject of type
3201// @p CurrentObjectType.
3203InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3204 QualType CurrentObjectType,
3205 InitListExpr *StructuredList,
3206 unsigned StructuredIndex,
3207 SourceRange InitRange,
3208 bool IsFullyOverwritten) {
3209 if (!StructuredList)
3210 return nullptr;
3211
3212 Expr *ExistingInit = nullptr;
3213 if (StructuredIndex < StructuredList->getNumInits())
3214 ExistingInit = StructuredList->getInit(StructuredIndex);
3215
3216 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3217 // There might have already been initializers for subobjects of the current
3218 // object, but a subsequent initializer list will overwrite the entirety
3219 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3220 //
3221 // struct P { char x[6]; };
3222 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3223 //
3224 // The first designated initializer is ignored, and l.x is just "f".
3225 if (!IsFullyOverwritten)
3226 return Result;
3227
3228 if (ExistingInit) {
3229 // We are creating an initializer list that initializes the
3230 // subobjects of the current object, but there was already an
3231 // initialization that completely initialized the current
3232 // subobject:
3233 //
3234 // struct X { int a, b; };
3235 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3236 //
3237 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3238 // designated initializer overwrites the [0].b initializer
3239 // from the prior initialization.
3240 //
3241 // When the existing initializer is an expression rather than an
3242 // initializer list, we cannot decompose and update it in this way.
3243 // For example:
3244 //
3245 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3246 //
3247 // This case is handled by CheckDesignatedInitializer.
3248 diagnoseInitOverride(ExistingInit, InitRange);
3249 }
3250
3251 unsigned ExpectedNumInits = 0;
3252 if (Index < IList->getNumInits()) {
3253 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3254 ExpectedNumInits = Init->getNumInits();
3255 else
3256 ExpectedNumInits = IList->getNumInits() - Index;
3257 }
3258
3259 InitListExpr *Result =
3260 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3261
3262 // Link this new initializer list into the structured initializer
3263 // lists.
3264 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3265 return Result;
3266}
3267
3269InitListChecker::createInitListExpr(QualType CurrentObjectType,
3270 SourceRange InitRange,
3271 unsigned ExpectedNumInits) {
3272 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3273 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3274
3275 QualType ResultType = CurrentObjectType;
3276 if (!ResultType->isArrayType())
3277 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3278 Result->setType(ResultType);
3279
3280 // Pre-allocate storage for the structured initializer list.
3281 unsigned NumElements = 0;
3282
3283 if (const ArrayType *AType
3284 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3285 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3286 NumElements = CAType->getSize().getZExtValue();
3287 // Simple heuristic so that we don't allocate a very large
3288 // initializer with many empty entries at the end.
3289 if (NumElements > ExpectedNumInits)
3290 NumElements = 0;
3291 }
3292 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3293 NumElements = VType->getNumElements();
3294 } else if (CurrentObjectType->isRecordType()) {
3295 NumElements = numStructUnionElements(CurrentObjectType);
3296 } else if (CurrentObjectType->isDependentType()) {
3297 NumElements = 1;
3298 }
3299
3300 Result->reserveInits(SemaRef.Context, NumElements);
3301
3302 return Result;
3303}
3304
3305/// Update the initializer at index @p StructuredIndex within the
3306/// structured initializer list to the value @p expr.
3307void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3308 unsigned &StructuredIndex,
3309 Expr *expr) {
3310 // No structured initializer list to update
3311 if (!StructuredList)
3312 return;
3313
3314 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3315 StructuredIndex, expr)) {
3316 // This initializer overwrites a previous initializer.
3317 // No need to diagnose when `expr` is nullptr because a more relevant
3318 // diagnostic has already been issued and this diagnostic is potentially
3319 // noise.
3320 if (expr)
3321 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3322 }
3323
3324 ++StructuredIndex;
3325}
3326
3327/// Determine whether we can perform aggregate initialization for the purposes
3328/// of overload resolution.
3330 const InitializedEntity &Entity, InitListExpr *From) {
3331 QualType Type = Entity.getType();
3332 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3333 /*TreatUnavailableAsInvalid=*/false,
3334 /*InOverloadResolution=*/true);
3335 return !Check.HadError();
3336}
3337
3338/// Check that the given Index expression is a valid array designator
3339/// value. This is essentially just a wrapper around
3340/// VerifyIntegerConstantExpression that also checks for negative values
3341/// and produces a reasonable diagnostic if there is a
3342/// failure. Returns the index expression, possibly with an implicit cast
3343/// added, on success. If everything went okay, Value will receive the
3344/// value of the constant expression.
3345static ExprResult
3346CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3347 SourceLocation Loc = Index->getBeginLoc();
3348
3349 // Make sure this is an integer constant expression.
3352 if (Result.isInvalid())
3353 return Result;
3354
3355 if (Value.isSigned() && Value.isNegative())
3356 return S.Diag(Loc, diag::err_array_designator_negative)
3357 << toString(Value, 10) << Index->getSourceRange();
3358
3359 Value.setIsUnsigned(true);
3360 return Result;
3361}
3362
3364 SourceLocation EqualOrColonLoc,
3365 bool GNUSyntax,
3366 ExprResult Init) {
3367 typedef DesignatedInitExpr::Designator ASTDesignator;
3368
3369 bool Invalid = false;
3371 SmallVector<Expr *, 32> InitExpressions;
3372
3373 // Build designators and check array designator expressions.
3374 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3375 const Designator &D = Desig.getDesignator(Idx);
3376
3377 if (D.isFieldDesignator()) {
3378 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3379 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3380 } else if (D.isArrayDesignator()) {
3381 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3382 llvm::APSInt IndexValue;
3383 if (!Index->isTypeDependent() && !Index->isValueDependent())
3384 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3385 if (!Index)
3386 Invalid = true;
3387 else {
3388 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3389 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3390 InitExpressions.push_back(Index);
3391 }
3392 } else if (D.isArrayRangeDesignator()) {
3393 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3394 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3395 llvm::APSInt StartValue;
3396 llvm::APSInt EndValue;
3397 bool StartDependent = StartIndex->isTypeDependent() ||
3398 StartIndex->isValueDependent();
3399 bool EndDependent = EndIndex->isTypeDependent() ||
3400 EndIndex->isValueDependent();
3401 if (!StartDependent)
3402 StartIndex =
3403 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3404 if (!EndDependent)
3405 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3406
3407 if (!StartIndex || !EndIndex)
3408 Invalid = true;
3409 else {
3410 // Make sure we're comparing values with the same bit width.
3411 if (StartDependent || EndDependent) {
3412 // Nothing to compute.
3413 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3414 EndValue = EndValue.extend(StartValue.getBitWidth());
3415 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3416 StartValue = StartValue.extend(EndValue.getBitWidth());
3417
3418 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3419 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3420 << toString(StartValue, 10) << toString(EndValue, 10)
3421 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3422 Invalid = true;
3423 } else {
3424 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3425 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3426 D.getRBracketLoc()));
3427 InitExpressions.push_back(StartIndex);
3428 InitExpressions.push_back(EndIndex);
3429 }
3430 }
3431 }
3432 }
3433
3434 if (Invalid || Init.isInvalid())
3435 return ExprError();
3436
3437 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3438 EqualOrColonLoc, GNUSyntax,
3439 Init.getAs<Expr>());
3440}
3441
3442//===----------------------------------------------------------------------===//
3443// Initialization entity
3444//===----------------------------------------------------------------------===//
3445
3446InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3448 : Parent(&Parent), Index(Index)
3449{
3450 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3451 Kind = EK_ArrayElement;
3452 Type = AT->getElementType();
3453 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3454 Kind = EK_VectorElement;
3455 Type = VT->getElementType();
3456 } else {
3457 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3458 assert(CT && "Unexpected type");
3459 Kind = EK_ComplexElement;
3460 Type = CT->getElementType();
3461 }
3462}
3463
3466 const CXXBaseSpecifier *Base,
3467 bool IsInheritedVirtualBase,
3468 const InitializedEntity *Parent) {
3470 Result.Kind = EK_Base;
3471 Result.Parent = Parent;
3472 Result.Base = {Base, IsInheritedVirtualBase};
3473 Result.Type = Base->getType();
3474 return Result;
3475}
3476
3478 switch (getKind()) {
3479 case EK_Parameter:
3481 ParmVarDecl *D = Parameter.getPointer();
3482 return (D ? D->getDeclName() : DeclarationName());
3483 }
3484
3485 case EK_Variable:
3486 case EK_Member:
3488 case EK_Binding:
3490 return Variable.VariableOrMember->getDeclName();
3491
3492 case EK_LambdaCapture:
3493 return DeclarationName(Capture.VarID);
3494
3495 case EK_Result:
3496 case EK_StmtExprResult:
3497 case EK_Exception:
3498 case EK_New:
3499 case EK_Temporary:
3500 case EK_Base:
3501 case EK_Delegating:
3502 case EK_ArrayElement:
3503 case EK_VectorElement:
3504 case EK_ComplexElement:
3505 case EK_BlockElement:
3508 case EK_RelatedResult:
3509 return DeclarationName();
3510 }
3511
3512 llvm_unreachable("Invalid EntityKind!");
3513}
3514
3516 switch (getKind()) {
3517 case EK_Variable:
3518 case EK_Member:
3520 case EK_Binding:
3522 return Variable.VariableOrMember;
3523
3524 case EK_Parameter:
3526 return Parameter.getPointer();
3527
3528 case EK_Result:
3529 case EK_StmtExprResult:
3530 case EK_Exception:
3531 case EK_New:
3532 case EK_Temporary:
3533 case EK_Base:
3534 case EK_Delegating:
3535 case EK_ArrayElement:
3536 case EK_VectorElement:
3537 case EK_ComplexElement:
3538 case EK_BlockElement:
3540 case EK_LambdaCapture:
3542 case EK_RelatedResult:
3543 return nullptr;
3544 }
3545
3546 llvm_unreachable("Invalid EntityKind!");
3547}
3548
3550 switch (getKind()) {
3551 case EK_Result:
3552 case EK_Exception:
3553 return LocAndNRVO.NRVO;
3554
3555 case EK_StmtExprResult:
3556 case EK_Variable:
3557 case EK_Parameter:
3560 case EK_Member:
3562 case EK_Binding:
3563 case EK_New:
3564 case EK_Temporary:
3566 case EK_Base:
3567 case EK_Delegating:
3568 case EK_ArrayElement:
3569 case EK_VectorElement:
3570 case EK_ComplexElement:
3571 case EK_BlockElement:
3573 case EK_LambdaCapture:
3574 case EK_RelatedResult:
3575 break;
3576 }
3577
3578 return false;
3579}
3580
3581unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3582 assert(getParent() != this);
3583 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3584 for (unsigned I = 0; I != Depth; ++I)
3585 OS << "`-";
3586
3587 switch (getKind()) {
3588 case EK_Variable: OS << "Variable"; break;
3589 case EK_Parameter: OS << "Parameter"; break;
3590 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3591 break;
3592 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3593 case EK_Result: OS << "Result"; break;
3594 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3595 case EK_Exception: OS << "Exception"; break;
3596 case EK_Member:
3598 OS << "Member";
3599 break;
3600 case EK_Binding: OS << "Binding"; break;
3601 case EK_New: OS << "New"; break;
3602 case EK_Temporary: OS << "Temporary"; break;
3603 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3604 case EK_RelatedResult: OS << "RelatedResult"; break;
3605 case EK_Base: OS << "Base"; break;
3606 case EK_Delegating: OS << "Delegating"; break;
3607 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3608 case EK_VectorElement: OS << "VectorElement " << Index; break;
3609 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3610 case EK_BlockElement: OS << "Block"; break;
3612 OS << "Block (lambda)";
3613 break;
3614 case EK_LambdaCapture:
3615 OS << "LambdaCapture ";
3616 OS << DeclarationName(Capture.VarID);
3617 break;
3618 }
3619
3620 if (auto *D = getDecl()) {
3621 OS << " ";
3622 D->printQualifiedName(OS);
3623 }
3624
3625 OS << " '" << getType() << "'\n";
3626
3627 return Depth + 1;
3628}
3629
3630LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3631 dumpImpl(llvm::errs());
3632}
3633
3634//===----------------------------------------------------------------------===//
3635// Initialization sequence
3636//===----------------------------------------------------------------------===//
3637
3639 switch (Kind) {
3644 case SK_BindReference:
3646 case SK_FinalCopy:
3648 case SK_UserConversion:
3655 case SK_UnwrapInitList:
3656 case SK_RewrapInitList:
3660 case SK_CAssignment:
3661 case SK_StringInit:
3663 case SK_ArrayLoopIndex:
3664 case SK_ArrayLoopInit:
3665 case SK_ArrayInit:
3666 case SK_GNUArrayInit:
3673 case SK_OCLSamplerInit:
3676 break;
3677
3680 delete ICS;
3681 }
3682}
3683
3685 // There can be some lvalue adjustments after the SK_BindReference step.
3686 for (const Step &S : llvm::reverse(Steps)) {
3687 if (S.Kind == SK_BindReference)
3688 return true;
3689 if (S.Kind == SK_BindReferenceToTemporary)
3690 return false;
3691 }
3692 return false;
3693}
3694
3696 if (!Failed())
3697 return false;
3698
3699 switch (getFailureKind()) {
3710 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3727 case FK_Incomplete:
3732 case FK_PlaceholderType:
3737 return false;
3738
3743 return FailedOverloadResult == OR_Ambiguous;
3744 }
3745
3746 llvm_unreachable("Invalid EntityKind!");
3747}
3748
3750 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3751}
3752
3753void
3754InitializationSequence
3755::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3756 DeclAccessPair Found,
3757 bool HadMultipleCandidates) {
3758 Step S;
3760 S.Type = Function->getType();
3761 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3762 S.Function.Function = Function;
3763 S.Function.FoundDecl = Found;
3764 Steps.push_back(S);
3765}
3766
3768 ExprValueKind VK) {
3769 Step S;
3770 switch (VK) {
3771 case VK_PRValue:
3773 break;
3774 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3775 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3776 }
3777 S.Type = BaseType;
3778 Steps.push_back(S);
3779}
3780
3782 bool BindingTemporary) {
3783 Step S;
3784 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3785 S.Type = T;
3786 Steps.push_back(S);
3787}
3788
3790 Step S;
3791 S.Kind = SK_FinalCopy;
3792 S.Type = T;
3793 Steps.push_back(S);
3794}
3795
3797 Step S;
3799 S.Type = T;
3800 Steps.push_back(S);
3801}
3802
3803void
3805 DeclAccessPair FoundDecl,
3806 QualType T,
3807 bool HadMultipleCandidates) {
3808 Step S;
3809 S.Kind = SK_UserConversion;
3810 S.Type = T;
3811 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3812 S.Function.Function = Function;
3813 S.Function.FoundDecl = FoundDecl;
3814 Steps.push_back(S);
3815}
3816
3818 ExprValueKind VK) {
3819 Step S;
3820 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3821 switch (VK) {
3822 case VK_PRValue:
3824 break;
3825 case VK_XValue:
3827 break;
3828 case VK_LValue:
3830 break;
3831 }
3832 S.Type = Ty;
3833 Steps.push_back(S);
3834}
3835
3837 Step S;
3839 S.Type = Ty;
3840 Steps.push_back(S);
3841}
3842
3844 Step S;
3845 S.Kind = SK_AtomicConversion;
3846 S.Type = Ty;
3847 Steps.push_back(S);
3848}
3849
3852 bool TopLevelOfInitList) {
3853 Step S;
3854 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3856 S.Type = T;
3857 S.ICS = new ImplicitConversionSequence(ICS);
3858 Steps.push_back(S);
3859}
3860
3862 Step S;
3863 S.Kind = SK_ListInitialization;
3864 S.Type = T;
3865 Steps.push_back(S);
3866}
3867
3869 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3870 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3871 Step S;
3872 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3875 S.Type = T;
3876 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3877 S.Function.Function = Constructor;
3878 S.Function.FoundDecl = FoundDecl;
3879 Steps.push_back(S);
3880}
3881
3883 Step S;
3884 S.Kind = SK_ZeroInitialization;
3885 S.Type = T;
3886 Steps.push_back(S);
3887}
3888
3890 Step S;
3891 S.Kind = SK_CAssignment;
3892 S.Type = T;
3893 Steps.push_back(S);
3894}
3895
3897 Step S;
3898 S.Kind = SK_StringInit;
3899 S.Type = T;
3900 Steps.push_back(S);
3901}
3902
3904 Step S;
3905 S.Kind = SK_ObjCObjectConversion;
3906 S.Type = T;
3907 Steps.push_back(S);
3908}
3909
3911 Step S;
3912 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3913 S.Type = T;
3914 Steps.push_back(S);
3915}
3916
3918 Step S;
3919 S.Kind = SK_ArrayLoopIndex;
3920 S.Type = EltT;
3921 Steps.insert(Steps.begin(), S);
3922
3923 S.Kind = SK_ArrayLoopInit;
3924 S.Type = T;
3925 Steps.push_back(S);
3926}
3927
3929 Step S;
3931 S.Type = T;
3932 Steps.push_back(S);
3933}
3934
3936 bool shouldCopy) {
3937 Step s;
3938 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3940 s.Type = type;
3941 Steps.push_back(s);
3942}
3943
3945 Step S;
3946 S.Kind = SK_ProduceObjCObject;
3947 S.Type = T;
3948 Steps.push_back(S);
3949}
3950
3952 Step S;
3953 S.Kind = SK_StdInitializerList;
3954 S.Type = T;
3955 Steps.push_back(S);
3956}
3957
3959 Step S;
3960 S.Kind = SK_OCLSamplerInit;
3961 S.Type = T;
3962 Steps.push_back(S);
3963}
3964
3966 Step S;
3967 S.Kind = SK_OCLZeroOpaqueType;
3968 S.Type = T;
3969 Steps.push_back(S);
3970}
3971
3973 Step S;
3974 S.Kind = SK_ParenthesizedListInit;
3975 S.Type = T;
3976 Steps.push_back(S);
3977}
3978
3980 InitListExpr *Syntactic) {
3981 assert(Syntactic->getNumInits() == 1 &&
3982 "Can only rewrap trivial init lists.");
3983 Step S;
3984 S.Kind = SK_UnwrapInitList;
3985 S.Type = Syntactic->getInit(0)->getType();
3986 Steps.insert(Steps.begin(), S);
3987
3988 S.Kind = SK_RewrapInitList;
3989 S.Type = T;
3990 S.WrappingSyntacticList = Syntactic;
3991 Steps.push_back(S);
3992}
3993
3997 this->Failure = Failure;
3998 this->FailedOverloadResult = Result;
3999}
4000
4001//===----------------------------------------------------------------------===//
4002// Attempt initialization
4003//===----------------------------------------------------------------------===//
4004
4005/// Tries to add a zero initializer. Returns true if that worked.
4006static bool
4008 const InitializedEntity &Entity) {
4010 return false;
4011
4012 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4013 if (VD->getInit() || VD->getEndLoc().isMacroID())
4014 return false;
4015
4016 QualType VariableTy = VD->getType().getCanonicalType();
4018 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4019 if (!Init.empty()) {
4020 Sequence.AddZeroInitializationStep(Entity.getType());
4021 Sequence.SetZeroInitializationFixit(Init, Loc);
4022 return true;
4023 }
4024 return false;
4025}
4026
4028 InitializationSequence &Sequence,
4029 const InitializedEntity &Entity) {
4030 if (!S.getLangOpts().ObjCAutoRefCount) return;
4031
4032 /// When initializing a parameter, produce the value if it's marked
4033 /// __attribute__((ns_consumed)).
4034 if (Entity.isParameterKind()) {
4035 if (!Entity.isParameterConsumed())
4036 return;
4037
4038 assert(Entity.getType()->isObjCRetainableType() &&
4039 "consuming an object of unretainable type?");
4040 Sequence.AddProduceObjCObjectStep(Entity.getType());
4041
4042 /// When initializing a return value, if the return type is a
4043 /// retainable type, then returns need to immediately retain the
4044 /// object. If an autorelease is required, it will be done at the
4045 /// last instant.
4046 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4048 if (!Entity.getType()->isObjCRetainableType())
4049 return;
4050
4051 Sequence.AddProduceObjCObjectStep(Entity.getType());
4052 }
4053}
4054
4055static void TryListInitialization(Sema &S,
4056 const InitializedEntity &Entity,
4057 const InitializationKind &Kind,
4058 InitListExpr *InitList,
4059 InitializationSequence &Sequence,
4060 bool TreatUnavailableAsInvalid);
4061
4062/// When initializing from init list via constructor, handle
4063/// initialization of an object of type std::initializer_list<T>.
4064///
4065/// \return true if we have handled initialization of an object of type
4066/// std::initializer_list<T>, false otherwise.
4068 InitListExpr *List,
4069 QualType DestType,
4070 InitializationSequence &Sequence,
4071 bool TreatUnavailableAsInvalid) {
4072 QualType E;
4073 if (!S.isStdInitializerList(DestType, &E))
4074 return false;
4075
4076 if (!S.isCompleteType(List->getExprLoc(), E)) {
4077 Sequence.setIncompleteTypeFailure(E);
4078 return true;
4079 }
4080
4081 // Try initializing a temporary array from the init list.
4083 E.withConst(),
4084 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4085 List->getNumInits()),
4087 InitializedEntity HiddenArray =
4090 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4091 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4092 TreatUnavailableAsInvalid);
4093 if (Sequence)
4094 Sequence.AddStdInitializerListConstructionStep(DestType);
4095 return true;
4096}
4097
4098/// Determine if the constructor has the signature of a copy or move
4099/// constructor for the type T of the class in which it was found. That is,
4100/// determine if its first parameter is of type T or reference to (possibly
4101/// cv-qualified) T.
4103 const ConstructorInfo &Info) {
4104 if (Info.Constructor->getNumParams() == 0)
4105 return false;
4106
4107 QualType ParmT =
4109 QualType ClassT =
4110 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4111
4112 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4113}
4114
4116 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4117 OverloadCandidateSet &CandidateSet, QualType DestType,
4119 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4120 bool IsListInit, bool RequireActualConstructor,
4121 bool SecondStepOfCopyInit = false) {
4123 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4124
4125 for (NamedDecl *D : Ctors) {
4126 auto Info = getConstructorInfo(D);
4127 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4128 continue;
4129
4130 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4131 continue;
4132
4133 // C++11 [over.best.ics]p4:
4134 // ... and the constructor or user-defined conversion function is a
4135 // candidate by
4136 // - 13.3.1.3, when the argument is the temporary in the second step
4137 // of a class copy-initialization, or
4138 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4139 // - the second phase of 13.3.1.7 when the initializer list has exactly
4140 // one element that is itself an initializer list, and the target is
4141 // the first parameter of a constructor of class X, and the conversion
4142 // is to X or reference to (possibly cv-qualified X),
4143 // user-defined conversion sequences are not considered.
4144 bool SuppressUserConversions =
4145 SecondStepOfCopyInit ||
4146 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4148
4149 if (Info.ConstructorTmpl)
4151 Info.ConstructorTmpl, Info.FoundDecl,
4152 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4153 /*PartialOverloading=*/false, AllowExplicit);
4154 else {
4155 // C++ [over.match.copy]p1:
4156 // - When initializing a temporary to be bound to the first parameter
4157 // of a constructor [for type T] that takes a reference to possibly
4158 // cv-qualified T as its first argument, called with a single
4159 // argument in the context of direct-initialization, explicit
4160 // conversion functions are also considered.
4161 // FIXME: What if a constructor template instantiates to such a signature?
4162 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4163 Args.size() == 1 &&
4165 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4166 CandidateSet, SuppressUserConversions,
4167 /*PartialOverloading=*/false, AllowExplicit,
4168 AllowExplicitConv);
4169 }
4170 }
4171
4172 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4173 //
4174 // When initializing an object of class type T by constructor
4175 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4176 // from a single expression of class type U, conversion functions of
4177 // U that convert to the non-reference type cv T are candidates.
4178 // Explicit conversion functions are only candidates during
4179 // direct-initialization.
4180 //
4181 // Note: SecondStepOfCopyInit is only ever true in this case when
4182 // evaluating whether to produce a C++98 compatibility warning.
4183 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4184 !RequireActualConstructor && !SecondStepOfCopyInit) {
4185 Expr *Initializer = Args[0];
4186 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4187 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4188 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4189 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4190 NamedDecl *D = *I;
4191 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4192 D = D->getUnderlyingDecl();
4193
4194 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4195 CXXConversionDecl *Conv;
4196 if (ConvTemplate)
4197 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4198 else
4199 Conv = cast<CXXConversionDecl>(D);
4200
4201 if (ConvTemplate)
4203 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4204 CandidateSet, AllowExplicit, AllowExplicit,
4205 /*AllowResultConversion*/ false);
4206 else
4207 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4208 DestType, CandidateSet, AllowExplicit,
4209 AllowExplicit,
4210 /*AllowResultConversion*/ false);
4211 }
4212 }
4213 }
4214
4215 // Perform overload resolution and return the result.
4216 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4217}
4218
4219/// Attempt initialization by constructor (C++ [dcl.init]), which
4220/// enumerates the constructors of the initialized entity and performs overload
4221/// resolution to select the best.
4222/// \param DestType The destination class type.
4223/// \param DestArrayType The destination type, which is either DestType or
4224/// a (possibly multidimensional) array of DestType.
4225/// \param IsListInit Is this list-initialization?
4226/// \param IsInitListCopy Is this non-list-initialization resulting from a
4227/// list-initialization from {x} where x is the same
4228/// type as the entity?
4230 const InitializedEntity &Entity,
4231 const InitializationKind &Kind,
4232 MultiExprArg Args, QualType DestType,
4233 QualType DestArrayType,
4234 InitializationSequence &Sequence,
4235 bool IsListInit = false,
4236 bool IsInitListCopy = false) {
4237 assert(((!IsListInit && !IsInitListCopy) ||
4238 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4239 "IsListInit/IsInitListCopy must come with a single initializer list "
4240 "argument.");
4241 InitListExpr *ILE =
4242 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4243 MultiExprArg UnwrappedArgs =
4244 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4245
4246 // The type we're constructing needs to be complete.
4247 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4248 Sequence.setIncompleteTypeFailure(DestType);
4249 return;
4250 }
4251
4252 bool RequireActualConstructor =
4253 !(Entity.getKind() != InitializedEntity::EK_Base &&
4255 Entity.getKind() !=
4257
4258 // C++17 [dcl.init]p17:
4259 // - If the initializer expression is a prvalue and the cv-unqualified
4260 // version of the source type is the same class as the class of the
4261 // destination, the initializer expression is used to initialize the
4262 // destination object.
4263 // Per DR (no number yet), this does not apply when initializing a base
4264 // class or delegating to another constructor from a mem-initializer.
4265 // ObjC++: Lambda captured by the block in the lambda to block conversion
4266 // should avoid copy elision.
4267 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4268 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4269 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4270 // Convert qualifications if necessary.
4271 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4272 if (ILE)
4273 Sequence.RewrapReferenceInitList(DestType, ILE);
4274 return;
4275 }
4276
4277 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4278 assert(DestRecordType && "Constructor initialization requires record type");
4279 CXXRecordDecl *DestRecordDecl
4280 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4281
4282 // Build the candidate set directly in the initialization sequence
4283 // structure, so that it will persist if we fail.
4284 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4285
4286 // Determine whether we are allowed to call explicit constructors or
4287 // explicit conversion operators.
4288 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4289 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4290
4291 // - Otherwise, if T is a class type, constructors are considered. The
4292 // applicable constructors are enumerated, and the best one is chosen
4293 // through overload resolution.
4294 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4295
4298 bool AsInitializerList = false;
4299
4300 // C++11 [over.match.list]p1, per DR1467:
4301 // When objects of non-aggregate type T are list-initialized, such that
4302 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4303 // according to the rules in this section, overload resolution selects
4304 // the constructor in two phases:
4305 //
4306 // - Initially, the candidate functions are the initializer-list
4307 // constructors of the class T and the argument list consists of the
4308 // initializer list as a single argument.
4309 if (IsListInit) {
4310 AsInitializerList = true;
4311
4312 // If the initializer list has no elements and T has a default constructor,
4313 // the first phase is omitted.
4314 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4316 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4317 CopyInitialization, AllowExplicit,
4318 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4319 }
4320
4321 // C++11 [over.match.list]p1:
4322 // - If no viable initializer-list constructor is found, overload resolution
4323 // is performed again, where the candidate functions are all the
4324 // constructors of the class T and the argument list consists of the
4325 // elements of the initializer list.
4327 AsInitializerList = false;
4329 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4330 Best, CopyInitialization, AllowExplicit,
4331 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4332 }
4333 if (Result) {
4334 Sequence.SetOverloadFailure(
4337 Result);
4338
4339 if (Result != OR_Deleted)
4340 return;
4341 }
4342
4343 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4344
4345 // In C++17, ResolveConstructorOverload can select a conversion function
4346 // instead of a constructor.
4347 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4348 // Add the user-defined conversion step that calls the conversion function.
4349 QualType ConvType = CD->getConversionType();
4350 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4351 "should not have selected this conversion function");
4352 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4353 HadMultipleCandidates);
4354 if (!S.Context.hasSameType(ConvType, DestType))
4355 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4356 if (IsListInit)
4357 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4358 return;
4359 }
4360
4361 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4362 if (Result != OR_Deleted) {
4363 // C++11 [dcl.init]p6:
4364 // If a program calls for the default initialization of an object
4365 // of a const-qualified type T, T shall be a class type with a
4366 // user-provided default constructor.
4367 // C++ core issue 253 proposal:
4368 // If the implicit default constructor initializes all subobjects, no
4369 // initializer should be required.
4370 // The 253 proposal is for example needed to process libstdc++ headers
4371 // in 5.x.
4372 if (Kind.getKind() == InitializationKind::IK_Default &&
4373 Entity.getType().isConstQualified()) {
4374 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4375 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4377 return;
4378 }
4379 }
4380
4381 // C++11 [over.match.list]p1:
4382 // In copy-list-initialization, if an explicit constructor is chosen, the
4383 // initializer is ill-formed.
4384 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4386 return;
4387 }
4388 }
4389
4390 // [class.copy.elision]p3:
4391 // In some copy-initialization contexts, a two-stage overload resolution
4392 // is performed.
4393 // If the first overload resolution selects a deleted function, we also
4394 // need the initialization sequence to decide whether to perform the second
4395 // overload resolution.
4396 // For deleted functions in other contexts, there is no need to get the
4397 // initialization sequence.
4398 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4399 return;
4400
4401 // Add the constructor initialization step. Any cv-qualification conversion is
4402 // subsumed by the initialization.
4404 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4405 IsListInit | IsInitListCopy, AsInitializerList);
4406}
4407
4408static bool
4411 QualType &SourceType,
4412 QualType &UnqualifiedSourceType,
4413 QualType UnqualifiedTargetType,
4414 InitializationSequence &Sequence) {
4415 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4416 S.Context.OverloadTy) {
4417 DeclAccessPair Found;
4418 bool HadMultipleCandidates = false;
4419 if (FunctionDecl *Fn
4421 UnqualifiedTargetType,
4422 false, Found,
4423 &HadMultipleCandidates)) {
4424 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4425 HadMultipleCandidates);
4426 SourceType = Fn->getType();
4427 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4428 } else if (!UnqualifiedTargetType->isRecordType()) {
4430 return true;
4431 }
4432 }
4433 return false;
4434}
4435
4437 const InitializedEntity &Entity,
4438 const InitializationKind &Kind,
4440 QualType cv1T1, QualType T1,
4441 Qualifiers T1Quals,
4442 QualType cv2T2, QualType T2,
4443 Qualifiers T2Quals,
4444 InitializationSequence &Sequence,
4445 bool TopLevelOfInitList);
4446
4447static void TryValueInitialization(Sema &S,
4448 const InitializedEntity &Entity,
4449 const InitializationKind &Kind,
4450 InitializationSequence &Sequence,
4451 InitListExpr *InitList = nullptr);
4452
4453/// Attempt list initialization of a reference.
4455 const InitializedEntity &Entity,
4456 const InitializationKind &Kind,
4457 InitListExpr *InitList,
4458 InitializationSequence &Sequence,
4459 bool TreatUnavailableAsInvalid) {
4460 // First, catch C++03 where this isn't possible.
4461 if (!S.getLangOpts().CPlusPlus11) {
4463 return;
4464 }
4465 // Can't reference initialize a compound literal.
4468 return;
4469 }
4470
4471 QualType DestType = Entity.getType();
4472 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4473 Qualifiers T1Quals;
4474 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4475
4476 // Reference initialization via an initializer list works thus:
4477 // If the initializer list consists of a single element that is
4478 // reference-related to the referenced type, bind directly to that element
4479 // (possibly creating temporaries).
4480 // Otherwise, initialize a temporary with the initializer list and
4481 // bind to that.
4482 if (InitList->getNumInits() == 1) {
4483 Expr *Initializer = InitList->getInit(0);
4485 Qualifiers T2Quals;
4486 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4487
4488 // If this fails, creating a temporary wouldn't work either.
4490 T1, Sequence))
4491 return;
4492
4493 SourceLocation DeclLoc = Initializer->getBeginLoc();
4494 Sema::ReferenceCompareResult RefRelationship
4495 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4496 if (RefRelationship >= Sema::Ref_Related) {
4497 // Try to bind the reference here.
4498 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4499 T1Quals, cv2T2, T2, T2Quals, Sequence,
4500 /*TopLevelOfInitList=*/true);
4501 if (Sequence)
4502 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4503 return;
4504 }
4505
4506 // Update the initializer if we've resolved an overloaded function.
4507 if (Sequence.step_begin() != Sequence.step_end())
4508 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4509 }
4510 // Perform address space compatibility check.
4511 QualType cv1T1IgnoreAS = cv1T1;
4512 if (T1Quals.hasAddressSpace()) {
4513 Qualifiers T2Quals;
4514 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4515 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4516 Sequence.SetFailed(
4518 return;
4519 }
4520 // Ignore address space of reference type at this point and perform address
4521 // space conversion after the reference binding step.
4522 cv1T1IgnoreAS =
4524 }
4525 // Not reference-related. Create a temporary and bind to that.
4526 InitializedEntity TempEntity =
4528
4529 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4530 TreatUnavailableAsInvalid);
4531 if (Sequence) {
4532 if (DestType->isRValueReferenceType() ||
4533 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4534 if (S.getLangOpts().CPlusPlus20 &&
4535 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4536 DestType->isRValueReferenceType()) {
4537 // C++20 [dcl.init.list]p3.10:
4538 // List-initialization of an object or reference of type T is defined as
4539 // follows:
4540 // ..., unless T is “reference to array of unknown bound of U”, in which
4541 // case the type of the prvalue is the type of x in the declaration U
4542 // x[] H, where H is the initializer list.
4544 }
4545 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4546 /*BindingTemporary=*/true);
4547 if (T1Quals.hasAddressSpace())
4549 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4550 } else
4551 Sequence.SetFailed(
4553 }
4554}
4555
4556/// Attempt list initialization (C++0x [dcl.init.list])
4558 const InitializedEntity &Entity,
4559 const InitializationKind &Kind,
4560 InitListExpr *InitList,
4561 InitializationSequence &Sequence,
4562 bool TreatUnavailableAsInvalid) {
4563 QualType DestType = Entity.getType();
4564
4565 // C++ doesn't allow scalar initialization with more than one argument.
4566 // But C99 complex numbers are scalars and it makes sense there.
4567 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4568 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4570 return;
4571 }
4572 if (DestType->isReferenceType()) {
4573 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4574 TreatUnavailableAsInvalid);
4575 return;
4576 }
4577
4578 if (DestType->isRecordType() &&
4579 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4580 Sequence.setIncompleteTypeFailure(DestType);
4581 return;
4582 }
4583
4584 // C++20 [dcl.init.list]p3:
4585 // - If the braced-init-list contains a designated-initializer-list, T shall
4586 // be an aggregate class. [...] Aggregate initialization is performed.
4587 //
4588 // We allow arrays here too in order to support array designators.
4589 //
4590 // FIXME: This check should precede the handling of reference initialization.
4591 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4592 // as a tentative DR resolution.
4593 bool IsDesignatedInit = InitList->hasDesignatedInit();
4594 if (!DestType->isAggregateType() && IsDesignatedInit) {
4595 Sequence.SetFailed(
4597 return;
4598 }
4599
4600 // C++11 [dcl.init.list]p3, per DR1467:
4601 // - If T is a class type and the initializer list has a single element of
4602 // type cv U, where U is T or a class derived from T, the object is
4603 // initialized from that element (by copy-initialization for
4604 // copy-list-initialization, or by direct-initialization for
4605 // direct-list-initialization).
4606 // - Otherwise, if T is a character array and the initializer list has a
4607 // single element that is an appropriately-typed string literal
4608 // (8.5.2 [dcl.init.string]), initialization is performed as described
4609 // in that section.
4610 // - Otherwise, if T is an aggregate, [...] (continue below).
4611 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4612 !IsDesignatedInit) {
4613 if (DestType->isRecordType()) {
4614 QualType InitType = InitList->getInit(0)->getType();
4615 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4616 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4617 Expr *InitListAsExpr = InitList;
4618 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4619 DestType, Sequence,
4620 /*InitListSyntax*/false,
4621 /*IsInitListCopy*/true);
4622 return;
4623 }
4624 }
4625 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4626 Expr *SubInit[1] = {InitList->getInit(0)};
4627 if (!isa<VariableArrayType>(DestAT) &&
4628 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4629 InitializationKind SubKind =
4630 Kind.getKind() == InitializationKind::IK_DirectList
4631 ? InitializationKind::CreateDirect(Kind.getLocation(),
4632 InitList->getLBraceLoc(),
4633 InitList->getRBraceLoc())
4634 : Kind;
4635 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4636 /*TopLevelOfInitList*/ true,
4637 TreatUnavailableAsInvalid);
4638
4639 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4640 // the element is not an appropriately-typed string literal, in which
4641 // case we should proceed as in C++11 (below).
4642 if (Sequence) {
4643 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4644 return;
4645 }
4646 }
4647 }
4648 }
4649
4650 // C++11 [dcl.init.list]p3:
4651 // - If T is an aggregate, aggregate initialization is performed.
4652 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4653 (S.getLangOpts().CPlusPlus11 &&
4654 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4655 if (S.getLangOpts().CPlusPlus11) {
4656 // - Otherwise, if the initializer list has no elements and T is a
4657 // class type with a default constructor, the object is
4658 // value-initialized.
4659 if (InitList->getNumInits() == 0) {
4660 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4661 if (S.LookupDefaultConstructor(RD)) {
4662 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4663 return;
4664 }
4665 }
4666
4667 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4668 // an initializer_list object constructed [...]
4669 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4670 TreatUnavailableAsInvalid))
4671 return;
4672
4673 // - Otherwise, if T is a class type, constructors are considered.
4674 Expr *InitListAsExpr = InitList;
4675 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4676 DestType, Sequence, /*InitListSyntax*/true);
4677 } else
4679 return;
4680 }
4681
4682 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4683 InitList->getNumInits() == 1) {
4684 Expr *E = InitList->getInit(0);
4685
4686 // - Otherwise, if T is an enumeration with a fixed underlying type,
4687 // the initializer-list has a single element v, and the initialization
4688 // is direct-list-initialization, the object is initialized with the
4689 // value T(v); if a narrowing conversion is required to convert v to
4690 // the underlying type of T, the program is ill-formed.
4691 auto *ET = DestType->getAs<EnumType>();
4692 if (S.getLangOpts().CPlusPlus17 &&
4693 Kind.getKind() == InitializationKind::IK_DirectList &&
4694 ET && ET->getDecl()->isFixed() &&
4695 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4697 E->getType()->isFloatingType())) {
4698 // There are two ways that T(v) can work when T is an enumeration type.
4699 // If there is either an implicit conversion sequence from v to T or
4700 // a conversion function that can convert from v to T, then we use that.
4701 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4702 // type, it is converted to the enumeration type via its underlying type.
4703 // There is no overlap possible between these two cases (except when the
4704 // source value is already of the destination type), and the first
4705 // case is handled by the general case for single-element lists below.
4707 ICS.setStandard();
4709 if (!E->isPRValue())
4711 // If E is of a floating-point type, then the conversion is ill-formed
4712 // due to narrowing, but go through the motions in order to produce the
4713 // right diagnostic.
4717 ICS.Standard.setFromType(E->getType());
4718 ICS.Standard.setToType(0, E->getType());
4719 ICS.Standard.setToType(1, DestType);
4720 ICS.Standard.setToType(2, DestType);
4721 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4722 /*TopLevelOfInitList*/true);
4723 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4724 return;
4725 }
4726
4727 // - Otherwise, if the initializer list has a single element of type E
4728 // [...references are handled above...], the object or reference is
4729 // initialized from that element (by copy-initialization for
4730 // copy-list-initialization, or by direct-initialization for
4731 // direct-list-initialization); if a narrowing conversion is required
4732 // to convert the element to T, the program is ill-formed.
4733 //
4734 // Per core-24034, this is direct-initialization if we were performing
4735 // direct-list-initialization and copy-initialization otherwise.
4736 // We can't use InitListChecker for this, because it always performs
4737 // copy-initialization. This only matters if we might use an 'explicit'
4738 // conversion operator, or for the special case conversion of nullptr_t to
4739 // bool, so we only need to handle those cases.
4740 //
4741 // FIXME: Why not do this in all cases?
4742 Expr *Init = InitList->getInit(0);
4743 if (Init->getType()->isRecordType() ||
4744 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4745 InitializationKind SubKind =
4746 Kind.getKind() == InitializationKind::IK_DirectList
4747 ? InitializationKind::CreateDirect(Kind.getLocation(),
4748 InitList->getLBraceLoc(),
4749 InitList->getRBraceLoc())
4750 : Kind;
4751 Expr *SubInit[1] = { Init };
4752 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4753 /*TopLevelOfInitList*/true,
4754 TreatUnavailableAsInvalid);
4755 if (Sequence)
4756 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4757 return;
4758 }
4759 }
4760
4761 InitListChecker CheckInitList(S, Entity, InitList,
4762 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4763 if (CheckInitList.HadError()) {
4765 return;
4766 }
4767
4768 // Add the list initialization step with the built init list.
4769 Sequence.AddListInitializationStep(DestType);
4770}
4771
4772/// Try a reference initialization that involves calling a conversion
4773/// function.
4775 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4776 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4777 InitializationSequence &Sequence) {
4778 QualType DestType = Entity.getType();
4779 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4780 QualType T1 = cv1T1.getUnqualifiedType();
4781 QualType cv2T2 = Initializer->getType();
4782 QualType T2 = cv2T2.getUnqualifiedType();
4783
4784 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4785 "Must have incompatible references when binding via conversion");
4786
4787 // Build the candidate set directly in the initialization sequence
4788 // structure, so that it will persist if we fail.
4789 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4791
4792 // Determine whether we are allowed to call explicit conversion operators.
4793 // Note that none of [over.match.copy], [over.match.conv], nor
4794 // [over.match.ref] permit an explicit constructor to be chosen when
4795 // initializing a reference, not even for direct-initialization.
4796 bool AllowExplicitCtors = false;
4797 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4798
4799 const RecordType *T1RecordType = nullptr;
4800 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4801 S.isCompleteType(Kind.getLocation(), T1)) {
4802 // The type we're converting to is a class type. Enumerate its constructors
4803 // to see if there is a suitable conversion.
4804 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4805
4806 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4807 auto Info = getConstructorInfo(D);
4808 if (!Info.Constructor)
4809 continue;
4810
4811 if (!Info.Constructor->isInvalidDecl() &&
4812 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4813 if (Info.ConstructorTmpl)
4815 Info.ConstructorTmpl, Info.FoundDecl,
4816 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4817 /*SuppressUserConversions=*/true,
4818 /*PartialOverloading*/ false, AllowExplicitCtors);
4819 else
4821 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4822 /*SuppressUserConversions=*/true,
4823 /*PartialOverloading*/ false, AllowExplicitCtors);
4824 }
4825 }
4826 }
4827 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4828 return OR_No_Viable_Function;
4829
4830 const RecordType *T2RecordType = nullptr;
4831 if ((T2RecordType = T2->getAs<RecordType>()) &&
4832 S.isCompleteType(Kind.getLocation(), T2)) {
4833 // The type we're converting from is a class type, enumerate its conversion
4834 // functions.
4835 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4836
4837 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4838 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4839 NamedDecl *D = *I;
4840 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4841 if (isa<UsingShadowDecl>(D))
4842 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4843
4844 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4845 CXXConversionDecl *Conv;
4846 if (ConvTemplate)
4847 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4848 else
4849 Conv = cast<CXXConversionDecl>(D);
4850
4851 // If the conversion function doesn't return a reference type,
4852 // it can't be considered for this conversion unless we're allowed to
4853 // consider rvalues.
4854 // FIXME: Do we need to make sure that we only consider conversion
4855 // candidates with reference-compatible results? That might be needed to
4856 // break recursion.
4857 if ((AllowRValues ||
4859 if (ConvTemplate)
4861 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4862 CandidateSet,
4863 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4864 else
4866 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4867 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4868 }
4869 }
4870 }
4871 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4872 return OR_No_Viable_Function;
4873
4874 SourceLocation DeclLoc = Initializer->getBeginLoc();
4875
4876 // Perform overload resolution. If it fails, return the failed result.
4879 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4880 return Result;
4881
4882 FunctionDecl *Function = Best->Function;
4883 // This is the overload that will be used for this initialization step if we
4884 // use this initialization. Mark it as referenced.
4885 Function->setReferenced();
4886
4887 // Compute the returned type and value kind of the conversion.
4888 QualType cv3T3;
4889 if (isa<CXXConversionDecl>(Function))
4890 cv3T3 = Function->getReturnType();
4891 else
4892 cv3T3 = T1;
4893
4895 if (cv3T3->isLValueReferenceType())
4896 VK = VK_LValue;
4897 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4898 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4899 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4900
4901 // Add the user-defined conversion step.
4902 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4903 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4904 HadMultipleCandidates);
4905
4906 // Determine whether we'll need to perform derived-to-base adjustments or
4907 // other conversions.
4909 Sema::ReferenceCompareResult NewRefRelationship =
4910 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4911
4912 // Add the final conversion sequence, if necessary.
4913 if (NewRefRelationship == Sema::Ref_Incompatible) {
4914 assert(!isa<CXXConstructorDecl>(Function) &&
4915 "should not have conversion after constructor");
4916
4918 ICS.setStandard();
4919 ICS.Standard = Best->FinalConversion;
4920 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4921
4922 // Every implicit conversion results in a prvalue, except for a glvalue
4923 // derived-to-base conversion, which we handle below.
4924 cv3T3 = ICS.Standard.getToType(2);
4925 VK = VK_PRValue;
4926 }
4927
4928 // If the converted initializer is a prvalue, its type T4 is adjusted to
4929 // type "cv1 T4" and the temporary materialization conversion is applied.
4930 //
4931 // We adjust the cv-qualifications to match the reference regardless of
4932 // whether we have a prvalue so that the AST records the change. In this
4933 // case, T4 is "cv3 T3".
4934 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4935 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4936 Sequence.AddQualificationConversionStep(cv1T4, VK);
4937 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4938 VK = IsLValueRef ? VK_LValue : VK_XValue;
4939
4940 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4941 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4942 else if (RefConv & Sema::ReferenceConversions::ObjC)
4943 Sequence.AddObjCObjectConversionStep(cv1T1);
4944 else if (RefConv & Sema::ReferenceConversions::Function)
4945 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4946 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4947 if (!S.Context.hasSameType(cv1T4, cv1T1))
4948 Sequence.AddQualificationConversionStep(cv1T1, VK);
4949 }
4950
4951 return OR_Success;
4952}
4953
4955 const InitializedEntity &Entity,
4956 Expr *CurInitExpr);
4957
4958/// Attempt reference initialization (C++0x [dcl.init.ref])
4960 const InitializationKind &Kind,
4962 InitializationSequence &Sequence,
4963 bool TopLevelOfInitList) {
4964 QualType DestType = Entity.getType();
4965 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4966 Qualifiers T1Quals;
4967 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4969 Qualifiers T2Quals;
4970 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4971
4972 // If the initializer is the address of an overloaded function, try
4973 // to resolve the overloaded function. If all goes well, T2 is the
4974 // type of the resulting function.
4976 T1, Sequence))
4977 return;
4978
4979 // Delegate everything else to a subfunction.
4980 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4981 T1Quals, cv2T2, T2, T2Quals, Sequence,
4982 TopLevelOfInitList);
4983}
4984
4985/// Determine whether an expression is a non-referenceable glvalue (one to
4986/// which a reference can never bind). Attempting to bind a reference to
4987/// such a glvalue will always create a temporary.
4989 return E->refersToBitField() || E->refersToVectorElement() ||
4991}
4992
4993/// Reference initialization without resolving overloaded functions.
4994///
4995/// We also can get here in C if we call a builtin which is declared as
4996/// a function with a parameter of reference type (such as __builtin_va_end()).
4998 const InitializedEntity &Entity,
4999 const InitializationKind &Kind,
5001 QualType cv1T1, QualType T1,
5002 Qualifiers T1Quals,
5003 QualType cv2T2, QualType T2,
5004 Qualifiers T2Quals,
5005 InitializationSequence &Sequence,
5006 bool TopLevelOfInitList) {
5007 QualType DestType = Entity.getType();
5008 SourceLocation DeclLoc = Initializer->getBeginLoc();
5009
5010 // Compute some basic properties of the types and the initializer.
5011 bool isLValueRef = DestType->isLValueReferenceType();
5012 bool isRValueRef = !isLValueRef;
5013 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5014
5016 Sema::ReferenceCompareResult RefRelationship =
5017 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5018
5019 // C++0x [dcl.init.ref]p5:
5020 // A reference to type "cv1 T1" is initialized by an expression of type
5021 // "cv2 T2" as follows:
5022 //
5023 // - If the reference is an lvalue reference and the initializer
5024 // expression
5025 // Note the analogous bullet points for rvalue refs to functions. Because
5026 // there are no function rvalues in C++, rvalue refs to functions are treated
5027 // like lvalue refs.
5028 OverloadingResult ConvOvlResult = OR_Success;
5029 bool T1Function = T1->isFunctionType();
5030 if (isLValueRef || T1Function) {
5031 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5032 (RefRelationship == Sema::Ref_Compatible ||
5033 (Kind.isCStyleOrFunctionalCast() &&
5034 RefRelationship == Sema::Ref_Related))) {
5035 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5036 // reference-compatible with "cv2 T2," or
5037 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5038 Sema::ReferenceConversions::ObjC)) {
5039 // If we're converting the pointee, add any qualifiers first;
5040 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5041 if (RefConv & (Sema::ReferenceConversions::Qualification))
5043 S.Context.getQualifiedType(T2, T1Quals),
5044 Initializer->getValueKind());
5045 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5046 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5047 else
5048 Sequence.AddObjCObjectConversionStep(cv1T1);
5049 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5050 // Perform a (possibly multi-level) qualification conversion.
5051 Sequence.AddQualificationConversionStep(cv1T1,
5052 Initializer->getValueKind());
5053 } else if (RefConv & Sema::ReferenceConversions::Function) {
5054 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5055 }
5056
5057 // We only create a temporary here when binding a reference to a
5058 // bit-field or vector element. Those cases are't supposed to be
5059 // handled by this bullet, but the outcome is the same either way.
5060 Sequence.AddReferenceBindingStep(cv1T1, false);
5061 return;
5062 }
5063
5064 // - has a class type (i.e., T2 is a class type), where T1 is not
5065 // reference-related to T2, and can be implicitly converted to an
5066 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5067 // with "cv3 T3" (this conversion is selected by enumerating the
5068 // applicable conversion functions (13.3.1.6) and choosing the best
5069 // one through overload resolution (13.3)),
5070 // If we have an rvalue ref to function type here, the rhs must be
5071 // an rvalue. DR1287 removed the "implicitly" here.
5072 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5073 (isLValueRef || InitCategory.isRValue())) {
5074 if (S.getLangOpts().CPlusPlus) {
5075 // Try conversion functions only for C++.
5076 ConvOvlResult = TryRefInitWithConversionFunction(
5077 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5078 /*IsLValueRef*/ isLValueRef, Sequence);
5079 if (ConvOvlResult == OR_Success)
5080 return;
5081 if (ConvOvlResult != OR_No_Viable_Function)
5082 Sequence.SetOverloadFailure(
5084 ConvOvlResult);
5085 } else {
5086 ConvOvlResult = OR_No_Viable_Function;
5087 }
5088 }
5089 }
5090
5091 // - Otherwise, the reference shall be an lvalue reference to a
5092 // non-volatile const type (i.e., cv1 shall be const), or the reference
5093 // shall be an rvalue reference.
5094 // For address spaces, we interpret this to mean that an addr space
5095 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5096 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5097 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5100 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5101 Sequence.SetOverloadFailure(
5103 ConvOvlResult);
5104 else if (!InitCategory.isLValue())
5105 Sequence.SetFailed(
5106 T1Quals.isAddressSpaceSupersetOf(T2Quals)
5110 else {
5112 switch (RefRelationship) {
5114 if (Initializer->refersToBitField())
5117 else if (Initializer->refersToVectorElement())
5120 else if (Initializer->refersToMatrixElement())
5123 else
5124 llvm_unreachable("unexpected kind of compatible initializer");
5125 break;
5126 case Sema::Ref_Related:
5128 break;
5132 break;
5133 }
5134 Sequence.SetFailed(FK);
5135 }
5136 return;
5137 }
5138
5139 // - If the initializer expression
5140 // - is an
5141 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5142 // [1z] rvalue (but not a bit-field) or
5143 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5144 //
5145 // Note: functions are handled above and below rather than here...
5146 if (!T1Function &&
5147 (RefRelationship == Sema::Ref_Compatible ||
5148 (Kind.isCStyleOrFunctionalCast() &&
5149 RefRelationship == Sema::Ref_Related)) &&
5150 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5151 (InitCategory.isPRValue() &&
5152 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5153 T2->isArrayType())))) {
5154 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5155 if (InitCategory.isPRValue() && T2->isRecordType()) {
5156 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5157 // compiler the freedom to perform a copy here or bind to the
5158 // object, while C++0x requires that we bind directly to the
5159 // object. Hence, we always bind to the object without making an
5160 // extra copy. However, in C++03 requires that we check for the
5161 // presence of a suitable copy constructor:
5162 //
5163 // The constructor that would be used to make the copy shall
5164 // be callable whether or not the copy is actually done.
5165 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5166 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5167 else if (S.getLangOpts().CPlusPlus11)
5169 }
5170
5171 // C++1z [dcl.init.ref]/5.2.1.2:
5172 // If the converted initializer is a prvalue, its type T4 is adjusted
5173 // to type "cv1 T4" and the temporary materialization conversion is
5174 // applied.
5175 // Postpone address space conversions to after the temporary materialization
5176 // conversion to allow creating temporaries in the alloca address space.
5177 auto T1QualsIgnoreAS = T1Quals;
5178 auto T2QualsIgnoreAS = T2Quals;
5179 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5180 T1QualsIgnoreAS.removeAddressSpace();
5181 T2QualsIgnoreAS.removeAddressSpace();
5182 }
5183 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5184 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5185 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5186 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5187 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5188 // Add addr space conversion if required.
5189 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5190 auto T4Quals = cv1T4.getQualifiers();
5191 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5192 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5193 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5194 cv1T4 = cv1T4WithAS;
5195 }
5196
5197 // In any case, the reference is bound to the resulting glvalue (or to
5198 // an appropriate base class subobject).
5199 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5200 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5201 else if (RefConv & Sema::ReferenceConversions::ObjC)
5202 Sequence.AddObjCObjectConversionStep(cv1T1);
5203 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5204 if (!S.Context.hasSameType(cv1T4, cv1T1))
5205 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5206 }
5207 return;
5208 }
5209
5210 // - has a class type (i.e., T2 is a class type), where T1 is not
5211 // reference-related to T2, and can be implicitly converted to an
5212 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5213 // where "cv1 T1" is reference-compatible with "cv3 T3",
5214 //
5215 // DR1287 removes the "implicitly" here.
5216 if (T2->isRecordType()) {
5217 if (RefRelationship == Sema::Ref_Incompatible) {
5218 ConvOvlResult = TryRefInitWithConversionFunction(
5219 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5220 /*IsLValueRef*/ isLValueRef, Sequence);
5221 if (ConvOvlResult)
5222 Sequence.SetOverloadFailure(
5224 ConvOvlResult);
5225
5226 return;
5227 }
5228
5229 if (RefRelationship == Sema::Ref_Compatible &&
5230 isRValueRef && InitCategory.isLValue()) {
5231 Sequence.SetFailed(
5233 return;
5234 }
5235
5237 return;
5238 }
5239
5240 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5241 // from the initializer expression using the rules for a non-reference
5242 // copy-initialization (8.5). The reference is then bound to the
5243 // temporary. [...]
5244
5245 // Ignore address space of reference type at this point and perform address
5246 // space conversion after the reference binding step.
5247 QualType cv1T1IgnoreAS =
5248 T1Quals.hasAddressSpace()
5250 : cv1T1;
5251
5252 InitializedEntity TempEntity =
5254
5255 // FIXME: Why do we use an implicit conversion here rather than trying
5256 // copy-initialization?
5258 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5259 /*SuppressUserConversions=*/false,
5260 Sema::AllowedExplicit::None,
5261 /*FIXME:InOverloadResolution=*/false,
5262 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5263 /*AllowObjCWritebackConversion=*/false);
5264
5265 if (ICS.isBad()) {
5266 // FIXME: Use the conversion function set stored in ICS to turn
5267 // this into an overloading ambiguity diagnostic. However, we need
5268 // to keep that set as an OverloadCandidateSet rather than as some
5269 // other kind of set.
5270 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5271 Sequence.SetOverloadFailure(
5273 ConvOvlResult);
5274 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5276 else
5278 return;
5279 } else {
5280 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5281 TopLevelOfInitList);
5282 }
5283
5284 // [...] If T1 is reference-related to T2, cv1 must be the
5285 // same cv-qualification as, or greater cv-qualification
5286 // than, cv2; otherwise, the program is ill-formed.
5287 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5288 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5289 if (RefRelationship == Sema::Ref_Related &&
5290 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5291 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5293 return;
5294 }
5295
5296 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5297 // reference, the initializer expression shall not be an lvalue.
5298 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5299 InitCategory.isLValue()) {
5300 Sequence.SetFailed(
5302 return;
5303 }
5304
5305 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5306
5307 if (T1Quals.hasAddressSpace()) {
5309 LangAS::Default)) {
5310 Sequence.SetFailed(
5312 return;
5313 }
5314 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5315 : VK_XValue);
5316 }
5317}
5318
5319/// Attempt character array initialization from a string literal
5320/// (C++ [dcl.init.string], C99 6.7.8).
5322 const InitializedEntity &Entity,
5323 const InitializationKind &Kind,
5325 InitializationSequence &Sequence) {
5326 Sequence.AddStringInitStep(Entity.getType());
5327}
5328
5329/// Attempt value initialization (C++ [dcl.init]p7).
5331 const InitializedEntity &Entity,
5332 const InitializationKind &Kind,
5333 InitializationSequence &Sequence,
5334 InitListExpr *InitList) {
5335 assert((!InitList || InitList->getNumInits() == 0) &&
5336 "Shouldn't use value-init for non-empty init lists");
5337
5338 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5339 //
5340 // To value-initialize an object of type T means:
5341 QualType T = Entity.getType();
5342
5343 // -- if T is an array type, then each element is value-initialized;
5344 T = S.Context.getBaseElementType(T);
5345
5346 if (const RecordType *RT = T->getAs<RecordType>()) {
5347 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5348 bool NeedZeroInitialization = true;
5349 // C++98:
5350 // -- if T is a class type (clause 9) with a user-declared constructor
5351 // (12.1), then the default constructor for T is called (and the
5352 // initialization is ill-formed if T has no accessible default
5353 // constructor);
5354 // C++11:
5355 // -- if T is a class type (clause 9) with either no default constructor
5356 // (12.1 [class.ctor]) or a default constructor that is user-provided
5357 // or deleted, then the object is default-initialized;
5358 //
5359 // Note that the C++11 rule is the same as the C++98 rule if there are no
5360 // defaulted or deleted constructors, so we just use it unconditionally.
5362 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5363 NeedZeroInitialization = false;
5364
5365 // -- if T is a (possibly cv-qualified) non-union class type without a
5366 // user-provided or deleted default constructor, then the object is
5367 // zero-initialized and, if T has a non-trivial default constructor,
5368 // default-initialized;
5369 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5370 // constructor' part was removed by DR1507.
5371 if (NeedZeroInitialization)
5372 Sequence.AddZeroInitializationStep(Entity.getType());
5373
5374 // C++03:
5375 // -- if T is a non-union class type without a user-declared constructor,
5376 // then every non-static data member and base class component of T is
5377 // value-initialized;
5378 // [...] A program that calls for [...] value-initialization of an
5379 // entity of reference type is ill-formed.
5380 //
5381 // C++11 doesn't need this handling, because value-initialization does not
5382 // occur recursively there, and the implicit default constructor is
5383 // defined as deleted in the problematic cases.
5384 if (!S.getLangOpts().CPlusPlus11 &&
5385 ClassDecl->hasUninitializedReferenceMember()) {
5387 return;
5388 }
5389
5390 // If this is list-value-initialization, pass the empty init list on when
5391 // building the constructor call. This affects the semantics of a few
5392 // things (such as whether an explicit default constructor can be called).
5393 Expr *InitListAsExpr = InitList;
5394 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5395 bool InitListSyntax = InitList;
5396
5397 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5398 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5400 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5401 }
5402 }
5403
5404 Sequence.AddZeroInitializationStep(Entity.getType());
5405}
5406
5407/// Attempt default initialization (C++ [dcl.init]p6).
5409 const InitializedEntity &Entity,
5410 const InitializationKind &Kind,
5411 InitializationSequence &Sequence) {
5412 assert(Kind.getKind() == InitializationKind::IK_Default);
5413
5414 // C++ [dcl.init]p6:
5415 // To default-initialize an object of type T means:
5416 // - if T is an array type, each element is default-initialized;
5417 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5418
5419 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5420 // constructor for T is called (and the initialization is ill-formed if
5421 // T has no accessible default constructor);
5422 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5423 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5424 Entity.getType(), Sequence);
5425 return;
5426 }
5427
5428 // - otherwise, no initialization is performed.
5429
5430 // If a program calls for the default initialization of an object of
5431 // a const-qualified type T, T shall be a class type with a user-provided
5432 // default constructor.
5433 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5434 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5436 return;
5437 }
5438
5439 // If the destination type has a lifetime property, zero-initialize it.
5440 if (DestType.getQualifiers().hasObjCLifetime()) {
5441 Sequence.AddZeroInitializationStep(Entity.getType());
5442 return;
5443 }
5444}
5445
5447 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5448 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5449 ExprResult *Result = nullptr) {
5450 unsigned EntityIndexToProcess = 0;
5451 SmallVector<Expr *, 4> InitExprs;
5452 QualType ResultType;
5453 Expr *ArrayFiller = nullptr;
5454 FieldDecl *InitializedFieldInUnion = nullptr;
5455
5456 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5457 const InitializationKind &SubKind,
5458 Expr *Arg, Expr **InitExpr = nullptr) {
5460 S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5461
5462 if (IS.Failed()) {
5463 if (!VerifyOnly) {
5464 IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);
5465 } else {
5466 Sequence.SetFailed(
5468 }
5469
5470 return false;
5471 }
5472 if (!VerifyOnly) {
5473 ExprResult ER;
5474 ER = IS.Perform(S, SubEntity, SubKind,
5475 Arg ? MultiExprArg(Arg) : std::nullopt);
5476 if (InitExpr)
5477 *InitExpr = ER.get();
5478 else
5479 InitExprs.push_back(ER.get());
5480 }
5481 return true;
5482 };
5483
5484 if (const ArrayType *AT =
5485 S.getASTContext().getAsArrayType(Entity.getType())) {
5486 SmallVector<InitializedEntity, 4> ElementEntities;
5487 uint64_t ArrayLength;
5488 // C++ [dcl.init]p16.5
5489 // if the destination type is an array, the object is initialized as
5490 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5491 // the destination type is an array of unknown bound, it is defined as
5492 // having k elements.
5493 if (const ConstantArrayType *CAT =
5495 ArrayLength = CAT->getSize().getZExtValue();
5496 ResultType = Entity.getType();
5497 } else if (const VariableArrayType *VAT =
5499 // Braced-initialization of variable array types is not allowed, even if
5500 // the size is greater than or equal to the number of args, so we don't
5501 // allow them to be initialized via parenthesized aggregate initialization
5502 // either.
5503 const Expr *SE = VAT->getSizeExpr();
5504 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5505 << SE->getSourceRange();
5506 return;
5507 } else {
5508 assert(isa<IncompleteArrayType>(Entity.getType()));
5509 ArrayLength = Args.size();
5510 }
5511 EntityIndexToProcess = ArrayLength;
5512
5513 // ...the ith array element is copy-initialized with xi for each
5514 // 1 <= i <= k
5515 for (Expr *E : Args) {
5517 S.getASTContext(), EntityIndexToProcess, Entity);
5519 E->getExprLoc(), /*isDirectInit=*/false, E);
5520 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5521 return;
5522 }
5523 // ...and value-initialized for each k < i <= n;
5524 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5526 S.getASTContext(), Args.size(), Entity);
5528 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5529 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5530 return;
5531 }
5532
5533 if (ResultType.isNull()) {
5534 ResultType = S.Context.getConstantArrayType(
5535 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5536 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5537 }
5538 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5539 bool IsUnion = RT->isUnionType();
5540 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5541 if (RD->isInvalidDecl()) {
5542 // Exit early to avoid confusion when processing members.
5543 // We do the same for braced list initialization in
5544 // `CheckStructUnionTypes`.
5545 Sequence.SetFailed(
5547 return;
5548 }
5549
5550 if (!IsUnion) {
5551 for (const CXXBaseSpecifier &Base : RD->bases()) {
5553 S.getASTContext(), &Base, false, &Entity);
5554 if (EntityIndexToProcess < Args.size()) {
5555 // C++ [dcl.init]p16.6.2.2.
5556 // ...the object is initialized is follows. Let e1, ..., en be the
5557 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5558 // the elements of the expression-list...The element ei is
5559 // copy-initialized with xi for 1 <= i <= k.
5560 Expr *E = Args[EntityIndexToProcess];
5562 E->getExprLoc(), /*isDirectInit=*/false, E);
5563 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5564 return;
5565 } else {
5566 // We've processed all of the args, but there are still base classes
5567 // that have to be initialized.
5568 // C++ [dcl.init]p17.6.2.2
5569 // The remaining elements...otherwise are value initialzed
5571 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5572 /*IsImplicit=*/true);
5573 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5574 return;
5575 }
5576 EntityIndexToProcess++;
5577 }
5578 }
5579
5580 for (FieldDecl *FD : RD->fields()) {
5581 // Unnamed bitfields should not be initialized at all, either with an arg
5582 // or by default.
5583 if (FD->isUnnamedBitfield())
5584 continue;
5585
5586 InitializedEntity SubEntity =
5588
5589 if (EntityIndexToProcess < Args.size()) {
5590 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5591 Expr *E = Args[EntityIndexToProcess];
5592
5593 // Incomplete array types indicate flexible array members. Do not allow
5594 // paren list initializations of structs with these members, as GCC
5595 // doesn't either.
5596 if (FD->getType()->isIncompleteArrayType()) {
5597 if (!VerifyOnly) {
5598 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5599 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5600 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5601 }
5602 Sequence.SetFailed(
5604 return;
5605 }
5606
5608 E->getExprLoc(), /*isDirectInit=*/false, E);
5609 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5610 return;
5611
5612 // Unions should have only one initializer expression, so we bail out
5613 // after processing the first field. If there are more initializers then
5614 // it will be caught when we later check whether EntityIndexToProcess is
5615 // less than Args.size();
5616 if (IsUnion) {
5617 InitializedFieldInUnion = FD;
5618 EntityIndexToProcess = 1;
5619 break;
5620 }
5621 } else {
5622 // We've processed all of the args, but there are still members that
5623 // have to be initialized.
5624 if (FD->hasInClassInitializer()) {
5625 if (!VerifyOnly) {
5626 // C++ [dcl.init]p16.6.2.2
5627 // The remaining elements are initialized with their default
5628 // member initializers, if any
5630 Kind.getParenOrBraceRange().getEnd(), FD);
5631 if (DIE.isInvalid())
5632 return;
5633 S.checkInitializerLifetime(SubEntity, DIE.get());
5634 InitExprs.push_back(DIE.get());
5635 }
5636 } else {
5637 // C++ [dcl.init]p17.6.2.2
5638 // The remaining elements...otherwise are value initialzed
5639 if (FD->getType()->isReferenceType()) {
5640 Sequence.SetFailed(
5642 if (!VerifyOnly) {
5643 SourceRange SR = Kind.getParenOrBraceRange();
5644 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5645 << FD->getType() << SR;
5646 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5647 }
5648 return;
5649 }
5651 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5652 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5653 return;
5654 }
5655 }
5656 EntityIndexToProcess++;
5657 }
5658 ResultType = Entity.getType();
5659 }
5660
5661 // Not all of the args have been processed, so there must've been more args
5662 // than were required to initialize the element.
5663 if (EntityIndexToProcess < Args.size()) {
5665 if (!VerifyOnly) {
5666 QualType T = Entity.getType();
5667 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5668 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5669 Args.back()->getEndLoc());
5670 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5671 << InitKind << ExcessInitSR;
5672 }
5673 return;
5674 }
5675
5676 if (VerifyOnly) {
5678 Sequence.AddParenthesizedListInitStep(Entity.getType());
5679 } else if (Result) {
5680 SourceRange SR = Kind.getParenOrBraceRange();
5681 auto *CPLIE = CXXParenListInitExpr::Create(
5682 S.getASTContext(), InitExprs, ResultType, Args.size(),
5683 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5684 if (ArrayFiller)
5685 CPLIE->setArrayFiller(ArrayFiller);
5686 if (InitializedFieldInUnion)
5687 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5688 *Result = CPLIE;
5689 S.Diag(Kind.getLocation(),
5690 diag::warn_cxx17_compat_aggregate_init_paren_list)
5691 << Kind.getLocation() << SR << ResultType;
5692 }
5693}
5694
5695/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5696/// which enumerates all conversion functions and performs overload resolution
5697/// to select the best.
5699 QualType DestType,
5700 const InitializationKind &Kind,
5702 InitializationSequence &Sequence,
5703 bool TopLevelOfInitList) {
5704 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5705 QualType SourceType = Initializer->getType();
5706 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5707 "Must have a class type to perform a user-defined conversion");
5708
5709 // Build the candidate set directly in the initialization sequence
5710 // structure, so that it will persist if we fail.
5711 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5713 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5714
5715 // Determine whether we are allowed to call explicit constructors or
5716 // explicit conversion operators.
5717 bool AllowExplicit = Kind.AllowExplicit();
5718
5719 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5720 // The type we're converting to is a class type. Enumerate its constructors
5721 // to see if there is a suitable conversion.
5722 CXXRecordDecl *DestRecordDecl
5723 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5724
5725 // Try to complete the type we're converting to.
5726 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5727 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5728 auto Info = getConstructorInfo(D);
5729 if (!Info.Constructor)
5730 continue;
5731
5732 if (!Info.Constructor->isInvalidDecl() &&
5733 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5734 if (Info.ConstructorTmpl)
5736 Info.ConstructorTmpl, Info.FoundDecl,
5737 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5738 /*SuppressUserConversions=*/true,
5739 /*PartialOverloading*/ false, AllowExplicit);
5740 else
5741 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5742 Initializer, CandidateSet,
5743 /*SuppressUserConversions=*/true,
5744 /*PartialOverloading*/ false, AllowExplicit);
5745 }
5746 }
5747 }
5748 }
5749
5750 SourceLocation DeclLoc = Initializer->getBeginLoc();
5751
5752 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5753 // The type we're converting from is a class type, enumerate its conversion
5754 // functions.
5755
5756 // We can only enumerate the conversion functions for a complete type; if
5757 // the type isn't complete, simply skip this step.
5758 if (S.isCompleteType(DeclLoc, SourceType)) {
5759 CXXRecordDecl *SourceRecordDecl
5760 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5761
5762 const auto &Conversions =
5763 SourceRecordDecl->getVisibleConversionFunctions();
5764 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5765 NamedDecl *D = *I;
5766 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5767 if (isa<UsingShadowDecl>(D))
5768 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5769
5770 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5771 CXXConversionDecl *Conv;
5772 if (ConvTemplate)
5773 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5774 else
5775 Conv = cast<CXXConversionDecl>(D);
5776
5777 if (ConvTemplate)
5779 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5780 CandidateSet, AllowExplicit, AllowExplicit);
5781 else
5782 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5783 DestType, CandidateSet, AllowExplicit,
5784 AllowExplicit);
5785 }
5786 }
5787 }
5788
5789 // Perform overload resolution. If it fails, return the failed result.
5792 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5793 Sequence.SetOverloadFailure(
5795
5796 // [class.copy.elision]p3:
5797 // In some copy-initialization contexts, a two-stage overload resolution
5798 // is performed.
5799 // If the first overload resolution selects a deleted function, we also
5800 // need the initialization sequence to decide whether to perform the second
5801 // overload resolution.
5802 if (!(Result == OR_Deleted &&
5803 Kind.getKind() == InitializationKind::IK_Copy))
5804 return;
5805 }
5806
5807 FunctionDecl *Function = Best->Function;
5808 Function->setReferenced();
5809 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5810
5811 if (isa<CXXConstructorDecl>(Function)) {
5812 // Add the user-defined conversion step. Any cv-qualification conversion is
5813 // subsumed by the initialization. Per DR5, the created temporary is of the
5814 // cv-unqualified type of the destination.
5815 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5816 DestType.getUnqualifiedType(),
5817 HadMultipleCandidates);
5818
5819 // C++14 and before:
5820 // - if the function is a constructor, the call initializes a temporary
5821 // of the cv-unqualified version of the destination type. The [...]
5822 // temporary [...] is then used to direct-initialize, according to the
5823 // rules above, the object that is the destination of the
5824 // copy-initialization.
5825 // Note that this just performs a simple object copy from the temporary.
5826 //
5827 // C++17:
5828 // - if the function is a constructor, the call is a prvalue of the
5829 // cv-unqualified version of the destination type whose return object
5830 // is initialized by the constructor. The call is used to
5831 // direct-initialize, according to the rules above, the object that
5832 // is the destination of the copy-initialization.
5833 // Therefore we need to do nothing further.
5834 //
5835 // FIXME: Mark this copy as extraneous.
5836 if (!S.getLangOpts().CPlusPlus17)
5837 Sequence.AddFinalCopy(DestType);
5838 else if (DestType.hasQualifiers())
5839 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5840 return;
5841 }
5842
5843 // Add the user-defined conversion step that calls the conversion function.
5844 QualType ConvType = Function->getCallResultType();
5845 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5846 HadMultipleCandidates);
5847
5848 if (ConvType->getAs<RecordType>()) {
5849 // The call is used to direct-initialize [...] the object that is the
5850 // destination of the copy-initialization.
5851 //
5852 // In C++17, this does not call a constructor if we enter /17.6.1:
5853 // - If the initializer expression is a prvalue and the cv-unqualified
5854 // version of the source type is the same as the class of the
5855 // destination [... do not make an extra copy]
5856 //
5857 // FIXME: Mark this copy as extraneous.
5858 if (!S.getLangOpts().CPlusPlus17 ||
5859 Function->getReturnType()->isReferenceType() ||
5860 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5861 Sequence.AddFinalCopy(DestType);
5862 else if (!S.Context.hasSameType(ConvType, DestType))
5863 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5864 return;
5865 }
5866
5867 // If the conversion following the call to the conversion function
5868 // is interesting, add it as a separate step.
5869 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5870 Best->FinalConversion.Third) {
5872 ICS.setStandard();
5873 ICS.Standard = Best->FinalConversion;
5874 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5875 }
5876}
5877
5878/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5879/// a function with a pointer return type contains a 'return false;' statement.
5880/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5881/// code using that header.
5882///
5883/// Work around this by treating 'return false;' as zero-initializing the result
5884/// if it's used in a pointer-returning function in a system header.
5886 const InitializedEntity &Entity,
5887 const Expr *Init) {
5888 return S.getLangOpts().CPlusPlus11 &&
5890 Entity.getType()->isPointerType() &&
5891 isa<CXXBoolLiteralExpr>(Init) &&
5892 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5893 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5894}
5895
5896/// The non-zero enum values here are indexes into diagnostic alternatives.
5898
5899/// Determines whether this expression is an acceptable ICR source.
5901 bool isAddressOf, bool &isWeakAccess) {
5902 // Skip parens.
5903 e = e->IgnoreParens();
5904
5905 // Skip address-of nodes.
5906 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5907 if (op->getOpcode() == UO_AddrOf)
5908 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5909 isWeakAccess);
5910
5911 // Skip certain casts.
5912 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5913 switch (ce->getCastKind()) {
5914 case CK_Dependent:
5915 case CK_BitCast:
5916 case CK_LValueBitCast:
5917 case CK_NoOp:
5918 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5919
5920 case CK_ArrayToPointerDecay:
5921 return IIK_nonscalar;
5922
5923 case CK_NullToPointer:
5924 return IIK_okay;
5925
5926 default:
5927 break;
5928 }
5929
5930 // If we have a declaration reference, it had better be a local variable.
5931 } else if (isa<DeclRefExpr>(e)) {
5932 // set isWeakAccess to true, to mean that there will be an implicit
5933 // load which requires a cleanup.
5935 isWeakAccess = true;
5936
5937 if (!isAddressOf) return IIK_nonlocal;
5938
5939 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5940 if (!var) return IIK_nonlocal;
5941
5942 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5943
5944 // If we have a conditional operator, check both sides.
5945 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5946 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5947 isWeakAccess))
5948 return iik;
5949
5950 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5951
5952 // These are never scalar.
5953 } else if (isa<ArraySubscriptExpr>(e)) {
5954 return IIK_nonscalar;
5955
5956 // Otherwise, it needs to be a null pointer constant.
5957 } else {
5960 }
5961
5962 return IIK_nonlocal;
5963}
5964
5965/// Check whether the given expression is a valid operand for an
5966/// indirect copy/restore.
5968 assert(src->isPRValue());
5969 bool isWeakAccess = false;
5970 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5971 // If isWeakAccess to true, there will be an implicit
5972 // load which requires a cleanup.
5973 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5975
5976 if (iik == IIK_okay) return;
5977
5978 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5979 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5980 << src->getSourceRange();
5981}
5982
5983/// Determine whether we have compatible array types for the
5984/// purposes of GNU by-copy array initialization.
5985static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5986 const ArrayType *Source) {
5987 // If the source and destination array types are equivalent, we're
5988 // done.
5989 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5990 return true;
5991
5992 // Make sure that the element types are the same.
5993 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5994 return false;
5995
5996 // The only mismatch we allow is when the destination is an
5997 // incomplete array type and the source is a constant array type.
5998 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5999}
6000
6002 InitializationSequence &Sequence,
6003 const InitializedEntity &Entity,
6004 Expr *Initializer) {
6005 bool ArrayDecay = false;
6006 QualType ArgType = Initializer->getType();
6007 QualType ArgPointee;
6008 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6009 ArrayDecay = true;
6010 ArgPointee = ArgArrayType->getElementType();
6011 ArgType = S.Context.getPointerType(ArgPointee);
6012 }
6013
6014 // Handle write-back conversion.
6015 QualType ConvertedArgType;
6016 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
6017 ConvertedArgType))
6018 return false;
6019
6020 // We should copy unless we're passing to an argument explicitly
6021 // marked 'out'.
6022 bool ShouldCopy = true;
6023 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6024 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6025
6026 // Do we need an lvalue conversion?
6027 if (ArrayDecay || Initializer->isGLValue()) {
6029 ICS.setStandard();
6031
6032 QualType ResultType;
6033 if (ArrayDecay) {
6035 ResultType = S.Context.getPointerType(ArgPointee);
6036 } else {
6038 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6039 }
6040
6041 Sequence.AddConversionSequenceStep(ICS, ResultType);
6042 }
6043
6044 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6045 return true;
6046}
6047
6049 InitializationSequence &Sequence,
6050 QualType DestType,
6051 Expr *Initializer) {
6052 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6053 (!Initializer->isIntegerConstantExpr(S.Context) &&
6054 !Initializer->getType()->isSamplerT()))
6055 return false;
6056
6057 Sequence.AddOCLSamplerInitStep(DestType);
6058 return true;
6059}
6060
6062 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6063 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6064}
6065
6067 InitializationSequence &Sequence,
6068 QualType DestType,
6069 Expr *Initializer) {
6070 if (!S.getLangOpts().OpenCL)
6071 return false;
6072
6073 //
6074 // OpenCL 1.2 spec, s6.12.10
6075 //
6076 // The event argument can also be used to associate the
6077 // async_work_group_copy with a previous async copy allowing
6078 // an event to be shared by multiple async copies; otherwise
6079 // event should be zero.
6080 //
6081 if (DestType->isEventT() || DestType->isQueueT()) {
6083 return false;
6084
6085 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6086 return true;
6087 }
6088
6089 // We should allow zero initialization for all types defined in the
6090 // cl_intel_device_side_avc_motion_estimation extension, except
6091 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6093 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6094 DestType->isOCLIntelSubgroupAVCType()) {
6095 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6096 DestType->isOCLIntelSubgroupAVCMceResultType())
6097 return false;
6099 return false;
6100
6101 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6102 return true;
6103 }
6104
6105 return false;
6106}
6107
6109 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6110 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6111 : FailedOverloadResult(OR_Success),
6112 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6113 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6114 TreatUnavailableAsInvalid);
6115}
6116
6117/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6118/// address of that function, this returns true. Otherwise, it returns false.
6119static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6120 auto *DRE = dyn_cast<DeclRefExpr>(E);
6121 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6122 return false;
6123
6125 cast<FunctionDecl>(DRE->getDecl()));
6126}
6127
6128/// Determine whether we can perform an elementwise array copy for this kind
6129/// of entity.
6130static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6131 switch (Entity.getKind()) {
6133 // C++ [expr.prim.lambda]p24:
6134 // For array members, the array elements are direct-initialized in
6135 // increasing subscript order.
6136 return true;
6137
6139 // C++ [dcl.decomp]p1:
6140 // [...] each element is copy-initialized or direct-initialized from the
6141 // corresponding element of the assignment-expression [...]
6142 return isa<DecompositionDecl>(Entity.getDecl());
6143
6145 // C++ [class.copy.ctor]p14:
6146 // - if the member is an array, each element is direct-initialized with
6147 // the corresponding subobject of x
6148 return Entity.isImplicitMemberInitializer();
6149
6151 // All the above cases are intended to apply recursively, even though none
6152 // of them actually say that.
6153 if (auto *E = Entity.getParent())
6154 return canPerformArrayCopy(*E);
6155 break;
6156
6157 default:
6158 break;
6159 }
6160
6161 return false;
6162}
6163
6165 const InitializedEntity &Entity,
6166 const InitializationKind &Kind,
6167 MultiExprArg Args,
6168 bool TopLevelOfInitList,
6169 bool TreatUnavailableAsInvalid) {
6170 ASTContext &Context = S.Context;
6171
6172 // Eliminate non-overload placeholder types in the arguments. We
6173 // need to do this before checking whether types are dependent
6174 // because lowering a pseudo-object expression might well give us
6175 // something of dependent type.
6176 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6177 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6178 // FIXME: should we be doing this here?
6179 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6180 if (result.isInvalid()) {
6182 return;
6183 }
6184 Args[I] = result.get();
6185 }
6186
6187 // C++0x [dcl.init]p16:
6188 // The semantics of initializers are as follows. The destination type is
6189 // the type of the object or reference being initialized and the source
6190 // type is the type of the initializer expression. The source type is not
6191 // defined when the initializer is a braced-init-list or when it is a
6192 // parenthesized list of expressions.
6193 QualType DestType = Entity.getType();
6194
6195 if (DestType->isDependentType() ||
6198 return;
6199 }
6200
6201 // Almost everything is a normal sequence.
6203
6204 QualType SourceType;
6205 Expr *Initializer = nullptr;
6206 if (Args.size() == 1) {
6207 Initializer = Args[0];
6208 if (S.getLangOpts().ObjC) {
6210 DestType, Initializer->getType(),
6211 Initializer) ||
6213 Args[0] = Initializer;
6214 }
6215 if (!isa<InitListExpr>(Initializer))
6216 SourceType = Initializer->getType();
6217 }
6218
6219 // - If the initializer is a (non-parenthesized) braced-init-list, the
6220 // object is list-initialized (8.5.4).
6221 if (Kind.getKind() != InitializationKind::IK_Direct) {
6222 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6223 TryListInitialization(S, Entity, Kind, InitList, *this,
6224 TreatUnavailableAsInvalid);
6225 return;
6226 }
6227 }
6228
6229 // - If the destination type is a reference type, see 8.5.3.
6230 if (DestType->isReferenceType()) {
6231 // C++0x [dcl.init.ref]p1:
6232 // A variable declared to be a T& or T&&, that is, "reference to type T"
6233 // (8.3.2), shall be initialized by an object, or function, of type T or
6234 // by an object that can be converted into a T.
6235 // (Therefore, multiple arguments are not permitted.)
6236 if (Args.size() != 1)
6238 // C++17 [dcl.init.ref]p5:
6239 // A reference [...] is initialized by an expression [...] as follows:
6240 // If the initializer is not an expression, presumably we should reject,
6241 // but the standard fails to actually say so.
6242 else if (isa<InitListExpr>(Args[0]))
6244 else
6245 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6246 TopLevelOfInitList);
6247 return;
6248 }
6249
6250 // - If the initializer is (), the object is value-initialized.
6251 if (Kind.getKind() == InitializationKind::IK_Value ||
6252 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6253 TryValueInitialization(S, Entity, Kind, *this);
6254 return;
6255 }
6256
6257 // Handle default initialization.
6258 if (Kind.getKind() == InitializationKind::IK_Default) {
6259 TryDefaultInitialization(S, Entity, Kind, *this);
6260 return;
6261 }
6262
6263 // - If the destination type is an array of characters, an array of
6264 // char16_t, an array of char32_t, or an array of wchar_t, and the
6265 // initializer is a string literal, see 8.5.2.
6266 // - Otherwise, if the destination type is an array, the program is
6267 // ill-formed.
6268 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
6269 if (Initializer && isa<VariableArrayType>(DestAT)) {
6271 return;
6272 }
6273
6274 if (Initializer) {
6275 switch (IsStringInit(Initializer, DestAT, Context)) {
6276 case SIF_None:
6277 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6278 return;
6281 return;
6284 return;
6287 return;
6290 return;
6293 return;
6294 case SIF_Other:
6295 break;
6296 }
6297 }
6298
6299 // Some kinds of initialization permit an array to be initialized from
6300 // another array of the same type, and perform elementwise initialization.
6301 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6303 Entity.getType()) &&
6304 canPerformArrayCopy(Entity)) {
6305 // If source is a prvalue, use it directly.
6306 if (Initializer->isPRValue()) {
6307 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6308 return;
6309 }
6310
6311 // Emit element-at-a-time copy loop.
6312 InitializedEntity Element =
6314 QualType InitEltT =
6315 Context.getAsArrayType(Initializer->getType())->getElementType();
6316 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6317 Initializer->getValueKind(),
6318 Initializer->getObjectKind());
6319 Expr *OVEAsExpr = &OVE;
6320 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6321 TreatUnavailableAsInvalid);
6322 if (!Failed())
6323 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6324 return;
6325 }
6326
6327 // Note: as an GNU C extension, we allow initialization of an
6328 // array from a compound literal that creates an array of the same
6329 // type, so long as the initializer has no side effects.
6330 if (!S.getLangOpts().CPlusPlus && Initializer &&
6331 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6332 Initializer->getType()->isArrayType()) {
6333 const ArrayType *SourceAT
6334 = Context.getAsArrayType(Initializer->getType());
6335 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6337 else if (Initializer->HasSideEffects(S.Context))
6339 else {
6340 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6341 }
6342 }
6343 // Note: as a GNU C++ extension, we allow list-initialization of a
6344 // class member of array type from a parenthesized initializer list.
6345 else if (S.getLangOpts().CPlusPlus &&
6347 Initializer && isa<InitListExpr>(Initializer)) {
6348 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6349 *this, TreatUnavailableAsInvalid);
6351 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6352 Kind.getKind() == InitializationKind::IK_Direct)
6353 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6354 /*VerifyOnly=*/true);
6355 else if (DestAT->getElementType()->isCharType())
6357 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6359 else
6361
6362 return;
6363 }
6364
6365 // Determine whether we should consider writeback conversions for
6366 // Objective-C ARC.
6367 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6368 Entity.isParameterKind();
6369
6370 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6371 return;
6372
6373 // We're at the end of the line for C: it's either a write-back conversion
6374 // or it's a C assignment. There's no need to check anything else.
6375 if (!S.getLangOpts().CPlusPlus) {
6376 assert(Initializer && "Initializer must be non-null");
6377 // If allowed, check whether this is an Objective-C writeback conversion.
6378 if (allowObjCWritebackConversion &&
6379 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6380 return;
6381 }
6382
6383 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6384 return;
6385
6386 // Handle initialization in C
6387 AddCAssignmentStep(DestType);
6388 MaybeProduceObjCObject(S, *this, Entity);
6389 return;
6390 }
6391
6392 assert(S.getLangOpts().CPlusPlus);
6393
6394 // - If the destination type is a (possibly cv-qualified) class type:
6395 if (DestType->isRecordType()) {
6396 // - If the initialization is direct-initialization, or if it is
6397 // copy-initialization where the cv-unqualified version of the
6398 // source type is the same class as, or a derived class of, the
6399 // class of the destination, constructors are considered. [...]
6400 if (Kind.getKind() == InitializationKind::IK_Direct ||
6401 (Kind.getKind() == InitializationKind::IK_Copy &&
6402 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6403 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6404 SourceType, DestType))))) {
6405 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6406 *this);
6407
6408 // We fall back to the "no matching constructor" path if the
6409 // failed candidate set has functions other than the three default
6410 // constructors. For example, conversion function.
6411 if (const auto *RD =
6412 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6413 // In general, we should call isCompleteType for RD to check its
6414 // completeness, we don't call it here as it was already called in the
6415 // above TryConstructorInitialization.
6416 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6417 RD->isAggregate() && Failed() &&
6419 // Do not attempt paren list initialization if overload resolution
6420 // resolves to a deleted function .
6421 //
6422 // We may reach this condition if we have a union wrapping a class with
6423 // a non-trivial copy or move constructor and we call one of those two
6424 // constructors. The union is an aggregate, but the matched constructor
6425 // is implicitly deleted, so we need to prevent aggregate initialization
6426 // (otherwise, it'll attempt aggregate initialization by initializing
6427 // the first element with a reference to the union).
6430 S, Kind.getLocation(), Best);
6432 // C++20 [dcl.init] 17.6.2.2:
6433 // - Otherwise, if no constructor is viable, the destination type is
6434 // an
6435 // aggregate class, and the initializer is a parenthesized
6436 // expression-list.
6437 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6438 /*VerifyOnly=*/true);
6439 }
6440 }
6441 } else {
6442 // - Otherwise (i.e., for the remaining copy-initialization cases),
6443 // user-defined conversion sequences that can convert from the
6444 // source type to the destination type or (when a conversion
6445 // function is used) to a derived class thereof are enumerated as
6446 // described in 13.3.1.4, and the best one is chosen through
6447 // overload resolution (13.3).
6448 assert(Initializer && "Initializer must be non-null");
6449 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6450 TopLevelOfInitList);
6451 }
6452 return;
6453 }
6454
6455 assert(Args.size() >= 1 && "Zero-argument case handled above");
6456
6457 // For HLSL ext vector types we allow list initialization behavior for C++
6458 // constructor syntax. This is accomplished by converting initialization
6459 // arguments an InitListExpr late.
6460 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6461 (SourceType.isNull() ||
6462 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6463
6465 for (auto *Arg : Args) {
6466 if (Arg->getType()->isExtVectorType()) {
6467 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6468 unsigned Elm = VTy->getNumElements();
6469 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6470 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6471 Arg,
6473 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6474 Context.IntTy, SourceLocation()),
6475 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6476 SourceLocation()));
6477 }
6478 } else
6479 InitArgs.emplace_back(Arg);
6480 }
6481 InitListExpr *ILE = new (Context) InitListExpr(
6482 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6483 Args[0] = ILE;
6484 AddListInitializationStep(DestType);
6485 return;
6486 }
6487
6488 // The remaining cases all need a source type.
6489 if (Args.size() > 1) {
6491 return;
6492 } else if (isa<InitListExpr>(Args[0])) {
6494 return;
6495 }
6496
6497 // - Otherwise, if the source type is a (possibly cv-qualified) class
6498 // type, conversion functions are considered.
6499 if (!SourceType.isNull() && SourceType->isRecordType()) {
6500 assert(Initializer && "Initializer must be non-null");
6501 // For a conversion to _Atomic(T) from either T or a class type derived
6502 // from T, initialize the T object then convert to _Atomic type.
6503 bool NeedAtomicConversion = false;
6504 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6505 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6506 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6507 Atomic->getValueType())) {
6508 DestType = Atomic->getValueType();
6509 NeedAtomicConversion = true;
6510 }
6511 }
6512
6513 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6514 TopLevelOfInitList);
6515 MaybeProduceObjCObject(S, *this, Entity);
6516 if (!Failed() && NeedAtomicConversion)
6518 return;
6519 }
6520
6521 // - Otherwise, if the initialization is direct-initialization, the source
6522 // type is std::nullptr_t, and the destination type is bool, the initial
6523 // value of the object being initialized is false.
6524 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6525 DestType->isBooleanType() &&
6526 Kind.getKind() == InitializationKind::IK_Direct) {
6529 Initializer->isGLValue()),
6530 DestType);
6531 return;
6532 }
6533
6534 // - Otherwise, the initial value of the object being initialized is the
6535 // (possibly converted) value of the initializer expression. Standard
6536 // conversions (Clause 4) will be used, if necessary, to convert the
6537 // initializer expression to the cv-unqualified version of the
6538 // destination type; no user-defined conversions are considered.
6539
6541 = S.TryImplicitConversion(Initializer, DestType,
6542 /*SuppressUserConversions*/true,
6543 Sema::AllowedExplicit::None,
6544 /*InOverloadResolution*/ false,
6545 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6546 allowObjCWritebackConversion);
6547
6548 if (ICS.isStandard() &&
6550 // Objective-C ARC writeback conversion.
6551
6552 // We should copy unless we're passing to an argument explicitly
6553 // marked 'out'.
6554 bool ShouldCopy = true;
6555 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6556 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6557
6558 // If there was an lvalue adjustment, add it as a separate conversion.
6559 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6562 LvalueICS.setStandard();
6564 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6565 LvalueICS.Standard.First = ICS.Standard.First;
6566 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6567 }
6568
6569 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6570 } else if (ICS.isBad()) {
6571 DeclAccessPair dap;
6574 } else if (Initializer->getType() == Context.OverloadTy &&
6576 false, dap))
6578 else if (Initializer->getType()->isFunctionType() &&
6581 else
6583 } else {
6584 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6585
6586 MaybeProduceObjCObject(S, *this, Entity);
6587 }
6588}
6589
6591 for (auto &S : Steps)
6592 S.Destroy();
6593}
6594
6595//===----------------------------------------------------------------------===//
6596// Perform initialization
6597//===----------------------------------------------------------------------===//
6599getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6600 switch(Entity.getKind()) {
6606 return Sema::AA_Initializing;
6607
6609 if (Entity.getDecl() &&
6610 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6611 return Sema::AA_Sending;
6612
6613 return Sema::AA_Passing;
6614
6616 if (Entity.getDecl() &&
6617 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6618 return Sema::AA_Sending;
6619
6620 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6621
6623 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6624 return Sema::AA_Returning;
6625
6628 // FIXME: Can we tell apart casting vs. converting?
6629 return Sema::AA_Casting;
6630
6632 // This is really initialization, but refer to it as conversion for
6633 // consistency with CheckConvertedConstantExpression.
6634 return Sema::AA_Converting;
6635
6646 return Sema::AA_Initializing;
6647 }
6648
6649 llvm_unreachable("Invalid EntityKind!");
6650}
6651
6652/// Whether we should bind a created object as a temporary when
6653/// initializing the given entity.
6654static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6655 switch (Entity.getKind()) {
6673 return false;
6674
6680 return true;
6681 }
6682
6683 llvm_unreachable("missed an InitializedEntity kind?");
6684}
6685
6686/// Whether the given entity, when initialized with an object
6687/// created for that initialization, requires destruction.
6688static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6689 switch (Entity.getKind()) {
6700 return false;
6701
6714 return true;
6715 }
6716
6717 llvm_unreachable("missed an InitializedEntity kind?");
6718}
6719
6720/// Get the location at which initialization diagnostics should appear.
6722 Expr *Initializer) {
6723 switch (Entity.getKind()) {
6726 return Entity.getReturnLoc();
6727
6729 return Entity.getThrowLoc();
6730
6733 return Entity.getDecl()->getLocation();
6734
6736 return Entity.getCaptureLoc();
6737
6754 return Initializer->getBeginLoc();
6755 }
6756 llvm_unreachable("missed an InitializedEntity kind?");
6757}
6758
6759/// Make a (potentially elidable) temporary copy of the object
6760/// provided by the given initializer by calling the appropriate copy
6761/// constructor.
6762///
6763/// \param S The Sema object used for type-checking.
6764///
6765/// \param T The type of the temporary object, which must either be
6766/// the type of the initializer expression or a superclass thereof.
6767///
6768/// \param Entity The entity being initialized.
6769///
6770/// \param CurInit The initializer expression.
6771///
6772/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6773/// is permitted in C++03 (but not C++0x) when binding a reference to
6774/// an rvalue.
6775///
6776/// \returns An expression that copies the initializer expression into
6777/// a temporary object, or an error expression if a copy could not be
6778/// created.
6780 QualType T,
6781 const InitializedEntity &Entity,
6782 ExprResult CurInit,
6783 bool IsExtraneousCopy) {
6784 if (CurInit.isInvalid())
6785 return CurInit;
6786 // Determine which class type we're copying to.
6787 Expr *CurInitExpr = (Expr *)CurInit.get();
6788 CXXRecordDecl *Class = nullptr;
6789 if (const RecordType *Record = T->getAs<RecordType>())
6790 Class = cast<CXXRecordDecl>(Record->getDecl());
6791 if (!Class)
6792 return CurInit;
6793
6794 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6795
6796 // Make sure that the type we are copying is complete.
6797 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6798 return CurInit;
6799
6800 // Perform overload resolution using the class's constructors. Per
6801 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6802 // is direct-initialization.
6805
6808 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6809 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6810 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6811 /*RequireActualConstructor=*/false,
6812 /*SecondStepOfCopyInit=*/true)) {
6813 case OR_Success:
6814 break;
6815
6817 CandidateSet.NoteCandidates(
6819 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6820 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6821 : diag::err_temp_copy_no_viable)
6822 << (int)Entity.getKind() << CurInitExpr->getType()
6823 << CurInitExpr->getSourceRange()),
6824 S, OCD_AllCandidates, CurInitExpr);
6825 if (!IsExtraneousCopy || S.isSFINAEContext())
6826 return ExprError();
6827 return CurInit;
6828
6829 case OR_Ambiguous:
6830 CandidateSet.NoteCandidates(
6831 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6832 << (int)Entity.getKind()
6833 << CurInitExpr->getType()
6834 << CurInitExpr->getSourceRange()),
6835 S, OCD_AmbiguousCandidates, CurInitExpr);
6836 return ExprError();
6837
6838 case OR_Deleted:
6839 S.Diag(Loc, diag::err_temp_copy_deleted)
6840 << (int)Entity.getKind() << CurInitExpr->getType()
6841 << CurInitExpr->getSourceRange();
6842 S.NoteDeletedFunction(Best->Function);
6843 return ExprError();
6844 }
6845
6846 bool HadMultipleCandidates = CandidateSet.size() > 1;
6847
6848 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6849 SmallVector<Expr*, 8> ConstructorArgs;
6850 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6851
6852 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6853 IsExtraneousCopy);
6854
6855 if (IsExtraneousCopy) {
6856 // If this is a totally extraneous copy for C++03 reference
6857 // binding purposes, just return the original initialization
6858 // expression. We don't generate an (elided) copy operation here
6859 // because doing so would require us to pass down a flag to avoid
6860 // infinite recursion, where each step adds another extraneous,
6861 // elidable copy.
6862
6863 // Instantiate the default arguments of any extra parameters in
6864 // the selected copy constructor, as if we were going to create a
6865 // proper call to the copy constructor.
6866 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6867 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6868 if (S.RequireCompleteType(Loc, Parm->getType(),
6869 diag::err_call_incomplete_argument))
6870 break;
6871
6872 // Build the default argument expression; we don't actually care
6873 // if this succeeds or not, because this routine will complain
6874 // if there was a problem.
6875 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6876 }
6877
6878 return CurInitExpr;
6879 }
6880
6881 // Determine the arguments required to actually perform the
6882 // constructor call (we might have derived-to-base conversions, or
6883 // the copy constructor may have default arguments).
6884 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6885 ConstructorArgs))
6886 return ExprError();
6887
6888 // C++0x [class.copy]p32:
6889 // When certain criteria are met, an implementation is allowed to
6890 // omit the copy/move construction of a class object, even if the
6891 // copy/move constructor and/or destructor for the object have
6892 // side effects. [...]
6893 // - when a temporary class object that has not been bound to a
6894 // reference (12.2) would be copied/moved to a class object
6895 // with the same cv-unqualified type, the copy/move operation
6896 // can be omitted by constructing the temporary object
6897 // directly into the target of the omitted copy/move
6898 //
6899 // Note that the other three bullets are handled elsewhere. Copy
6900 // elision for return statements and throw expressions are handled as part
6901 // of constructor initialization, while copy elision for exception handlers
6902 // is handled by the run-time.
6903 //
6904 // FIXME: If the function parameter is not the same type as the temporary, we
6905 // should still be able to elide the copy, but we don't have a way to
6906 // represent in the AST how much should be elided in this case.
6907 bool Elidable =
6908 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6910 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6911 CurInitExpr->getType());
6912
6913 // Actually perform the constructor call.
6914 CurInit = S.BuildCXXConstructExpr(
6915 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
6916 HadMultipleCandidates,
6917 /*ListInit*/ false,
6918 /*StdInitListInit*/ false,
6919 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
6920
6921 // If we're supposed to bind temporaries, do so.
6922 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6923 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6924 return CurInit;
6925}
6926
6927/// Check whether elidable copy construction for binding a reference to
6928/// a temporary would have succeeded if we were building in C++98 mode, for
6929/// -Wc++98-compat.
6931 const InitializedEntity &Entity,
6932 Expr *CurInitExpr) {
6933 assert(S.getLangOpts().CPlusPlus11);
6934
6935 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6936 if (!Record)
6937 return;
6938
6939 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6940 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6941 return;
6942
6943 // Find constructors which would have been considered.
6946 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6947
6948 // Perform overload resolution.
6951 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6952 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6953 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6954 /*RequireActualConstructor=*/false,
6955 /*SecondStepOfCopyInit=*/true);
6956
6957 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6958 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6959 << CurInitExpr->getSourceRange();
6960
6961 switch (OR) {
6962 case OR_Success:
6963 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6964 Best->FoundDecl, Entity, Diag);
6965 // FIXME: Check default arguments as far as that's possible.
6966 break;
6967
6969 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6970 OCD_AllCandidates, CurInitExpr);
6971 break;
6972
6973 case OR_Ambiguous:
6974 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6975 OCD_AmbiguousCandidates, CurInitExpr);
6976 break;
6977
6978 case OR_Deleted:
6979 S.Diag(Loc, Diag);
6980 S.NoteDeletedFunction(Best->Function);
6981 break;
6982 }
6983}
6984
6985void InitializationSequence::PrintInitLocationNote(Sema &S,
6986 const InitializedEntity &Entity) {
6987 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6988 if (Entity.getDecl()->getLocation().isInvalid())
6989 return;
6990
6991 if (Entity.getDecl()->getDeclName())
6992 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6993 << Entity.getDecl()->getDeclName();
6994 else
6995 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6996 }
6997 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6998 Entity.getMethodDecl())
6999 S.Diag(Entity.getMethodDecl()->getLocation(),
7000 diag::note_method_return_type_change)
7001 << Entity.getMethodDecl()->getDeclName();
7002}
7003
7004/// Returns true if the parameters describe a constructor initialization of
7005/// an explicit temporary object, e.g. "Point(x, y)".
7006static bool isExplicitTemporary(const InitializedEntity &Entity,
7007 const InitializationKind &Kind,
7008 unsigned NumArgs) {
7009 switch (Entity.getKind()) {
7013 break;
7014 default:
7015 return false;
7016 }
7017
7018 switch (Kind.getKind()) {
7020 return true;
7021 // FIXME: Hack to work around cast weirdness.
7024 return NumArgs != 1;
7025 default:
7026 return false;
7027 }
7028}
7029
7030static ExprResult
7032 const InitializedEntity &Entity,
7033 const InitializationKind &Kind,
7034 MultiExprArg Args,
7035 const InitializationSequence::Step& Step,
7036 bool &ConstructorInitRequiresZeroInit,
7037 bool IsListInitialization,
7038 bool IsStdInitListInitialization,
7039 SourceLocation LBraceLoc,
7040 SourceLocation RBraceLoc) {
7041 unsigned NumArgs = Args.size();
7042 CXXConstructorDecl *Constructor
7043 = cast<CXXConstructorDecl>(Step.Function.Function);
7044 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7045
7046 // Build a call to the selected constructor.
7047 SmallVector<Expr*, 8> ConstructorArgs;
7048 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7049 ? Kind.getEqualLoc()
7050 : Kind.getLocation();
7051
7052 if (Kind.getKind() == InitializationKind::IK_Default) {
7053 // Force even a trivial, implicit default constructor to be
7054 // semantically checked. We do this explicitly because we don't build
7055 // the definition for completely trivial constructors.
7056 assert(Constructor->getParent() && "No parent class for constructor.");
7057 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7058 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7059 S.runWithSufficientStackSpace(Loc, [&] {
7060 S.DefineImplicitDefaultConstructor(Loc, Constructor);
7061 });
7062 }
7063 }
7064
7065 ExprResult CurInit((Expr *)nullptr);
7066
7067 // C++ [over.match.copy]p1:
7068 // - When initializing a temporary to be bound to the first parameter
7069 // of a constructor that takes a reference to possibly cv-qualified
7070 // T as its first argument, called with a single argument in the
7071 // context of direct-initialization, explicit conversion functions
7072 // are also considered.
7073 bool AllowExplicitConv =
7074 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7077
7078 // Determine the arguments required to actually perform the constructor
7079 // call.
7080 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7081 ConstructorArgs, AllowExplicitConv,
7082 IsListInitialization))
7083 return ExprError();
7084
7085 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7086 // An explicitly-constructed temporary, e.g., X(1, 2).
7087 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7088 return ExprError();
7089
7090 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7091 if (!TSInfo)
7092 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7093 SourceRange ParenOrBraceRange =
7094 (Kind.getKind() == InitializationKind::IK_DirectList)
7095 ? SourceRange(LBraceLoc, RBraceLoc)
7096 : Kind.getParenOrBraceRange();
7097
7098 CXXConstructorDecl *CalleeDecl = Constructor;
7099 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7100 Step.Function.FoundDecl.getDecl())) {
7101 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7102 }
7103 S.MarkFunctionReferenced(Loc, CalleeDecl);
7104
7105 CurInit = S.CheckForImmediateInvocation(
7107 S.Context, CalleeDecl,
7108 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7109 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7110 IsListInitialization, IsStdInitListInitialization,
7111 ConstructorInitRequiresZeroInit),
7112 CalleeDecl);
7113 } else {
7115
7116 if (Entity.getKind() == InitializedEntity::EK_Base) {
7117 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7120 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7121 ConstructKind = CXXConstructionKind::Delegating;
7122 }
7123
7124 // Only get the parenthesis or brace range if it is a list initialization or
7125 // direct construction.
7126 SourceRange ParenOrBraceRange;
7127 if (IsListInitialization)
7128 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7129 else if (Kind.getKind() == InitializationKind::IK_Direct)
7130 ParenOrBraceRange = Kind.getParenOrBraceRange();
7131
7132 // If the entity allows NRVO, mark the construction as elidable
7133 // unconditionally.
7134 if (Entity.allowsNRVO())
7135 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7136 Step.Function.FoundDecl,
7137 Constructor, /*Elidable=*/true,
7138 ConstructorArgs,
7139 HadMultipleCandidates,
7140 IsListInitialization,
7141 IsStdInitListInitialization,
7142 ConstructorInitRequiresZeroInit,
7143 ConstructKind,
7144 ParenOrBraceRange);
7145 else
7146 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7147 Step.Function.FoundDecl,
7148 Constructor,
7149 ConstructorArgs,
7150 HadMultipleCandidates,
7151 IsListInitialization,
7152 IsStdInitListInitialization,
7153 ConstructorInitRequiresZeroInit,
7154 ConstructKind,
7155 ParenOrBraceRange);
7156 }
7157 if (CurInit.isInvalid())
7158 return ExprError();
7159
7160 // Only check access if all of that succeeded.
7161 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7162 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7163 return ExprError();
7164
7165 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7167 return ExprError();
7168
7169 if (shouldBindAsTemporary(Entity))
7170 CurInit = S.MaybeBindToTemporary(CurInit.get());
7171
7172 return CurInit;
7173}
7174
7175namespace {
7176enum LifetimeKind {
7177 /// The lifetime of a temporary bound to this entity ends at the end of the
7178 /// full-expression, and that's (probably) fine.
7179 LK_FullExpression,
7180
7181 /// The lifetime of a temporary bound to this entity is extended to the
7182 /// lifeitme of the entity itself.
7183 LK_Extended,
7184
7185 /// The lifetime of a temporary bound to this entity probably ends too soon,
7186 /// because the entity is allocated in a new-expression.
7187 LK_New,
7188
7189 /// The lifetime of a temporary bound to this entity ends too soon, because
7190 /// the entity is a return object.
7191 LK_Return,
7192
7193 /// The lifetime of a temporary bound to this entity ends too soon, because
7194 /// the entity is the result of a statement expression.
7195 LK_StmtExprResult,
7196
7197 /// This is a mem-initializer: if it would extend a temporary (other than via
7198 /// a default member initializer), the program is ill-formed.
7199 LK_MemInitializer,
7200};
7201using LifetimeResult =
7202 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7203}
7204
7205/// Determine the declaration which an initialized entity ultimately refers to,
7206/// for the purpose of lifetime-extending a temporary bound to a reference in
7207/// the initialization of \p Entity.
7208static LifetimeResult getEntityLifetime(
7209 const InitializedEntity *Entity,
7210 const InitializedEntity *InitField = nullptr) {
7211 // C++11 [class.temporary]p5:
7212 switch (Entity->getKind()) {
7214 // The temporary [...] persists for the lifetime of the reference
7215 return {Entity, LK_Extended};
7216
7218 // For subobjects, we look at the complete object.
7219 if (Entity->getParent())
7220 return getEntityLifetime(Entity->getParent(), Entity);
7221
7222 // except:
7223 // C++17 [class.base.init]p8:
7224 // A temporary expression bound to a reference member in a
7225 // mem-initializer is ill-formed.
7226 // C++17 [class.base.init]p11:
7227 // A temporary expression bound to a reference member from a
7228 // default member initializer is ill-formed.
7229 //
7230 // The context of p11 and its example suggest that it's only the use of a
7231 // default member initializer from a constructor that makes the program
7232 // ill-formed, not its mere existence, and that it can even be used by
7233 // aggregate initialization.
7234 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7235 : LK_MemInitializer};
7236
7238 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7239 // type.
7240 return {Entity, LK_Extended};
7241
7244 // -- A temporary bound to a reference parameter in a function call
7245 // persists until the completion of the full-expression containing
7246 // the call.
7247 return {nullptr, LK_FullExpression};
7248
7250 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7251 return {nullptr, LK_FullExpression};
7252
7254 // -- The lifetime of a temporary bound to the returned value in a
7255 // function return statement is not extended; the temporary is
7256 // destroyed at the end of the full-expression in the return statement.
7257 return {nullptr, LK_Return};
7258
7260 // FIXME: Should we lifetime-extend through the result of a statement
7261 // expression?
7262 return {nullptr, LK_StmtExprResult};
7263
7265 // -- A temporary bound to a reference in a new-initializer persists
7266 // until the completion of the full-expression containing the
7267 // new-initializer.
7268 return {nullptr, LK_New};
7269
7273 // We don't yet know the storage duration of the surrounding temporary.
7274 // Assume it's got full-expression duration for now, it will patch up our
7275 // storage duration if that's not correct.
7276 return {nullptr, LK_FullExpression};
7277
7279 // For subobjects, we look at the complete object.
7280 return getEntityLifetime(Entity->getParent(), InitField);
7281
7283 // For subobjects, we look at the complete object.
7284 if (Entity->getParent())
7285 return getEntityLifetime(Entity->getParent(), InitField);
7286 return {InitField, LK_MemInitializer};
7287
7289 // We can reach this case for aggregate initialization in a constructor:
7290 // struct A { int &&r; };
7291 // struct B : A { B() : A{0} {} };
7292 // In this case, use the outermost field decl as the context.
7293 return {InitField, LK_MemInitializer};
7294
7300 return {nullptr, LK_FullExpression};
7301
7303 // FIXME: Can we diagnose lifetime problems with exceptions?
7304 return {nullptr, LK_FullExpression};
7305
7307 // -- A temporary object bound to a reference element of an aggregate of
7308 // class type initialized from a parenthesized expression-list
7309 // [dcl.init, 9.3] persists until the completion of the full-expression
7310 // containing the expression-list.
7311 return {nullptr, LK_FullExpression};
7312 }
7313
7314 llvm_unreachable("unknown entity kind");
7315}
7316
7317namespace {
7318enum ReferenceKind {
7319 /// Lifetime would be extended by a reference binding to a temporary.
7320 RK_ReferenceBinding,
7321 /// Lifetime would be extended by a std::initializer_list object binding to
7322 /// its backing array.
7323 RK_StdInitializerList,
7324};
7325
7326/// A temporary or local variable. This will be one of:
7327/// * A MaterializeTemporaryExpr.
7328/// * A DeclRefExpr whose declaration is a local.
7329/// * An AddrLabelExpr.
7330/// * A BlockExpr for a block with captures.
7331using Local = Expr*;
7332
7333/// Expressions we stepped over when looking for the local state. Any steps
7334/// that would inhibit lifetime extension or take us out of subexpressions of
7335/// the initializer are included.
7336struct IndirectLocalPathEntry {
7337 enum EntryKind {
7338 DefaultInit,
7339 AddressOf,
7340 VarInit,
7341 LValToRVal,
7342 LifetimeBoundCall,
7343 TemporaryCopy,
7344 LambdaCaptureInit,
7345 GslReferenceInit,
7346 GslPointerInit
7347 } Kind;
7348 Expr *E;
7349 union {
7350 const Decl *D = nullptr;
7351 const LambdaCapture *Capture;
7352 };
7353 IndirectLocalPathEntry() {}
7354 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7355 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7356 : Kind(K), E(E), D(D) {}
7357 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7358 : Kind(K), E(E), Capture(Capture) {}
7359};
7360
7361using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7362
7363struct RevertToOldSizeRAII {
7364 IndirectLocalPath &Path;
7365 unsigned OldSize = Path.size();
7366 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7367 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7368};
7369
7370using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7371 ReferenceKind RK)>;
7372}
7373
7374static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7375 for (auto E : Path)
7376 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7377 return true;
7378 return false;
7379}
7380
7381static bool pathContainsInit(IndirectLocalPath &Path) {
7382 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7383 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7384 E.Kind == IndirectLocalPathEntry::VarInit;
7385 });
7386}
7387
7388static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7389 Expr *Init, LocalVisitor Visit,
7390 bool RevisitSubinits,
7391 bool EnableLifetimeWarnings);
7392
7393static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7394 Expr *Init, ReferenceKind RK,
7395 LocalVisitor Visit,
7396 bool EnableLifetimeWarnings);
7397
7398template <typename T> static bool isRecordWithAttr(QualType Type) {
7399 if (auto *RD = Type->getAsCXXRecordDecl())
7400 return RD->hasAttr<T>();
7401 return false;
7402}
7403
7404// Decl::isInStdNamespace will return false for iterators in some STL
7405// implementations due to them being defined in a namespace outside of the std
7406// namespace.
7407static bool isInStlNamespace(const Decl *D) {
7408 const DeclContext *DC = D->getDeclContext();
7409 if (!DC)
7410 return false;
7411 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7412 if (const IdentifierInfo *II = ND->getIdentifier()) {
7413 StringRef Name = II->getName();
7414 if (Name.size() >= 2 && Name.front() == '_' &&
7415 (Name[1] == '_' || isUppercase(Name[1])))
7416 return true;
7417 }
7418
7419 return DC->isStdNamespace();
7420}
7421
7423 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7424 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7425 return true;
7426 if (!isInStlNamespace(Callee->getParent()))
7427 return false;
7428 if (!isRecordWithAttr<PointerAttr>(
7429 Callee->getFunctionObjectParameterType()) &&
7430 !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7431 return false;
7432 if (Callee->getReturnType()->isPointerType() ||
7433 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7434 if (!Callee->getIdentifier())
7435 return false;
7436 return llvm::StringSwitch<bool>(Callee->getName())
7437 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7438 .Cases("end", "rend", "cend", "crend", true)
7439 .Cases("c_str", "data", "get", true)
7440 // Map and set types.
7441 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7442 .Default(false);
7443 } else if (Callee->getReturnType()->isReferenceType()) {
7444 if (!Callee->getIdentifier()) {
7445 auto OO = Callee->getOverloadedOperator();
7446 return OO == OverloadedOperatorKind::OO_Subscript ||
7447 OO == OverloadedOperatorKind::OO_Star;
7448 }
7449 return llvm::StringSwitch<bool>(Callee->getName())
7450 .Cases("front", "back", "at", "top", "value", true)
7451 .Default(false);
7452 }
7453 return false;
7454}
7455
7457 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7458 return false;
7459 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7460 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7461 return false;
7462 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7463 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7464 return false;
7465 if (FD->getReturnType()->isPointerType() ||
7466 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7467 return llvm::StringSwitch<bool>(FD->getName())
7468 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7469 .Cases("end", "rend", "cend", "crend", true)
7470 .Case("data", true)
7471 .Default(false);
7472 } else if (FD->getReturnType()->isReferenceType()) {
7473 return llvm::StringSwitch<bool>(FD->getName())
7474 .Cases("get", "any_cast", true)
7475 .Default(false);
7476 }
7477 return false;
7478}
7479
7480static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7481 LocalVisitor Visit) {
7482 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7483 // We are not interested in the temporary base objects of gsl Pointers:
7484 // Temp().ptr; // Here ptr might not dangle.
7485 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7486 return;
7487 // Once we initialized a value with a reference, it can no longer dangle.
7488 if (!Value) {
7489 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7490 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7491 continue;
7492 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7493 return;
7494 break;
7495 }
7496 }
7497 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7498 : IndirectLocalPathEntry::GslReferenceInit,
7499 Arg, D});
7500 if (Arg->isGLValue())
7501 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7502 Visit,
7503 /*EnableLifetimeWarnings=*/true);
7504 else
7505 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7506 /*EnableLifetimeWarnings=*/true);
7507 Path.pop_back();
7508 };
7509
7510 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7511 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7512 if (MD && shouldTrackImplicitObjectArg(MD))
7513 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7514 !MD->getReturnType()->isReferenceType());
7515 return;
7516 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7517 FunctionDecl *Callee = OCE->getDirectCallee();
7518 if (Callee && Callee->isCXXInstanceMember() &&
7519 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7520 VisitPointerArg(Callee, OCE->getArg(0),
7521 !Callee->getReturnType()->isReferenceType());
7522 return;
7523 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7524 FunctionDecl *Callee = CE->getDirectCallee();
7525 if (Callee && shouldTrackFirstArgument(Callee))
7526 VisitPointerArg(Callee, CE->getArg(0),
7527 !Callee->getReturnType()->isReferenceType());
7528 return;
7529 }
7530
7531 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7532 const auto *Ctor = CCE->getConstructor();
7533 const CXXRecordDecl *RD = Ctor->getParent();
7534 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7535 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7536 }
7537}
7538
7540 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7541 if (!TSI)
7542 return false;
7543 // Don't declare this variable in the second operand of the for-statement;
7544 // GCC miscompiles that by ending its lifetime before evaluating the
7545 // third operand. See gcc.gnu.org/PR86769.
7547 for (TypeLoc TL = TSI->getTypeLoc();
7548 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7549 TL = ATL.getModifiedLoc()) {
7550 if (ATL.getAttrAs<LifetimeBoundAttr>())
7551 return true;
7552 }
7553
7554 // Assume that all assignment operators with a "normal" return type return
7555 // *this, that is, an lvalue reference that is the same type as the implicit
7556 // object parameter (or the LHS for a non-member operator$=).
7558 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7559 QualType RetT = FD->getReturnType();
7560 if (RetT->isLValueReferenceType()) {
7561 ASTContext &Ctx = FD->getASTContext();
7562 QualType LHST;
7563 auto *MD = dyn_cast<CXXMethodDecl>(FD);
7564 if (MD && MD->isCXXInstanceMember())
7565 LHST = Ctx.getLValueReferenceType(MD->getFunctionObjectParameterType());
7566 else
7567 LHST = MD->getParamDecl(0)->getType();
7568 if (Ctx.hasSameType(RetT, LHST))
7569 return true;
7570 }
7571 }
7572
7573 return false;
7574}
7575
7576static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7577 LocalVisitor Visit) {
7578 const FunctionDecl *Callee;
7579 ArrayRef<Expr*> Args;
7580
7581 if (auto *CE = dyn_cast<CallExpr>(Call)) {
7582 Callee = CE->getDirectCallee();
7583 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7584 } else {
7585 auto *CCE = cast<CXXConstructExpr>(Call);
7586 Callee = CCE->getConstructor();
7587 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7588 }
7589 if (!Callee)
7590 return;
7591
7592 Expr *ObjectArg = nullptr;
7593 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7594 ObjectArg = Args[0];
7595 Args = Args.slice(1);
7596 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7597 ObjectArg = MCE->getImplicitObjectArgument();
7598 }
7599
7600 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7601 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7602 if (Arg->isGLValue())
7603 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7604 Visit,
7605 /*EnableLifetimeWarnings=*/false);
7606 else
7607 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7608 /*EnableLifetimeWarnings=*/false);
7609 Path.pop_back();
7610 };
7611
7612 bool CheckCoroCall = false;
7613 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7614 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7615 RD->hasAttr<CoroReturnTypeAttr>() &&
7616 !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
7617 }
7618
7619 if (ObjectArg) {
7620 bool CheckCoroObjArg = CheckCoroCall;
7621 // Coroutine lambda objects with empty capture list are not lifetimebound.
7622 if (auto *LE = dyn_cast<LambdaExpr>(ObjectArg->IgnoreImplicit());
7623 LE && LE->captures().empty())
7624 CheckCoroObjArg = false;
7625 // Allow `get_return_object()` as the object param (__promise) is not
7626 // lifetimebound.
7627 if (Sema::CanBeGetReturnObject(Callee))
7628 CheckCoroObjArg = false;
7629 if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
7630 VisitLifetimeBoundArg(Callee, ObjectArg);
7631 }
7632
7633 for (unsigned I = 0,
7634 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7635 I != N; ++I) {
7636 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7637 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7638 }
7639}
7640
7641/// Visit the locals that would be reachable through a reference bound to the
7642/// glvalue expression \c Init.
7643static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7644 Expr *Init, ReferenceKind RK,
7645 LocalVisitor Visit,
7646 bool EnableLifetimeWarnings) {
7647 RevertToOldSizeRAII RAII(Path);
7648
7649 // Walk past any constructs which we can lifetime-extend across.
7650 Expr *Old;
7651 do {
7652 Old = Init;
7653
7654 if (auto *FE = dyn_cast<FullExpr>(Init))
7655 Init = FE->getSubExpr();
7656
7657 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7658 // If this is just redundant braces around an initializer, step over it.
7659 if (ILE->isTransparent())
7660 Init = ILE->getInit(0);
7661 }
7662
7663 // Step over any subobject adjustments; we may have a materialized
7664 // temporary inside them.
7665 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7666
7667 // Per current approach for DR1376, look through casts to reference type
7668 // when performing lifetime extension.
7669 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7670 if (CE->getSubExpr()->isGLValue())
7671 Init = CE->getSubExpr();
7672
7673 // Per the current approach for DR1299, look through array element access
7674 // on array glvalues when performing lifetime extension.
7675 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7676 Init = ASE->getBase();
7677 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7678 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7679 Init = ICE->getSubExpr();
7680 else
7681 // We can't lifetime extend through this but we might still find some
7682 // retained temporaries.
7683 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7684 EnableLifetimeWarnings);
7685 }
7686
7687 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7688 // constructor inherits one as an implicit mem-initializer.
7689 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7690 Path.push_back(
7691 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7692 Init = DIE->getExpr();
7693 }
7694 } while (Init != Old);
7695
7696 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7697 if (Visit(Path, Local(MTE), RK))
7698 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7699 EnableLifetimeWarnings);
7700 }
7701
7702 if (isa<CallExpr>(Init)) {
7703 if (EnableLifetimeWarnings)
7704 handleGslAnnotatedTypes(Path, Init, Visit);
7705 return visitLifetimeBoundArguments(Path, Init, Visit);
7706 }
7707
7708 switch (Init->getStmtClass()) {
7709 case Stmt::DeclRefExprClass: {
7710 // If we find the name of a local non-reference parameter, we could have a
7711 // lifetime problem.
7712 auto *DRE = cast<DeclRefExpr>(Init);
7713 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7714 if (VD && VD->hasLocalStorage() &&
7715 !DRE->refersToEnclosingVariableOrCapture()) {
7716 if (!VD->getType()->isReferenceType()) {
7717 Visit(Path, Local(DRE), RK);
7718 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7719 // The lifetime of a reference parameter is unknown; assume it's OK
7720 // for now.
7721 break;
7722 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7723 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7724 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7725 RK_ReferenceBinding, Visit,
7726 EnableLifetimeWarnings);
7727 }
7728 }
7729 break;
7730 }
7731
7732 case Stmt::UnaryOperatorClass: {
7733 // The only unary operator that make sense to handle here
7734 // is Deref. All others don't resolve to a "name." This includes
7735 // handling all sorts of rvalues passed to a unary operator.
7736 const UnaryOperator *U = cast<UnaryOperator>(Init);
7737 if (U->getOpcode() == UO_Deref)
7738 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7739 EnableLifetimeWarnings);
7740 break;
7741 }
7742
7743 case Stmt::OMPArraySectionExprClass: {
7745 cast<OMPArraySectionExpr>(Init)->getBase(),
7746 Visit, true, EnableLifetimeWarnings);
7747 break;
7748 }
7749
7750 case Stmt::ConditionalOperatorClass:
7751 case Stmt::BinaryConditionalOperatorClass: {
7752 auto *C = cast<AbstractConditionalOperator>(Init);
7753 if (!C->getTrueExpr()->getType()->isVoidType())
7754 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7755 EnableLifetimeWarnings);
7756 if (!C->getFalseExpr()->getType()->isVoidType())
7757 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7758 EnableLifetimeWarnings);
7759 break;
7760 }
7761
7762 case Stmt::CompoundLiteralExprClass: {
7763 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
7764 if (!CLE->isFileScope())
7765 Visit(Path, Local(CLE), RK);
7766 }
7767 break;
7768 }
7769
7770 // FIXME: Visit the left-hand side of an -> or ->*.
7771
7772 default:
7773 break;
7774 }
7775}
7776
7777/// Visit the locals that would be reachable through an object initialized by
7778/// the prvalue expression \c Init.
7779static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7780 Expr *Init, LocalVisitor Visit,
7781 bool RevisitSubinits,
7782 bool EnableLifetimeWarnings) {
7783 RevertToOldSizeRAII RAII(Path);
7784
7785 Expr *Old;
7786 do {
7787 Old = Init;
7788
7789 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7790 // constructor inherits one as an implicit mem-initializer.
7791 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7792 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7793 Init = DIE->getExpr();
7794 }
7795
7796 if (auto *FE = dyn_cast<FullExpr>(Init))
7797 Init = FE->getSubExpr();
7798
7799 // Dig out the expression which constructs the extended temporary.
7800 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7801
7802 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7803 Init = BTE->getSubExpr();
7804
7805 Init = Init->IgnoreParens();
7806
7807 // Step over value-preserving rvalue casts.
7808 if (auto *CE = dyn_cast<CastExpr>(Init)) {
7809 switch (CE->getCastKind()) {
7810 case CK_LValueToRValue:
7811 // If we can match the lvalue to a const object, we can look at its
7812 // initializer.
7813 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7815 Path, Init, RK_ReferenceBinding,
7816 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7817 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7818 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7819 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7820 !isVarOnPath(Path, VD)) {
7821 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7822 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7823 EnableLifetimeWarnings);
7824 }
7825 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7826 if (MTE->getType().isConstQualified())
7827 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7828 true, EnableLifetimeWarnings);
7829 }
7830 return false;
7831 }, EnableLifetimeWarnings);
7832
7833 // We assume that objects can be retained by pointers cast to integers,
7834 // but not if the integer is cast to floating-point type or to _Complex.
7835 // We assume that casts to 'bool' do not preserve enough information to
7836 // retain a local object.
7837 case CK_NoOp:
7838 case CK_BitCast:
7839 case CK_BaseToDerived:
7840 case CK_DerivedToBase:
7841 case CK_UncheckedDerivedToBase:
7842 case CK_Dynamic:
7843 case CK_ToUnion:
7844 case CK_UserDefinedConversion:
7845 case CK_ConstructorConversion:
7846 case CK_IntegralToPointer:
7847 case CK_PointerToIntegral:
7848 case CK_VectorSplat:
7849 case CK_IntegralCast:
7850 case CK_CPointerToObjCPointerCast:
7851 case CK_BlockPointerToObjCPointerCast:
7852 case CK_AnyPointerToBlockPointerCast:
7853 case CK_AddressSpaceConversion:
7854 break;
7855
7856 case CK_ArrayToPointerDecay:
7857 // Model array-to-pointer decay as taking the address of the array
7858 // lvalue.
7859 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7860 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7861 RK_ReferenceBinding, Visit,
7862 EnableLifetimeWarnings);
7863
7864 default:
7865 return;
7866 }
7867
7868 Init = CE->getSubExpr();
7869 }
7870 } while (Old != Init);
7871
7872 // C++17 [dcl.init.list]p6:
7873 // initializing an initializer_list object from the array extends the
7874 // lifetime of the array exactly like binding a reference to a temporary.
7875 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7876 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7877 RK_StdInitializerList, Visit,
7878 EnableLifetimeWarnings);
7879
7880 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7881 // We already visited the elements of this initializer list while
7882 // performing the initialization. Don't visit them again unless we've
7883 // changed the lifetime of the initialized entity.
7884 if (!RevisitSubinits)
7885 return;
7886
7887 if (ILE->isTransparent())
7888 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7889 RevisitSubinits,
7890 EnableLifetimeWarnings);
7891
7892 if (ILE->getType()->isArrayType()) {
7893 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7894 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7895 RevisitSubinits,
7896 EnableLifetimeWarnings);
7897 return;
7898 }
7899
7900 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7901 assert(RD->isAggregate() && "aggregate init on non-aggregate");
7902
7903 // If we lifetime-extend a braced initializer which is initializing an
7904 // aggregate, and that aggregate contains reference members which are
7905 // bound to temporaries, those temporaries are also lifetime-extended.
7906 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7909 RK_ReferenceBinding, Visit,
7910 EnableLifetimeWarnings);
7911 else {
7912 unsigned Index = 0;
7913 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7914 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7915 RevisitSubinits,
7916 EnableLifetimeWarnings);
7917 for (const auto *I : RD->fields()) {
7918 if (Index >= ILE->getNumInits())
7919 break;
7920 if (I->isUnnamedBitfield())
7921 continue;
7922 Expr *SubInit = ILE->getInit(Index);
7923 if (I->getType()->isReferenceType())
7925 RK_ReferenceBinding, Visit,
7926 EnableLifetimeWarnings);
7927 else
7928 // This might be either aggregate-initialization of a member or
7929 // initialization of a std::initializer_list object. Regardless,
7930 // we should recursively lifetime-extend that initializer.
7931 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7932 RevisitSubinits,
7933 EnableLifetimeWarnings);
7934 ++Index;
7935 }
7936 }
7937 }
7938 return;
7939 }
7940
7941 // The lifetime of an init-capture is that of the closure object constructed
7942 // by a lambda-expression.
7943 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7944 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7945 for (Expr *E : LE->capture_inits()) {
7946 assert(CapI != LE->capture_end());
7947 const LambdaCapture &Cap = *CapI++;
7948 if (!E)
7949 continue;
7950 if (Cap.capturesVariable())
7951 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7952 if (E->isGLValue())
7953 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7954 Visit, EnableLifetimeWarnings);
7955 else
7956 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7957 EnableLifetimeWarnings);
7958 if (Cap.capturesVariable())
7959 Path.pop_back();
7960 }
7961 }
7962
7963 // Assume that a copy or move from a temporary references the same objects
7964 // that the temporary does.
7965 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7966 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7967 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7968 Expr *Arg = MTE->getSubExpr();
7969 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7970 CCE->getConstructor()});
7971 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7972 /*EnableLifetimeWarnings*/false);
7973 Path.pop_back();
7974 }
7975 }
7976 }
7977
7978 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7979 if (EnableLifetimeWarnings)
7980 handleGslAnnotatedTypes(Path, Init, Visit);
7981 return visitLifetimeBoundArguments(Path, Init, Visit);
7982 }
7983
7984 switch (Init->getStmtClass()) {
7985 case Stmt::UnaryOperatorClass: {
7986 auto *UO = cast<UnaryOperator>(Init);
7987 // If the initializer is the address of a local, we could have a lifetime
7988 // problem.
7989 if (UO->getOpcode() == UO_AddrOf) {
7990 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7991 // it. Don't produce a redundant warning about the lifetime of the
7992 // temporary.
7993 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7994 return;
7995
7996 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7997 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7998 RK_ReferenceBinding, Visit,
7999 EnableLifetimeWarnings);
8000 }
8001 break;
8002 }
8003
8004 case Stmt::BinaryOperatorClass: {
8005 // Handle pointer arithmetic.
8006 auto *BO = cast<BinaryOperator>(Init);
8007 BinaryOperatorKind BOK = BO->getOpcode();
8008 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
8009 break;
8010
8011 if (BO->getLHS()->getType()->isPointerType())
8012 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
8013 EnableLifetimeWarnings);
8014 else if (BO->getRHS()->getType()->isPointerType())
8015 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
8016 EnableLifetimeWarnings);
8017 break;
8018 }
8019
8020 case Stmt::ConditionalOperatorClass:
8021 case Stmt::BinaryConditionalOperatorClass: {
8022 auto *C = cast<AbstractConditionalOperator>(Init);
8023 // In C++, we can have a throw-expression operand, which has 'void' type
8024 // and isn't interesting from a lifetime perspective.
8025 if (!C->getTrueExpr()->getType()->isVoidType())
8026 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
8027 EnableLifetimeWarnings);
8028 if (!C->getFalseExpr()->getType()->isVoidType())
8029 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
8030 EnableLifetimeWarnings);
8031 break;
8032 }
8033
8034 case Stmt::BlockExprClass:
8035 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
8036 // This is a local block, whose lifetime is that of the function.
8037 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
8038 }
8039 break;
8040
8041 case Stmt::AddrLabelExprClass:
8042 // We want to warn if the address of a label would escape the function.
8043 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
8044 break;
8045
8046 default:
8047 break;
8048 }
8049}
8050
8051/// Whether a path to an object supports lifetime extension.
8053 /// Lifetime-extend along this path.
8055 /// We should lifetime-extend, but we don't because (due to technical
8056 /// limitations) we can't. This happens for default member initializers,
8057 /// which we don't clone for every use, so we don't have a unique
8058 /// MaterializeTemporaryExpr to update.
8060 /// Do not lifetime extend along this path.
8061 NoExtend
8063
8064/// Determine whether this is an indirect path to a temporary that we are
8065/// supposed to lifetime-extend along.
8066static PathLifetimeKind
8067shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8068 PathLifetimeKind Kind = PathLifetimeKind::Extend;
8069 for (auto Elem : Path) {
8070 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8071 Kind = PathLifetimeKind::ShouldExtend;
8072 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8073 return PathLifetimeKind::NoExtend;
8074 }
8075 return Kind;
8076}
8077
8078/// Find the range for the first interesting entry in the path at or after I.
8079static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8080 Expr *E) {
8081 for (unsigned N = Path.size(); I != N; ++I) {
8082 switch (Path[I].Kind) {
8083 case IndirectLocalPathEntry::AddressOf:
8084 case IndirectLocalPathEntry::LValToRVal:
8085 case IndirectLocalPathEntry::LifetimeBoundCall:
8086 case IndirectLocalPathEntry::TemporaryCopy:
8087 case IndirectLocalPathEntry::GslReferenceInit:
8088 case IndirectLocalPathEntry::GslPointerInit:
8089 // These exist primarily to mark the path as not permitting or
8090 // supporting lifetime extension.
8091 break;
8092
8093 case IndirectLocalPathEntry::VarInit:
8094 if (cast<VarDecl>(Path[I].D)->isImplicit())
8095 return SourceRange();
8096 [[fallthrough]];
8097 case IndirectLocalPathEntry::DefaultInit:
8098 return Path[I].E->getSourceRange();
8099
8100 case IndirectLocalPathEntry::LambdaCaptureInit:
8101 if (!Path[I].Capture->capturesVariable())
8102 continue;
8103 return Path[I].E->getSourceRange();
8104 }
8105 }
8106 return E->getSourceRange();
8107}
8108
8109static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8110 for (const auto &It : llvm::reverse(Path)) {
8111 if (It.Kind == IndirectLocalPathEntry::VarInit)
8112 continue;
8113 if (It.Kind == IndirectLocalPathEntry::AddressOf)
8114 continue;
8115 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8116 continue;
8117 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8118 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8119 }
8120 return false;
8121}
8122
8124 Expr *Init) {
8125 LifetimeResult LR = getEntityLifetime(&Entity);
8126 LifetimeKind LK = LR.getInt();
8127 const InitializedEntity *ExtendingEntity = LR.getPointer();
8128
8129 // If this entity doesn't have an interesting lifetime, don't bother looking
8130 // for temporaries within its initializer.
8131 if (LK == LK_FullExpression)
8132 return;
8133
8134 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8135 ReferenceKind RK) -> bool {
8136 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8137 SourceLocation DiagLoc = DiagRange.getBegin();
8138
8139 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8140
8141 bool IsGslPtrInitWithGslTempOwner = false;
8142 bool IsLocalGslOwner = false;
8144 if (isa<DeclRefExpr>(L)) {
8145 // We do not want to follow the references when returning a pointer originating
8146 // from a local owner to avoid the following false positive:
8147 // int &p = *localUniquePtr;
8148 // someContainer.add(std::move(localUniquePtr));
8149 // return p;
8150 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8151 if (pathContainsInit(Path) || !IsLocalGslOwner)
8152 return false;
8153 } else {
8154 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8155 isRecordWithAttr<OwnerAttr>(MTE->getType());
8156 // Skipping a chain of initializing gsl::Pointer annotated objects.
8157 // We are looking only for the final source to find out if it was
8158 // a local or temporary owner or the address of a local variable/param.
8159 if (!IsGslPtrInitWithGslTempOwner)
8160 return true;
8161 }
8162 }
8163
8164 switch (LK) {
8165 case LK_FullExpression:
8166 llvm_unreachable("already handled this");
8167
8168 case LK_Extended: {
8169 if (!MTE) {
8170 // The initialized entity has lifetime beyond the full-expression,
8171 // and the local entity does too, so don't warn.
8172 //
8173 // FIXME: We should consider warning if a static / thread storage
8174 // duration variable retains an automatic storage duration local.
8175 return false;
8176 }
8177
8178 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8179 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8180 return false;
8181 }
8182
8183 switch (shouldLifetimeExtendThroughPath(Path)) {
8184 case PathLifetimeKind::Extend:
8185 // Update the storage duration of the materialized temporary.
8186 // FIXME: Rebuild the expression instead of mutating it.
8187 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8188 ExtendingEntity->allocateManglingNumber());
8189 // Also visit the temporaries lifetime-extended by this initializer.
8190 return true;
8191
8192 case PathLifetimeKind::ShouldExtend:
8193 // We're supposed to lifetime-extend the temporary along this path (per
8194 // the resolution of DR1815), but we don't support that yet.
8195 //
8196 // FIXME: Properly handle this situation. Perhaps the easiest approach
8197 // would be to clone the initializer expression on each use that would
8198 // lifetime extend its temporaries.
8199 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8200 << RK << DiagRange;
8201 break;
8202
8203 case PathLifetimeKind::NoExtend:
8204 // If the path goes through the initialization of a variable or field,
8205 // it can't possibly reach a temporary created in this full-expression.
8206 // We will have already diagnosed any problems with the initializer.
8207 if (pathContainsInit(Path))
8208 return false;
8209
8210 Diag(DiagLoc, diag::warn_dangling_variable)
8211 << RK << !Entity.getParent()
8212 << ExtendingEntity->getDecl()->isImplicit()
8213 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8214 break;
8215 }
8216 break;
8217 }
8218
8219 case LK_MemInitializer: {
8220 if (isa<MaterializeTemporaryExpr>(L)) {
8221 // Under C++ DR1696, if a mem-initializer (or a default member
8222 // initializer used by the absence of one) would lifetime-extend a
8223 // temporary, the program is ill-formed.
8224 if (auto *ExtendingDecl =
8225 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8226 if (IsGslPtrInitWithGslTempOwner) {
8227 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8228 << ExtendingDecl << DiagRange;
8229 Diag(ExtendingDecl->getLocation(),
8230 diag::note_ref_or_ptr_member_declared_here)
8231 << true;
8232 return false;
8233 }
8234 bool IsSubobjectMember = ExtendingEntity != &Entity;
8235 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8236 PathLifetimeKind::NoExtend
8237 ? diag::err_dangling_member
8238 : diag::warn_dangling_member)
8239 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8240 // Don't bother adding a note pointing to the field if we're inside
8241 // its default member initializer; our primary diagnostic points to
8242 // the same place in that case.
8243 if (Path.empty() ||
8244 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8245 Diag(ExtendingDecl->getLocation(),
8246 diag::note_lifetime_extending_member_declared_here)
8247 << RK << IsSubobjectMember;
8248 }
8249 } else {
8250 // We have a mem-initializer but no particular field within it; this
8251 // is either a base class or a delegating initializer directly
8252 // initializing the base-class from something that doesn't live long
8253 // enough.
8254 //
8255 // FIXME: Warn on this.
8256 return false;
8257 }
8258 } else {
8259 // Paths via a default initializer can only occur during error recovery
8260 // (there's no other way that a default initializer can refer to a
8261 // local). Don't produce a bogus warning on those cases.
8262 if (pathContainsInit(Path))
8263 return false;
8264
8265 // Suppress false positives for code like the one below:
8266 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8267 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8268 return false;
8269
8270 auto *DRE = dyn_cast<DeclRefExpr>(L);
8271 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8272 if (!VD) {
8273 // A member was initialized to a local block.
8274 // FIXME: Warn on this.
8275 return false;
8276 }
8277
8278 if (auto *Member =
8279 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8280 bool IsPointer = !Member->getType()->isReferenceType();
8281 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8282 : diag::warn_bind_ref_member_to_parameter)
8283 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8284 Diag(Member->getLocation(),
8285 diag::note_ref_or_ptr_member_declared_here)
8286 << (unsigned)IsPointer;
8287 }
8288 }
8289 break;
8290 }
8291
8292 case LK_New:
8293 if (isa<MaterializeTemporaryExpr>(L)) {
8294 if (IsGslPtrInitWithGslTempOwner)
8295 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8296 else
8297 Diag(DiagLoc, RK == RK_ReferenceBinding
8298 ? diag::warn_new_dangling_reference
8299 : diag::warn_new_dangling_initializer_list)
8300 << !Entity.getParent() << DiagRange;
8301 } else {
8302 // We can't determine if the allocation outlives the local declaration.
8303 return false;
8304 }
8305 break;
8306
8307 case LK_Return:
8308 case LK_StmtExprResult:
8309 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8310 // We can't determine if the local variable outlives the statement
8311 // expression.
8312 if (LK == LK_StmtExprResult)
8313 return false;
8314 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8315 << Entity.getType()->isReferenceType() << DRE->getDecl()
8316 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8317 } else if (isa<BlockExpr>(L)) {
8318 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8319 } else if (isa<AddrLabelExpr>(L)) {
8320 // Don't warn when returning a label from a statement expression.
8321 // Leaving the scope doesn't end its lifetime.
8322 if (LK == LK_StmtExprResult)
8323 return false;
8324 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8325 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(L)) {
8326 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8327 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 2
8328 << DiagRange;
8329 } else {
8330 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8331 << Entity.getType()->isReferenceType() << DiagRange;
8332 }
8333 break;
8334 }
8335
8336 for (unsigned I = 0; I != Path.size(); ++I) {
8337 auto Elem = Path[I];
8338
8339 switch (Elem.Kind) {
8340 case IndirectLocalPathEntry::AddressOf:
8341 case IndirectLocalPathEntry::LValToRVal:
8342 // These exist primarily to mark the path as not permitting or
8343 // supporting lifetime extension.
8344 break;
8345
8346 case IndirectLocalPathEntry::LifetimeBoundCall:
8347 case IndirectLocalPathEntry::TemporaryCopy:
8348 case IndirectLocalPathEntry::GslPointerInit:
8349 case IndirectLocalPathEntry::GslReferenceInit:
8350 // FIXME: Consider adding a note for these.
8351 break;
8352
8353 case IndirectLocalPathEntry::DefaultInit: {
8354 auto *FD = cast<FieldDecl>(Elem.D);
8355 Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8356 << FD << nextPathEntryRange(Path, I + 1, L);
8357 break;
8358 }
8359
8360 case IndirectLocalPathEntry::VarInit: {
8361 const VarDecl *VD = cast<VarDecl>(Elem.D);
8362 Diag(VD->getLocation(), diag::note_local_var_initializer)
8363 << VD->getType()->isReferenceType()
8364 << VD->isImplicit() << VD->getDeclName()
8365 << nextPathEntryRange(Path, I + 1, L);
8366 break;
8367 }
8368
8369 case IndirectLocalPathEntry::LambdaCaptureInit:
8370 if (!Elem.Capture->capturesVariable())
8371 break;
8372 // FIXME: We can't easily tell apart an init-capture from a nested
8373 // capture of an init-capture.
8374 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8375 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8376 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8377 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8378 << nextPathEntryRange(Path, I + 1, L);
8379 break;
8380 }
8381 }
8382
8383 // We didn't lifetime-extend, so don't go any further; we don't need more
8384 // warnings or errors on inner temporaries within this one's initializer.
8385 return false;
8386 };
8387
8388 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8389 diag::warn_dangling_lifetime_pointer, SourceLocation());
8391 if (Init->isGLValue())
8392 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8393 TemporaryVisitor,
8394 EnableLifetimeWarnings);
8395 else
8396 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8397 EnableLifetimeWarnings);
8398}
8399
8400static void DiagnoseNarrowingInInitList(Sema &S,
8401 const ImplicitConversionSequence &ICS,
8402 QualType PreNarrowingType,
8403 QualType EntityType,
8404 const Expr *PostInit);
8405
8406static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
8407 QualType ToType, Expr *Init);
8408
8409/// Provide warnings when std::move is used on construction.
8410static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8411 bool IsReturnStmt) {
8412 if (!InitExpr)
8413 return;
8414
8416 return;
8417
8418 QualType DestType = InitExpr->getType();
8419 if (!DestType->isRecordType())
8420 return;
8421
8422 unsigned DiagID = 0;
8423 if (IsReturnStmt) {
8424 const CXXConstructExpr *CCE =
8425 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8426 if (!CCE || CCE->getNumArgs() != 1)
8427 return;
8428
8430 return;
8431
8432 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8433 }
8434
8435 // Find the std::move call and get the argument.
8436 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8437 if (!CE || !CE->isCallToStdMove())
8438 return;
8439
8440 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8441
8442 if (IsReturnStmt) {
8443 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8444 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8445 return;
8446
8447 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8448 if (!VD || !VD->hasLocalStorage())
8449 return;
8450
8451 // __block variables are not moved implicitly.
8452 if (VD->hasAttr<BlocksAttr>())
8453 return;
8454
8455 QualType SourceType = VD->getType();
8456 if (!SourceType->isRecordType())
8457 return;
8458
8459 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8460 return;
8461 }
8462
8463 // If we're returning a function parameter, copy elision
8464 // is not possible.
8465 if (isa<ParmVarDecl>(VD))
8466 DiagID = diag::warn_redundant_move_on_return;
8467 else
8468 DiagID = diag::warn_pessimizing_move_on_return;
8469 } else {
8470 DiagID = diag::warn_pessimizing_move_on_initialization;
8471 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8472 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8473 return;
8474 }
8475
8476 S.Diag(CE->getBeginLoc(), DiagID);
8477
8478 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8479 // is within a macro.
8480 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8481 if (CallBegin.isMacroID())
8482 return;
8483 SourceLocation RParen = CE->getRParenLoc();
8484 if (RParen.isMacroID())
8485 return;
8486 SourceLocation LParen;
8487 SourceLocation ArgLoc = Arg->getBeginLoc();
8488
8489 // Special testing for the argument location. Since the fix-it needs the
8490 // location right before the argument, the argument location can be in a
8491 // macro only if it is at the beginning of the macro.
8492 while (ArgLoc.isMacroID() &&
8495 }
8496
8497 if (LParen.isMacroID())
8498 return;
8499
8500 LParen = ArgLoc.getLocWithOffset(-1);
8501
8502 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8503 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8504 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8505}
8506
8507static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8508 // Check to see if we are dereferencing a null pointer. If so, this is
8509 // undefined behavior, so warn about it. This only handles the pattern
8510 // "*null", which is a very syntactic check.
8511 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8512 if (UO->getOpcode() == UO_Deref &&
8513 UO->getSubExpr()->IgnoreParenCasts()->
8514 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8515 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8516 S.PDiag(diag::warn_binding_null_to_reference)
8517 << UO->getSubExpr()->getSourceRange());
8518 }
8519}
8520
8523 bool BoundToLvalueReference) {
8524 auto MTE = new (Context)
8525 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8526
8527 // Order an ExprWithCleanups for lifetime marks.
8528 //
8529 // TODO: It'll be good to have a single place to check the access of the
8530 // destructor and generate ExprWithCleanups for various uses. Currently these
8531 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8532 // but there may be a chance to merge them.
8535 auto &Record = ExprEvalContexts.back();
8536 Record.ForRangeLifetimeExtendTemps.push_back(MTE);
8537 }
8538 return MTE;
8539}
8540
8542 // In C++98, we don't want to implicitly create an xvalue.
8543 // FIXME: This means that AST consumers need to deal with "prvalues" that
8544 // denote materialized temporaries. Maybe we should add another ValueKind
8545 // for "xvalue pretending to be a prvalue" for C++98 support.
8546 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8547 return E;
8548
8549 // C++1z [conv.rval]/1: T shall be a complete type.
8550 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8551 // If so, we should check for a non-abstract class type here too.
8552 QualType T = E->getType();
8553 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8554 return ExprError();
8555
8556 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8557}
8558
8560 ExprValueKind VK,
8562
8563 CastKind CK = CK_NoOp;
8564
8565 if (VK == VK_PRValue) {
8566 auto PointeeTy = Ty->getPointeeType();
8567 auto ExprPointeeTy = E->getType()->getPointeeType();
8568 if (!PointeeTy.isNull() &&
8569 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8570 CK = CK_AddressSpaceConversion;
8571 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8572 CK = CK_AddressSpaceConversion;
8573 }
8574
8575 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8576}
8577
8579 const InitializedEntity &Entity,
8580 const InitializationKind &Kind,
8581 MultiExprArg Args,
8582 QualType *ResultType) {
8583 if (Failed()) {
8584 Diagnose(S, Entity, Kind, Args);
8585 return ExprError();
8586 }
8587 if (!ZeroInitializationFixit.empty()) {
8588 const Decl *D = Entity.getDecl();
8589 const auto *VD = dyn_cast_or_null<VarDecl>(D);
8590 QualType DestType = Entity.getType();
8591
8592 // The initialization would have succeeded with this fixit. Since the fixit
8593 // is on the error, we need to build a valid AST in this case, so this isn't
8594 // handled in the Failed() branch above.
8595 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8596 // Use a more useful diagnostic for constexpr variables.
8597 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8598 << VD
8599 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8600 ZeroInitializationFixit);
8601 } else {
8602 unsigned DiagID = diag::err_default_init_const;
8603 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8604 DiagID = diag::ext_default_init_const;
8605
8606 S.Diag(Kind.getLocation(), DiagID)
8607 << DestType << (bool)DestType->getAs<RecordType>()
8608 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8609 ZeroInitializationFixit);
8610 }
8611 }
8612
8613 if (getKind() == DependentSequence) {
8614 // If the declaration is a non-dependent, incomplete array type
8615 // that has an initializer, then its type will be completed once
8616 // the initializer is instantiated.
8617 if (ResultType && !Entity.getType()->isDependentType() &&
8618 Args.size() == 1) {
8619 QualType DeclType = Entity.getType();
8620 if (const IncompleteArrayType *ArrayT
8621 = S.Context.getAsIncompleteArrayType(DeclType)) {
8622 // FIXME: We don't currently have the ability to accurately
8623 // compute the length of an initializer list without
8624 // performing full type-checking of the initializer list
8625 // (since we have to determine where braces are implicitly
8626 // introduced and such). So, we fall back to making the array
8627 // type a dependently-sized array type with no specified
8628 // bound.
8629 if (isa<InitListExpr>((Expr *)Args[0])) {
8630 SourceRange Brackets;
8631
8632 // Scavange the location of the brackets from the entity, if we can.
8633 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8634 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8635 TypeLoc TL = TInfo->getTypeLoc();
8636 if (IncompleteArrayTypeLoc ArrayLoc =
8638 Brackets = ArrayLoc.getBracketsRange();
8639 }
8640 }
8641
8642 *ResultType
8643 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8644 /*NumElts=*/nullptr,
8645 ArrayT->getSizeModifier(),
8646 ArrayT->getIndexTypeCVRQualifiers(),
8647 Brackets);
8648 }
8649
8650 }
8651 }
8652 if (Kind.getKind() == InitializationKind::IK_Direct &&
8653 !Kind.isExplicitCast()) {
8654 // Rebuild the ParenListExpr.
8655 SourceRange ParenRange = Kind.getParenOrBraceRange();
8656 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8657 Args);
8658 }
8659 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8660 Kind.isExplicitCast() ||
8661 Kind.getKind() == InitializationKind::IK_DirectList);
8662 return ExprResult(Args[0]);
8663 }
8664
8665 // No steps means no initialization.
8666 if (Steps.empty())
8667 return ExprResult((Expr *)nullptr);
8668
8669 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8670 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8671 !Entity.isParamOrTemplateParamKind()) {
8672 // Produce a C++98 compatibility warning if we are initializing a reference
8673 // from an initializer list. For parameters, we produce a better warning
8674 // elsewhere.
8675 Expr *Init = Args[0];
8676 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8677 << Init->getSourceRange();
8678 }
8679
8680 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8681 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8682 // Produce a Microsoft compatibility warning when initializing from a
8683 // predefined expression since MSVC treats predefined expressions as string
8684 // literals.
8685 Expr *Init = Args[0];
8686 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8687 }
8688
8689 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8690 QualType ETy = Entity.getType();
8691 bool HasGlobalAS = ETy.hasAddressSpace() &&
8693
8694 if (S.getLangOpts().OpenCLVersion >= 200 &&
8695 ETy->isAtomicType() && !HasGlobalAS &&
8696 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8697 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8698 << 1
8699 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8700 return ExprError();
8701 }
8702
8703 QualType DestType = Entity.getType().getNonReferenceType();
8704 // FIXME: Ugly hack around the fact that Entity.getType() is not
8705 // the same as Entity.getDecl()->getType() in cases involving type merging,
8706 // and we want latter when it makes sense.
8707 if (ResultType)
8708 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8709 Entity.getType();
8710
8711 ExprResult CurInit((Expr *)nullptr);
8712 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8713
8714 // HLSL allows vector initialization to function like list initialization, but
8715 // use the syntax of a C++-like constructor.
8716 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8717 isa<InitListExpr>(Args[0]);
8718 (void)IsHLSLVectorInit;
8719
8720 // For initialization steps that start with a single initializer,
8721 // grab the only argument out the Args and place it into the "current"
8722 // initializer.
8723 switch (Steps.front().Kind) {
8728 case SK_BindReference:
8730 case SK_FinalCopy:
8732 case SK_UserConversion:
8741 case SK_UnwrapInitList:
8742 case SK_RewrapInitList:
8743 case SK_CAssignment:
8744 case SK_StringInit:
8746 case SK_ArrayLoopIndex:
8747 case SK_ArrayLoopInit:
8748 case SK_ArrayInit:
8749 case SK_GNUArrayInit:
8755 case SK_OCLSamplerInit:
8756 case SK_OCLZeroOpaqueType: {
8757 assert(Args.size() == 1 || IsHLSLVectorInit);
8758 CurInit = Args[0];
8759 if (!CurInit.get()) return ExprError();
8760 break;
8761 }
8762
8768 break;
8769 }
8770
8771 // Promote from an unevaluated context to an unevaluated list context in
8772 // C++11 list-initialization; we need to instantiate entities usable in
8773 // constant expressions here in order to perform narrowing checks =(
8776 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8777
8778 // C++ [class.abstract]p2:
8779 // no objects of an abstract class can be created except as subobjects
8780 // of a class derived from it
8781 auto checkAbstractType = [&](QualType T) -> bool {
8782 if (Entity.getKind() == InitializedEntity::EK_Base ||
8784 return false;
8785 return S.RequireNonAbstractType(Kind.getLocation(), T,
8786 diag::err_allocation_of_abstract_type);
8787 };
8788
8789 // Walk through the computed steps for the initialization sequence,
8790 // performing the specified conversions along the way.
8791 bool ConstructorInitRequiresZeroInit = false;
8792 for (step_iterator Step = step_begin(), StepEnd = step_end();
8793 Step != StepEnd; ++Step) {
8794 if (CurInit.isInvalid())
8795 return ExprError();
8796
8797 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8798
8799 switch (Step->Kind) {
8801 // Overload resolution determined which function invoke; update the
8802 // initializer to reflect that choice.
8804 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8805 return ExprError();
8806 CurInit = S.FixOverloadedFunctionReference(CurInit,
8809 // We might get back another placeholder expression if we resolved to a
8810 // builtin.
8811 if (!CurInit.isInvalid())
8812 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8813 break;
8814
8818 // We have a derived-to-base cast that produces either an rvalue or an
8819 // lvalue. Perform that cast.
8820
8821 CXXCastPath BasePath;
8822
8823 // Casts to inaccessible base classes are allowed with C-style casts.
8824 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8826 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8827 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8828 return ExprError();
8829
8830 ExprValueKind VK =
8832 ? VK_LValue
8834 : VK_PRValue);
8836 CK_DerivedToBase, CurInit.get(),
8837 &BasePath, VK, FPOptionsOverride());
8838 break;
8839 }
8840
8841 case SK_BindReference:
8842 // Reference binding does not have any corresponding ASTs.
8843
8844 // Check exception specifications
8845 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8846 return ExprError();
8847
8848 // We don't check for e.g. function pointers here, since address
8849 // availability checks should only occur when the function first decays
8850 // into a pointer or reference.
8851 if (CurInit.get()->getType()->isFunctionProtoType()) {
8852 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8853 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8854 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8855 DRE->getBeginLoc()))
8856 return ExprError();
8857 }
8858 }
8859 }
8860
8861 CheckForNullPointerDereference(S, CurInit.get());
8862 break;
8863
8865 // Make sure the "temporary" is actually an rvalue.
8866 assert(CurInit.get()->isPRValue() && "not a temporary");
8867
8868 // Check exception specifications
8869 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8870 return ExprError();
8871
8872 QualType MTETy = Step->Type;
8873
8874 // When this is an incomplete array type (such as when this is
8875 // initializing an array of unknown bounds from an init list), use THAT
8876 // type instead so that we propagate the array bounds.
8877 if (MTETy->isIncompleteArrayType() &&
8878 !CurInit.get()->getType()->isIncompleteArrayType() &&
8881 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8882 MTETy = CurInit.get()->getType();
8883
8884 // Materialize the temporary into memory.
8886 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8887 CurInit = MTE;
8888
8889 // If we're extending this temporary to automatic storage duration -- we
8890 // need to register its cleanup during the full-expression's cleanups.
8891 if (MTE->getStorageDuration() == SD_Automatic &&
8892 MTE->getType().isDestructedType())
8894 break;
8895 }
8896
8897 case SK_FinalCopy:
8898 if (checkAbstractType(Step->Type))
8899 return ExprError();
8900
8901 // If the overall initialization is initializing a temporary, we already
8902 // bound our argument if it was necessary to do so. If not (if we're
8903 // ultimately initializing a non-temporary), our argument needs to be
8904 // bound since it's initializing a function parameter.
8905 // FIXME: This is a mess. Rationalize temporary destruction.
8906 if (!shouldBindAsTemporary(Entity))
8907 CurInit = S.MaybeBindToTemporary(CurInit.get());
8908 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8909 /*IsExtraneousCopy=*/false);
8910 break;
8911
8913 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8914 /*IsExtraneousCopy=*/true);
8915 break;
8916
8917 case SK_UserConversion: {
8918 // We have a user-defined conversion that invokes either a constructor
8919 // or a conversion function.
8923 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8924 bool CreatedObject = false;
8925 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8926 // Build a call to the selected constructor.
8927 SmallVector<Expr*, 8> ConstructorArgs;
8928 SourceLocation Loc = CurInit.get()->getBeginLoc();
8929
8930 // Determine the arguments required to actually perform the constructor
8931 // call.
8932 Expr *Arg = CurInit.get();
8933 if (S.CompleteConstructorCall(Constructor, Step->Type,
8934 MultiExprArg(&Arg, 1), Loc,
8935 ConstructorArgs))
8936 return ExprError();
8937
8938 // Build an expression that constructs a temporary.
8939 CurInit = S.BuildCXXConstructExpr(
8940 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8941 HadMultipleCandidates,
8942 /*ListInit*/ false,
8943 /*StdInitListInit*/ false,
8944 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8945 if (CurInit.isInvalid())
8946 return ExprError();
8947
8948 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8949 Entity);
8950 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8951 return ExprError();
8952
8953 CastKind = CK_ConstructorConversion;
8954 CreatedObject = true;
8955 } else {
8956 // Build a call to the conversion function.
8957 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8958 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8959 FoundFn);
8960 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8961 return ExprError();
8962
8963 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8964 HadMultipleCandidates);
8965 if (CurInit.isInvalid())
8966 return ExprError();
8967
8968 CastKind = CK_UserDefinedConversion;
8969 CreatedObject = Conversion->getReturnType()->isRecordType();
8970 }
8971
8972 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8973 return ExprError();
8974
8975 CurInit = ImplicitCastExpr::Create(
8976 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8977 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8978
8979 if (shouldBindAsTemporary(Entity))
8980 // The overall entity is temporary, so this expression should be
8981 // destroyed at the end of its full-expression.
8982 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8983 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8984 // The object outlasts the full-expression, but we need to prepare for
8985 // a destructor being run on it.
8986 // FIXME: It makes no sense to do this here. This should happen
8987 // regardless of how we initialized the entity.
8988 QualType T = CurInit.get()->getType();
8989 if (const RecordType *Record = T->getAs<RecordType>()) {
8990 CXXDestructorDecl *Destructor
8991 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8992 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8993 S.PDiag(diag::err_access_dtor_temp) << T);
8994 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8995 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8996 return ExprError();
8997 }
8998 }
8999 break;
9000 }
9001
9005 // Perform a qualification conversion; these can never go wrong.
9006 ExprValueKind VK =
9008 ? VK_LValue
9010 : VK_PRValue);
9011 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
9012 break;
9013 }
9014
9016 assert(CurInit.get()->isLValue() &&
9017 "function reference should be lvalue");
9018 CurInit =
9019 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
9020 break;
9021
9022 case SK_AtomicConversion: {
9023 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
9024 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9025 CK_NonAtomicToAtomic, VK_PRValue);
9026 break;
9027 }
9028
9031 if (const auto *FromPtrType =
9032 CurInit.get()->getType()->getAs<PointerType>()) {
9033 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
9034 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9035 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9036 // Do not check static casts here because they are checked earlier
9037 // in Sema::ActOnCXXNamedCast()
9038 if (!Kind.isStaticCast()) {
9039 S.Diag(CurInit.get()->getExprLoc(),
9040 diag::warn_noderef_to_dereferenceable_pointer)
9041 << CurInit.get()->getSourceRange();
9042 }
9043 }
9044 }
9045 }
9046
9048 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
9049 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
9050 : Kind.isExplicitCast()? Sema::CCK_OtherCast
9052 ExprResult CurInitExprRes =
9053 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
9054 getAssignmentAction(Entity), CCK);
9055 if (CurInitExprRes.isInvalid())
9056 return ExprError();
9057
9059
9060 CurInit = CurInitExprRes;
9061
9063 S.getLangOpts().CPlusPlus)
9064 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9065 CurInit.get());
9066
9067 break;
9068 }
9069
9070 case SK_ListInitialization: {
9071 if (checkAbstractType(Step->Type))
9072 return ExprError();
9073
9074 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9075 // If we're not initializing the top-level entity, we need to create an
9076 // InitializeTemporary entity for our target type.
9077 QualType Ty = Step->Type;
9078 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9080 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9081 InitListChecker PerformInitList(S, InitEntity,
9082 InitList, Ty, /*VerifyOnly=*/false,
9083 /*TreatUnavailableAsInvalid=*/false);
9084 if (PerformInitList.HadError())
9085 return ExprError();
9086
9087 // Hack: We must update *ResultType if available in order to set the
9088 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9089 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9090 if (ResultType &&
9091 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9092 if ((*ResultType)->isRValueReferenceType())
9094 else if ((*ResultType)->isLValueReferenceType())
9096 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9097 *ResultType = Ty;
9098 }
9099
9100 InitListExpr *StructuredInitList =
9101 PerformInitList.getFullyStructuredList();
9102 CurInit.get();
9103 CurInit = shouldBindAsTemporary(InitEntity)
9104 ? S.MaybeBindToTemporary(StructuredInitList)
9105 : StructuredInitList;
9106 break;
9107 }
9108
9110 if (checkAbstractType(Step->Type))
9111 return ExprError();
9112
9113 // When an initializer list is passed for a parameter of type "reference
9114 // to object", we don't get an EK_Temporary entity, but instead an
9115 // EK_Parameter entity with reference type.
9116 // FIXME: This is a hack. What we really should do is create a user
9117 // conversion step for this case, but this makes it considerably more
9118 // complicated. For now, this will do.
9120 Entity.getType().getNonReferenceType());
9121 bool UseTemporary = Entity.getType()->isReferenceType();
9122 assert(Args.size() == 1 && "expected a single argument for list init");
9123 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9124 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9125 << InitList->getSourceRange();
9126 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9127 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9128 Entity,
9129 Kind, Arg, *Step,
9130 ConstructorInitRequiresZeroInit,
9131 /*IsListInitialization*/true,
9132 /*IsStdInitListInit*/false,
9133 InitList->getLBraceLoc(),
9134 InitList->getRBraceLoc());
9135 break;
9136 }
9137
9138 case SK_UnwrapInitList:
9139 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9140 break;
9141
9142 case SK_RewrapInitList: {
9143 Expr *E = CurInit.get();
9145 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9146 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9147 ILE->setSyntacticForm(Syntactic);
9148 ILE->setType(E->getType());
9149 ILE->setValueKind(E->getValueKind());
9150 CurInit = ILE;
9151 break;
9152 }
9153
9156 if (checkAbstractType(Step->Type))
9157 return ExprError();
9158
9159 // When an initializer list is passed for a parameter of type "reference
9160 // to object", we don't get an EK_Temporary entity, but instead an
9161 // EK_Parameter entity with reference type.
9162 // FIXME: This is a hack. What we really should do is create a user
9163 // conversion step for this case, but this makes it considerably more
9164 // complicated. For now, this will do.
9166 Entity.getType().getNonReferenceType());
9167 bool UseTemporary = Entity.getType()->isReferenceType();
9168 bool IsStdInitListInit =
9170 Expr *Source = CurInit.get();
9171 SourceRange Range = Kind.hasParenOrBraceRange()
9172 ? Kind.getParenOrBraceRange()
9173 : SourceRange();
9175 S, UseTemporary ? TempEntity : Entity, Kind,
9176 Source ? MultiExprArg(Source) : Args, *Step,
9177 ConstructorInitRequiresZeroInit,
9178 /*IsListInitialization*/ IsStdInitListInit,
9179 /*IsStdInitListInitialization*/ IsStdInitListInit,
9180 /*LBraceLoc*/ Range.getBegin(),
9181 /*RBraceLoc*/ Range.getEnd());
9182 break;
9183 }
9184
9185 case SK_ZeroInitialization: {
9186 step_iterator NextStep = Step;
9187 ++NextStep;
9188 if (NextStep != StepEnd &&
9189 (NextStep->Kind == SK_ConstructorInitialization ||
9190 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9191 // The need for zero-initialization is recorded directly into
9192 // the call to the object's constructor within the next step.
9193 ConstructorInitRequiresZeroInit = true;
9194 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9195 S.getLangOpts().CPlusPlus &&
9196 !Kind.isImplicitValueInit()) {
9197 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9198 if (!TSInfo)
9200 Kind.getRange().getBegin());
9201
9202 CurInit = new (S.Context) CXXScalarValueInitExpr(
9203 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9204 Kind.getRange().getEnd());
9205 } else {
9206 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9207 }
9208 break;
9209 }
9210
9211 case SK_CAssignment: {
9212 QualType SourceType = CurInit.get()->getType();
9213
9214 // Save off the initial CurInit in case we need to emit a diagnostic
9215 ExprResult InitialCurInit = CurInit;
9216 ExprResult Result = CurInit;
9220 if (Result.isInvalid())
9221 return ExprError();
9222 CurInit = Result;
9223
9224 // If this is a call, allow conversion to a transparent union.
9225 ExprResult CurInitExprRes = CurInit;
9226 if (ConvTy != Sema::Compatible &&
9227 Entity.isParameterKind() &&
9230 ConvTy = Sema::Compatible;
9231 if (CurInitExprRes.isInvalid())
9232 return ExprError();
9233 CurInit = CurInitExprRes;
9234
9235 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
9236 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
9237 CurInit.get());
9238
9239 // C23 6.7.1p6: If an object or subobject declared with storage-class
9240 // specifier constexpr has pointer, integer, or arithmetic type, any
9241 // explicit initializer value for it shall be null, an integer
9242 // constant expression, or an arithmetic constant expression,
9243 // respectively.
9245 if (Entity.getType()->getAs<PointerType>() &&
9246 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
9247 !ER.Val.isNullPointer()) {
9248 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
9249 }
9250 }
9251
9252 bool Complained;
9253 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9254 Step->Type, SourceType,
9255 InitialCurInit.get(),
9256 getAssignmentAction(Entity, true),
9257 &Complained)) {
9258 PrintInitLocationNote(S, Entity);
9259 return ExprError();
9260 } else if (Complained)
9261 PrintInitLocationNote(S, Entity);
9262 break;
9263 }
9264
9265 case SK_StringInit: {
9266 QualType Ty = Step->Type;
9267 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9268 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9269 S.Context.getAsArrayType(Ty), S,
9270 S.getLangOpts().C23 &&
9272 break;
9273 }
9274
9276 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9277 CK_ObjCObjectLValueCast,
9278 CurInit.get()->getValueKind());
9279 break;
9280
9281 case SK_ArrayLoopIndex: {
9282 Expr *Cur = CurInit.get();
9283 Expr *BaseExpr = new (S.Context)
9284 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9285 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9286 Expr *IndexExpr =
9289 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9290 ArrayLoopCommonExprs.push_back(BaseExpr);
9291 break;
9292 }
9293
9294 case SK_ArrayLoopInit: {
9295 assert(!ArrayLoopCommonExprs.empty() &&
9296 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9297 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9298 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9299 CurInit.get());
9300 break;
9301 }
9302
9303 case SK_GNUArrayInit:
9304 // Okay: we checked everything before creating this step. Note that
9305 // this is a GNU extension.
9306 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9307 << Step->Type << CurInit.get()->getType()
9308 << CurInit.get()->getSourceRange();
9310 [[fallthrough]];
9311 case SK_ArrayInit:
9312 // If the destination type is an incomplete array type, update the
9313 // type accordingly.
9314 if (ResultType) {
9315 if (const IncompleteArrayType *IncompleteDest
9317 if (const ConstantArrayType *ConstantSource
9318 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9319 *ResultType = S.Context.getConstantArrayType(
9320 IncompleteDest->getElementType(), ConstantSource->getSize(),
9321 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9322 }
9323 }
9324 }
9325 break;
9326
9328 // Okay: we checked everything before creating this step. Note that
9329 // this is a GNU extension.
9330 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9331 << CurInit.get()->getSourceRange();
9332 break;
9333
9336 checkIndirectCopyRestoreSource(S, CurInit.get());
9337 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9338 CurInit.get(), Step->Type,
9340 break;
9341
9343 CurInit = ImplicitCastExpr::Create(
9344 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9346 break;
9347
9348 case SK_StdInitializerList: {
9349 S.Diag(CurInit.get()->getExprLoc(),
9350 diag::warn_cxx98_compat_initializer_list_init)
9351 << CurInit.get()->getSourceRange();
9352
9353 // Materialize the temporary into memory.
9355 CurInit.get()->getType(), CurInit.get(),
9356 /*BoundToLvalueReference=*/false);
9357
9358 // Wrap it in a construction of a std::initializer_list<T>.
9359 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9360
9361 // Bind the result, in case the library has given initializer_list a
9362 // non-trivial destructor.
9363 if (shouldBindAsTemporary(Entity))
9364 CurInit = S.MaybeBindToTemporary(CurInit.get());
9365 break;
9366 }
9367
9368 case SK_OCLSamplerInit: {
9369 // Sampler initialization have 5 cases:
9370 // 1. function argument passing
9371 // 1a. argument is a file-scope variable
9372 // 1b. argument is a function-scope variable
9373 // 1c. argument is one of caller function's parameters
9374 // 2. variable initialization
9375 // 2a. initializing a file-scope variable
9376 // 2b. initializing a function-scope variable
9377 //
9378 // For file-scope variables, since they cannot be initialized by function
9379 // call of __translate_sampler_initializer in LLVM IR, their references
9380 // need to be replaced by a cast from their literal initializers to
9381 // sampler type. Since sampler variables can only be used in function
9382 // calls as arguments, we only need to replace them when handling the
9383 // argument passing.
9384 assert(Step->Type->isSamplerT() &&
9385 "Sampler initialization on non-sampler type.");
9386 Expr *Init = CurInit.get()->IgnoreParens();
9387 QualType SourceType = Init->getType();
9388 // Case 1
9389 if (Entity.isParameterKind()) {
9390 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9391 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9392 << SourceType;
9393 break;
9394 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9395 auto Var = cast<VarDecl>(DRE->getDecl());
9396 // Case 1b and 1c
9397 // No cast from integer to sampler is needed.
9398 if (!Var->hasGlobalStorage()) {
9399 CurInit = ImplicitCastExpr::Create(
9400 S.Context, Step->Type, CK_LValueToRValue, Init,
9401 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9402 break;
9403 }
9404 // Case 1a
9405 // For function call with a file-scope sampler variable as argument,
9406 // get the integer literal.
9407 // Do not diagnose if the file-scope variable does not have initializer
9408 // since this has already been diagnosed when parsing the variable
9409 // declaration.
9410 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9411 break;
9412 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9413 Var->getInit()))->getSubExpr();
9414 SourceType = Init->getType();
9415 }
9416 } else {
9417 // Case 2
9418 // Check initializer is 32 bit integer constant.
9419 // If the initializer is taken from global variable, do not diagnose since
9420 // this has already been done when parsing the variable declaration.
9421 if (!Init->isConstantInitializer(S.Context, false))
9422 break;
9423
9424 if (!SourceType->isIntegerType() ||
9425 32 != S.Context.getIntWidth(SourceType)) {
9426 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9427 << SourceType;
9428 break;
9429 }
9430
9431 Expr::EvalResult EVResult;
9432 Init->EvaluateAsInt(EVResult, S.Context);
9433 llvm::APSInt Result = EVResult.Val.getInt();
9434 const uint64_t SamplerValue = Result.getLimitedValue();
9435 // 32-bit value of sampler's initializer is interpreted as
9436 // bit-field with the following structure:
9437 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9438 // |31 6|5 4|3 1| 0|
9439 // This structure corresponds to enum values of sampler properties
9440 // defined in SPIR spec v1.2 and also opencl-c.h
9441 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9442 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9443 if (FilterMode != 1 && FilterMode != 2 &&
9445 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9446 S.Diag(Kind.getLocation(),
9447 diag::warn_sampler_initializer_invalid_bits)
9448 << "Filter Mode";
9449 if (AddressingMode > 4)
9450 S.Diag(Kind.getLocation(),
9451 diag::warn_sampler_initializer_invalid_bits)
9452 << "Addressing Mode";
9453 }
9454
9455 // Cases 1a, 2a and 2b
9456 // Insert cast from integer to sampler.
9458 CK_IntToOCLSampler);
9459 break;
9460 }
9461 case SK_OCLZeroOpaqueType: {
9462 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9464 "Wrong type for initialization of OpenCL opaque type.");
9465
9466 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9467 CK_ZeroToOCLOpaqueType,
9468 CurInit.get()->getValueKind());
9469 break;
9470 }
9472 CurInit = nullptr;
9473 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9474 /*VerifyOnly=*/false, &CurInit);
9475 if (CurInit.get() && ResultType)
9476 *ResultType = CurInit.get()->getType();
9477 if (shouldBindAsTemporary(Entity))
9478 CurInit = S.MaybeBindToTemporary(CurInit.get());
9479 break;
9480 }
9481 }
9482 }
9483
9484 Expr *Init = CurInit.get();
9485 if (!Init)
9486 return ExprError();
9487
9488 // Check whether the initializer has a shorter lifetime than the initialized
9489 // entity, and if not, either lifetime-extend or warn as appropriate.
9490 S.checkInitializerLifetime(Entity, Init);
9491
9492 // Diagnose non-fatal problems with the completed initialization.
9493 if (InitializedEntity::EntityKind EK = Entity.getKind();
9496 cast<FieldDecl>(Entity.getDecl())->isBitField())
9497 S.CheckBitFieldInitialization(Kind.getLocation(),
9498 cast<FieldDecl>(Entity.getDecl()), Init);
9499
9500 // Check for std::move on construction.
9503
9504 return Init;
9505}
9506
9507/// Somewhere within T there is an uninitialized reference subobject.
9508/// Dig it out and diagnose it.
9510 QualType T) {
9511 if (T->isReferenceType()) {
9512 S.Diag(Loc, diag::err_reference_without_init)
9513 << T.getNonReferenceType();
9514 return true;
9515 }
9516
9518 if (!RD || !RD->hasUninitializedReferenceMember())
9519 return false;
9520
9521 for (const auto *FI : RD->fields()) {
9522 if (FI->isUnnamedBitfield())
9523 continue;
9524
9525 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9526 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9527 return true;
9528 }
9529 }
9530
9531 for (const auto &BI : RD->bases()) {
9532 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9533 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9534 return true;
9535 }
9536 }
9537
9538 return false;
9539}
9540
9541
9542//===----------------------------------------------------------------------===//
9543// Diagnose initialization failures
9544//===----------------------------------------------------------------------===//
9545
9546/// Emit notes associated with an initialization that failed due to a
9547/// "simple" conversion failure.
9548static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9549 Expr *op) {
9550 QualType destType = entity.getType();
9551 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9553
9554 // Emit a possible note about the conversion failing because the
9555 // operand is a message send with a related result type.
9557
9558 // Emit a possible note about a return failing because we're
9559 // expecting a related result type.
9560 if (entity.getKind() == InitializedEntity::EK_Result)
9562 }
9563 QualType fromType = op->getType();
9564 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9565 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9566 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9567 auto *destDecl = destType->getPointeeCXXRecordDecl();
9568 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9569 destDecl->getDeclKind() == Decl::CXXRecord &&
9570 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9571 !fromDecl->hasDefinition() &&
9572 destPointeeType.getQualifiers().compatiblyIncludes(
9573 fromPointeeType.getQualifiers()))
9574 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9575 << S.getASTContext().getTagDeclType(fromDecl)
9576 << S.getASTContext().getTagDeclType(destDecl);
9577}
9578
9579static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9580 InitListExpr *InitList) {
9581 QualType DestType = Entity.getType();
9582
9583 QualType E;
9584 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9586 E.withConst(),
9587 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9588 InitList->getNumInits()),
9590 InitializedEntity HiddenArray =
9592 return diagnoseListInit(S, HiddenArray, InitList);
9593 }
9594
9595 if (DestType->isReferenceType()) {
9596 // A list-initialization failure for a reference means that we tried to
9597 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9598 // inner initialization failed.
9599 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9601 SourceLocation Loc = InitList->getBeginLoc();
9602 if (auto *D = Entity.getDecl())
9603 Loc = D->getLocation();
9604 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9605 return;
9606 }
9607
9608 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9609 /*VerifyOnly=*/false,
9610 /*TreatUnavailableAsInvalid=*/false);
9611 assert(DiagnoseInitList.HadError() &&
9612 "Inconsistent init list check result.");
9613}
9614
9616 const InitializedEntity &Entity,
9617 const InitializationKind &Kind,
9618 ArrayRef<Expr *> Args) {
9619 if (!Failed())
9620 return false;
9621
9622 // When we want to diagnose only one element of a braced-init-list,
9623 // we need to factor it out.
9624 Expr *OnlyArg;
9625 if (Args.size() == 1) {
9626 auto *List = dyn_cast<InitListExpr>(Args[0]);
9627 if (List && List->getNumInits() == 1)
9628 OnlyArg = List->getInit(0);
9629 else
9630 OnlyArg = Args[0];
9631 }
9632 else
9633 OnlyArg = nullptr;
9634
9635 QualType DestType = Entity.getType();
9636 switch (Failure) {
9638 // FIXME: Customize for the initialized entity?
9639 if (Args.empty()) {
9640 // Dig out the reference subobject which is uninitialized and diagnose it.
9641 // If this is value-initialization, this could be nested some way within
9642 // the target type.
9643 assert(Kind.getKind() == InitializationKind::IK_Value ||
9644 DestType->isReferenceType());
9645 bool Diagnosed =
9646 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9647 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9648 (void)Diagnosed;
9649 } else // FIXME: diagnostic below could be better!
9650 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9651 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9652 break;
9654 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9655 << 1 << Entity.getType() << Args[0]->getSourceRange();
9656 break;
9657
9659 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9660 break;
9662 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9663 break;
9665 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9666 break;
9668 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9669 break;
9671 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9672 break;
9674 S.Diag(Kind.getLocation(),
9675 diag::err_array_init_incompat_wide_string_into_wchar);
9676 break;
9678 S.Diag(Kind.getLocation(),
9679 diag::err_array_init_plain_string_into_char8_t);
9680 S.Diag(Args.front()->getBeginLoc(),
9681 diag::note_array_init_plain_string_into_char8_t)
9682 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9683 break;
9685 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9686 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9687 break;
9690 S.Diag(Kind.getLocation(),
9691 (Failure == FK_ArrayTypeMismatch
9692 ? diag::err_array_init_different_type
9693 : diag::err_array_init_non_constant_array))
9694 << DestType.getNonReferenceType()
9695 << OnlyArg->getType()
9696 << Args[0]->getSourceRange();
9697 break;
9698
9700 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9701 << Args[0]->getSourceRange();
9702 break;
9703
9705 DeclAccessPair Found;
9707 DestType.getNonReferenceType(),
9708 true,
9709 Found);
9710 break;
9711 }
9712
9714 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9715 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9716 OnlyArg->getBeginLoc());
9717 break;
9718 }
9719
9722 switch (FailedOverloadResult) {
9723 case OR_Ambiguous:
9724
9725 FailedCandidateSet.NoteCandidates(
9727 Kind.getLocation(),
9729 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9730 << OnlyArg->getType() << DestType
9731 << Args[0]->getSourceRange())
9732 : (S.PDiag(diag::err_ref_init_ambiguous)
9733 << DestType << OnlyArg->getType()
9734 << Args[0]->getSourceRange())),
9735 S, OCD_AmbiguousCandidates, Args);
9736 break;
9737
9738 case OR_No_Viable_Function: {
9739 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9740 if (!S.RequireCompleteType(Kind.getLocation(),
9741 DestType.getNonReferenceType(),
9742 diag::err_typecheck_nonviable_condition_incomplete,
9743 OnlyArg->getType(), Args[0]->getSourceRange()))
9744 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9745 << (Entity.getKind() == InitializedEntity::EK_Result)
9746 << OnlyArg->getType() << Args[0]->getSourceRange()
9747 << DestType.getNonReferenceType();
9748
9749 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9750 break;
9751 }
9752 case OR_Deleted: {
9753 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9754 << OnlyArg->getType() << DestType.getNonReferenceType()
9755 << Args[0]->getSourceRange();
9758 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9759 if (Ovl == OR_Deleted) {
9760 S.NoteDeletedFunction(Best->Function);
9761 } else {
9762 llvm_unreachable("Inconsistent overload resolution?");
9763 }
9764 break;
9765 }
9766
9767 case OR_Success:
9768 llvm_unreachable("Conversion did not fail!");
9769 }
9770 break;
9771
9773 if (isa<InitListExpr>(Args[0])) {
9774 S.Diag(Kind.getLocation(),
9775 diag::err_lvalue_reference_bind_to_initlist)
9777 << DestType.getNonReferenceType()
9778 << Args[0]->getSourceRange();
9779 break;
9780 }
9781 [[fallthrough]];
9782
9784 S.Diag(Kind.getLocation(),
9786 ? diag::err_lvalue_reference_bind_to_temporary
9787 : diag::err_lvalue_reference_bind_to_unrelated)
9789 << DestType.getNonReferenceType()
9790 << OnlyArg->getType()
9791 << Args[0]->getSourceRange();
9792 break;
9793
9795 // We don't necessarily have an unambiguous source bit-field.
9796 FieldDecl *BitField = Args[0]->getSourceBitField();
9797 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9798 << DestType.isVolatileQualified()
9799 << (BitField ? BitField->getDeclName() : DeclarationName())
9800 << (BitField != nullptr)
9801 << Args[0]->getSourceRange();
9802 if (BitField)
9803 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9804 break;
9805 }
9806
9808 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9809 << DestType.isVolatileQualified()
9810 << Args[0]->getSourceRange();
9811 break;
9812
9814 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9815 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9816 break;
9817
9819 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9820 << DestType.getNonReferenceType() << OnlyArg->getType()
9821 << Args[0]->getSourceRange();
9822 break;
9823
9825 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9826 << DestType << Args[0]->getSourceRange();
9827 break;
9828
9830 QualType SourceType = OnlyArg->getType();
9831 QualType NonRefType = DestType.getNonReferenceType();
9832 Qualifiers DroppedQualifiers =
9833 SourceType.getQualifiers() - NonRefType.getQualifiers();
9834
9835 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9836 SourceType.getQualifiers()))
9837 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9838 << NonRefType << SourceType << 1 /*addr space*/
9839 << Args[0]->getSourceRange();
9840 else if (DroppedQualifiers.hasQualifiers())
9841 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9842 << NonRefType << SourceType << 0 /*cv quals*/
9843 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9844 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9845 else
9846 // FIXME: Consider decomposing the type and explaining which qualifiers
9847 // were dropped where, or on which level a 'const' is missing, etc.
9848 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9849 << NonRefType << SourceType << 2 /*incompatible quals*/
9850 << Args[0]->getSourceRange();
9851 break;
9852 }
9853
9855 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9856 << DestType.getNonReferenceType()
9857 << DestType.getNonReferenceType()->isIncompleteType()
9858 << OnlyArg->isLValue()
9859 << OnlyArg->getType()
9860 << Args[0]->getSourceRange();
9861 emitBadConversionNotes(S, Entity, Args[0]);
9862 break;
9863
9864 case FK_ConversionFailed: {
9865 QualType FromType = OnlyArg->getType();
9866 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9867 << (int)Entity.getKind()
9868 << DestType
9869 << OnlyArg->isLValue()
9870 << FromType
9871 << Args[0]->getSourceRange();
9872 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9873 S.Diag(Kind.getLocation(), PDiag);
9874 emitBadConversionNotes(S, Entity, Args[0]);
9875 break;
9876 }
9877
9879 // No-op. This error has already been reported.
9880 break;
9881
9883 SourceRange R;
9884
9885 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9886 if (InitList && InitList->getNumInits() >= 1) {
9887 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9888 } else {
9889 assert(Args.size() > 1 && "Expected multiple initializers!");
9890 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9891 }
9892
9894 if (Kind.isCStyleOrFunctionalCast())
9895 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9896 << R;
9897 else
9898 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9899 << /*scalar=*/2 << R;
9900 break;
9901 }
9902
9904 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9905 << 0 << Entity.getType() << Args[0]->getSourceRange();
9906 break;
9907
9909 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9910 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9911 break;
9912
9914 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9915 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9916 break;
9917
9920 SourceRange ArgsRange;
9921 if (Args.size())
9922 ArgsRange =
9923 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9924
9925 if (Failure == FK_ListConstructorOverloadFailed) {
9926 assert(Args.size() == 1 &&
9927 "List construction from other than 1 argument.");
9928 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9929 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9930 }
9931
9932 // FIXME: Using "DestType" for the entity we're printing is probably
9933 // bad.
9934 switch (FailedOverloadResult) {
9935 case OR_Ambiguous:
9936 FailedCandidateSet.NoteCandidates(
9937 PartialDiagnosticAt(Kind.getLocation(),
9938 S.PDiag(diag::err_ovl_ambiguous_init)
9939 << DestType << ArgsRange),
9940 S, OCD_AmbiguousCandidates, Args);
9941 break;
9942
9944 if (Kind.getKind() == InitializationKind::IK_Default &&
9945 (Entity.getKind() == InitializedEntity::EK_Base ||
9948 isa<CXXConstructorDecl>(S.CurContext)) {
9949 // This is implicit default initialization of a member or
9950 // base within a constructor. If no viable function was
9951 // found, notify the user that they need to explicitly
9952 // initialize this base/member.
9953 CXXConstructorDecl *Constructor
9954 = cast<CXXConstructorDecl>(S.CurContext);
9955 const CXXRecordDecl *InheritedFrom = nullptr;
9956 if (auto Inherited = Constructor->getInheritedConstructor())
9957 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9958 if (Entity.getKind() == InitializedEntity::EK_Base) {
9959 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9960 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9961 << S.Context.getTypeDeclType(Constructor->getParent())
9962 << /*base=*/0
9963 << Entity.getType()
9964 << InheritedFrom;
9965
9966 RecordDecl *BaseDecl
9967 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9968 ->getDecl();
9969 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9970 << S.Context.getTagDeclType(BaseDecl);
9971 } else {
9972 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9973 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9974 << S.Context.getTypeDeclType(Constructor->getParent())
9975 << /*member=*/1
9976 << Entity.getName()
9977 << InheritedFrom;
9978 S.Diag(Entity.getDecl()->getLocation(),
9979 diag::note_member_declared_at);
9980
9981 if (const RecordType *Record
9982 = Entity.getType()->getAs<RecordType>())
9983 S.Diag(Record->getDecl()->getLocation(),
9984 diag::note_previous_decl)
9985 << S.Context.getTagDeclType(Record->getDecl());
9986 }
9987 break;
9988 }
9989
9990 FailedCandidateSet.NoteCandidates(
9992 Kind.getLocation(),
9993 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9994 << DestType << ArgsRange),
9995 S, OCD_AllCandidates, Args);
9996 break;
9997
9998 case OR_Deleted: {
10001 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10002 if (Ovl != OR_Deleted) {
10003 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10004 << DestType << ArgsRange;
10005 llvm_unreachable("Inconsistent overload resolution?");
10006 break;
10007 }
10008
10009 // If this is a defaulted or implicitly-declared function, then
10010 // it was implicitly deleted. Make it clear that the deletion was
10011 // implicit.
10012 if (S.isImplicitlyDeleted(Best->Function))
10013 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
10014 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
10015 << DestType << ArgsRange;
10016 else
10017 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10018 << DestType << ArgsRange;
10019
10020 S.NoteDeletedFunction(Best->Function);
10021 break;
10022 }
10023
10024 case OR_Success:
10025 llvm_unreachable("Conversion did not fail!");
10026 }
10027 }
10028 break;
10029
10031 if (Entity.getKind() == InitializedEntity::EK_Member &&
10032 isa<CXXConstructorDecl>(S.CurContext)) {
10033 // This is implicit default-initialization of a const member in
10034 // a constructor. Complain that it needs to be explicitly
10035 // initialized.
10036 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
10037 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
10038 << (Constructor->getInheritedConstructor() ? 2 :
10039 Constructor->isImplicit() ? 1 : 0)
10040 << S.Context.getTypeDeclType(Constructor->getParent())
10041 << /*const=*/1
10042 << Entity.getName();
10043 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
10044 << Entity.getName();
10045 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
10046 VD && VD->isConstexpr()) {
10047 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
10048 << VD;
10049 } else {
10050 S.Diag(Kind.getLocation(), diag::err_default_init_const)
10051 << DestType << (bool)DestType->getAs<RecordType>();
10052 }
10053 break;
10054
10055 case FK_Incomplete:
10056 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
10057 diag::err_init_incomplete_type);
10058 break;
10059
10061 // Run the init list checker again to emit diagnostics.
10062 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10063 diagnoseListInit(S, Entity, InitList);
10064 break;
10065 }
10066
10067 case FK_PlaceholderType: {
10068 // FIXME: Already diagnosed!
10069 break;
10070 }
10071
10073 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
10074 << Args[0]->getSourceRange();
10077 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10078 (void)Ovl;
10079 assert(Ovl == OR_Success && "Inconsistent overload resolution");
10080 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10081 S.Diag(CtorDecl->getLocation(),
10082 diag::note_explicit_ctor_deduction_guide_here) << false;
10083 break;
10084 }
10085
10087 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10088 /*VerifyOnly=*/false);
10089 break;
10090
10092 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10093 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10094 << Entity.getType() << InitList->getSourceRange();
10095 break;
10096 }
10097
10098 PrintInitLocationNote(S, Entity);
10099 return true;
10100}
10101
10102void InitializationSequence::dump(raw_ostream &OS) const {
10103 switch (SequenceKind) {
10104 case FailedSequence: {
10105 OS << "Failed sequence: ";
10106 switch (Failure) {
10108 OS << "too many initializers for reference";
10109 break;
10110
10112 OS << "parenthesized list init for reference";
10113 break;
10114
10116 OS << "array requires initializer list";
10117 break;
10118
10120 OS << "address of unaddressable function was taken";
10121 break;
10122
10124 OS << "array requires initializer list or string literal";
10125 break;
10126
10128 OS << "array requires initializer list or wide string literal";
10129 break;
10130
10132 OS << "narrow string into wide char array";
10133 break;
10134
10136 OS << "wide string into char array";
10137 break;
10138
10140 OS << "incompatible wide string into wide char array";
10141 break;
10142
10144 OS << "plain string literal into char8_t array";
10145 break;
10146
10148 OS << "u8 string literal into char array";
10149 break;
10150
10152 OS << "array type mismatch";
10153 break;
10154
10156 OS << "non-constant array initializer";
10157 break;
10158
10160 OS << "address of overloaded function failed";
10161 break;
10162
10164 OS << "overload resolution for reference initialization failed";
10165 break;
10166
10168 OS << "non-const lvalue reference bound to temporary";
10169 break;
10170
10172 OS << "non-const lvalue reference bound to bit-field";
10173 break;
10174
10176 OS << "non-const lvalue reference bound to vector element";
10177 break;
10178
10180 OS << "non-const lvalue reference bound to matrix element";
10181 break;
10182
10184 OS << "non-const lvalue reference bound to unrelated type";
10185 break;
10186
10188 OS << "rvalue reference bound to an lvalue";
10189 break;
10190
10192 OS << "reference initialization drops qualifiers";
10193 break;
10194
10196 OS << "reference with mismatching address space bound to temporary";
10197 break;
10198
10200 OS << "reference initialization failed";
10201 break;
10202
10204 OS << "conversion failed";
10205 break;
10206
10208 OS << "conversion from property failed";
10209 break;
10210
10212 OS << "too many initializers for scalar";
10213 break;
10214
10216 OS << "parenthesized list init for reference";
10217 break;
10218
10220 OS << "referencing binding to initializer list";
10221 break;
10222
10224 OS << "initializer list for non-aggregate, non-scalar type";
10225 break;
10226
10228 OS << "overloading failed for user-defined conversion";
10229 break;
10230
10232 OS << "constructor overloading failed";
10233 break;
10234
10236 OS << "default initialization of a const variable";
10237 break;
10238
10239 case FK_Incomplete:
10240 OS << "initialization of incomplete type";
10241 break;
10242
10244 OS << "list initialization checker failure";
10245 break;
10246
10248 OS << "variable length array has an initializer";
10249 break;
10250
10251 case FK_PlaceholderType:
10252 OS << "initializer expression isn't contextually valid";
10253 break;
10254
10256 OS << "list constructor overloading failed";
10257 break;
10258
10260 OS << "list copy initialization chose explicit constructor";
10261 break;
10262
10264 OS << "parenthesized list initialization failed";
10265 break;
10266
10268 OS << "designated initializer for non-aggregate type";
10269 break;
10270 }
10271 OS << '\n';
10272 return;
10273 }
10274
10275 case DependentSequence:
10276 OS << "Dependent sequence\n";
10277 return;
10278
10279 case NormalSequence:
10280 OS << "Normal sequence: ";
10281 break;
10282 }
10283
10284 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10285 if (S != step_begin()) {
10286 OS << " -> ";
10287 }
10288
10289 switch (S->Kind) {
10291 OS << "resolve address of overloaded function";
10292 break;
10293
10295 OS << "derived-to-base (prvalue)";
10296 break;
10297
10299 OS << "derived-to-base (xvalue)";
10300 break;
10301
10303 OS << "derived-to-base (lvalue)";
10304 break;
10305
10306 case SK_BindReference:
10307 OS << "bind reference to lvalue";
10308 break;
10309
10311 OS << "bind reference to a temporary";
10312 break;
10313
10314 case SK_FinalCopy:
10315 OS << "final copy in class direct-initialization";
10316 break;
10317
10319 OS << "extraneous C++03 copy to temporary";
10320 break;
10321
10322 case SK_UserConversion:
10323 OS << "user-defined conversion via " << *S->Function.Function;
10324 break;
10325
10327 OS << "qualification conversion (prvalue)";
10328 break;
10329
10331 OS << "qualification conversion (xvalue)";
10332 break;
10333
10335 OS << "qualification conversion (lvalue)";
10336 break;
10337
10339 OS << "function reference conversion";
10340 break;
10341
10343 OS << "non-atomic-to-atomic conversion";
10344 break;
10345
10347 OS << "implicit conversion sequence (";
10348 S->ICS->dump(); // FIXME: use OS
10349 OS << ")";
10350 break;
10351
10353 OS << "implicit conversion sequence with narrowing prohibited (";
10354 S->ICS->dump(); // FIXME: use OS
10355 OS << ")";
10356 break;
10357
10359 OS << "list aggregate initialization";
10360 break;
10361
10362 case SK_UnwrapInitList:
10363 OS << "unwrap reference initializer list";
10364 break;
10365
10366 case SK_RewrapInitList:
10367 OS << "rewrap reference initializer list";
10368 break;
10369
10371 OS << "constructor initialization";
10372 break;
10373
10375 OS << "list initialization via constructor";
10376 break;
10377
10379 OS << "zero initialization";
10380 break;
10381
10382 case SK_CAssignment:
10383 OS << "C assignment";
10384 break;
10385
10386 case SK_StringInit:
10387 OS << "string initialization";
10388 break;
10389
10391 OS << "Objective-C object conversion";
10392 break;
10393
10394 case SK_ArrayLoopIndex:
10395 OS << "indexing for array initialization loop";
10396 break;
10397
10398 case SK_ArrayLoopInit:
10399 OS << "array initialization loop";
10400 break;
10401
10402 case SK_ArrayInit:
10403 OS << "array initialization";
10404 break;
10405
10406 case SK_GNUArrayInit:
10407 OS << "array initialization (GNU extension)";
10408 break;
10409
10411 OS << "parenthesized array initialization";
10412 break;
10413
10415 OS << "pass by indirect copy and restore";
10416 break;
10417
10419 OS << "pass by indirect restore";
10420 break;
10421
10423 OS << "Objective-C object retension";
10424 break;
10425
10427 OS << "std::initializer_list from initializer list";
10428 break;
10429
10431 OS << "list initialization from std::initializer_list";
10432 break;
10433
10434 case SK_OCLSamplerInit:
10435 OS << "OpenCL sampler_t from integer constant";
10436 break;
10437
10439 OS << "OpenCL opaque type from zero";
10440 break;
10442 OS << "initialization from a parenthesized list of values";
10443 break;
10444 }
10445
10446 OS << " [" << S->Type << ']';
10447 }
10448
10449 OS << '\n';
10450}
10451
10453 dump(llvm::errs());
10454}
10455
10457 const ImplicitConversionSequence &ICS,
10458 QualType PreNarrowingType,
10459 QualType EntityType,
10460 const Expr *PostInit) {
10461 const StandardConversionSequence *SCS = nullptr;
10462 switch (ICS.getKind()) {
10464 SCS = &ICS.Standard;
10465 break;
10467 SCS = &ICS.UserDefined.After;
10468 break;
10473 return;
10474 }
10475
10476 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
10477 unsigned ConstRefDiagID, unsigned WarnDiagID) {
10478 unsigned DiagID;
10479 auto &L = S.getLangOpts();
10480 if (L.CPlusPlus11 &&
10481 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
10482 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
10483 else
10484 DiagID = WarnDiagID;
10485 return S.Diag(PostInit->getBeginLoc(), DiagID)
10486 << PostInit->getSourceRange();
10487 };
10488
10489 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10490 APValue ConstantValue;
10491 QualType ConstantType;
10492 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10493 ConstantType)) {
10494 case NK_Not_Narrowing:
10496 // No narrowing occurred.
10497 return;
10498
10499 case NK_Type_Narrowing: {
10500 // This was a floating-to-integer conversion, which is always considered a
10501 // narrowing conversion even if the value is a constant and can be
10502 // represented exactly as an integer.
10503 QualType T = EntityType.getNonReferenceType();
10504 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10505 diag::ext_init_list_type_narrowing_const_reference,
10506 diag::warn_init_list_type_narrowing)
10507 << PreNarrowingType.getLocalUnqualifiedType()
10509 break;
10510 }
10511
10512 case NK_Constant_Narrowing: {
10513 // A constant value was narrowed.
10514 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10515 diag::ext_init_list_constant_narrowing,
10516 diag::ext_init_list_constant_narrowing_const_reference,
10517 diag::warn_init_list_constant_narrowing)
10518 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10520 break;
10521 }
10522
10523 case NK_Variable_Narrowing: {
10524 // A variable's value may have been narrowed.
10525 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10526 diag::ext_init_list_variable_narrowing,
10527 diag::ext_init_list_variable_narrowing_const_reference,
10528 diag::warn_init_list_variable_narrowing)
10529 << PreNarrowingType.getLocalUnqualifiedType()
10531 break;
10532 }
10533 }
10534
10535 SmallString<128> StaticCast;
10536 llvm::raw_svector_ostream OS(StaticCast);
10537 OS << "static_cast<";
10538 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10539 // It's important to use the typedef's name if there is one so that the
10540 // fixit doesn't break code using types like int64_t.
10541 //
10542 // FIXME: This will break if the typedef requires qualification. But
10543 // getQualifiedNameAsString() includes non-machine-parsable components.
10544 OS << *TT->getDecl();
10545 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10546 OS << BT->getName(S.getLangOpts());
10547 else {
10548 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10549 // with a broken cast.
10550 return;
10551 }
10552 OS << ">(";
10553 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10554 << PostInit->getSourceRange()
10555 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10557 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10558}
10559
10561 QualType ToType, Expr *Init) {
10562 assert(S.getLangOpts().C23);
10564 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10565 Sema::AllowedExplicit::None,
10566 /*InOverloadResolution*/ false,
10567 /*CStyle*/ false,
10568 /*AllowObjCWritebackConversion=*/false);
10569
10570 if (!ICS.isStandard())
10571 return;
10572
10573 APValue Value;
10574 QualType PreNarrowingType;
10575 // Reuse C++ narrowing check.
10576 switch (ICS.Standard.getNarrowingKind(
10577 S.Context, Init, Value, PreNarrowingType,
10578 /*IgnoreFloatToIntegralConversion*/ false)) {
10579 // The value doesn't fit.
10581 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10582 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10583 return;
10584
10585 // Conversion to a narrower type.
10586 case NK_Type_Narrowing:
10587 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10588 << ToType << FromType;
10589 return;
10590
10591 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10592 // not really interested in these cases.
10595 case NK_Not_Narrowing:
10596 return;
10597 }
10598 llvm_unreachable("unhandled case in switch");
10599}
10600
10602 Sema &SemaRef, QualType &TT) {
10603 assert(SemaRef.getLangOpts().C23);
10604 // character that string literal contains fits into TT - target type.
10605 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10606 QualType CharType = AT->getElementType();
10607 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10608 bool isUnsigned = CharType->isUnsignedIntegerType();
10609 llvm::APSInt Value(BitWidth, isUnsigned);
10610 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10611 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10612 Value = C;
10613 if (Value != C) {
10614 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10615 diag::err_c23_constexpr_init_not_representable)
10616 << C << CharType;
10617 return;
10618 }
10619 }
10620 return;
10621}
10622
10623//===----------------------------------------------------------------------===//
10624// Initialization helper functions
10625//===----------------------------------------------------------------------===//
10626bool
10628 ExprResult Init) {
10629 if (Init.isInvalid())
10630 return false;
10631
10632 Expr *InitE = Init.get();
10633 assert(InitE && "No initialization expression");
10634
10635 InitializationKind Kind =
10637 InitializationSequence Seq(*this, Entity, Kind, InitE);
10638 return !Seq.Failed();
10639}
10640
10643 SourceLocation EqualLoc,
10645 bool TopLevelOfInitList,
10646 bool AllowExplicit) {
10647 if (Init.isInvalid())
10648 return ExprError();
10649
10650 Expr *InitE = Init.get();
10651 assert(InitE && "No initialization expression?");
10652
10653 if (EqualLoc.isInvalid())
10654 EqualLoc = InitE->getBeginLoc();
10655
10657 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10658 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10659
10660 // Prevent infinite recursion when performing parameter copy-initialization.
10661 const bool ShouldTrackCopy =
10662 Entity.isParameterKind() && Seq.isConstructorInitialization();
10663 if (ShouldTrackCopy) {
10664 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10665 Seq.SetOverloadFailure(
10668
10669 // Try to give a meaningful diagnostic note for the problematic
10670 // constructor.
10671 const auto LastStep = Seq.step_end() - 1;
10672 assert(LastStep->Kind ==
10674 const FunctionDecl *Function = LastStep->Function.Function;
10675 auto Candidate =
10676 llvm::find_if(Seq.getFailedCandidateSet(),
10677 [Function](const OverloadCandidate &Candidate) -> bool {
10678 return Candidate.Viable &&
10679 Candidate.Function == Function &&
10680 Candidate.Conversions.size() > 0;
10681 });
10682 if (Candidate != Seq.getFailedCandidateSet().end() &&
10683 Function->getNumParams() > 0) {
10684 Candidate->Viable = false;
10687 InitE,
10688 Function->getParamDecl(0)->getType());
10689 }
10690 }
10691 CurrentParameterCopyTypes.push_back(Entity.getType());
10692 }
10693
10694 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10695
10696 if (ShouldTrackCopy)
10697 CurrentParameterCopyTypes.pop_back();
10698
10699 return Result;
10700}
10701
10702/// Determine whether RD is, or is derived from, a specialization of CTD.
10704 ClassTemplateDecl *CTD) {
10705 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10706 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10707 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10708 };
10709 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10710}
10711
10713 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10714 const InitializationKind &Kind, MultiExprArg Inits) {
10715 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10716 TSInfo->getType()->getContainedDeducedType());
10717 assert(DeducedTST && "not a deduced template specialization type");
10718
10719 auto TemplateName = DeducedTST->getTemplateName();
10721 return SubstAutoTypeDependent(TSInfo->getType());
10722
10723 // We can only perform deduction for class templates or alias templates.
10724 auto *Template =
10725 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10726 TemplateDecl *LookupTemplateDecl = Template;
10727 if (!Template) {
10728 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10730 Diag(Kind.getLocation(),
10731 diag::warn_cxx17_compat_ctad_for_alias_templates);
10732 LookupTemplateDecl = AliasTemplate;
10733 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10734 ->getUnderlyingType()
10735 .getCanonicalType();
10736 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10737 // of the form
10738 // [typename] [nested-name-specifier] [template] simple-template-id
10739 if (const auto *TST =
10740 UnderlyingType->getAs<TemplateSpecializationType>()) {
10741 Template = dyn_cast_or_null<ClassTemplateDecl>(
10742 TST->getTemplateName().getAsTemplateDecl());
10743 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10744 // Cases where template arguments in the RHS of the alias are not
10745 // dependent. e.g.
10746 // using AliasFoo = Foo<bool>;
10747 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
10748 RT->getAsCXXRecordDecl()))
10749 Template = CTSD->getSpecializedTemplate();
10750 }
10751 }
10752 }
10753 if (!Template) {
10754 Diag(Kind.getLocation(),
10755 diag::err_deduced_non_class_or_alias_template_specialization_type)
10757 if (auto *TD = TemplateName.getAsTemplateDecl())
10759 return QualType();
10760 }
10761
10762 // Can't deduce from dependent arguments.
10764 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10765 diag::warn_cxx14_compat_class_template_argument_deduction)
10766 << TSInfo->getTypeLoc().getSourceRange() << 0;
10767 return SubstAutoTypeDependent(TSInfo->getType());
10768 }
10769
10770 // FIXME: Perform "exact type" matching first, per CWG discussion?
10771 // Or implement this via an implied 'T(T) -> T' deduction guide?
10772
10773 // FIXME: Do we need/want a std::initializer_list<T> special case?
10774
10775 // Look up deduction guides, including those synthesized from constructors.
10776 //
10777 // C++1z [over.match.class.deduct]p1:
10778 // A set of functions and function templates is formed comprising:
10779 // - For each constructor of the class template designated by the
10780 // template-name, a function template [...]
10781 // - For each deduction-guide, a function or function template [...]
10782 DeclarationNameInfo NameInfo(
10784 TSInfo->getTypeLoc().getEndLoc());
10785 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10786 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10787
10788 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10789 // clear on this, but they're not found by name so access does not apply.
10790 Guides.suppressDiagnostics();
10791
10792 // Figure out if this is list-initialization.
10794 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10795 ? dyn_cast<InitListExpr>(Inits[0])
10796 : nullptr;
10797
10798 // C++1z [over.match.class.deduct]p1:
10799 // Initialization and overload resolution are performed as described in
10800 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10801 // (as appropriate for the type of initialization performed) for an object
10802 // of a hypothetical class type, where the selected functions and function
10803 // templates are considered to be the constructors of that class type
10804 //
10805 // Since we know we're initializing a class type of a type unrelated to that
10806 // of the initializer, this reduces to something fairly reasonable.
10807 OverloadCandidateSet Candidates(Kind.getLocation(),
10810
10811 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10812
10813 // Return true if the candidate is added successfully, false otherwise.
10814 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10816 DeclAccessPair FoundDecl,
10817 bool OnlyListConstructors,
10818 bool AllowAggregateDeductionCandidate) {
10819 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10820 // For copy-initialization, the candidate functions are all the
10821 // converting constructors (12.3.1) of that class.
10822 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10823 // The converting constructors of T are candidate functions.
10824 if (!AllowExplicit) {
10825 // Overload resolution checks whether the deduction guide is declared
10826 // explicit for us.
10827
10828 // When looking for a converting constructor, deduction guides that
10829 // could never be called with one argument are not interesting to
10830 // check or note.
10831 if (GD->getMinRequiredArguments() > 1 ||
10832 (GD->getNumParams() == 0 && !GD->isVariadic()))
10833 return;
10834 }
10835
10836 // C++ [over.match.list]p1.1: (first phase list initialization)
10837 // Initially, the candidate functions are the initializer-list
10838 // constructors of the class T
10839 if (OnlyListConstructors && !isInitListConstructor(GD))
10840 return;
10841
10842 if (!AllowAggregateDeductionCandidate &&
10843 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10844 return;
10845
10846 // C++ [over.match.list]p1.2: (second phase list initialization)
10847 // the candidate functions are all the constructors of the class T
10848 // C++ [over.match.ctor]p1: (all other cases)
10849 // the candidate functions are all the constructors of the class of
10850 // the object being initialized
10851
10852 // C++ [over.best.ics]p4:
10853 // When [...] the constructor [...] is a candidate by
10854 // - [over.match.copy] (in all cases)
10855 // FIXME: The "second phase of [over.match.list] case can also
10856 // theoretically happen here, but it's not clear whether we can
10857 // ever have a parameter of the right type.
10858 bool SuppressUserConversions = Kind.isCopyInit();
10859
10860 if (TD) {
10861 SmallVector<Expr *, 8> TmpInits;
10862 for (Expr *E : Inits)
10863 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10864 TmpInits.push_back(DI->getInit());
10865 else
10866 TmpInits.push_back(E);
10868 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10869 SuppressUserConversions,
10870 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10871 /*PO=*/{}, AllowAggregateDeductionCandidate);
10872 } else {
10873 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10874 SuppressUserConversions,
10875 /*PartialOverloading=*/false, AllowExplicit);
10876 }
10877 };
10878
10879 bool FoundDeductionGuide = false;
10880
10881 auto TryToResolveOverload =
10882 [&](bool OnlyListConstructors) -> OverloadingResult {
10884 bool HasAnyDeductionGuide = false;
10885
10886 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10887 auto *Pattern = Template;
10888 while (Pattern->getInstantiatedFromMemberTemplate()) {
10889 if (Pattern->isMemberSpecialization())
10890 break;
10891 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10892 }
10893
10894 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10895 if (!(RD->getDefinition() && RD->isAggregate()))
10896 return;
10898 SmallVector<QualType, 8> ElementTypes;
10899
10900 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10901 if (!CheckInitList.HadError()) {
10902 // C++ [over.match.class.deduct]p1.8:
10903 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10904 // rvalue reference to the declared type of e_i and
10905 // C++ [over.match.class.deduct]p1.9:
10906 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10907 // lvalue reference to the const-qualified declared type of e_i and
10908 // C++ [over.match.class.deduct]p1.10:
10909 // otherwise, T_i is the declared type of e_i
10910 for (int I = 0, E = ListInit->getNumInits();
10911 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10912 if (ElementTypes[I]->isArrayType()) {
10913 if (isa<InitListExpr>(ListInit->getInit(I)))
10914 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10915 else if (isa<StringLiteral>(
10916 ListInit->getInit(I)->IgnoreParenImpCasts()))
10917 ElementTypes[I] =
10918 Context.getLValueReferenceType(ElementTypes[I].withConst());
10919 }
10920
10921 llvm::FoldingSetNodeID ID;
10922 ID.AddPointer(Template);
10923 for (auto &T : ElementTypes)
10924 T.getCanonicalType().Profile(ID);
10925 unsigned Hash = ID.ComputeHash();
10926 if (AggregateDeductionCandidates.count(Hash) == 0) {
10927 if (FunctionTemplateDecl *TD =
10929 Template, ElementTypes,
10930 TSInfo->getTypeLoc().getEndLoc())) {
10931 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10932 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
10934 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10935 OnlyListConstructors,
10936 /*AllowAggregateDeductionCandidate=*/true);
10937 }
10938 } else {
10941 assert(TD && "aggregate deduction candidate is function template");
10942 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10943 OnlyListConstructors,
10944 /*AllowAggregateDeductionCandidate=*/true);
10945 }
10946 HasAnyDeductionGuide = true;
10947 }
10948 };
10949
10950 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10951 NamedDecl *D = (*I)->getUnderlyingDecl();
10952 if (D->isInvalidDecl())
10953 continue;
10954
10955 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10956 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10957 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10958 if (!GD)
10959 continue;
10960
10961 if (!GD->isImplicit())
10962 HasAnyDeductionGuide = true;
10963
10964 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10965 /*AllowAggregateDeductionCandidate=*/false);
10966 }
10967
10968 // C++ [over.match.class.deduct]p1.4:
10969 // if C is defined and its definition satisfies the conditions for an
10970 // aggregate class ([dcl.init.aggr]) with the assumption that any
10971 // dependent base class has no virtual functions and no virtual base
10972 // classes, and the initializer is a non-empty braced-init-list or
10973 // parenthesized expression-list, and there are no deduction-guides for
10974 // C, the set contains an additional function template, called the
10975 // aggregate deduction candidate, defined as follows.
10976 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10977 if (ListInit && ListInit->getNumInits()) {
10978 SynthesizeAggrGuide(ListInit);
10979 } else if (Inits.size()) { // parenthesized expression-list
10980 // Inits are expressions inside the parentheses. We don't have
10981 // the parentheses source locations, use the begin/end of Inits as the
10982 // best heuristic.
10983 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10984 Inits, Inits.back()->getEndLoc());
10985 SynthesizeAggrGuide(&TempListInit);
10986 }
10987 }
10988
10989 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10990
10991 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10992 };
10993
10995
10996 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10997 // try initializer-list constructors.
10998 if (ListInit) {
10999 bool TryListConstructors = true;
11000
11001 // Try list constructors unless the list is empty and the class has one or
11002 // more default constructors, in which case those constructors win.
11003 if (!ListInit->getNumInits()) {
11004 for (NamedDecl *D : Guides) {
11005 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
11006 if (FD && FD->getMinRequiredArguments() == 0) {
11007 TryListConstructors = false;
11008 break;
11009 }
11010 }
11011 } else if (ListInit->getNumInits() == 1) {
11012 // C++ [over.match.class.deduct]:
11013 // As an exception, the first phase in [over.match.list] (considering
11014 // initializer-list constructors) is omitted if the initializer list
11015 // consists of a single expression of type cv U, where U is a
11016 // specialization of C or a class derived from a specialization of C.
11017 Expr *E = ListInit->getInit(0);
11018 auto *RD = E->getType()->getAsCXXRecordDecl();
11019 if (!isa<InitListExpr>(E) && RD &&
11020 isCompleteType(Kind.getLocation(), E->getType()) &&
11022 TryListConstructors = false;
11023 }
11024
11025 if (TryListConstructors)
11026 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
11027 // Then unwrap the initializer list and try again considering all
11028 // constructors.
11029 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
11030 }
11031
11032 // If list-initialization fails, or if we're doing any other kind of
11033 // initialization, we (eventually) consider constructors.
11035 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
11036
11037 switch (Result) {
11038 case OR_Ambiguous:
11039 // FIXME: For list-initialization candidates, it'd usually be better to
11040 // list why they were not viable when given the initializer list itself as
11041 // an argument.
11042 Candidates.NoteCandidates(
11044 Kind.getLocation(),
11045 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
11046 << TemplateName),
11047 *this, OCD_AmbiguousCandidates, Inits);
11048 return QualType();
11049
11050 case OR_No_Viable_Function: {
11051 CXXRecordDecl *Primary =
11052 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
11053 bool Complete =
11054 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
11055 Candidates.NoteCandidates(
11057 Kind.getLocation(),
11058 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
11059 : diag::err_deduced_class_template_incomplete)
11060 << TemplateName << !Guides.empty()),
11061 *this, OCD_AllCandidates, Inits);
11062 return QualType();
11063 }
11064
11065 case OR_Deleted: {
11066 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
11067 << TemplateName;
11068 NoteDeletedFunction(Best->Function);
11069 return QualType();
11070 }
11071
11072 case OR_Success:
11073 // C++ [over.match.list]p1:
11074 // In copy-list-initialization, if an explicit constructor is chosen, the
11075 // initialization is ill-formed.
11076 if (Kind.isCopyInit() && ListInit &&
11077 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
11078 bool IsDeductionGuide = !Best->Function->isImplicit();
11079 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
11080 << TemplateName << IsDeductionGuide;
11081 Diag(Best->Function->getLocation(),
11082 diag::note_explicit_ctor_deduction_guide_here)
11083 << IsDeductionGuide;
11084 return QualType();
11085 }
11086
11087 // Make sure we didn't select an unusable deduction guide, and mark it
11088 // as referenced.
11089 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
11090 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
11091 break;
11092 }
11093
11094 // C++ [dcl.type.class.deduct]p1:
11095 // The placeholder is replaced by the return type of the function selected
11096 // by overload resolution for class template deduction.
11098 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
11099 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11100 diag::warn_cxx14_compat_class_template_argument_deduction)
11101 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
11102
11103 // Warn if CTAD was used on a type that does not have any user-defined
11104 // deduction guides.
11105 if (!FoundDeductionGuide) {
11106 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11107 diag::warn_ctad_maybe_unsupported)
11108 << TemplateName;
11109 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
11110 }
11111
11112 return DeducedType;
11113}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
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:28
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:563
static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
Definition: SemaInit.cpp:7539
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
Definition: SemaInit.cpp:6119
static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee)
Definition: SemaInit.cpp:7422
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:172
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition: SemaInit.cpp:184
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition: SemaInit.cpp:193
static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7576
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:1171
static bool shouldDestroyEntity(const InitializedEntity &Entity)
Whether the given entity, when initialized with an object created for that initialization,...
Definition: SemaInit.cpp:6688
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
Definition: SemaInit.cpp:6721
static bool hasAnyDesignatedInits(const InitListExpr *IL)
Definition: SemaInit.cpp:974
static bool tryObjCWritebackConversion(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity, Expr *Initializer)
Definition: SemaInit.cpp:6001
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
Definition: SemaInit.cpp:2494
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:6779
static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
Definition: SemaInit.cpp:6599
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
Definition: SemaInit.cpp:5446
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
Definition: SemaInit.cpp:8410
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
Definition: SemaInit.cpp:10601
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:6930
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
Definition: SemaInit.cpp:10703
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:4067
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, ASTContext &Context)
Check whether the array of type AT can be initialized by the Init expression by means of string initi...
Definition: SemaInit.cpp:72
StringInitFailureKind
Definition: SemaInit.cpp:58
@ SIF_None
Definition: SemaInit.cpp:59
@ SIF_PlainStringIntoUTF8Char
Definition: SemaInit.cpp:64
@ SIF_IncompatWideStringIntoWideChar
Definition: SemaInit.cpp:62
@ SIF_UTF8StringIntoPlainChar
Definition: SemaInit.cpp:63
@ SIF_NarrowStringIntoWideChar
Definition: SemaInit.cpp:60
@ SIF_Other
Definition: SemaInit.cpp:65
@ SIF_WideStringIntoChar
Definition: SemaInit.cpp:61
static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7480
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
Definition: SemaInit.cpp:5408
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6048
static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path)
Definition: SemaInit.cpp:8109
static bool isInStlNamespace(const Decl *D)
Definition: SemaInit.cpp:7407
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
Definition: SemaInit.cpp:4007
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:3346
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
Definition: SemaInit.cpp:6130
static bool IsZeroInitializer(Expr *Initializer, Sema &S)
Definition: SemaInit.cpp:6061
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:4997
static PathLifetimeKind shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path)
Determine whether this is an indirect path to a temporary that we are supposed to lifetime-extend alo...
Definition: SemaInit.cpp:8067
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
Definition: SemaInit.cpp:10560
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:2466
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:5330
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:5698
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:4115
static LifetimeResult getEntityLifetime(const InitializedEntity *Entity, const InitializedEntity *InitField=nullptr)
Determine the declaration which an initialized entity ultimately refers to, for the purpose of lifeti...
Definition: SemaInit.cpp:7208
static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD)
Definition: SemaInit.cpp:7374
static bool shouldTrackFirstArgument(const FunctionDecl *FD)
Definition: SemaInit.cpp:7456
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:4557
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:5321
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:1926
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:4959
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
Definition: SemaInit.cpp:10456
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:5985
static bool pathContainsInit(IndirectLocalPath &Path)
Definition: SemaInit.cpp:7381
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, bool CheckC23ConstexprInit=false)
Definition: SemaInit.cpp:211
static bool isRecordWithAttr(QualType Type)
Definition: SemaInit.cpp:7398
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:7006
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:4988
PathLifetimeKind
Whether a path to an object supports lifetime extension.
Definition: SemaInit.cpp:8052
@ ShouldExtend
We should lifetime-extend, but we don't because (due to technical limitations) we can't.
Definition: SemaInit.cpp:8059
@ NoExtend
Do not lifetime extend along this path.
Definition: SemaInit.cpp:8061
@ Extend
Lifetime-extend along this path.
Definition: SemaInit.cpp:8054
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6066
static bool IsWideCharCompatible(QualType T, ASTContext &Context)
Check whether T is compatible with a wide character type (wchar_t, char16_t or char32_t).
Definition: SemaInit.cpp:48
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
Definition: SemaInit.cpp:9579
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:4774
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:4229
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:9548
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:1048
static void MaybeProduceObjCObject(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Definition: SemaInit.cpp:4027
static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, Expr *E)
Find the range for the first interesting entry in the path at or after I.
Definition: SemaInit.cpp:8079
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
Definition: SemaInit.cpp:5967
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
Definition: SemaInit.cpp:6654
static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, Expr *Init, ReferenceKind RK, LocalVisitor Visit, bool EnableLifetimeWarnings)
Visit the locals that would be reachable through a reference bound to the glvalue expression Init.
Definition: SemaInit.cpp:7643
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
Definition: SemaInit.cpp:4409
static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, Expr *Init, LocalVisitor Visit, bool RevisitSubinits, bool EnableLifetimeWarnings)
Visit the locals that would be reachable through an object initialized by the prvalue expression Init...
Definition: SemaInit.cpp:7779
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
Definition: SemaInit.cpp:5897
@ IIK_okay
Definition: SemaInit.cpp:5897
@ IIK_nonlocal
Definition: SemaInit.cpp:5897
@ IIK_nonscalar
Definition: SemaInit.cpp:5897
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:7031
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:4454
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:5885
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:4102
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
Definition: SemaInit.cpp:9509
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
Definition: SemaInit.cpp:5900
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
__device__ int
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:942
bool isNullPointer() const
Definition: APValue.cpp:1006
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2742
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:643
QualType getRecordType(const RecordDecl *Decl) const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
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:1093
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:2748
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:1575
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:770
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:1095
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType OverloadTy
Definition: ASTContext.h:1114
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:2592
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:2315
CanQualType OCLSamplerTy
Definition: ASTContext.h:1122
CanQualType VoidTy
Definition: ASTContext.h:1086
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:2745
CanQualType Char32Ty
Definition: ASTContext.h:1094
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:752
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:1778
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2319
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:5558
Represents a loop initializing the elements of an array.
Definition: Expr.h:5505
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2663
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
QualType getElementType() const
Definition: Type.h:3159
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
This class is used for builtin types like 'int'.
Definition: Type.h:2740
Kind getKind() const
Definition: Type.h:2782
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 binding an expression to a temporary.
Definition: ExprCXX.h:1475
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1530
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1673
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1593
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1670
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2770
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2607
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2771
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2895
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1947
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2792
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2179
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition: ExprCXX.cpp:1885
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:1161
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1391
base_class_range bases()
Definition: DeclCXX.h:618
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1832
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
llvm::iterator_range< base_class_iterator > base_class_range
Definition: DeclCXX.h:614
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:616
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 a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2165
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:1076
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2819
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3010
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1618
bool isCallToStdMove() const
Definition: Expr.cpp:3496
Expr * getCallee()
Definition: Expr.h:2969
SourceLocation getRParenLoc() const
Definition: Expr.h:3129
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:3489
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:2845
QualType getElementType() const
Definition: Type.h:2855
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4173
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3186
const llvm::APInt & getSize() const
Definition: Type.h:3207
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:202
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:1379
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2289
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2352
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2201
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:1958
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
bool isStdNamespace() const
Definition: DeclBase.cpp:1249
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2332
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1458
ValueDecl * getDecl()
Definition: Expr.h:1328
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:440
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
bool isInvalidDecl() const
Definition: DeclBase.h:593
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getDeclContext()
Definition: DeclBase.h:453
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
bool hasAttr() const
Definition: DeclBase.h:582
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5490
Represents a single C99 designator.
Definition: Expr.h:5129
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:5291
void setFieldDecl(FieldDecl *FD)
Definition: Expr.h:5227
FieldDecl * getFieldDecl() const
Definition: Expr.h:5220
SourceLocation getFieldLoc() const
Definition: Expr.h:5237
const IdentifierInfo * getFieldName() const
Definition: Expr.cpp:4526
SourceLocation getDotLoc() const
Definition: Expr.h:5232
SourceLocation getLBracketLoc() const
Definition: Expr.h:5273
Represents a C99 designated initializer expression.
Definition: Expr.h:5086
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition: Expr.h:5346
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:4635
void setInit(Expr *init)
Definition: Expr.h:5358
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:5368
llvm::MutableArrayRef< Designator > designators()
Definition: Expr.h:5319
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition: Expr.h:5350
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:4630
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:4642
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4568
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4625
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:5327
Expr * getInit() const
Retrieve the initializer value.
Definition: Expr.h:5354
unsigned size() const
Returns the number of designators in this initializer.
Definition: Expr.h:5316
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4604
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4621
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition: Expr.h:5341
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition: Expr.h:5366
InitListExpr * getUpdater() const
Definition: Expr.h:5473
Designation - Represent a full designation, which is a sequence of designators.
Definition: Designator.h:208
const Designator & getDesignator(unsigned Idx) const
Definition: Designator.h:219
unsigned getNumDesignators() const
Definition: Designator.h:218
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
SourceLocation getFieldLoc() const
Definition: Designator.h:133
SourceLocation getDotLoc() const
Definition: Designator.h:128
Expr * getArrayRangeStart() const
Definition: Designator.h:181
bool isArrayDesignator() const
Definition: Designator.h:108
SourceLocation getLBracketLoc() const
Definition: Designator.h:154
bool isArrayRangeDesignator() const
Definition: Designator.h:109
bool isFieldDesignator() const
Definition: Designator.h:107
SourceLocation getRBracketLoc() const
Definition: Designator.h:161
SourceLocation getEllipsisLoc() const
Definition: Designator.h:191
Expr * getArrayRangeEnd() const
Definition: Designator.h:186
const IdentifierInfo * getFieldDecl() const
Definition: Designator.h:123
Expr * getArrayIndex() const
Definition: Designator.h:149
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
Definition: Designator.h:115
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
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:5118
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
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3050
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:4119
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:3045
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3033
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3041
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:3265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
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:3542
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3025
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:3179
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:3904
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:3604
Represents difference between two FPOptions values.
Definition: LangOptions.h:870
Represents a member of a struct/union/class.
Definition: Decl.h:3025
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3186
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4611
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4633
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3119
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
Represents a function declaration or definition.
Definition: Decl.h:1959
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2674
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3678
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4007
QualType getReturnType() const
Definition: Decl.h:2722
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2477
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2322
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3657
Declaration of a template function.
Definition: DeclTemplate.h:958
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:2060
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:540
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:591
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:595
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:739
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5594
Represents a C array with an unspecified size.
Definition: Type.h:3246
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3309
chain_iterator chain_end() const
Definition: Decl.h:3334
chain_iterator chain_begin() const
Definition: Decl.h:3333
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition: Decl.h:3328
Describes an C or C++ initializer list.
Definition: Expr.h:4841
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4945
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:5011
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition: Expr.h:4907
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4948
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2418
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2378
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:4960
unsigned getNumInits() const
Definition: Expr.h:4871
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2452
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4897
SourceLocation getLBraceLoc() const
Definition: Expr.h:4995
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:2382
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2394
InitListExpr * getSyntacticForm() const
Definition: Expr.h:5007
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4935
SourceLocation getRBraceLoc() const
Definition: Expr.h:4997
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4887
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:2441
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2470
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4966
bool isSyntacticForm() const
Definition: Expr.h:5004
void setRBraceLoc(SourceLocation Loc)
Definition: Expr.h:4998
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:5021
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:4874
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:3861
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:8578
void AddStringInitStep(QualType T)
Add a string init step.
Definition: SemaInit.cpp:3896
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
Definition: SemaInit.cpp:3951
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
Definition: SemaInit.cpp:3868
@ 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:3804
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:6108
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
Definition: SemaInit.cpp:3817
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
Definition: SemaInit.cpp:3836
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
Definition: SemaInit.cpp:3767
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:6164
void AddParenthesizedListInitStep(QualType T)
Definition: SemaInit.cpp:3972
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:3695
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:3965
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:3789
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:3903
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
Definition: SemaInit.cpp:3994
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
Definition: SemaInit.cpp:3928
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:3796
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:3958
void AddCAssignmentStep(QualType T)
Add a C assignment step.
Definition: SemaInit.cpp:3889
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
Definition: SemaInit.cpp:3935
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:3979
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:9615
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:3843
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
Definition: SemaInit.cpp:10452
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
Definition: SemaInit.cpp:3850
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
Definition: SemaInit.cpp:3882
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
Definition: SemaInit.cpp:3944
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:3781
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:3684
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
Definition: SemaInit.cpp:3917
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:3755
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
Definition: SemaInit.cpp:3910
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3749
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:3465
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:3477
unsigned allocateManglingNumber() const
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
Definition: SemaInit.cpp:3515
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:3549
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
Definition: SemaInit.cpp:3630
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.
bool isDefaultMemberInitializer() const
Is this the default member initializer of a member (specified inside the class definition)?
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:5764
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:957
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3053
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:88
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:359
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:629
iterator end() const
Definition: Lookup.h:356
iterator begin() const
Definition: Lookup.h:355
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4679
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4704
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represent a C++ namespace.
Definition: Decl.h:547
Represents a place-holder for an object not to be initialized by anything.
Definition: Expr.h:5414
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
QualType getEncodedType() const
Definition: ExprObjC.h:429
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
Definition: ExprObjC.h:1575
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
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:977
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition: Overload.h:1212
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:998
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:993
@ CSK_Normal
Normal lookup.
Definition: Overload.h:981
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1150
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:1749
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
A (possibly-)qualified type.
Definition: Type.h:737
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6985
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3403
QualType withConst() const
Definition: Type.h:951
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1017
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
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:7102
QualType getCanonicalType() const
Definition: Type.h:6954
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6974
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7022
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1323
The collection of all-type qualifiers we support.
Definition: Type.h:147
unsigned getCVRQualifiers() const
Definition: Type.h:295
void addAddressSpace(LangAS space)
Definition: Type.h:404
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
bool hasConst() const
Definition: Type.h:264
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition: Type.h:439
bool hasAddressSpace() const
Definition: Type.h:377
Qualifiers withoutAddressSpace() const
Definition: Type.h:345
void removeAddressSpace()
Definition: Type.h:403
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:240
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:495
bool hasVolatile() const
Definition: Type.h:274
bool hasObjCLifetime() const
Definition: Type.h:351
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:532
LangAS getAddressSpace() const
Definition: Type.h:378
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3071
Represents a struct/union/class.
Definition: Decl.h:4133
bool hasFlexibleArrayMember() const
Definition: Decl.h:4166
field_iterator field_end() const
Definition: Decl.h:4342
field_range fields() const
Definition: Decl.h:4339
bool isRandomized() const
Definition: Decl.h:4283
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4336
bool field_empty() const
Definition: Decl.h:4347
field_iterator field_begin() const
Definition: Decl.cpp:5035
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3009
bool isSpelledAsLValue() const
Definition: Type.h:3022
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4810
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7607
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7615
bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, RecordDecl *ClassDecl, const IdentifierInfo *Name)
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:166
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:8388
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8391
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8397
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8395
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...
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:17996
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
Definition: SemaInit.cpp:3363
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1556
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CCK_ImplicitConversion)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
ASTContext & Context
Definition: Sema.h:1030
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
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())
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:6010
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:755
ASTContext & getASTContext() const
Definition: Sema.h:501
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:10510
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:8694
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition: Sema.h:7290
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
FunctionTemplateDecl * DeclareImplicitDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
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:58
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:494
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 ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:636
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition: Sema.h:7293
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:18327
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8541
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:68
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5371
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:10562
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CCK_ImplicitConversion)
Definition: SemaInit.cpp:8559
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:10712
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:6513
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8522
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:6309
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6311
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6390
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1305
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21731
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...
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:890
@ CCK_OtherCast
A cast other than a C-style cast.
Definition: Sema.h:898
@ CCK_CStyleCast
A C-style cast.
Definition: Sema.h:894
@ CCK_ImplicitConversion
An implicit conversion.
Definition: Sema.h:892
@ CCK_FunctionalCast
A functional-style cast.
Definition: Sema.h:896
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10722
SourceManager & getSourceManager() const
Definition: Sema.h:499
AssignmentAction
Definition: Sema.h:5379
@ AA_Returning
Definition: Sema.h:5382
@ AA_Passing_CFAudited
Definition: Sema.h:5387
@ AA_Initializing
Definition: Sema.h:5384
@ AA_Converting
Definition: Sema.h:5383
@ AA_Passing
Definition: Sema.h:5381
@ AA_Casting
Definition: Sema.h:5386
@ AA_Sending
Definition: Sema.h:5385
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:21009
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:6256
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:224
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11943
@ CTK_ErrorRecovery
Definition: Sema.h:7859
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3329
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:117
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5898
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:9249
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...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
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:8123
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6669
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9190
SourceManager & SourceMgr
Definition: Sema.h:1033
DiagnosticsEngine & Diags
Definition: Sema.h:1032
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:495
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16050
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10642
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:6331
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:511
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:17663
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:18892
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:17589
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:10627
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
ValueDecl * tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, const IdentifierInfo *MemberOrBase)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
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:264
void setFromType(QualType T)
Definition: Overload.h:354
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:275
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:269
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:356
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:361
QualType getToType(unsigned Idx) const
Definition: Overload.h:371
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
unsigned getLength() const
Definition: Expr.h:1890
StringLiteralKind getKind() const
Definition: Expr.h:1893
int64_t getCodeUnitS(size_t I, uint64_t BitWidth) const
Definition: Expr.h:1879
bool isUnion() const
Definition: Decl.h:3755
bool isBigEndian() const
Definition: TargetInfo.h:1614
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isDependent() const
Determines whether this is a dependent template name.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5632
const Type * getTypeForDecl() const
Definition: Decl.h:3381
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
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2653
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:6873
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:6884
The base class of the type hierarchy.
Definition: Type.h:1606
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isVoidType() const
Definition: Type.h:7443
bool isBooleanType() const
Definition: Type.h:7567
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7614
bool isIncompleteArrayType() const
Definition: Type.h:7228
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2083
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2008
bool isRValueReferenceType() const
Definition: Type.h:7174
bool isConstantArrayType() const
Definition: Type.h:7224
bool isArrayType() const
Definition: Type.h:7220
bool isCharType() const
Definition: Type.cpp:2026
bool isPointerType() const
Definition: Type.h:7154
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7479
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isReferenceType() const
Definition: Type.h:7166
bool isScalarType() const
Definition: Type.h:7538
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:1804
bool isChar8Type() const
Definition: Type.cpp:2042
bool isSizelessBuiltinType() const
Definition: Type.cpp:2370
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isExtVectorType() const
Definition: Type.h:7260
bool isOCLIntelSubgroupAVCType() const
Definition: Type.h:7388
bool isLValueReferenceType() const
Definition: Type.h:7170
bool isOpenCLSpecificType() const
Definition: Type.h:7403
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2275
bool isAnyComplexType() const
Definition: Type.h:7252
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1948
bool isQueueT() const
Definition: Type.h:7359
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7607
bool isAtomicType() const
Definition: Type.h:7295
bool isFunctionProtoType() const
Definition: Type.h:2263
bool isObjCObjectType() const
Definition: Type.h:7286
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7710
bool isEventT() const
Definition: Type.h:7351
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2299
bool isFunctionType() const
Definition: Type.h:7150
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isVectorType() const
Definition: Type.h:7256
bool isFloatingType() const
Definition: Type.cpp:2186
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:2133
bool isSamplerT() const
Definition: Type.h:7347
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:565
bool isNullPtrType() const
Definition: Type.h:7472
bool isRecordType() const
Definition: Type.h:7244
bool isObjCRetainableType() const
Definition: Type.cpp:4758
bool isUnionType() const
Definition: Type.cpp:621
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:2182
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5330
Represents a variable declaration or definition.
Definition: Decl.h:918
const Expr * getInit() const
Definition: Decl.h:1352
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1168
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3290
Represents a GCC generic vector type.
Definition: Type.h:3512
unsigned getNumElements() const
Definition: Type.h:3527
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3536
VectorKind getVectorKind() const
Definition: Type.h:3532
QualType getElementType() const
Definition: Type.h:3526
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:1809
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus11
Definition: LangStandard.h:55
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
bool isCompoundAssignmentOperator(OverloadedOperatorKind Kind)
Determine if this is a compound assignment operator.
Definition: OperatorKinds.h:53
@ ovl_fail_bad_conversion
Definition: Overload.h:774
@ 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:1522
LLVM_READONLY bool isUppercase(unsigned char c)
Return true if this character is an uppercase ASCII letter: [A-Z].
Definition: CharInfo.h:127
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
BinaryOperatorKind
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:325
@ Result
The result type of a method or function.
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
Expr * IgnoreParensSingleStep(Expr *E)
Definition: IgnoreExpr.h:150
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:242
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:248
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:256
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:245
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:252
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1238
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Braces
New-expression has a C++11 list-initializer.
@ AS_public
Definition: Specifiers.h:121
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
unsigned long uint64_t
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
CXXConstructorDecl * Constructor
Definition: Overload.h:1230
DeclAccessPair FoundDecl
Definition: Overload.h:1229
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:845
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:874
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:908
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:868
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8405
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:424