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/STLForwardCompat.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/SmallVector.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
40
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// Sema Initialization Checking
45//===----------------------------------------------------------------------===//
46
47/// Check whether T is compatible with a wide character type (wchar_t,
48/// char16_t or char32_t).
49static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
50 if (Context.typesAreCompatible(Context.getWideCharType(), T))
51 return true;
52 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
53 return Context.typesAreCompatible(Context.Char16Ty, T) ||
54 Context.typesAreCompatible(Context.Char32Ty, T);
55 }
56 return false;
57}
58
67};
68
69/// Check whether the array of type AT can be initialized by the Init
70/// expression by means of string initialization. Returns SIF_None if so,
71/// otherwise returns a StringInitFailureKind that describes why the
72/// initialization would not work.
74 ASTContext &Context) {
75 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
76 return SIF_Other;
77
78 // See if this is a string literal or @encode.
79 Init = Init->IgnoreParens();
80
81 // Handle @encode, which is a narrow string.
82 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
83 return SIF_None;
84
85 // Otherwise we can only handle string literals.
86 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
87 if (!SL)
88 return SIF_Other;
89
90 const QualType ElemTy =
92
93 auto IsCharOrUnsignedChar = [](const QualType &T) {
94 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
95 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
96 };
97
98 switch (SL->getKind()) {
99 case StringLiteralKind::UTF8:
100 // char8_t array can be initialized with a UTF-8 string.
101 // - C++20 [dcl.init.string] (DR)
102 // Additionally, an array of char or unsigned char may be initialized
103 // by a UTF-8 string literal.
104 if (ElemTy->isChar8Type() ||
105 (Context.getLangOpts().Char8 &&
106 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
107 return SIF_None;
108 [[fallthrough]];
109 case StringLiteralKind::Ordinary:
110 // char array can be initialized with a narrow string.
111 // Only allow char x[] = "foo"; not char x[] = L"foo";
112 if (ElemTy->isCharType())
113 return (SL->getKind() == StringLiteralKind::UTF8 &&
114 Context.getLangOpts().Char8)
116 : SIF_None;
117 if (ElemTy->isChar8Type())
119 if (IsWideCharCompatible(ElemTy, Context))
121 return SIF_Other;
122 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
123 // "An array with element type compatible with a qualified or unqualified
124 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
125 // string literal with the corresponding encoding prefix (L, u, or U,
126 // respectively), optionally enclosed in braces.
127 case StringLiteralKind::UTF16:
128 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
129 return SIF_None;
130 if (ElemTy->isCharType() || ElemTy->isChar8Type())
132 if (IsWideCharCompatible(ElemTy, Context))
134 return SIF_Other;
135 case StringLiteralKind::UTF32:
136 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
137 return SIF_None;
138 if (ElemTy->isCharType() || ElemTy->isChar8Type())
140 if (IsWideCharCompatible(ElemTy, Context))
142 return SIF_Other;
143 case StringLiteralKind::Wide:
144 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
145 return SIF_None;
146 if (ElemTy->isCharType() || ElemTy->isChar8Type())
148 if (IsWideCharCompatible(ElemTy, Context))
150 return SIF_Other;
151 case StringLiteralKind::Unevaluated:
152 assert(false && "Unevaluated string literal in initialization");
153 break;
154 }
155
156 llvm_unreachable("missed a StringLiteral kind?");
157}
158
160 ASTContext &Context) {
161 const ArrayType *arrayType = Context.getAsArrayType(declType);
162 if (!arrayType)
163 return SIF_Other;
164 return IsStringInit(init, arrayType, Context);
165}
166
168 return ::IsStringInit(Init, AT, Context) == SIF_None;
169}
170
171/// Update the type of a string literal, including any surrounding parentheses,
172/// to match the type of the object which it is initializing.
174 while (true) {
175 E->setType(Ty);
177 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
178 break;
180 }
181}
182
183/// Fix a compound literal initializing an array so it's correctly marked
184/// as an rvalue.
186 while (true) {
188 if (isa<CompoundLiteralExpr>(E))
189 break;
191 }
192}
193
195 Decl *D = Entity.getDecl();
196 const InitializedEntity *Parent = &Entity;
197
198 while (Parent) {
199 D = Parent->getDecl();
200 Parent = Parent->getParent();
201 }
202
203 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
204 return true;
205
206 return false;
207}
208
210 Sema &SemaRef, QualType &TT);
211
212static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
213 Sema &S, bool CheckC23ConstexprInit = false) {
214 // Get the length of the string as parsed.
215 auto *ConstantArrayTy =
216 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
217 uint64_t StrLength = ConstantArrayTy->getZExtSize();
218
219 if (CheckC23ConstexprInit)
220 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
222
223 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
224 // C99 6.7.8p14. We have an array of character type with unknown size
225 // being initialized to a string literal.
226 llvm::APInt ConstVal(32, StrLength);
227 // Return a new array type (C99 6.7.8p22).
229 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
230 updateStringLiteralType(Str, DeclT);
231 return;
232 }
233
234 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
235
236 // We have an array of character type with known size. However,
237 // the size may be smaller or larger than the string we are initializing.
238 // FIXME: Avoid truncation for 64-bit length strings.
239 if (S.getLangOpts().CPlusPlus) {
240 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
241 // For Pascal strings it's OK to strip off the terminating null character,
242 // so the example below is valid:
243 //
244 // unsigned char a[2] = "\pa";
245 if (SL->isPascal())
246 StrLength--;
247 }
248
249 // [dcl.init.string]p2
250 if (StrLength > CAT->getZExtSize())
251 S.Diag(Str->getBeginLoc(),
252 diag::err_initializer_string_for_char_array_too_long)
253 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
254 } else {
255 // C99 6.7.8p14.
256 if (StrLength - 1 > CAT->getZExtSize())
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->getZExtSize();
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->getZExtSize());
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
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 can stop entirely.
2334 if (InitializedSomething && RD->isUnion())
2335 return;
2336
2337 // Stop if we've hit a flexible array member.
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 if (RD->isUnion() && StructuredList) {
2462 // Initialize the first field within the union.
2463 StructuredList->setInitializedFieldInUnion(*Field);
2464 }
2465}
2466
2467/// Expand a field designator that refers to a member of an
2468/// anonymous struct or union into a series of field designators that
2469/// refers to the field within the appropriate subobject.
2470///
2472 DesignatedInitExpr *DIE,
2473 unsigned DesigIdx,
2474 IndirectFieldDecl *IndirectField) {
2476
2477 // Build the replacement designators.
2478 SmallVector<Designator, 4> Replacements;
2479 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2480 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2481 if (PI + 1 == PE)
2482 Replacements.push_back(Designator::CreateFieldDesignator(
2483 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2484 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2485 else
2486 Replacements.push_back(Designator::CreateFieldDesignator(
2487 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2488 assert(isa<FieldDecl>(*PI));
2489 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2490 }
2491
2492 // Expand the current designator into the set of replacement
2493 // designators, so we have a full subobject path down to where the
2494 // member of the anonymous struct/union is actually stored.
2495 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2496 &Replacements[0] + Replacements.size());
2497}
2498
2500 DesignatedInitExpr *DIE) {
2501 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2502 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2503 for (unsigned I = 0; I < NumIndexExprs; ++I)
2504 IndexExprs[I] = DIE->getSubExpr(I + 1);
2505 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2506 IndexExprs,
2507 DIE->getEqualOrColonLoc(),
2508 DIE->usesGNUSyntax(), DIE->getInit());
2509}
2510
2511namespace {
2512
2513// Callback to only accept typo corrections that are for field members of
2514// the given struct or union.
2515class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2516 public:
2517 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2518 : Record(RD) {}
2519
2520 bool ValidateCandidate(const TypoCorrection &candidate) override {
2521 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2522 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2523 }
2524
2525 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2526 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2527 }
2528
2529 private:
2530 const RecordDecl *Record;
2531};
2532
2533} // end anonymous namespace
2534
2535/// Check the well-formedness of a C99 designated initializer.
2536///
2537/// Determines whether the designated initializer @p DIE, which
2538/// resides at the given @p Index within the initializer list @p
2539/// IList, is well-formed for a current object of type @p DeclType
2540/// (C99 6.7.8). The actual subobject that this designator refers to
2541/// within the current subobject is returned in either
2542/// @p NextField or @p NextElementIndex (whichever is appropriate).
2543///
2544/// @param IList The initializer list in which this designated
2545/// initializer occurs.
2546///
2547/// @param DIE The designated initializer expression.
2548///
2549/// @param DesigIdx The index of the current designator.
2550///
2551/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2552/// into which the designation in @p DIE should refer.
2553///
2554/// @param NextField If non-NULL and the first designator in @p DIE is
2555/// a field, this will be set to the field declaration corresponding
2556/// to the field named by the designator. On input, this is expected to be
2557/// the next field that would be initialized in the absence of designation,
2558/// if the complete object being initialized is a struct.
2559///
2560/// @param NextElementIndex If non-NULL and the first designator in @p
2561/// DIE is an array designator or GNU array-range designator, this
2562/// will be set to the last index initialized by this designator.
2563///
2564/// @param Index Index into @p IList where the designated initializer
2565/// @p DIE occurs.
2566///
2567/// @param StructuredList The initializer list expression that
2568/// describes all of the subobject initializers in the order they'll
2569/// actually be initialized.
2570///
2571/// @returns true if there was an error, false otherwise.
2572bool
2573InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2574 InitListExpr *IList,
2575 DesignatedInitExpr *DIE,
2576 unsigned DesigIdx,
2577 QualType &CurrentObjectType,
2578 RecordDecl::field_iterator *NextField,
2579 llvm::APSInt *NextElementIndex,
2580 unsigned &Index,
2581 InitListExpr *StructuredList,
2582 unsigned &StructuredIndex,
2583 bool FinishSubobjectInit,
2584 bool TopLevelObject) {
2585 if (DesigIdx == DIE->size()) {
2586 // C++20 designated initialization can result in direct-list-initialization
2587 // of the designated subobject. This is the only way that we can end up
2588 // performing direct initialization as part of aggregate initialization, so
2589 // it needs special handling.
2590 if (DIE->isDirectInit()) {
2591 Expr *Init = DIE->getInit();
2592 assert(isa<InitListExpr>(Init) &&
2593 "designator result in direct non-list initialization?");
2595 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2596 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2597 /*TopLevelOfInitList*/ true);
2598 if (StructuredList) {
2599 ExprResult Result = VerifyOnly
2600 ? getDummyInit()
2601 : Seq.Perform(SemaRef, Entity, Kind, Init);
2602 UpdateStructuredListElement(StructuredList, StructuredIndex,
2603 Result.get());
2604 }
2605 ++Index;
2606 if (AggrDeductionCandidateParamTypes)
2607 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2608 return !Seq;
2609 }
2610
2611 // Check the actual initialization for the designated object type.
2612 bool prevHadError = hadError;
2613
2614 // Temporarily remove the designator expression from the
2615 // initializer list that the child calls see, so that we don't try
2616 // to re-process the designator.
2617 unsigned OldIndex = Index;
2618 IList->setInit(OldIndex, DIE->getInit());
2619
2620 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2621 StructuredIndex, /*DirectlyDesignated=*/true);
2622
2623 // Restore the designated initializer expression in the syntactic
2624 // form of the initializer list.
2625 if (IList->getInit(OldIndex) != DIE->getInit())
2626 DIE->setInit(IList->getInit(OldIndex));
2627 IList->setInit(OldIndex, DIE);
2628
2629 return hadError && !prevHadError;
2630 }
2631
2633 bool IsFirstDesignator = (DesigIdx == 0);
2634 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2635 // Determine the structural initializer list that corresponds to the
2636 // current subobject.
2637 if (IsFirstDesignator)
2638 StructuredList = FullyStructuredList;
2639 else {
2640 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2641 StructuredList->getInit(StructuredIndex) : nullptr;
2642 if (!ExistingInit && StructuredList->hasArrayFiller())
2643 ExistingInit = StructuredList->getArrayFiller();
2644
2645 if (!ExistingInit)
2646 StructuredList = getStructuredSubobjectInit(
2647 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2648 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2649 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2650 StructuredList = Result;
2651 else {
2652 // We are creating an initializer list that initializes the
2653 // subobjects of the current object, but there was already an
2654 // initialization that completely initialized the current
2655 // subobject, e.g., by a compound literal:
2656 //
2657 // struct X { int a, b; };
2658 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2659 //
2660 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2661 // designated initializer re-initializes only its current object
2662 // subobject [0].b.
2663 diagnoseInitOverride(ExistingInit,
2664 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2665 /*UnionOverride=*/false,
2666 /*FullyOverwritten=*/false);
2667
2668 if (!VerifyOnly) {
2670 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2671 StructuredList = E->getUpdater();
2672 else {
2673 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2675 ExistingInit, DIE->getEndLoc());
2676 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2677 StructuredList = DIUE->getUpdater();
2678 }
2679 } else {
2680 // We don't need to track the structured representation of a
2681 // designated init update of an already-fully-initialized object in
2682 // verify-only mode. The only reason we would need the structure is
2683 // to determine where the uninitialized "holes" are, and in this
2684 // case, we know there aren't any and we can't introduce any.
2685 StructuredList = nullptr;
2686 }
2687 }
2688 }
2689 }
2690
2691 if (D->isFieldDesignator()) {
2692 // C99 6.7.8p7:
2693 //
2694 // If a designator has the form
2695 //
2696 // . identifier
2697 //
2698 // then the current object (defined below) shall have
2699 // structure or union type and the identifier shall be the
2700 // name of a member of that type.
2701 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2702 if (!RD) {
2703 SourceLocation Loc = D->getDotLoc();
2704 if (Loc.isInvalid())
2705 Loc = D->getFieldLoc();
2706 if (!VerifyOnly)
2707 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2708 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2709 ++Index;
2710 return true;
2711 }
2712
2713 FieldDecl *KnownField = D->getFieldDecl();
2714 if (!KnownField) {
2715 const IdentifierInfo *FieldName = D->getFieldName();
2716 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2717 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2718 KnownField = FD;
2719 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2720 // In verify mode, don't modify the original.
2721 if (VerifyOnly)
2722 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2723 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2724 D = DIE->getDesignator(DesigIdx);
2725 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2726 }
2727 if (!KnownField) {
2728 if (VerifyOnly) {
2729 ++Index;
2730 return true; // No typo correction when just trying this out.
2731 }
2732
2733 // We found a placeholder variable
2734 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2735 FieldName)) {
2736 ++Index;
2737 return true;
2738 }
2739 // Name lookup found something, but it wasn't a field.
2740 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2741 !Lookup.empty()) {
2742 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2743 << FieldName;
2744 SemaRef.Diag(Lookup.front()->getLocation(),
2745 diag::note_field_designator_found);
2746 ++Index;
2747 return true;
2748 }
2749
2750 // Name lookup didn't find anything.
2751 // Determine whether this was a typo for another field name.
2752 FieldInitializerValidatorCCC CCC(RD);
2753 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2754 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2755 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2757 SemaRef.diagnoseTypo(
2758 Corrected,
2759 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2760 << FieldName << CurrentObjectType);
2761 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2762 hadError = true;
2763 } else {
2764 // Typo correction didn't find anything.
2765 SourceLocation Loc = D->getFieldLoc();
2766
2767 // The loc can be invalid with a "null" designator (i.e. an anonymous
2768 // union/struct). Do our best to approximate the location.
2769 if (Loc.isInvalid())
2770 Loc = IList->getBeginLoc();
2771
2772 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2773 << FieldName << CurrentObjectType << DIE->getSourceRange();
2774 ++Index;
2775 return true;
2776 }
2777 }
2778 }
2779
2780 unsigned NumBases = 0;
2781 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2782 NumBases = CXXRD->getNumBases();
2783
2784 unsigned FieldIndex = NumBases;
2785
2786 for (auto *FI : RD->fields()) {
2787 if (FI->isUnnamedBitField())
2788 continue;
2789 if (declaresSameEntity(KnownField, FI)) {
2790 KnownField = FI;
2791 break;
2792 }
2793 ++FieldIndex;
2794 }
2795
2798
2799 // All of the fields of a union are located at the same place in
2800 // the initializer list.
2801 if (RD->isUnion()) {
2802 FieldIndex = 0;
2803 if (StructuredList) {
2804 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2805 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2806 assert(StructuredList->getNumInits() == 1
2807 && "A union should never have more than one initializer!");
2808
2809 Expr *ExistingInit = StructuredList->getInit(0);
2810 if (ExistingInit) {
2811 // We're about to throw away an initializer, emit warning.
2812 diagnoseInitOverride(
2813 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2814 /*UnionOverride=*/true,
2815 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2816 : true);
2817 }
2818
2819 // remove existing initializer
2820 StructuredList->resizeInits(SemaRef.Context, 0);
2821 StructuredList->setInitializedFieldInUnion(nullptr);
2822 }
2823
2824 StructuredList->setInitializedFieldInUnion(*Field);
2825 }
2826 }
2827
2828 // Make sure we can use this declaration.
2829 bool InvalidUse;
2830 if (VerifyOnly)
2831 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2832 else
2833 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2834 if (InvalidUse) {
2835 ++Index;
2836 return true;
2837 }
2838
2839 // C++20 [dcl.init.list]p3:
2840 // The ordered identifiers in the designators of the designated-
2841 // initializer-list shall form a subsequence of the ordered identifiers
2842 // in the direct non-static data members of T.
2843 //
2844 // Note that this is not a condition on forming the aggregate
2845 // initialization, only on actually performing initialization,
2846 // so it is not checked in VerifyOnly mode.
2847 //
2848 // FIXME: This is the only reordering diagnostic we produce, and it only
2849 // catches cases where we have a top-level field designator that jumps
2850 // backwards. This is the only such case that is reachable in an
2851 // otherwise-valid C++20 program, so is the only case that's required for
2852 // conformance, but for consistency, we should diagnose all the other
2853 // cases where a designator takes us backwards too.
2854 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2855 NextField &&
2856 (*NextField == RD->field_end() ||
2857 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2858 // Find the field that we just initialized.
2859 FieldDecl *PrevField = nullptr;
2860 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2861 if (FI->isUnnamedBitField())
2862 continue;
2863 if (*NextField != RD->field_end() &&
2864 declaresSameEntity(*FI, **NextField))
2865 break;
2866 PrevField = *FI;
2867 }
2868
2869 if (PrevField &&
2870 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2871 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2872 diag::ext_designated_init_reordered)
2873 << KnownField << PrevField << DIE->getSourceRange();
2874
2875 unsigned OldIndex = StructuredIndex - 1;
2876 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2877 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2878 SemaRef.Diag(PrevInit->getBeginLoc(),
2879 diag::note_previous_field_init)
2880 << PrevField << PrevInit->getSourceRange();
2881 }
2882 }
2883 }
2884 }
2885
2886
2887 // Update the designator with the field declaration.
2888 if (!VerifyOnly)
2889 D->setFieldDecl(*Field);
2890
2891 // Make sure that our non-designated initializer list has space
2892 // for a subobject corresponding to this field.
2893 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2894 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2895
2896 // This designator names a flexible array member.
2897 if (Field->getType()->isIncompleteArrayType()) {
2898 bool Invalid = false;
2899 if ((DesigIdx + 1) != DIE->size()) {
2900 // We can't designate an object within the flexible array
2901 // member (because GCC doesn't allow it).
2902 if (!VerifyOnly) {
2904 = DIE->getDesignator(DesigIdx + 1);
2905 SemaRef.Diag(NextD->getBeginLoc(),
2906 diag::err_designator_into_flexible_array_member)
2907 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2908 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2909 << *Field;
2910 }
2911 Invalid = true;
2912 }
2913
2914 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2915 !isa<StringLiteral>(DIE->getInit())) {
2916 // The initializer is not an initializer list.
2917 if (!VerifyOnly) {
2918 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2919 diag::err_flexible_array_init_needs_braces)
2920 << DIE->getInit()->getSourceRange();
2921 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2922 << *Field;
2923 }
2924 Invalid = true;
2925 }
2926
2927 // Check GNU flexible array initializer.
2928 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2929 TopLevelObject))
2930 Invalid = true;
2931
2932 if (Invalid) {
2933 ++Index;
2934 return true;
2935 }
2936
2937 // Initialize the array.
2938 bool prevHadError = hadError;
2939 unsigned newStructuredIndex = FieldIndex;
2940 unsigned OldIndex = Index;
2941 IList->setInit(Index, DIE->getInit());
2942
2943 InitializedEntity MemberEntity =
2944 InitializedEntity::InitializeMember(*Field, &Entity);
2945 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2946 StructuredList, newStructuredIndex);
2947
2948 IList->setInit(OldIndex, DIE);
2949 if (hadError && !prevHadError) {
2950 ++Field;
2951 ++FieldIndex;
2952 if (NextField)
2953 *NextField = Field;
2954 StructuredIndex = FieldIndex;
2955 return true;
2956 }
2957 } else {
2958 // Recurse to check later designated subobjects.
2959 QualType FieldType = Field->getType();
2960 unsigned newStructuredIndex = FieldIndex;
2961
2962 InitializedEntity MemberEntity =
2963 InitializedEntity::InitializeMember(*Field, &Entity);
2964 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2965 FieldType, nullptr, nullptr, Index,
2966 StructuredList, newStructuredIndex,
2967 FinishSubobjectInit, false))
2968 return true;
2969 }
2970
2971 // Find the position of the next field to be initialized in this
2972 // subobject.
2973 ++Field;
2974 ++FieldIndex;
2975
2976 // If this the first designator, our caller will continue checking
2977 // the rest of this struct/class/union subobject.
2978 if (IsFirstDesignator) {
2979 if (Field != RD->field_end() && Field->isUnnamedBitField())
2980 ++Field;
2981
2982 if (NextField)
2983 *NextField = Field;
2984
2985 StructuredIndex = FieldIndex;
2986 return false;
2987 }
2988
2989 if (!FinishSubobjectInit)
2990 return false;
2991
2992 // We've already initialized something in the union; we're done.
2993 if (RD->isUnion())
2994 return hadError;
2995
2996 // Check the remaining fields within this class/struct/union subobject.
2997 bool prevHadError = hadError;
2998
2999 auto NoBases =
3002 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3003 false, Index, StructuredList, FieldIndex);
3004 return hadError && !prevHadError;
3005 }
3006
3007 // C99 6.7.8p6:
3008 //
3009 // If a designator has the form
3010 //
3011 // [ constant-expression ]
3012 //
3013 // then the current object (defined below) shall have array
3014 // type and the expression shall be an integer constant
3015 // expression. If the array is of unknown size, any
3016 // nonnegative value is valid.
3017 //
3018 // Additionally, cope with the GNU extension that permits
3019 // designators of the form
3020 //
3021 // [ constant-expression ... constant-expression ]
3022 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3023 if (!AT) {
3024 if (!VerifyOnly)
3025 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3026 << CurrentObjectType;
3027 ++Index;
3028 return true;
3029 }
3030
3031 Expr *IndexExpr = nullptr;
3032 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3033 if (D->isArrayDesignator()) {
3034 IndexExpr = DIE->getArrayIndex(*D);
3035 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3036 DesignatedEndIndex = DesignatedStartIndex;
3037 } else {
3038 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3039
3040 DesignatedStartIndex =
3042 DesignatedEndIndex =
3044 IndexExpr = DIE->getArrayRangeEnd(*D);
3045
3046 // Codegen can't handle evaluating array range designators that have side
3047 // effects, because we replicate the AST value for each initialized element.
3048 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3049 // elements with something that has a side effect, so codegen can emit an
3050 // "error unsupported" error instead of miscompiling the app.
3051 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3052 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3053 FullyStructuredList->sawArrayRangeDesignator();
3054 }
3055
3056 if (isa<ConstantArrayType>(AT)) {
3057 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3058 DesignatedStartIndex
3059 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3060 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3061 DesignatedEndIndex
3062 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3063 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3064 if (DesignatedEndIndex >= MaxElements) {
3065 if (!VerifyOnly)
3066 SemaRef.Diag(IndexExpr->getBeginLoc(),
3067 diag::err_array_designator_too_large)
3068 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3069 << IndexExpr->getSourceRange();
3070 ++Index;
3071 return true;
3072 }
3073 } else {
3074 unsigned DesignatedIndexBitWidth =
3076 DesignatedStartIndex =
3077 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3078 DesignatedEndIndex =
3079 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3080 DesignatedStartIndex.setIsUnsigned(true);
3081 DesignatedEndIndex.setIsUnsigned(true);
3082 }
3083
3084 bool IsStringLiteralInitUpdate =
3085 StructuredList && StructuredList->isStringLiteralInit();
3086 if (IsStringLiteralInitUpdate && VerifyOnly) {
3087 // We're just verifying an update to a string literal init. We don't need
3088 // to split the string up into individual characters to do that.
3089 StructuredList = nullptr;
3090 } else if (IsStringLiteralInitUpdate) {
3091 // We're modifying a string literal init; we have to decompose the string
3092 // so we can modify the individual characters.
3093 ASTContext &Context = SemaRef.Context;
3094 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3095
3096 // Compute the character type
3097 QualType CharTy = AT->getElementType();
3098
3099 // Compute the type of the integer literals.
3100 QualType PromotedCharTy = CharTy;
3101 if (Context.isPromotableIntegerType(CharTy))
3102 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3103 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3104
3105 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3106 // Get the length of the string.
3107 uint64_t StrLen = SL->getLength();
3108 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3109 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3110 StructuredList->resizeInits(Context, StrLen);
3111
3112 // Build a literal for each character in the string, and put them into
3113 // the init list.
3114 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3115 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3116 Expr *Init = new (Context) IntegerLiteral(
3117 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3118 if (CharTy != PromotedCharTy)
3119 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3120 Init, nullptr, VK_PRValue,
3122 StructuredList->updateInit(Context, i, Init);
3123 }
3124 } else {
3125 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3126 std::string Str;
3127 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3128
3129 // Get the length of the string.
3130 uint64_t StrLen = Str.size();
3131 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3132 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3133 StructuredList->resizeInits(Context, StrLen);
3134
3135 // Build a literal for each character in the string, and put them into
3136 // the init list.
3137 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3138 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3139 Expr *Init = new (Context) IntegerLiteral(
3140 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3141 if (CharTy != PromotedCharTy)
3142 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3143 Init, nullptr, VK_PRValue,
3145 StructuredList->updateInit(Context, i, Init);
3146 }
3147 }
3148 }
3149
3150 // Make sure that our non-designated initializer list has space
3151 // for a subobject corresponding to this array element.
3152 if (StructuredList &&
3153 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3154 StructuredList->resizeInits(SemaRef.Context,
3155 DesignatedEndIndex.getZExtValue() + 1);
3156
3157 // Repeatedly perform subobject initializations in the range
3158 // [DesignatedStartIndex, DesignatedEndIndex].
3159
3160 // Move to the next designator
3161 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3162 unsigned OldIndex = Index;
3163
3164 InitializedEntity ElementEntity =
3166
3167 while (DesignatedStartIndex <= DesignatedEndIndex) {
3168 // Recurse to check later designated subobjects.
3169 QualType ElementType = AT->getElementType();
3170 Index = OldIndex;
3171
3172 ElementEntity.setElementIndex(ElementIndex);
3173 if (CheckDesignatedInitializer(
3174 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3175 nullptr, Index, StructuredList, ElementIndex,
3176 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3177 false))
3178 return true;
3179
3180 // Move to the next index in the array that we'll be initializing.
3181 ++DesignatedStartIndex;
3182 ElementIndex = DesignatedStartIndex.getZExtValue();
3183 }
3184
3185 // If this the first designator, our caller will continue checking
3186 // the rest of this array subobject.
3187 if (IsFirstDesignator) {
3188 if (NextElementIndex)
3189 *NextElementIndex = DesignatedStartIndex;
3190 StructuredIndex = ElementIndex;
3191 return false;
3192 }
3193
3194 if (!FinishSubobjectInit)
3195 return false;
3196
3197 // Check the remaining elements within this array subobject.
3198 bool prevHadError = hadError;
3199 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3200 /*SubobjectIsDesignatorContext=*/false, Index,
3201 StructuredList, ElementIndex);
3202 return hadError && !prevHadError;
3203}
3204
3205// Get the structured initializer list for a subobject of type
3206// @p CurrentObjectType.
3208InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3209 QualType CurrentObjectType,
3210 InitListExpr *StructuredList,
3211 unsigned StructuredIndex,
3212 SourceRange InitRange,
3213 bool IsFullyOverwritten) {
3214 if (!StructuredList)
3215 return nullptr;
3216
3217 Expr *ExistingInit = nullptr;
3218 if (StructuredIndex < StructuredList->getNumInits())
3219 ExistingInit = StructuredList->getInit(StructuredIndex);
3220
3221 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3222 // There might have already been initializers for subobjects of the current
3223 // object, but a subsequent initializer list will overwrite the entirety
3224 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3225 //
3226 // struct P { char x[6]; };
3227 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3228 //
3229 // The first designated initializer is ignored, and l.x is just "f".
3230 if (!IsFullyOverwritten)
3231 return Result;
3232
3233 if (ExistingInit) {
3234 // We are creating an initializer list that initializes the
3235 // subobjects of the current object, but there was already an
3236 // initialization that completely initialized the current
3237 // subobject:
3238 //
3239 // struct X { int a, b; };
3240 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3241 //
3242 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3243 // designated initializer overwrites the [0].b initializer
3244 // from the prior initialization.
3245 //
3246 // When the existing initializer is an expression rather than an
3247 // initializer list, we cannot decompose and update it in this way.
3248 // For example:
3249 //
3250 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3251 //
3252 // This case is handled by CheckDesignatedInitializer.
3253 diagnoseInitOverride(ExistingInit, InitRange);
3254 }
3255
3256 unsigned ExpectedNumInits = 0;
3257 if (Index < IList->getNumInits()) {
3258 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3259 ExpectedNumInits = Init->getNumInits();
3260 else
3261 ExpectedNumInits = IList->getNumInits() - Index;
3262 }
3263
3264 InitListExpr *Result =
3265 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3266
3267 // Link this new initializer list into the structured initializer
3268 // lists.
3269 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3270 return Result;
3271}
3272
3274InitListChecker::createInitListExpr(QualType CurrentObjectType,
3275 SourceRange InitRange,
3276 unsigned ExpectedNumInits) {
3277 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3278 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3279
3280 QualType ResultType = CurrentObjectType;
3281 if (!ResultType->isArrayType())
3282 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3283 Result->setType(ResultType);
3284
3285 // Pre-allocate storage for the structured initializer list.
3286 unsigned NumElements = 0;
3287
3288 if (const ArrayType *AType
3289 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3290 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3291 NumElements = CAType->getZExtSize();
3292 // Simple heuristic so that we don't allocate a very large
3293 // initializer with many empty entries at the end.
3294 if (NumElements > ExpectedNumInits)
3295 NumElements = 0;
3296 }
3297 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3298 NumElements = VType->getNumElements();
3299 } else if (CurrentObjectType->isRecordType()) {
3300 NumElements = numStructUnionElements(CurrentObjectType);
3301 } else if (CurrentObjectType->isDependentType()) {
3302 NumElements = 1;
3303 }
3304
3305 Result->reserveInits(SemaRef.Context, NumElements);
3306
3307 return Result;
3308}
3309
3310/// Update the initializer at index @p StructuredIndex within the
3311/// structured initializer list to the value @p expr.
3312void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3313 unsigned &StructuredIndex,
3314 Expr *expr) {
3315 // No structured initializer list to update
3316 if (!StructuredList)
3317 return;
3318
3319 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3320 StructuredIndex, expr)) {
3321 // This initializer overwrites a previous initializer.
3322 // No need to diagnose when `expr` is nullptr because a more relevant
3323 // diagnostic has already been issued and this diagnostic is potentially
3324 // noise.
3325 if (expr)
3326 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3327 }
3328
3329 ++StructuredIndex;
3330}
3331
3332/// Determine whether we can perform aggregate initialization for the purposes
3333/// of overload resolution.
3335 const InitializedEntity &Entity, InitListExpr *From) {
3336 QualType Type = Entity.getType();
3337 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3338 /*TreatUnavailableAsInvalid=*/false,
3339 /*InOverloadResolution=*/true);
3340 return !Check.HadError();
3341}
3342
3343/// Check that the given Index expression is a valid array designator
3344/// value. This is essentially just a wrapper around
3345/// VerifyIntegerConstantExpression that also checks for negative values
3346/// and produces a reasonable diagnostic if there is a
3347/// failure. Returns the index expression, possibly with an implicit cast
3348/// added, on success. If everything went okay, Value will receive the
3349/// value of the constant expression.
3350static ExprResult
3351CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3352 SourceLocation Loc = Index->getBeginLoc();
3353
3354 // Make sure this is an integer constant expression.
3357 if (Result.isInvalid())
3358 return Result;
3359
3360 if (Value.isSigned() && Value.isNegative())
3361 return S.Diag(Loc, diag::err_array_designator_negative)
3362 << toString(Value, 10) << Index->getSourceRange();
3363
3364 Value.setIsUnsigned(true);
3365 return Result;
3366}
3367
3369 SourceLocation EqualOrColonLoc,
3370 bool GNUSyntax,
3371 ExprResult Init) {
3372 typedef DesignatedInitExpr::Designator ASTDesignator;
3373
3374 bool Invalid = false;
3376 SmallVector<Expr *, 32> InitExpressions;
3377
3378 // Build designators and check array designator expressions.
3379 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3380 const Designator &D = Desig.getDesignator(Idx);
3381
3382 if (D.isFieldDesignator()) {
3383 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3384 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3385 } else if (D.isArrayDesignator()) {
3386 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3387 llvm::APSInt IndexValue;
3388 if (!Index->isTypeDependent() && !Index->isValueDependent())
3389 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3390 if (!Index)
3391 Invalid = true;
3392 else {
3393 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3394 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3395 InitExpressions.push_back(Index);
3396 }
3397 } else if (D.isArrayRangeDesignator()) {
3398 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3399 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3400 llvm::APSInt StartValue;
3401 llvm::APSInt EndValue;
3402 bool StartDependent = StartIndex->isTypeDependent() ||
3403 StartIndex->isValueDependent();
3404 bool EndDependent = EndIndex->isTypeDependent() ||
3405 EndIndex->isValueDependent();
3406 if (!StartDependent)
3407 StartIndex =
3408 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3409 if (!EndDependent)
3410 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3411
3412 if (!StartIndex || !EndIndex)
3413 Invalid = true;
3414 else {
3415 // Make sure we're comparing values with the same bit width.
3416 if (StartDependent || EndDependent) {
3417 // Nothing to compute.
3418 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3419 EndValue = EndValue.extend(StartValue.getBitWidth());
3420 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3421 StartValue = StartValue.extend(EndValue.getBitWidth());
3422
3423 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3424 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3425 << toString(StartValue, 10) << toString(EndValue, 10)
3426 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3427 Invalid = true;
3428 } else {
3429 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3430 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3431 D.getRBracketLoc()));
3432 InitExpressions.push_back(StartIndex);
3433 InitExpressions.push_back(EndIndex);
3434 }
3435 }
3436 }
3437 }
3438
3439 if (Invalid || Init.isInvalid())
3440 return ExprError();
3441
3442 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3443 EqualOrColonLoc, GNUSyntax,
3444 Init.getAs<Expr>());
3445}
3446
3447//===----------------------------------------------------------------------===//
3448// Initialization entity
3449//===----------------------------------------------------------------------===//
3450
3451InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3453 : Parent(&Parent), Index(Index)
3454{
3455 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3456 Kind = EK_ArrayElement;
3457 Type = AT->getElementType();
3458 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3459 Kind = EK_VectorElement;
3460 Type = VT->getElementType();
3461 } else {
3462 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3463 assert(CT && "Unexpected type");
3464 Kind = EK_ComplexElement;
3465 Type = CT->getElementType();
3466 }
3467}
3468
3471 const CXXBaseSpecifier *Base,
3472 bool IsInheritedVirtualBase,
3473 const InitializedEntity *Parent) {
3475 Result.Kind = EK_Base;
3476 Result.Parent = Parent;
3477 Result.Base = {Base, IsInheritedVirtualBase};
3478 Result.Type = Base->getType();
3479 return Result;
3480}
3481
3483 switch (getKind()) {
3484 case EK_Parameter:
3486 ParmVarDecl *D = Parameter.getPointer();
3487 return (D ? D->getDeclName() : DeclarationName());
3488 }
3489
3490 case EK_Variable:
3491 case EK_Member:
3493 case EK_Binding:
3495 return Variable.VariableOrMember->getDeclName();
3496
3497 case EK_LambdaCapture:
3498 return DeclarationName(Capture.VarID);
3499
3500 case EK_Result:
3501 case EK_StmtExprResult:
3502 case EK_Exception:
3503 case EK_New:
3504 case EK_Temporary:
3505 case EK_Base:
3506 case EK_Delegating:
3507 case EK_ArrayElement:
3508 case EK_VectorElement:
3509 case EK_ComplexElement:
3510 case EK_BlockElement:
3513 case EK_RelatedResult:
3514 return DeclarationName();
3515 }
3516
3517 llvm_unreachable("Invalid EntityKind!");
3518}
3519
3521 switch (getKind()) {
3522 case EK_Variable:
3523 case EK_Member:
3525 case EK_Binding:
3527 return Variable.VariableOrMember;
3528
3529 case EK_Parameter:
3531 return Parameter.getPointer();
3532
3533 case EK_Result:
3534 case EK_StmtExprResult:
3535 case EK_Exception:
3536 case EK_New:
3537 case EK_Temporary:
3538 case EK_Base:
3539 case EK_Delegating:
3540 case EK_ArrayElement:
3541 case EK_VectorElement:
3542 case EK_ComplexElement:
3543 case EK_BlockElement:
3545 case EK_LambdaCapture:
3547 case EK_RelatedResult:
3548 return nullptr;
3549 }
3550
3551 llvm_unreachable("Invalid EntityKind!");
3552}
3553
3555 switch (getKind()) {
3556 case EK_Result:
3557 case EK_Exception:
3558 return LocAndNRVO.NRVO;
3559
3560 case EK_StmtExprResult:
3561 case EK_Variable:
3562 case EK_Parameter:
3565 case EK_Member:
3567 case EK_Binding:
3568 case EK_New:
3569 case EK_Temporary:
3571 case EK_Base:
3572 case EK_Delegating:
3573 case EK_ArrayElement:
3574 case EK_VectorElement:
3575 case EK_ComplexElement:
3576 case EK_BlockElement:
3578 case EK_LambdaCapture:
3579 case EK_RelatedResult:
3580 break;
3581 }
3582
3583 return false;
3584}
3585
3586unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3587 assert(getParent() != this);
3588 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3589 for (unsigned I = 0; I != Depth; ++I)
3590 OS << "`-";
3591
3592 switch (getKind()) {
3593 case EK_Variable: OS << "Variable"; break;
3594 case EK_Parameter: OS << "Parameter"; break;
3595 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3596 break;
3597 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3598 case EK_Result: OS << "Result"; break;
3599 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3600 case EK_Exception: OS << "Exception"; break;
3601 case EK_Member:
3603 OS << "Member";
3604 break;
3605 case EK_Binding: OS << "Binding"; break;
3606 case EK_New: OS << "New"; break;
3607 case EK_Temporary: OS << "Temporary"; break;
3608 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3609 case EK_RelatedResult: OS << "RelatedResult"; break;
3610 case EK_Base: OS << "Base"; break;
3611 case EK_Delegating: OS << "Delegating"; break;
3612 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3613 case EK_VectorElement: OS << "VectorElement " << Index; break;
3614 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3615 case EK_BlockElement: OS << "Block"; break;
3617 OS << "Block (lambda)";
3618 break;
3619 case EK_LambdaCapture:
3620 OS << "LambdaCapture ";
3621 OS << DeclarationName(Capture.VarID);
3622 break;
3623 }
3624
3625 if (auto *D = getDecl()) {
3626 OS << " ";
3627 D->printQualifiedName(OS);
3628 }
3629
3630 OS << " '" << getType() << "'\n";
3631
3632 return Depth + 1;
3633}
3634
3635LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3636 dumpImpl(llvm::errs());
3637}
3638
3639//===----------------------------------------------------------------------===//
3640// Initialization sequence
3641//===----------------------------------------------------------------------===//
3642
3644 switch (Kind) {
3649 case SK_BindReference:
3651 case SK_FinalCopy:
3653 case SK_UserConversion:
3660 case SK_UnwrapInitList:
3661 case SK_RewrapInitList:
3665 case SK_CAssignment:
3666 case SK_StringInit:
3668 case SK_ArrayLoopIndex:
3669 case SK_ArrayLoopInit:
3670 case SK_ArrayInit:
3671 case SK_GNUArrayInit:
3678 case SK_OCLSamplerInit:
3681 break;
3682
3685 delete ICS;
3686 }
3687}
3688
3690 // There can be some lvalue adjustments after the SK_BindReference step.
3691 for (const Step &S : llvm::reverse(Steps)) {
3692 if (S.Kind == SK_BindReference)
3693 return true;
3694 if (S.Kind == SK_BindReferenceToTemporary)
3695 return false;
3696 }
3697 return false;
3698}
3699
3701 if (!Failed())
3702 return false;
3703
3704 switch (getFailureKind()) {
3715 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3732 case FK_Incomplete:
3737 case FK_PlaceholderType:
3742 return false;
3743
3748 return FailedOverloadResult == OR_Ambiguous;
3749 }
3750
3751 llvm_unreachable("Invalid EntityKind!");
3752}
3753
3755 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3756}
3757
3758void
3759InitializationSequence
3760::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3761 DeclAccessPair Found,
3762 bool HadMultipleCandidates) {
3763 Step S;
3765 S.Type = Function->getType();
3766 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3767 S.Function.Function = Function;
3768 S.Function.FoundDecl = Found;
3769 Steps.push_back(S);
3770}
3771
3773 ExprValueKind VK) {
3774 Step S;
3775 switch (VK) {
3776 case VK_PRValue:
3778 break;
3779 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3780 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3781 }
3782 S.Type = BaseType;
3783 Steps.push_back(S);
3784}
3785
3787 bool BindingTemporary) {
3788 Step S;
3789 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3790 S.Type = T;
3791 Steps.push_back(S);
3792}
3793
3795 Step S;
3796 S.Kind = SK_FinalCopy;
3797 S.Type = T;
3798 Steps.push_back(S);
3799}
3800
3802 Step S;
3804 S.Type = T;
3805 Steps.push_back(S);
3806}
3807
3808void
3810 DeclAccessPair FoundDecl,
3811 QualType T,
3812 bool HadMultipleCandidates) {
3813 Step S;
3814 S.Kind = SK_UserConversion;
3815 S.Type = T;
3816 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3817 S.Function.Function = Function;
3818 S.Function.FoundDecl = FoundDecl;
3819 Steps.push_back(S);
3820}
3821
3823 ExprValueKind VK) {
3824 Step S;
3825 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3826 switch (VK) {
3827 case VK_PRValue:
3829 break;
3830 case VK_XValue:
3832 break;
3833 case VK_LValue:
3835 break;
3836 }
3837 S.Type = Ty;
3838 Steps.push_back(S);
3839}
3840
3842 Step S;
3844 S.Type = Ty;
3845 Steps.push_back(S);
3846}
3847
3849 Step S;
3850 S.Kind = SK_AtomicConversion;
3851 S.Type = Ty;
3852 Steps.push_back(S);
3853}
3854
3857 bool TopLevelOfInitList) {
3858 Step S;
3859 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3861 S.Type = T;
3862 S.ICS = new ImplicitConversionSequence(ICS);
3863 Steps.push_back(S);
3864}
3865
3867 Step S;
3868 S.Kind = SK_ListInitialization;
3869 S.Type = T;
3870 Steps.push_back(S);
3871}
3872
3874 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3875 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3876 Step S;
3877 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3880 S.Type = T;
3881 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3882 S.Function.Function = Constructor;
3883 S.Function.FoundDecl = FoundDecl;
3884 Steps.push_back(S);
3885}
3886
3888 Step S;
3889 S.Kind = SK_ZeroInitialization;
3890 S.Type = T;
3891 Steps.push_back(S);
3892}
3893
3895 Step S;
3896 S.Kind = SK_CAssignment;
3897 S.Type = T;
3898 Steps.push_back(S);
3899}
3900
3902 Step S;
3903 S.Kind = SK_StringInit;
3904 S.Type = T;
3905 Steps.push_back(S);
3906}
3907
3909 Step S;
3910 S.Kind = SK_ObjCObjectConversion;
3911 S.Type = T;
3912 Steps.push_back(S);
3913}
3914
3916 Step S;
3917 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3918 S.Type = T;
3919 Steps.push_back(S);
3920}
3921
3923 Step S;
3924 S.Kind = SK_ArrayLoopIndex;
3925 S.Type = EltT;
3926 Steps.insert(Steps.begin(), S);
3927
3928 S.Kind = SK_ArrayLoopInit;
3929 S.Type = T;
3930 Steps.push_back(S);
3931}
3932
3934 Step S;
3936 S.Type = T;
3937 Steps.push_back(S);
3938}
3939
3941 bool shouldCopy) {
3942 Step s;
3943 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3945 s.Type = type;
3946 Steps.push_back(s);
3947}
3948
3950 Step S;
3951 S.Kind = SK_ProduceObjCObject;
3952 S.Type = T;
3953 Steps.push_back(S);
3954}
3955
3957 Step S;
3958 S.Kind = SK_StdInitializerList;
3959 S.Type = T;
3960 Steps.push_back(S);
3961}
3962
3964 Step S;
3965 S.Kind = SK_OCLSamplerInit;
3966 S.Type = T;
3967 Steps.push_back(S);
3968}
3969
3971 Step S;
3972 S.Kind = SK_OCLZeroOpaqueType;
3973 S.Type = T;
3974 Steps.push_back(S);
3975}
3976
3978 Step S;
3979 S.Kind = SK_ParenthesizedListInit;
3980 S.Type = T;
3981 Steps.push_back(S);
3982}
3983
3985 InitListExpr *Syntactic) {
3986 assert(Syntactic->getNumInits() == 1 &&
3987 "Can only rewrap trivial init lists.");
3988 Step S;
3989 S.Kind = SK_UnwrapInitList;
3990 S.Type = Syntactic->getInit(0)->getType();
3991 Steps.insert(Steps.begin(), S);
3992
3993 S.Kind = SK_RewrapInitList;
3994 S.Type = T;
3995 S.WrappingSyntacticList = Syntactic;
3996 Steps.push_back(S);
3997}
3998
4002 this->Failure = Failure;
4003 this->FailedOverloadResult = Result;
4004}
4005
4006//===----------------------------------------------------------------------===//
4007// Attempt initialization
4008//===----------------------------------------------------------------------===//
4009
4010/// Tries to add a zero initializer. Returns true if that worked.
4011static bool
4013 const InitializedEntity &Entity) {
4015 return false;
4016
4017 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4018 if (VD->getInit() || VD->getEndLoc().isMacroID())
4019 return false;
4020
4021 QualType VariableTy = VD->getType().getCanonicalType();
4023 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4024 if (!Init.empty()) {
4025 Sequence.AddZeroInitializationStep(Entity.getType());
4026 Sequence.SetZeroInitializationFixit(Init, Loc);
4027 return true;
4028 }
4029 return false;
4030}
4031
4033 InitializationSequence &Sequence,
4034 const InitializedEntity &Entity) {
4035 if (!S.getLangOpts().ObjCAutoRefCount) return;
4036
4037 /// When initializing a parameter, produce the value if it's marked
4038 /// __attribute__((ns_consumed)).
4039 if (Entity.isParameterKind()) {
4040 if (!Entity.isParameterConsumed())
4041 return;
4042
4043 assert(Entity.getType()->isObjCRetainableType() &&
4044 "consuming an object of unretainable type?");
4045 Sequence.AddProduceObjCObjectStep(Entity.getType());
4046
4047 /// When initializing a return value, if the return type is a
4048 /// retainable type, then returns need to immediately retain the
4049 /// object. If an autorelease is required, it will be done at the
4050 /// last instant.
4051 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4053 if (!Entity.getType()->isObjCRetainableType())
4054 return;
4055
4056 Sequence.AddProduceObjCObjectStep(Entity.getType());
4057 }
4058}
4059
4060static void TryListInitialization(Sema &S,
4061 const InitializedEntity &Entity,
4062 const InitializationKind &Kind,
4063 InitListExpr *InitList,
4064 InitializationSequence &Sequence,
4065 bool TreatUnavailableAsInvalid);
4066
4067/// When initializing from init list via constructor, handle
4068/// initialization of an object of type std::initializer_list<T>.
4069///
4070/// \return true if we have handled initialization of an object of type
4071/// std::initializer_list<T>, false otherwise.
4073 InitListExpr *List,
4074 QualType DestType,
4075 InitializationSequence &Sequence,
4076 bool TreatUnavailableAsInvalid) {
4077 QualType E;
4078 if (!S.isStdInitializerList(DestType, &E))
4079 return false;
4080
4081 if (!S.isCompleteType(List->getExprLoc(), E)) {
4082 Sequence.setIncompleteTypeFailure(E);
4083 return true;
4084 }
4085
4086 // Try initializing a temporary array from the init list.
4088 E.withConst(),
4089 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4090 List->getNumInits()),
4092 InitializedEntity HiddenArray =
4095 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4096 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4097 TreatUnavailableAsInvalid);
4098 if (Sequence)
4099 Sequence.AddStdInitializerListConstructionStep(DestType);
4100 return true;
4101}
4102
4103/// Determine if the constructor has the signature of a copy or move
4104/// constructor for the type T of the class in which it was found. That is,
4105/// determine if its first parameter is of type T or reference to (possibly
4106/// cv-qualified) T.
4108 const ConstructorInfo &Info) {
4109 if (Info.Constructor->getNumParams() == 0)
4110 return false;
4111
4112 QualType ParmT =
4114 QualType ClassT =
4115 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4116
4117 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4118}
4119
4121 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4122 OverloadCandidateSet &CandidateSet, QualType DestType,
4124 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4125 bool IsListInit, bool RequireActualConstructor,
4126 bool SecondStepOfCopyInit = false) {
4128 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4129
4130 for (NamedDecl *D : Ctors) {
4131 auto Info = getConstructorInfo(D);
4132 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4133 continue;
4134
4135 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4136 continue;
4137
4138 // C++11 [over.best.ics]p4:
4139 // ... and the constructor or user-defined conversion function is a
4140 // candidate by
4141 // - 13.3.1.3, when the argument is the temporary in the second step
4142 // of a class copy-initialization, or
4143 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4144 // - the second phase of 13.3.1.7 when the initializer list has exactly
4145 // one element that is itself an initializer list, and the target is
4146 // the first parameter of a constructor of class X, and the conversion
4147 // is to X or reference to (possibly cv-qualified X),
4148 // user-defined conversion sequences are not considered.
4149 bool SuppressUserConversions =
4150 SecondStepOfCopyInit ||
4151 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4153
4154 if (Info.ConstructorTmpl)
4156 Info.ConstructorTmpl, Info.FoundDecl,
4157 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4158 /*PartialOverloading=*/false, AllowExplicit);
4159 else {
4160 // C++ [over.match.copy]p1:
4161 // - When initializing a temporary to be bound to the first parameter
4162 // of a constructor [for type T] that takes a reference to possibly
4163 // cv-qualified T as its first argument, called with a single
4164 // argument in the context of direct-initialization, explicit
4165 // conversion functions are also considered.
4166 // FIXME: What if a constructor template instantiates to such a signature?
4167 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4168 Args.size() == 1 &&
4170 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4171 CandidateSet, SuppressUserConversions,
4172 /*PartialOverloading=*/false, AllowExplicit,
4173 AllowExplicitConv);
4174 }
4175 }
4176
4177 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4178 //
4179 // When initializing an object of class type T by constructor
4180 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4181 // from a single expression of class type U, conversion functions of
4182 // U that convert to the non-reference type cv T are candidates.
4183 // Explicit conversion functions are only candidates during
4184 // direct-initialization.
4185 //
4186 // Note: SecondStepOfCopyInit is only ever true in this case when
4187 // evaluating whether to produce a C++98 compatibility warning.
4188 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4189 !RequireActualConstructor && !SecondStepOfCopyInit) {
4190 Expr *Initializer = Args[0];
4191 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4192 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4193 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4194 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4195 NamedDecl *D = *I;
4196 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4197 D = D->getUnderlyingDecl();
4198
4199 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4200 CXXConversionDecl *Conv;
4201 if (ConvTemplate)
4202 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4203 else
4204 Conv = cast<CXXConversionDecl>(D);
4205
4206 if (ConvTemplate)
4208 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4209 CandidateSet, AllowExplicit, AllowExplicit,
4210 /*AllowResultConversion*/ false);
4211 else
4212 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4213 DestType, CandidateSet, AllowExplicit,
4214 AllowExplicit,
4215 /*AllowResultConversion*/ false);
4216 }
4217 }
4218 }
4219
4220 // Perform overload resolution and return the result.
4221 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4222}
4223
4224/// Attempt initialization by constructor (C++ [dcl.init]), which
4225/// enumerates the constructors of the initialized entity and performs overload
4226/// resolution to select the best.
4227/// \param DestType The destination class type.
4228/// \param DestArrayType The destination type, which is either DestType or
4229/// a (possibly multidimensional) array of DestType.
4230/// \param IsListInit Is this list-initialization?
4231/// \param IsInitListCopy Is this non-list-initialization resulting from a
4232/// list-initialization from {x} where x is the same
4233/// type as the entity?
4235 const InitializedEntity &Entity,
4236 const InitializationKind &Kind,
4237 MultiExprArg Args, QualType DestType,
4238 QualType DestArrayType,
4239 InitializationSequence &Sequence,
4240 bool IsListInit = false,
4241 bool IsInitListCopy = false) {
4242 assert(((!IsListInit && !IsInitListCopy) ||
4243 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4244 "IsListInit/IsInitListCopy must come with a single initializer list "
4245 "argument.");
4246 InitListExpr *ILE =
4247 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4248 MultiExprArg UnwrappedArgs =
4249 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4250
4251 // The type we're constructing needs to be complete.
4252 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4253 Sequence.setIncompleteTypeFailure(DestType);
4254 return;
4255 }
4256
4257 bool RequireActualConstructor =
4258 !(Entity.getKind() != InitializedEntity::EK_Base &&
4260 Entity.getKind() !=
4262
4263 // C++17 [dcl.init]p17:
4264 // - If the initializer expression is a prvalue and the cv-unqualified
4265 // version of the source type is the same class as the class of the
4266 // destination, the initializer expression is used to initialize the
4267 // destination object.
4268 // Per DR (no number yet), this does not apply when initializing a base
4269 // class or delegating to another constructor from a mem-initializer.
4270 // ObjC++: Lambda captured by the block in the lambda to block conversion
4271 // should avoid copy elision.
4272 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4273 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4274 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4275 // Convert qualifications if necessary.
4276 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4277 if (ILE)
4278 Sequence.RewrapReferenceInitList(DestType, ILE);
4279 return;
4280 }
4281
4282 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4283 assert(DestRecordType && "Constructor initialization requires record type");
4284 CXXRecordDecl *DestRecordDecl
4285 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4286
4287 // Build the candidate set directly in the initialization sequence
4288 // structure, so that it will persist if we fail.
4289 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4290
4291 // Determine whether we are allowed to call explicit constructors or
4292 // explicit conversion operators.
4293 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4294 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4295
4296 // - Otherwise, if T is a class type, constructors are considered. The
4297 // applicable constructors are enumerated, and the best one is chosen
4298 // through overload resolution.
4299 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4300
4303 bool AsInitializerList = false;
4304
4305 // C++11 [over.match.list]p1, per DR1467:
4306 // When objects of non-aggregate type T are list-initialized, such that
4307 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4308 // according to the rules in this section, overload resolution selects
4309 // the constructor in two phases:
4310 //
4311 // - Initially, the candidate functions are the initializer-list
4312 // constructors of the class T and the argument list consists of the
4313 // initializer list as a single argument.
4314 if (IsListInit) {
4315 AsInitializerList = true;
4316
4317 // If the initializer list has no elements and T has a default constructor,
4318 // the first phase is omitted.
4319 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4321 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4322 CopyInitialization, AllowExplicit,
4323 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4324 }
4325
4326 // C++11 [over.match.list]p1:
4327 // - If no viable initializer-list constructor is found, overload resolution
4328 // is performed again, where the candidate functions are all the
4329 // constructors of the class T and the argument list consists of the
4330 // elements of the initializer list.
4332 AsInitializerList = false;
4334 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4335 Best, CopyInitialization, AllowExplicit,
4336 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4337 }
4338 if (Result) {
4339 Sequence.SetOverloadFailure(
4342 Result);
4343
4344 if (Result != OR_Deleted)
4345 return;
4346 }
4347
4348 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4349
4350 // In C++17, ResolveConstructorOverload can select a conversion function
4351 // instead of a constructor.
4352 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4353 // Add the user-defined conversion step that calls the conversion function.
4354 QualType ConvType = CD->getConversionType();
4355 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4356 "should not have selected this conversion function");
4357 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4358 HadMultipleCandidates);
4359 if (!S.Context.hasSameType(ConvType, DestType))
4360 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4361 if (IsListInit)
4362 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4363 return;
4364 }
4365
4366 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4367 if (Result != OR_Deleted) {
4368 // C++11 [dcl.init]p6:
4369 // If a program calls for the default initialization of an object
4370 // of a const-qualified type T, T shall be a class type with a
4371 // user-provided default constructor.
4372 // C++ core issue 253 proposal:
4373 // If the implicit default constructor initializes all subobjects, no
4374 // initializer should be required.
4375 // The 253 proposal is for example needed to process libstdc++ headers
4376 // in 5.x.
4377 if (Kind.getKind() == InitializationKind::IK_Default &&
4378 Entity.getType().isConstQualified()) {
4379 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4380 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4382 return;
4383 }
4384 }
4385
4386 // C++11 [over.match.list]p1:
4387 // In copy-list-initialization, if an explicit constructor is chosen, the
4388 // initializer is ill-formed.
4389 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4391 return;
4392 }
4393 }
4394
4395 // [class.copy.elision]p3:
4396 // In some copy-initialization contexts, a two-stage overload resolution
4397 // is performed.
4398 // If the first overload resolution selects a deleted function, we also
4399 // need the initialization sequence to decide whether to perform the second
4400 // overload resolution.
4401 // For deleted functions in other contexts, there is no need to get the
4402 // initialization sequence.
4403 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4404 return;
4405
4406 // Add the constructor initialization step. Any cv-qualification conversion is
4407 // subsumed by the initialization.
4409 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4410 IsListInit | IsInitListCopy, AsInitializerList);
4411}
4412
4413static bool
4416 QualType &SourceType,
4417 QualType &UnqualifiedSourceType,
4418 QualType UnqualifiedTargetType,
4419 InitializationSequence &Sequence) {
4420 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4421 S.Context.OverloadTy) {
4422 DeclAccessPair Found;
4423 bool HadMultipleCandidates = false;
4424 if (FunctionDecl *Fn
4426 UnqualifiedTargetType,
4427 false, Found,
4428 &HadMultipleCandidates)) {
4429 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4430 HadMultipleCandidates);
4431 SourceType = Fn->getType();
4432 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4433 } else if (!UnqualifiedTargetType->isRecordType()) {
4435 return true;
4436 }
4437 }
4438 return false;
4439}
4440
4442 const InitializedEntity &Entity,
4443 const InitializationKind &Kind,
4445 QualType cv1T1, QualType T1,
4446 Qualifiers T1Quals,
4447 QualType cv2T2, QualType T2,
4448 Qualifiers T2Quals,
4449 InitializationSequence &Sequence,
4450 bool TopLevelOfInitList);
4451
4452static void TryValueInitialization(Sema &S,
4453 const InitializedEntity &Entity,
4454 const InitializationKind &Kind,
4455 InitializationSequence &Sequence,
4456 InitListExpr *InitList = nullptr);
4457
4458/// Attempt list initialization of a reference.
4460 const InitializedEntity &Entity,
4461 const InitializationKind &Kind,
4462 InitListExpr *InitList,
4463 InitializationSequence &Sequence,
4464 bool TreatUnavailableAsInvalid) {
4465 // First, catch C++03 where this isn't possible.
4466 if (!S.getLangOpts().CPlusPlus11) {
4468 return;
4469 }
4470 // Can't reference initialize a compound literal.
4473 return;
4474 }
4475
4476 QualType DestType = Entity.getType();
4477 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4478 Qualifiers T1Quals;
4479 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4480
4481 // Reference initialization via an initializer list works thus:
4482 // If the initializer list consists of a single element that is
4483 // reference-related to the referenced type, bind directly to that element
4484 // (possibly creating temporaries).
4485 // Otherwise, initialize a temporary with the initializer list and
4486 // bind to that.
4487 if (InitList->getNumInits() == 1) {
4488 Expr *Initializer = InitList->getInit(0);
4490 Qualifiers T2Quals;
4491 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4492
4493 // If this fails, creating a temporary wouldn't work either.
4495 T1, Sequence))
4496 return;
4497
4498 SourceLocation DeclLoc = Initializer->getBeginLoc();
4499 Sema::ReferenceCompareResult RefRelationship
4500 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4501 if (RefRelationship >= Sema::Ref_Related) {
4502 // Try to bind the reference here.
4503 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4504 T1Quals, cv2T2, T2, T2Quals, Sequence,
4505 /*TopLevelOfInitList=*/true);
4506 if (Sequence)
4507 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4508 return;
4509 }
4510
4511 // Update the initializer if we've resolved an overloaded function.
4512 if (Sequence.step_begin() != Sequence.step_end())
4513 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4514 }
4515 // Perform address space compatibility check.
4516 QualType cv1T1IgnoreAS = cv1T1;
4517 if (T1Quals.hasAddressSpace()) {
4518 Qualifiers T2Quals;
4519 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4520 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4521 Sequence.SetFailed(
4523 return;
4524 }
4525 // Ignore address space of reference type at this point and perform address
4526 // space conversion after the reference binding step.
4527 cv1T1IgnoreAS =
4529 }
4530 // Not reference-related. Create a temporary and bind to that.
4531 InitializedEntity TempEntity =
4533
4534 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4535 TreatUnavailableAsInvalid);
4536 if (Sequence) {
4537 if (DestType->isRValueReferenceType() ||
4538 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4539 if (S.getLangOpts().CPlusPlus20 &&
4540 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4541 DestType->isRValueReferenceType()) {
4542 // C++20 [dcl.init.list]p3.10:
4543 // List-initialization of an object or reference of type T is defined as
4544 // follows:
4545 // ..., unless T is “reference to array of unknown bound of U”, in which
4546 // case the type of the prvalue is the type of x in the declaration U
4547 // x[] H, where H is the initializer list.
4549 }
4550 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4551 /*BindingTemporary=*/true);
4552 if (T1Quals.hasAddressSpace())
4554 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4555 } else
4556 Sequence.SetFailed(
4558 }
4559}
4560
4561/// Attempt list initialization (C++0x [dcl.init.list])
4563 const InitializedEntity &Entity,
4564 const InitializationKind &Kind,
4565 InitListExpr *InitList,
4566 InitializationSequence &Sequence,
4567 bool TreatUnavailableAsInvalid) {
4568 QualType DestType = Entity.getType();
4569
4570 // C++ doesn't allow scalar initialization with more than one argument.
4571 // But C99 complex numbers are scalars and it makes sense there.
4572 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4573 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4575 return;
4576 }
4577 if (DestType->isReferenceType()) {
4578 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4579 TreatUnavailableAsInvalid);
4580 return;
4581 }
4582
4583 if (DestType->isRecordType() &&
4584 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4585 Sequence.setIncompleteTypeFailure(DestType);
4586 return;
4587 }
4588
4589 // C++20 [dcl.init.list]p3:
4590 // - If the braced-init-list contains a designated-initializer-list, T shall
4591 // be an aggregate class. [...] Aggregate initialization is performed.
4592 //
4593 // We allow arrays here too in order to support array designators.
4594 //
4595 // FIXME: This check should precede the handling of reference initialization.
4596 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4597 // as a tentative DR resolution.
4598 bool IsDesignatedInit = InitList->hasDesignatedInit();
4599 if (!DestType->isAggregateType() && IsDesignatedInit) {
4600 Sequence.SetFailed(
4602 return;
4603 }
4604
4605 // C++11 [dcl.init.list]p3, per DR1467:
4606 // - If T is a class type and the initializer list has a single element of
4607 // type cv U, where U is T or a class derived from T, the object is
4608 // initialized from that element (by copy-initialization for
4609 // copy-list-initialization, or by direct-initialization for
4610 // direct-list-initialization).
4611 // - Otherwise, if T is a character array and the initializer list has a
4612 // single element that is an appropriately-typed string literal
4613 // (8.5.2 [dcl.init.string]), initialization is performed as described
4614 // in that section.
4615 // - Otherwise, if T is an aggregate, [...] (continue below).
4616 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4617 !IsDesignatedInit) {
4618 if (DestType->isRecordType()) {
4619 QualType InitType = InitList->getInit(0)->getType();
4620 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4621 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4622 Expr *InitListAsExpr = InitList;
4623 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4624 DestType, Sequence,
4625 /*InitListSyntax*/false,
4626 /*IsInitListCopy*/true);
4627 return;
4628 }
4629 }
4630 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4631 Expr *SubInit[1] = {InitList->getInit(0)};
4632 if (!isa<VariableArrayType>(DestAT) &&
4633 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4634 InitializationKind SubKind =
4635 Kind.getKind() == InitializationKind::IK_DirectList
4636 ? InitializationKind::CreateDirect(Kind.getLocation(),
4637 InitList->getLBraceLoc(),
4638 InitList->getRBraceLoc())
4639 : Kind;
4640 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4641 /*TopLevelOfInitList*/ true,
4642 TreatUnavailableAsInvalid);
4643
4644 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4645 // the element is not an appropriately-typed string literal, in which
4646 // case we should proceed as in C++11 (below).
4647 if (Sequence) {
4648 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4649 return;
4650 }
4651 }
4652 }
4653 }
4654
4655 // C++11 [dcl.init.list]p3:
4656 // - If T is an aggregate, aggregate initialization is performed.
4657 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4658 (S.getLangOpts().CPlusPlus11 &&
4659 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4660 if (S.getLangOpts().CPlusPlus11) {
4661 // - Otherwise, if the initializer list has no elements and T is a
4662 // class type with a default constructor, the object is
4663 // value-initialized.
4664 if (InitList->getNumInits() == 0) {
4665 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4666 if (S.LookupDefaultConstructor(RD)) {
4667 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4668 return;
4669 }
4670 }
4671
4672 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4673 // an initializer_list object constructed [...]
4674 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4675 TreatUnavailableAsInvalid))
4676 return;
4677
4678 // - Otherwise, if T is a class type, constructors are considered.
4679 Expr *InitListAsExpr = InitList;
4680 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4681 DestType, Sequence, /*InitListSyntax*/true);
4682 } else
4684 return;
4685 }
4686
4687 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4688 InitList->getNumInits() == 1) {
4689 Expr *E = InitList->getInit(0);
4690
4691 // - Otherwise, if T is an enumeration with a fixed underlying type,
4692 // the initializer-list has a single element v, and the initialization
4693 // is direct-list-initialization, the object is initialized with the
4694 // value T(v); if a narrowing conversion is required to convert v to
4695 // the underlying type of T, the program is ill-formed.
4696 auto *ET = DestType->getAs<EnumType>();
4697 if (S.getLangOpts().CPlusPlus17 &&
4698 Kind.getKind() == InitializationKind::IK_DirectList &&
4699 ET && ET->getDecl()->isFixed() &&
4700 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4702 E->getType()->isFloatingType())) {
4703 // There are two ways that T(v) can work when T is an enumeration type.
4704 // If there is either an implicit conversion sequence from v to T or
4705 // a conversion function that can convert from v to T, then we use that.
4706 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4707 // type, it is converted to the enumeration type via its underlying type.
4708 // There is no overlap possible between these two cases (except when the
4709 // source value is already of the destination type), and the first
4710 // case is handled by the general case for single-element lists below.
4712 ICS.setStandard();
4714 if (!E->isPRValue())
4716 // If E is of a floating-point type, then the conversion is ill-formed
4717 // due to narrowing, but go through the motions in order to produce the
4718 // right diagnostic.
4722 ICS.Standard.setFromType(E->getType());
4723 ICS.Standard.setToType(0, E->getType());
4724 ICS.Standard.setToType(1, DestType);
4725 ICS.Standard.setToType(2, DestType);
4726 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4727 /*TopLevelOfInitList*/true);
4728 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4729 return;
4730 }
4731
4732 // - Otherwise, if the initializer list has a single element of type E
4733 // [...references are handled above...], the object or reference is
4734 // initialized from that element (by copy-initialization for
4735 // copy-list-initialization, or by direct-initialization for
4736 // direct-list-initialization); if a narrowing conversion is required
4737 // to convert the element to T, the program is ill-formed.
4738 //
4739 // Per core-24034, this is direct-initialization if we were performing
4740 // direct-list-initialization and copy-initialization otherwise.
4741 // We can't use InitListChecker for this, because it always performs
4742 // copy-initialization. This only matters if we might use an 'explicit'
4743 // conversion operator, or for the special case conversion of nullptr_t to
4744 // bool, so we only need to handle those cases.
4745 //
4746 // FIXME: Why not do this in all cases?
4747 Expr *Init = InitList->getInit(0);
4748 if (Init->getType()->isRecordType() ||
4749 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4750 InitializationKind SubKind =
4751 Kind.getKind() == InitializationKind::IK_DirectList
4752 ? InitializationKind::CreateDirect(Kind.getLocation(),
4753 InitList->getLBraceLoc(),
4754 InitList->getRBraceLoc())
4755 : Kind;
4756 Expr *SubInit[1] = { Init };
4757 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4758 /*TopLevelOfInitList*/true,
4759 TreatUnavailableAsInvalid);
4760 if (Sequence)
4761 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4762 return;
4763 }
4764 }
4765
4766 InitListChecker CheckInitList(S, Entity, InitList,
4767 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4768 if (CheckInitList.HadError()) {
4770 return;
4771 }
4772
4773 // Add the list initialization step with the built init list.
4774 Sequence.AddListInitializationStep(DestType);
4775}
4776
4777/// Try a reference initialization that involves calling a conversion
4778/// function.
4780 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4781 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4782 InitializationSequence &Sequence) {
4783 QualType DestType = Entity.getType();
4784 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4785 QualType T1 = cv1T1.getUnqualifiedType();
4786 QualType cv2T2 = Initializer->getType();
4787 QualType T2 = cv2T2.getUnqualifiedType();
4788
4789 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4790 "Must have incompatible references when binding via conversion");
4791
4792 // Build the candidate set directly in the initialization sequence
4793 // structure, so that it will persist if we fail.
4794 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4796
4797 // Determine whether we are allowed to call explicit conversion operators.
4798 // Note that none of [over.match.copy], [over.match.conv], nor
4799 // [over.match.ref] permit an explicit constructor to be chosen when
4800 // initializing a reference, not even for direct-initialization.
4801 bool AllowExplicitCtors = false;
4802 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4803
4804 const RecordType *T1RecordType = nullptr;
4805 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4806 S.isCompleteType(Kind.getLocation(), T1)) {
4807 // The type we're converting to is a class type. Enumerate its constructors
4808 // to see if there is a suitable conversion.
4809 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4810
4811 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4812 auto Info = getConstructorInfo(D);
4813 if (!Info.Constructor)
4814 continue;
4815
4816 if (!Info.Constructor->isInvalidDecl() &&
4817 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4818 if (Info.ConstructorTmpl)
4820 Info.ConstructorTmpl, Info.FoundDecl,
4821 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4822 /*SuppressUserConversions=*/true,
4823 /*PartialOverloading*/ false, AllowExplicitCtors);
4824 else
4826 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4827 /*SuppressUserConversions=*/true,
4828 /*PartialOverloading*/ false, AllowExplicitCtors);
4829 }
4830 }
4831 }
4832 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4833 return OR_No_Viable_Function;
4834
4835 const RecordType *T2RecordType = nullptr;
4836 if ((T2RecordType = T2->getAs<RecordType>()) &&
4837 S.isCompleteType(Kind.getLocation(), T2)) {
4838 // The type we're converting from is a class type, enumerate its conversion
4839 // functions.
4840 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4841
4842 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4843 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4844 NamedDecl *D = *I;
4845 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4846 if (isa<UsingShadowDecl>(D))
4847 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4848
4849 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4850 CXXConversionDecl *Conv;
4851 if (ConvTemplate)
4852 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4853 else
4854 Conv = cast<CXXConversionDecl>(D);
4855
4856 // If the conversion function doesn't return a reference type,
4857 // it can't be considered for this conversion unless we're allowed to
4858 // consider rvalues.
4859 // FIXME: Do we need to make sure that we only consider conversion
4860 // candidates with reference-compatible results? That might be needed to
4861 // break recursion.
4862 if ((AllowRValues ||
4864 if (ConvTemplate)
4866 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4867 CandidateSet,
4868 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4869 else
4871 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4872 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4873 }
4874 }
4875 }
4876 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4877 return OR_No_Viable_Function;
4878
4879 SourceLocation DeclLoc = Initializer->getBeginLoc();
4880
4881 // Perform overload resolution. If it fails, return the failed result.
4884 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4885 return Result;
4886
4887 FunctionDecl *Function = Best->Function;
4888 // This is the overload that will be used for this initialization step if we
4889 // use this initialization. Mark it as referenced.
4890 Function->setReferenced();
4891
4892 // Compute the returned type and value kind of the conversion.
4893 QualType cv3T3;
4894 if (isa<CXXConversionDecl>(Function))
4895 cv3T3 = Function->getReturnType();
4896 else
4897 cv3T3 = T1;
4898
4900 if (cv3T3->isLValueReferenceType())
4901 VK = VK_LValue;
4902 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4903 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4904 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4905
4906 // Add the user-defined conversion step.
4907 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4908 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4909 HadMultipleCandidates);
4910
4911 // Determine whether we'll need to perform derived-to-base adjustments or
4912 // other conversions.
4914 Sema::ReferenceCompareResult NewRefRelationship =
4915 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4916
4917 // Add the final conversion sequence, if necessary.
4918 if (NewRefRelationship == Sema::Ref_Incompatible) {
4919 assert(!isa<CXXConstructorDecl>(Function) &&
4920 "should not have conversion after constructor");
4921
4923 ICS.setStandard();
4924 ICS.Standard = Best->FinalConversion;
4925 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4926
4927 // Every implicit conversion results in a prvalue, except for a glvalue
4928 // derived-to-base conversion, which we handle below.
4929 cv3T3 = ICS.Standard.getToType(2);
4930 VK = VK_PRValue;
4931 }
4932
4933 // If the converted initializer is a prvalue, its type T4 is adjusted to
4934 // type "cv1 T4" and the temporary materialization conversion is applied.
4935 //
4936 // We adjust the cv-qualifications to match the reference regardless of
4937 // whether we have a prvalue so that the AST records the change. In this
4938 // case, T4 is "cv3 T3".
4939 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4940 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4941 Sequence.AddQualificationConversionStep(cv1T4, VK);
4942 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4943 VK = IsLValueRef ? VK_LValue : VK_XValue;
4944
4945 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4946 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4947 else if (RefConv & Sema::ReferenceConversions::ObjC)
4948 Sequence.AddObjCObjectConversionStep(cv1T1);
4949 else if (RefConv & Sema::ReferenceConversions::Function)
4950 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4951 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4952 if (!S.Context.hasSameType(cv1T4, cv1T1))
4953 Sequence.AddQualificationConversionStep(cv1T1, VK);
4954 }
4955
4956 return OR_Success;
4957}
4958
4960 const InitializedEntity &Entity,
4961 Expr *CurInitExpr);
4962
4963/// Attempt reference initialization (C++0x [dcl.init.ref])
4965 const InitializationKind &Kind,
4967 InitializationSequence &Sequence,
4968 bool TopLevelOfInitList) {
4969 QualType DestType = Entity.getType();
4970 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4971 Qualifiers T1Quals;
4972 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4974 Qualifiers T2Quals;
4975 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4976
4977 // If the initializer is the address of an overloaded function, try
4978 // to resolve the overloaded function. If all goes well, T2 is the
4979 // type of the resulting function.
4981 T1, Sequence))
4982 return;
4983
4984 // Delegate everything else to a subfunction.
4985 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4986 T1Quals, cv2T2, T2, T2Quals, Sequence,
4987 TopLevelOfInitList);
4988}
4989
4990/// Determine whether an expression is a non-referenceable glvalue (one to
4991/// which a reference can never bind). Attempting to bind a reference to
4992/// such a glvalue will always create a temporary.
4994 return E->refersToBitField() || E->refersToVectorElement() ||
4996}
4997
4998/// Reference initialization without resolving overloaded functions.
4999///
5000/// We also can get here in C if we call a builtin which is declared as
5001/// a function with a parameter of reference type (such as __builtin_va_end()).
5003 const InitializedEntity &Entity,
5004 const InitializationKind &Kind,
5006 QualType cv1T1, QualType T1,
5007 Qualifiers T1Quals,
5008 QualType cv2T2, QualType T2,
5009 Qualifiers T2Quals,
5010 InitializationSequence &Sequence,
5011 bool TopLevelOfInitList) {
5012 QualType DestType = Entity.getType();
5013 SourceLocation DeclLoc = Initializer->getBeginLoc();
5014
5015 // Compute some basic properties of the types and the initializer.
5016 bool isLValueRef = DestType->isLValueReferenceType();
5017 bool isRValueRef = !isLValueRef;
5018 Expr::Classification InitCategory = Initializer->Classify(S.Context);
5019
5021 Sema::ReferenceCompareResult RefRelationship =
5022 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
5023
5024 // C++0x [dcl.init.ref]p5:
5025 // A reference to type "cv1 T1" is initialized by an expression of type
5026 // "cv2 T2" as follows:
5027 //
5028 // - If the reference is an lvalue reference and the initializer
5029 // expression
5030 // Note the analogous bullet points for rvalue refs to functions. Because
5031 // there are no function rvalues in C++, rvalue refs to functions are treated
5032 // like lvalue refs.
5033 OverloadingResult ConvOvlResult = OR_Success;
5034 bool T1Function = T1->isFunctionType();
5035 if (isLValueRef || T1Function) {
5036 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5037 (RefRelationship == Sema::Ref_Compatible ||
5038 (Kind.isCStyleOrFunctionalCast() &&
5039 RefRelationship == Sema::Ref_Related))) {
5040 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5041 // reference-compatible with "cv2 T2," or
5042 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5043 Sema::ReferenceConversions::ObjC)) {
5044 // If we're converting the pointee, add any qualifiers first;
5045 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5046 if (RefConv & (Sema::ReferenceConversions::Qualification))
5048 S.Context.getQualifiedType(T2, T1Quals),
5049 Initializer->getValueKind());
5050 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5051 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5052 else
5053 Sequence.AddObjCObjectConversionStep(cv1T1);
5054 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5055 // Perform a (possibly multi-level) qualification conversion.
5056 Sequence.AddQualificationConversionStep(cv1T1,
5057 Initializer->getValueKind());
5058 } else if (RefConv & Sema::ReferenceConversions::Function) {
5059 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5060 }
5061
5062 // We only create a temporary here when binding a reference to a
5063 // bit-field or vector element. Those cases are't supposed to be
5064 // handled by this bullet, but the outcome is the same either way.
5065 Sequence.AddReferenceBindingStep(cv1T1, false);
5066 return;
5067 }
5068
5069 // - has a class type (i.e., T2 is a class type), where T1 is not
5070 // reference-related to T2, and can be implicitly converted to an
5071 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5072 // with "cv3 T3" (this conversion is selected by enumerating the
5073 // applicable conversion functions (13.3.1.6) and choosing the best
5074 // one through overload resolution (13.3)),
5075 // If we have an rvalue ref to function type here, the rhs must be
5076 // an rvalue. DR1287 removed the "implicitly" here.
5077 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5078 (isLValueRef || InitCategory.isRValue())) {
5079 if (S.getLangOpts().CPlusPlus) {
5080 // Try conversion functions only for C++.
5081 ConvOvlResult = TryRefInitWithConversionFunction(
5082 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5083 /*IsLValueRef*/ isLValueRef, Sequence);
5084 if (ConvOvlResult == OR_Success)
5085 return;
5086 if (ConvOvlResult != OR_No_Viable_Function)
5087 Sequence.SetOverloadFailure(
5089 ConvOvlResult);
5090 } else {
5091 ConvOvlResult = OR_No_Viable_Function;
5092 }
5093 }
5094 }
5095
5096 // - Otherwise, the reference shall be an lvalue reference to a
5097 // non-volatile const type (i.e., cv1 shall be const), or the reference
5098 // shall be an rvalue reference.
5099 // For address spaces, we interpret this to mean that an addr space
5100 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5101 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5102 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5105 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5106 Sequence.SetOverloadFailure(
5108 ConvOvlResult);
5109 else if (!InitCategory.isLValue())
5110 Sequence.SetFailed(
5111 T1Quals.isAddressSpaceSupersetOf(T2Quals)
5115 else {
5117 switch (RefRelationship) {
5119 if (Initializer->refersToBitField())
5122 else if (Initializer->refersToVectorElement())
5125 else if (Initializer->refersToMatrixElement())
5128 else
5129 llvm_unreachable("unexpected kind of compatible initializer");
5130 break;
5131 case Sema::Ref_Related:
5133 break;
5137 break;
5138 }
5139 Sequence.SetFailed(FK);
5140 }
5141 return;
5142 }
5143
5144 // - If the initializer expression
5145 // - is an
5146 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5147 // [1z] rvalue (but not a bit-field) or
5148 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5149 //
5150 // Note: functions are handled above and below rather than here...
5151 if (!T1Function &&
5152 (RefRelationship == Sema::Ref_Compatible ||
5153 (Kind.isCStyleOrFunctionalCast() &&
5154 RefRelationship == Sema::Ref_Related)) &&
5155 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5156 (InitCategory.isPRValue() &&
5157 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5158 T2->isArrayType())))) {
5159 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5160 if (InitCategory.isPRValue() && T2->isRecordType()) {
5161 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5162 // compiler the freedom to perform a copy here or bind to the
5163 // object, while C++0x requires that we bind directly to the
5164 // object. Hence, we always bind to the object without making an
5165 // extra copy. However, in C++03 requires that we check for the
5166 // presence of a suitable copy constructor:
5167 //
5168 // The constructor that would be used to make the copy shall
5169 // be callable whether or not the copy is actually done.
5170 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5171 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5172 else if (S.getLangOpts().CPlusPlus11)
5174 }
5175
5176 // C++1z [dcl.init.ref]/5.2.1.2:
5177 // If the converted initializer is a prvalue, its type T4 is adjusted
5178 // to type "cv1 T4" and the temporary materialization conversion is
5179 // applied.
5180 // Postpone address space conversions to after the temporary materialization
5181 // conversion to allow creating temporaries in the alloca address space.
5182 auto T1QualsIgnoreAS = T1Quals;
5183 auto T2QualsIgnoreAS = T2Quals;
5184 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5185 T1QualsIgnoreAS.removeAddressSpace();
5186 T2QualsIgnoreAS.removeAddressSpace();
5187 }
5188 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5189 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5190 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5191 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5192 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5193 // Add addr space conversion if required.
5194 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5195 auto T4Quals = cv1T4.getQualifiers();
5196 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5197 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5198 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5199 cv1T4 = cv1T4WithAS;
5200 }
5201
5202 // In any case, the reference is bound to the resulting glvalue (or to
5203 // an appropriate base class subobject).
5204 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5205 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5206 else if (RefConv & Sema::ReferenceConversions::ObjC)
5207 Sequence.AddObjCObjectConversionStep(cv1T1);
5208 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5209 if (!S.Context.hasSameType(cv1T4, cv1T1))
5210 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5211 }
5212 return;
5213 }
5214
5215 // - has a class type (i.e., T2 is a class type), where T1 is not
5216 // reference-related to T2, and can be implicitly converted to an
5217 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5218 // where "cv1 T1" is reference-compatible with "cv3 T3",
5219 //
5220 // DR1287 removes the "implicitly" here.
5221 if (T2->isRecordType()) {
5222 if (RefRelationship == Sema::Ref_Incompatible) {
5223 ConvOvlResult = TryRefInitWithConversionFunction(
5224 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5225 /*IsLValueRef*/ isLValueRef, Sequence);
5226 if (ConvOvlResult)
5227 Sequence.SetOverloadFailure(
5229 ConvOvlResult);
5230
5231 return;
5232 }
5233
5234 if (RefRelationship == Sema::Ref_Compatible &&
5235 isRValueRef && InitCategory.isLValue()) {
5236 Sequence.SetFailed(
5238 return;
5239 }
5240
5242 return;
5243 }
5244
5245 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5246 // from the initializer expression using the rules for a non-reference
5247 // copy-initialization (8.5). The reference is then bound to the
5248 // temporary. [...]
5249
5250 // Ignore address space of reference type at this point and perform address
5251 // space conversion after the reference binding step.
5252 QualType cv1T1IgnoreAS =
5253 T1Quals.hasAddressSpace()
5255 : cv1T1;
5256
5257 InitializedEntity TempEntity =
5259
5260 // FIXME: Why do we use an implicit conversion here rather than trying
5261 // copy-initialization?
5263 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5264 /*SuppressUserConversions=*/false,
5265 Sema::AllowedExplicit::None,
5266 /*FIXME:InOverloadResolution=*/false,
5267 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5268 /*AllowObjCWritebackConversion=*/false);
5269
5270 if (ICS.isBad()) {
5271 // FIXME: Use the conversion function set stored in ICS to turn
5272 // this into an overloading ambiguity diagnostic. However, we need
5273 // to keep that set as an OverloadCandidateSet rather than as some
5274 // other kind of set.
5275 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5276 Sequence.SetOverloadFailure(
5278 ConvOvlResult);
5279 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5281 else
5283 return;
5284 } else {
5285 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5286 TopLevelOfInitList);
5287 }
5288
5289 // [...] If T1 is reference-related to T2, cv1 must be the
5290 // same cv-qualification as, or greater cv-qualification
5291 // than, cv2; otherwise, the program is ill-formed.
5292 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5293 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5294 if (RefRelationship == Sema::Ref_Related &&
5295 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5296 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5298 return;
5299 }
5300
5301 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5302 // reference, the initializer expression shall not be an lvalue.
5303 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5304 InitCategory.isLValue()) {
5305 Sequence.SetFailed(
5307 return;
5308 }
5309
5310 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5311
5312 if (T1Quals.hasAddressSpace()) {
5314 LangAS::Default)) {
5315 Sequence.SetFailed(
5317 return;
5318 }
5319 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5320 : VK_XValue);
5321 }
5322}
5323
5324/// Attempt character array initialization from a string literal
5325/// (C++ [dcl.init.string], C99 6.7.8).
5327 const InitializedEntity &Entity,
5328 const InitializationKind &Kind,
5330 InitializationSequence &Sequence) {
5331 Sequence.AddStringInitStep(Entity.getType());
5332}
5333
5334/// Attempt value initialization (C++ [dcl.init]p7).
5336 const InitializedEntity &Entity,
5337 const InitializationKind &Kind,
5338 InitializationSequence &Sequence,
5339 InitListExpr *InitList) {
5340 assert((!InitList || InitList->getNumInits() == 0) &&
5341 "Shouldn't use value-init for non-empty init lists");
5342
5343 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5344 //
5345 // To value-initialize an object of type T means:
5346 QualType T = Entity.getType();
5347
5348 // -- if T is an array type, then each element is value-initialized;
5350
5351 if (const RecordType *RT = T->getAs<RecordType>()) {
5352 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5353 bool NeedZeroInitialization = true;
5354 // C++98:
5355 // -- if T is a class type (clause 9) with a user-declared constructor
5356 // (12.1), then the default constructor for T is called (and the
5357 // initialization is ill-formed if T has no accessible default
5358 // constructor);
5359 // C++11:
5360 // -- if T is a class type (clause 9) with either no default constructor
5361 // (12.1 [class.ctor]) or a default constructor that is user-provided
5362 // or deleted, then the object is default-initialized;
5363 //
5364 // Note that the C++11 rule is the same as the C++98 rule if there are no
5365 // defaulted or deleted constructors, so we just use it unconditionally.
5367 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5368 NeedZeroInitialization = false;
5369
5370 // -- if T is a (possibly cv-qualified) non-union class type without a
5371 // user-provided or deleted default constructor, then the object is
5372 // zero-initialized and, if T has a non-trivial default constructor,
5373 // default-initialized;
5374 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5375 // constructor' part was removed by DR1507.
5376 if (NeedZeroInitialization)
5377 Sequence.AddZeroInitializationStep(Entity.getType());
5378
5379 // C++03:
5380 // -- if T is a non-union class type without a user-declared constructor,
5381 // then every non-static data member and base class component of T is
5382 // value-initialized;
5383 // [...] A program that calls for [...] value-initialization of an
5384 // entity of reference type is ill-formed.
5385 //
5386 // C++11 doesn't need this handling, because value-initialization does not
5387 // occur recursively there, and the implicit default constructor is
5388 // defined as deleted in the problematic cases.
5389 if (!S.getLangOpts().CPlusPlus11 &&
5390 ClassDecl->hasUninitializedReferenceMember()) {
5392 return;
5393 }
5394
5395 // If this is list-value-initialization, pass the empty init list on when
5396 // building the constructor call. This affects the semantics of a few
5397 // things (such as whether an explicit default constructor can be called).
5398 Expr *InitListAsExpr = InitList;
5399 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5400 bool InitListSyntax = InitList;
5401
5402 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5403 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5405 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5406 }
5407 }
5408
5409 Sequence.AddZeroInitializationStep(Entity.getType());
5410}
5411
5412/// Attempt default initialization (C++ [dcl.init]p6).
5414 const InitializedEntity &Entity,
5415 const InitializationKind &Kind,
5416 InitializationSequence &Sequence) {
5417 assert(Kind.getKind() == InitializationKind::IK_Default);
5418
5419 // C++ [dcl.init]p6:
5420 // To default-initialize an object of type T means:
5421 // - if T is an array type, each element is default-initialized;
5422 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5423
5424 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5425 // constructor for T is called (and the initialization is ill-formed if
5426 // T has no accessible default constructor);
5427 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5428 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5429 Entity.getType(), Sequence);
5430 return;
5431 }
5432
5433 // - otherwise, no initialization is performed.
5434
5435 // If a program calls for the default initialization of an object of
5436 // a const-qualified type T, T shall be a class type with a user-provided
5437 // default constructor.
5438 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5439 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5441 return;
5442 }
5443
5444 // If the destination type has a lifetime property, zero-initialize it.
5445 if (DestType.getQualifiers().hasObjCLifetime()) {
5446 Sequence.AddZeroInitializationStep(Entity.getType());
5447 return;
5448 }
5449}
5450
5452 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5453 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5454 ExprResult *Result = nullptr) {
5455 unsigned EntityIndexToProcess = 0;
5456 SmallVector<Expr *, 4> InitExprs;
5457 QualType ResultType;
5458 Expr *ArrayFiller = nullptr;
5459 FieldDecl *InitializedFieldInUnion = nullptr;
5460
5461 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5462 const InitializationKind &SubKind,
5463 Expr *Arg, Expr **InitExpr = nullptr) {
5465 S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5466
5467 if (IS.Failed()) {
5468 if (!VerifyOnly) {
5469 IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);
5470 } else {
5471 Sequence.SetFailed(
5473 }
5474
5475 return false;
5476 }
5477 if (!VerifyOnly) {
5478 ExprResult ER;
5479 ER = IS.Perform(S, SubEntity, SubKind,
5480 Arg ? MultiExprArg(Arg) : std::nullopt);
5481 if (InitExpr)
5482 *InitExpr = ER.get();
5483 else
5484 InitExprs.push_back(ER.get());
5485 }
5486 return true;
5487 };
5488
5489 if (const ArrayType *AT =
5490 S.getASTContext().getAsArrayType(Entity.getType())) {
5491 SmallVector<InitializedEntity, 4> ElementEntities;
5492 uint64_t ArrayLength;
5493 // C++ [dcl.init]p16.5
5494 // if the destination type is an array, the object is initialized as
5495 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5496 // the destination type is an array of unknown bound, it is defined as
5497 // having k elements.
5498 if (const ConstantArrayType *CAT =
5500 ArrayLength = CAT->getZExtSize();
5501 ResultType = Entity.getType();
5502 } else if (const VariableArrayType *VAT =
5504 // Braced-initialization of variable array types is not allowed, even if
5505 // the size is greater than or equal to the number of args, so we don't
5506 // allow them to be initialized via parenthesized aggregate initialization
5507 // either.
5508 const Expr *SE = VAT->getSizeExpr();
5509 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5510 << SE->getSourceRange();
5511 return;
5512 } else {
5513 assert(isa<IncompleteArrayType>(Entity.getType()));
5514 ArrayLength = Args.size();
5515 }
5516 EntityIndexToProcess = ArrayLength;
5517
5518 // ...the ith array element is copy-initialized with xi for each
5519 // 1 <= i <= k
5520 for (Expr *E : Args) {
5522 S.getASTContext(), EntityIndexToProcess, Entity);
5524 E->getExprLoc(), /*isDirectInit=*/false, E);
5525 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5526 return;
5527 }
5528 // ...and value-initialized for each k < i <= n;
5529 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5531 S.getASTContext(), Args.size(), Entity);
5533 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5534 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5535 return;
5536 }
5537
5538 if (ResultType.isNull()) {
5539 ResultType = S.Context.getConstantArrayType(
5540 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5541 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5542 }
5543 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5544 bool IsUnion = RT->isUnionType();
5545 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5546 if (RD->isInvalidDecl()) {
5547 // Exit early to avoid confusion when processing members.
5548 // We do the same for braced list initialization in
5549 // `CheckStructUnionTypes`.
5550 Sequence.SetFailed(
5552 return;
5553 }
5554
5555 if (!IsUnion) {
5556 for (const CXXBaseSpecifier &Base : RD->bases()) {
5558 S.getASTContext(), &Base, false, &Entity);
5559 if (EntityIndexToProcess < Args.size()) {
5560 // C++ [dcl.init]p16.6.2.2.
5561 // ...the object is initialized is follows. Let e1, ..., en be the
5562 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5563 // the elements of the expression-list...The element ei is
5564 // copy-initialized with xi for 1 <= i <= k.
5565 Expr *E = Args[EntityIndexToProcess];
5567 E->getExprLoc(), /*isDirectInit=*/false, E);
5568 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5569 return;
5570 } else {
5571 // We've processed all of the args, but there are still base classes
5572 // that have to be initialized.
5573 // C++ [dcl.init]p17.6.2.2
5574 // The remaining elements...otherwise are value initialzed
5576 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5577 /*IsImplicit=*/true);
5578 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5579 return;
5580 }
5581 EntityIndexToProcess++;
5582 }
5583 }
5584
5585 for (FieldDecl *FD : RD->fields()) {
5586 // Unnamed bitfields should not be initialized at all, either with an arg
5587 // or by default.
5588 if (FD->isUnnamedBitField())
5589 continue;
5590
5591 InitializedEntity SubEntity =
5593
5594 if (EntityIndexToProcess < Args.size()) {
5595 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5596 Expr *E = Args[EntityIndexToProcess];
5597
5598 // Incomplete array types indicate flexible array members. Do not allow
5599 // paren list initializations of structs with these members, as GCC
5600 // doesn't either.
5601 if (FD->getType()->isIncompleteArrayType()) {
5602 if (!VerifyOnly) {
5603 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5604 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5605 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5606 }
5607 Sequence.SetFailed(
5609 return;
5610 }
5611
5613 E->getExprLoc(), /*isDirectInit=*/false, E);
5614 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5615 return;
5616
5617 // Unions should have only one initializer expression, so we bail out
5618 // after processing the first field. If there are more initializers then
5619 // it will be caught when we later check whether EntityIndexToProcess is
5620 // less than Args.size();
5621 if (IsUnion) {
5622 InitializedFieldInUnion = FD;
5623 EntityIndexToProcess = 1;
5624 break;
5625 }
5626 } else {
5627 // We've processed all of the args, but there are still members that
5628 // have to be initialized.
5629 if (FD->hasInClassInitializer()) {
5630 if (!VerifyOnly) {
5631 // C++ [dcl.init]p16.6.2.2
5632 // The remaining elements are initialized with their default
5633 // member initializers, if any
5635 Kind.getParenOrBraceRange().getEnd(), FD);
5636 if (DIE.isInvalid())
5637 return;
5638 S.checkInitializerLifetime(SubEntity, DIE.get());
5639 InitExprs.push_back(DIE.get());
5640 }
5641 } else {
5642 // C++ [dcl.init]p17.6.2.2
5643 // The remaining elements...otherwise are value initialzed
5644 if (FD->getType()->isReferenceType()) {
5645 Sequence.SetFailed(
5647 if (!VerifyOnly) {
5648 SourceRange SR = Kind.getParenOrBraceRange();
5649 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5650 << FD->getType() << SR;
5651 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5652 }
5653 return;
5654 }
5656 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5657 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5658 return;
5659 }
5660 }
5661 EntityIndexToProcess++;
5662 }
5663 ResultType = Entity.getType();
5664 }
5665
5666 // Not all of the args have been processed, so there must've been more args
5667 // than were required to initialize the element.
5668 if (EntityIndexToProcess < Args.size()) {
5670 if (!VerifyOnly) {
5671 QualType T = Entity.getType();
5672 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5673 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5674 Args.back()->getEndLoc());
5675 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5676 << InitKind << ExcessInitSR;
5677 }
5678 return;
5679 }
5680
5681 if (VerifyOnly) {
5683 Sequence.AddParenthesizedListInitStep(Entity.getType());
5684 } else if (Result) {
5685 SourceRange SR = Kind.getParenOrBraceRange();
5686 auto *CPLIE = CXXParenListInitExpr::Create(
5687 S.getASTContext(), InitExprs, ResultType, Args.size(),
5688 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5689 if (ArrayFiller)
5690 CPLIE->setArrayFiller(ArrayFiller);
5691 if (InitializedFieldInUnion)
5692 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5693 *Result = CPLIE;
5694 S.Diag(Kind.getLocation(),
5695 diag::warn_cxx17_compat_aggregate_init_paren_list)
5696 << Kind.getLocation() << SR << ResultType;
5697 }
5698}
5699
5700/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5701/// which enumerates all conversion functions and performs overload resolution
5702/// to select the best.
5704 QualType DestType,
5705 const InitializationKind &Kind,
5707 InitializationSequence &Sequence,
5708 bool TopLevelOfInitList) {
5709 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5710 QualType SourceType = Initializer->getType();
5711 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5712 "Must have a class type to perform a user-defined conversion");
5713
5714 // Build the candidate set directly in the initialization sequence
5715 // structure, so that it will persist if we fail.
5716 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5718 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5719
5720 // Determine whether we are allowed to call explicit constructors or
5721 // explicit conversion operators.
5722 bool AllowExplicit = Kind.AllowExplicit();
5723
5724 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5725 // The type we're converting to is a class type. Enumerate its constructors
5726 // to see if there is a suitable conversion.
5727 CXXRecordDecl *DestRecordDecl
5728 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5729
5730 // Try to complete the type we're converting to.
5731 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5732 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5733 auto Info = getConstructorInfo(D);
5734 if (!Info.Constructor)
5735 continue;
5736
5737 if (!Info.Constructor->isInvalidDecl() &&
5738 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5739 if (Info.ConstructorTmpl)
5741 Info.ConstructorTmpl, Info.FoundDecl,
5742 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5743 /*SuppressUserConversions=*/true,
5744 /*PartialOverloading*/ false, AllowExplicit);
5745 else
5746 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5747 Initializer, CandidateSet,
5748 /*SuppressUserConversions=*/true,
5749 /*PartialOverloading*/ false, AllowExplicit);
5750 }
5751 }
5752 }
5753 }
5754
5755 SourceLocation DeclLoc = Initializer->getBeginLoc();
5756
5757 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5758 // The type we're converting from is a class type, enumerate its conversion
5759 // functions.
5760
5761 // We can only enumerate the conversion functions for a complete type; if
5762 // the type isn't complete, simply skip this step.
5763 if (S.isCompleteType(DeclLoc, SourceType)) {
5764 CXXRecordDecl *SourceRecordDecl
5765 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5766
5767 const auto &Conversions =
5768 SourceRecordDecl->getVisibleConversionFunctions();
5769 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5770 NamedDecl *D = *I;
5771 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5772 if (isa<UsingShadowDecl>(D))
5773 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5774
5775 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5776 CXXConversionDecl *Conv;
5777 if (ConvTemplate)
5778 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5779 else
5780 Conv = cast<CXXConversionDecl>(D);
5781
5782 if (ConvTemplate)
5784 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5785 CandidateSet, AllowExplicit, AllowExplicit);
5786 else
5787 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5788 DestType, CandidateSet, AllowExplicit,
5789 AllowExplicit);
5790 }
5791 }
5792 }
5793
5794 // Perform overload resolution. If it fails, return the failed result.
5797 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5798 Sequence.SetOverloadFailure(
5800
5801 // [class.copy.elision]p3:
5802 // In some copy-initialization contexts, a two-stage overload resolution
5803 // is performed.
5804 // If the first overload resolution selects a deleted function, we also
5805 // need the initialization sequence to decide whether to perform the second
5806 // overload resolution.
5807 if (!(Result == OR_Deleted &&
5808 Kind.getKind() == InitializationKind::IK_Copy))
5809 return;
5810 }
5811
5812 FunctionDecl *Function = Best->Function;
5813 Function->setReferenced();
5814 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5815
5816 if (isa<CXXConstructorDecl>(Function)) {
5817 // Add the user-defined conversion step. Any cv-qualification conversion is
5818 // subsumed by the initialization. Per DR5, the created temporary is of the
5819 // cv-unqualified type of the destination.
5820 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5821 DestType.getUnqualifiedType(),
5822 HadMultipleCandidates);
5823
5824 // C++14 and before:
5825 // - if the function is a constructor, the call initializes a temporary
5826 // of the cv-unqualified version of the destination type. The [...]
5827 // temporary [...] is then used to direct-initialize, according to the
5828 // rules above, the object that is the destination of the
5829 // copy-initialization.
5830 // Note that this just performs a simple object copy from the temporary.
5831 //
5832 // C++17:
5833 // - if the function is a constructor, the call is a prvalue of the
5834 // cv-unqualified version of the destination type whose return object
5835 // is initialized by the constructor. The call is used to
5836 // direct-initialize, according to the rules above, the object that
5837 // is the destination of the copy-initialization.
5838 // Therefore we need to do nothing further.
5839 //
5840 // FIXME: Mark this copy as extraneous.
5841 if (!S.getLangOpts().CPlusPlus17)
5842 Sequence.AddFinalCopy(DestType);
5843 else if (DestType.hasQualifiers())
5844 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5845 return;
5846 }
5847
5848 // Add the user-defined conversion step that calls the conversion function.
5849 QualType ConvType = Function->getCallResultType();
5850 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5851 HadMultipleCandidates);
5852
5853 if (ConvType->getAs<RecordType>()) {
5854 // The call is used to direct-initialize [...] the object that is the
5855 // destination of the copy-initialization.
5856 //
5857 // In C++17, this does not call a constructor if we enter /17.6.1:
5858 // - If the initializer expression is a prvalue and the cv-unqualified
5859 // version of the source type is the same as the class of the
5860 // destination [... do not make an extra copy]
5861 //
5862 // FIXME: Mark this copy as extraneous.
5863 if (!S.getLangOpts().CPlusPlus17 ||
5864 Function->getReturnType()->isReferenceType() ||
5865 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5866 Sequence.AddFinalCopy(DestType);
5867 else if (!S.Context.hasSameType(ConvType, DestType))
5868 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5869 return;
5870 }
5871
5872 // If the conversion following the call to the conversion function
5873 // is interesting, add it as a separate step.
5874 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5875 Best->FinalConversion.Third) {
5877 ICS.setStandard();
5878 ICS.Standard = Best->FinalConversion;
5879 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5880 }
5881}
5882
5883/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5884/// a function with a pointer return type contains a 'return false;' statement.
5885/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5886/// code using that header.
5887///
5888/// Work around this by treating 'return false;' as zero-initializing the result
5889/// if it's used in a pointer-returning function in a system header.
5891 const InitializedEntity &Entity,
5892 const Expr *Init) {
5893 return S.getLangOpts().CPlusPlus11 &&
5895 Entity.getType()->isPointerType() &&
5896 isa<CXXBoolLiteralExpr>(Init) &&
5897 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5898 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5899}
5900
5901/// The non-zero enum values here are indexes into diagnostic alternatives.
5903
5904/// Determines whether this expression is an acceptable ICR source.
5906 bool isAddressOf, bool &isWeakAccess) {
5907 // Skip parens.
5908 e = e->IgnoreParens();
5909
5910 // Skip address-of nodes.
5911 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5912 if (op->getOpcode() == UO_AddrOf)
5913 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5914 isWeakAccess);
5915
5916 // Skip certain casts.
5917 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5918 switch (ce->getCastKind()) {
5919 case CK_Dependent:
5920 case CK_BitCast:
5921 case CK_LValueBitCast:
5922 case CK_NoOp:
5923 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5924
5925 case CK_ArrayToPointerDecay:
5926 return IIK_nonscalar;
5927
5928 case CK_NullToPointer:
5929 return IIK_okay;
5930
5931 default:
5932 break;
5933 }
5934
5935 // If we have a declaration reference, it had better be a local variable.
5936 } else if (isa<DeclRefExpr>(e)) {
5937 // set isWeakAccess to true, to mean that there will be an implicit
5938 // load which requires a cleanup.
5940 isWeakAccess = true;
5941
5942 if (!isAddressOf) return IIK_nonlocal;
5943
5944 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5945 if (!var) return IIK_nonlocal;
5946
5947 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5948
5949 // If we have a conditional operator, check both sides.
5950 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5951 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5952 isWeakAccess))
5953 return iik;
5954
5955 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5956
5957 // These are never scalar.
5958 } else if (isa<ArraySubscriptExpr>(e)) {
5959 return IIK_nonscalar;
5960
5961 // Otherwise, it needs to be a null pointer constant.
5962 } else {
5965 }
5966
5967 return IIK_nonlocal;
5968}
5969
5970/// Check whether the given expression is a valid operand for an
5971/// indirect copy/restore.
5973 assert(src->isPRValue());
5974 bool isWeakAccess = false;
5975 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5976 // If isWeakAccess to true, there will be an implicit
5977 // load which requires a cleanup.
5978 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5980
5981 if (iik == IIK_okay) return;
5982
5983 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5984 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5985 << src->getSourceRange();
5986}
5987
5988/// Determine whether we have compatible array types for the
5989/// purposes of GNU by-copy array initialization.
5990static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5991 const ArrayType *Source) {
5992 // If the source and destination array types are equivalent, we're
5993 // done.
5994 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5995 return true;
5996
5997 // Make sure that the element types are the same.
5998 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5999 return false;
6000
6001 // The only mismatch we allow is when the destination is an
6002 // incomplete array type and the source is a constant array type.
6003 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6004}
6005
6007 InitializationSequence &Sequence,
6008 const InitializedEntity &Entity,
6009 Expr *Initializer) {
6010 bool ArrayDecay = false;
6011 QualType ArgType = Initializer->getType();
6012 QualType ArgPointee;
6013 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
6014 ArrayDecay = true;
6015 ArgPointee = ArgArrayType->getElementType();
6016 ArgType = S.Context.getPointerType(ArgPointee);
6017 }
6018
6019 // Handle write-back conversion.
6020 QualType ConvertedArgType;
6021 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
6022 ConvertedArgType))
6023 return false;
6024
6025 // We should copy unless we're passing to an argument explicitly
6026 // marked 'out'.
6027 bool ShouldCopy = true;
6028 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6029 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6030
6031 // Do we need an lvalue conversion?
6032 if (ArrayDecay || Initializer->isGLValue()) {
6034 ICS.setStandard();
6036
6037 QualType ResultType;
6038 if (ArrayDecay) {
6040 ResultType = S.Context.getPointerType(ArgPointee);
6041 } else {
6043 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6044 }
6045
6046 Sequence.AddConversionSequenceStep(ICS, ResultType);
6047 }
6048
6049 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6050 return true;
6051}
6052
6054 InitializationSequence &Sequence,
6055 QualType DestType,
6056 Expr *Initializer) {
6057 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6058 (!Initializer->isIntegerConstantExpr(S.Context) &&
6059 !Initializer->getType()->isSamplerT()))
6060 return false;
6061
6062 Sequence.AddOCLSamplerInitStep(DestType);
6063 return true;
6064}
6065
6067 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6068 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6069}
6070
6072 InitializationSequence &Sequence,
6073 QualType DestType,
6074 Expr *Initializer) {
6075 if (!S.getLangOpts().OpenCL)
6076 return false;
6077
6078 //
6079 // OpenCL 1.2 spec, s6.12.10
6080 //
6081 // The event argument can also be used to associate the
6082 // async_work_group_copy with a previous async copy allowing
6083 // an event to be shared by multiple async copies; otherwise
6084 // event should be zero.
6085 //
6086 if (DestType->isEventT() || DestType->isQueueT()) {
6088 return false;
6089
6090 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6091 return true;
6092 }
6093
6094 // We should allow zero initialization for all types defined in the
6095 // cl_intel_device_side_avc_motion_estimation extension, except
6096 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6098 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6099 DestType->isOCLIntelSubgroupAVCType()) {
6100 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6101 DestType->isOCLIntelSubgroupAVCMceResultType())
6102 return false;
6104 return false;
6105
6106 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6107 return true;
6108 }
6109
6110 return false;
6111}
6112
6114 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6115 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6116 : FailedOverloadResult(OR_Success),
6117 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6118 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6119 TreatUnavailableAsInvalid);
6120}
6121
6122/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6123/// address of that function, this returns true. Otherwise, it returns false.
6124static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6125 auto *DRE = dyn_cast<DeclRefExpr>(E);
6126 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6127 return false;
6128
6130 cast<FunctionDecl>(DRE->getDecl()));
6131}
6132
6133/// Determine whether we can perform an elementwise array copy for this kind
6134/// of entity.
6135static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6136 switch (Entity.getKind()) {
6138 // C++ [expr.prim.lambda]p24:
6139 // For array members, the array elements are direct-initialized in
6140 // increasing subscript order.
6141 return true;
6142
6144 // C++ [dcl.decomp]p1:
6145 // [...] each element is copy-initialized or direct-initialized from the
6146 // corresponding element of the assignment-expression [...]
6147 return isa<DecompositionDecl>(Entity.getDecl());
6148
6150 // C++ [class.copy.ctor]p14:
6151 // - if the member is an array, each element is direct-initialized with
6152 // the corresponding subobject of x
6153 return Entity.isImplicitMemberInitializer();
6154
6156 // All the above cases are intended to apply recursively, even though none
6157 // of them actually say that.
6158 if (auto *E = Entity.getParent())
6159 return canPerformArrayCopy(*E);
6160 break;
6161
6162 default:
6163 break;
6164 }
6165
6166 return false;
6167}
6168
6170 const InitializedEntity &Entity,
6171 const InitializationKind &Kind,
6172 MultiExprArg Args,
6173 bool TopLevelOfInitList,
6174 bool TreatUnavailableAsInvalid) {
6175 ASTContext &Context = S.Context;
6176
6177 // Eliminate non-overload placeholder types in the arguments. We
6178 // need to do this before checking whether types are dependent
6179 // because lowering a pseudo-object expression might well give us
6180 // something of dependent type.
6181 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6182 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6183 // FIXME: should we be doing this here?
6184 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6185 if (result.isInvalid()) {
6187 return;
6188 }
6189 Args[I] = result.get();
6190 }
6191
6192 // C++0x [dcl.init]p16:
6193 // The semantics of initializers are as follows. The destination type is
6194 // the type of the object or reference being initialized and the source
6195 // type is the type of the initializer expression. The source type is not
6196 // defined when the initializer is a braced-init-list or when it is a
6197 // parenthesized list of expressions.
6198 QualType DestType = Entity.getType();
6199
6200 if (DestType->isDependentType() ||
6203 return;
6204 }
6205
6206 // Almost everything is a normal sequence.
6208
6209 QualType SourceType;
6210 Expr *Initializer = nullptr;
6211 if (Args.size() == 1) {
6212 Initializer = Args[0];
6213 if (S.getLangOpts().ObjC) {
6215 DestType, Initializer->getType(),
6216 Initializer) ||
6218 Args[0] = Initializer;
6219 }
6220 if (!isa<InitListExpr>(Initializer))
6221 SourceType = Initializer->getType();
6222 }
6223
6224 // - If the initializer is a (non-parenthesized) braced-init-list, the
6225 // object is list-initialized (8.5.4).
6226 if (Kind.getKind() != InitializationKind::IK_Direct) {
6227 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6228 TryListInitialization(S, Entity, Kind, InitList, *this,
6229 TreatUnavailableAsInvalid);
6230 return;
6231 }
6232 }
6233
6234 // - If the destination type is a reference type, see 8.5.3.
6235 if (DestType->isReferenceType()) {
6236 // C++0x [dcl.init.ref]p1:
6237 // A variable declared to be a T& or T&&, that is, "reference to type T"
6238 // (8.3.2), shall be initialized by an object, or function, of type T or
6239 // by an object that can be converted into a T.
6240 // (Therefore, multiple arguments are not permitted.)
6241 if (Args.size() != 1)
6243 // C++17 [dcl.init.ref]p5:
6244 // A reference [...] is initialized by an expression [...] as follows:
6245 // If the initializer is not an expression, presumably we should reject,
6246 // but the standard fails to actually say so.
6247 else if (isa<InitListExpr>(Args[0]))
6249 else
6250 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6251 TopLevelOfInitList);
6252 return;
6253 }
6254
6255 // - If the initializer is (), the object is value-initialized.
6256 if (Kind.getKind() == InitializationKind::IK_Value ||
6257 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6258 TryValueInitialization(S, Entity, Kind, *this);
6259 return;
6260 }
6261
6262 // Handle default initialization.
6263 if (Kind.getKind() == InitializationKind::IK_Default) {
6264 TryDefaultInitialization(S, Entity, Kind, *this);
6265 return;
6266 }
6267
6268 // - If the destination type is an array of characters, an array of
6269 // char16_t, an array of char32_t, or an array of wchar_t, and the
6270 // initializer is a string literal, see 8.5.2.
6271 // - Otherwise, if the destination type is an array, the program is
6272 // ill-formed.
6273 // - Except in HLSL, where non-decaying array parameters behave like
6274 // non-array types for initialization.
6275 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6276 const ArrayType *DestAT = Context.getAsArrayType(DestType);
6277 if (Initializer && isa<VariableArrayType>(DestAT)) {
6279 return;
6280 }
6281
6282 if (Initializer) {
6283 switch (IsStringInit(Initializer, DestAT, Context)) {
6284 case SIF_None:
6285 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6286 return;
6289 return;
6292 return;
6295 return;
6298 return;
6301 return;
6302 case SIF_Other:
6303 break;
6304 }
6305 }
6306
6307 // Some kinds of initialization permit an array to be initialized from
6308 // another array of the same type, and perform elementwise initialization.
6309 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6311 Entity.getType()) &&
6312 canPerformArrayCopy(Entity)) {
6313 // If source is a prvalue, use it directly.
6314 if (Initializer->isPRValue()) {
6315 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6316 return;
6317 }
6318
6319 // Emit element-at-a-time copy loop.
6320 InitializedEntity Element =
6322 QualType InitEltT =
6323 Context.getAsArrayType(Initializer->getType())->getElementType();
6324 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6325 Initializer->getValueKind(),
6326 Initializer->getObjectKind());
6327 Expr *OVEAsExpr = &OVE;
6328 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6329 TreatUnavailableAsInvalid);
6330 if (!Failed())
6331 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6332 return;
6333 }
6334
6335 // Note: as an GNU C extension, we allow initialization of an
6336 // array from a compound literal that creates an array of the same
6337 // type, so long as the initializer has no side effects.
6338 if (!S.getLangOpts().CPlusPlus && Initializer &&
6339 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6340 Initializer->getType()->isArrayType()) {
6341 const ArrayType *SourceAT
6342 = Context.getAsArrayType(Initializer->getType());
6343 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6345 else if (Initializer->HasSideEffects(S.Context))
6347 else {
6348 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6349 }
6350 }
6351 // Note: as a GNU C++ extension, we allow list-initialization of a
6352 // class member of array type from a parenthesized initializer list.
6353 else if (S.getLangOpts().CPlusPlus &&
6355 Initializer && isa<InitListExpr>(Initializer)) {
6356 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6357 *this, TreatUnavailableAsInvalid);
6359 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6360 Kind.getKind() == InitializationKind::IK_Direct)
6361 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6362 /*VerifyOnly=*/true);
6363 else if (DestAT->getElementType()->isCharType())
6365 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6367 else
6369
6370 return;
6371 }
6372
6373 // Determine whether we should consider writeback conversions for
6374 // Objective-C ARC.
6375 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6376 Entity.isParameterKind();
6377
6378 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6379 return;
6380
6381 // We're at the end of the line for C: it's either a write-back conversion
6382 // or it's a C assignment. There's no need to check anything else.
6383 if (!S.getLangOpts().CPlusPlus) {
6384 assert(Initializer && "Initializer must be non-null");
6385 // If allowed, check whether this is an Objective-C writeback conversion.
6386 if (allowObjCWritebackConversion &&
6387 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6388 return;
6389 }
6390
6391 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6392 return;
6393
6394 // Handle initialization in C
6395 AddCAssignmentStep(DestType);
6396 MaybeProduceObjCObject(S, *this, Entity);
6397 return;
6398 }
6399
6400 assert(S.getLangOpts().CPlusPlus);
6401
6402 // - If the destination type is a (possibly cv-qualified) class type:
6403 if (DestType->isRecordType()) {
6404 // - If the initialization is direct-initialization, or if it is
6405 // copy-initialization where the cv-unqualified version of the
6406 // source type is the same class as, or a derived class of, the
6407 // class of the destination, constructors are considered. [...]
6408 if (Kind.getKind() == InitializationKind::IK_Direct ||
6409 (Kind.getKind() == InitializationKind::IK_Copy &&
6410 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6411 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6412 SourceType, DestType))))) {
6413 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6414 *this);
6415
6416 // We fall back to the "no matching constructor" path if the
6417 // failed candidate set has functions other than the three default
6418 // constructors. For example, conversion function.
6419 if (const auto *RD =
6420 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6421 // In general, we should call isCompleteType for RD to check its
6422 // completeness, we don't call it here as it was already called in the
6423 // above TryConstructorInitialization.
6424 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6425 RD->isAggregate() && Failed() &&
6427 // Do not attempt paren list initialization if overload resolution
6428 // resolves to a deleted function .
6429 //
6430 // We may reach this condition if we have a union wrapping a class with
6431 // a non-trivial copy or move constructor and we call one of those two
6432 // constructors. The union is an aggregate, but the matched constructor
6433 // is implicitly deleted, so we need to prevent aggregate initialization
6434 // (otherwise, it'll attempt aggregate initialization by initializing
6435 // the first element with a reference to the union).
6438 S, Kind.getLocation(), Best);
6440 // C++20 [dcl.init] 17.6.2.2:
6441 // - Otherwise, if no constructor is viable, the destination type is
6442 // an
6443 // aggregate class, and the initializer is a parenthesized
6444 // expression-list.
6445 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6446 /*VerifyOnly=*/true);
6447 }
6448 }
6449 } else {
6450 // - Otherwise (i.e., for the remaining copy-initialization cases),
6451 // user-defined conversion sequences that can convert from the
6452 // source type to the destination type or (when a conversion
6453 // function is used) to a derived class thereof are enumerated as
6454 // described in 13.3.1.4, and the best one is chosen through
6455 // overload resolution (13.3).
6456 assert(Initializer && "Initializer must be non-null");
6457 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6458 TopLevelOfInitList);
6459 }
6460 return;
6461 }
6462
6463 assert(Args.size() >= 1 && "Zero-argument case handled above");
6464
6465 // For HLSL ext vector types we allow list initialization behavior for C++
6466 // constructor syntax. This is accomplished by converting initialization
6467 // arguments an InitListExpr late.
6468 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6469 (SourceType.isNull() ||
6470 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6471
6473 for (auto *Arg : Args) {
6474 if (Arg->getType()->isExtVectorType()) {
6475 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6476 unsigned Elm = VTy->getNumElements();
6477 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6478 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6479 Arg,
6481 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6482 Context.IntTy, SourceLocation()),
6483 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6484 SourceLocation()));
6485 }
6486 } else
6487 InitArgs.emplace_back(Arg);
6488 }
6489 InitListExpr *ILE = new (Context) InitListExpr(
6490 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6491 Args[0] = ILE;
6492 AddListInitializationStep(DestType);
6493 return;
6494 }
6495
6496 // The remaining cases all need a source type.
6497 if (Args.size() > 1) {
6499 return;
6500 } else if (isa<InitListExpr>(Args[0])) {
6502 return;
6503 }
6504
6505 // - Otherwise, if the source type is a (possibly cv-qualified) class
6506 // type, conversion functions are considered.
6507 if (!SourceType.isNull() && SourceType->isRecordType()) {
6508 assert(Initializer && "Initializer must be non-null");
6509 // For a conversion to _Atomic(T) from either T or a class type derived
6510 // from T, initialize the T object then convert to _Atomic type.
6511 bool NeedAtomicConversion = false;
6512 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6513 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6514 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6515 Atomic->getValueType())) {
6516 DestType = Atomic->getValueType();
6517 NeedAtomicConversion = true;
6518 }
6519 }
6520
6521 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6522 TopLevelOfInitList);
6523 MaybeProduceObjCObject(S, *this, Entity);
6524 if (!Failed() && NeedAtomicConversion)
6526 return;
6527 }
6528
6529 // - Otherwise, if the initialization is direct-initialization, the source
6530 // type is std::nullptr_t, and the destination type is bool, the initial
6531 // value of the object being initialized is false.
6532 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6533 DestType->isBooleanType() &&
6534 Kind.getKind() == InitializationKind::IK_Direct) {
6537 Initializer->isGLValue()),
6538 DestType);
6539 return;
6540 }
6541
6542 // - Otherwise, the initial value of the object being initialized is the
6543 // (possibly converted) value of the initializer expression. Standard
6544 // conversions (Clause 4) will be used, if necessary, to convert the
6545 // initializer expression to the cv-unqualified version of the
6546 // destination type; no user-defined conversions are considered.
6547
6549 = S.TryImplicitConversion(Initializer, DestType,
6550 /*SuppressUserConversions*/true,
6551 Sema::AllowedExplicit::None,
6552 /*InOverloadResolution*/ false,
6553 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6554 allowObjCWritebackConversion);
6555
6556 if (ICS.isStandard() &&
6558 // Objective-C ARC writeback conversion.
6559
6560 // We should copy unless we're passing to an argument explicitly
6561 // marked 'out'.
6562 bool ShouldCopy = true;
6563 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6564 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6565
6566 // If there was an lvalue adjustment, add it as a separate conversion.
6567 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6570 LvalueICS.setStandard();
6572 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6573 LvalueICS.Standard.First = ICS.Standard.First;
6574 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6575 }
6576
6577 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6578 } else if (ICS.isBad()) {
6579 DeclAccessPair dap;
6582 } else if (Initializer->getType() == Context.OverloadTy &&
6584 false, dap))
6586 else if (Initializer->getType()->isFunctionType() &&
6589 else
6591 } else {
6592 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6593
6594 MaybeProduceObjCObject(S, *this, Entity);
6595 }
6596}
6597
6599 for (auto &S : Steps)
6600 S.Destroy();
6601}
6602
6603//===----------------------------------------------------------------------===//
6604// Perform initialization
6605//===----------------------------------------------------------------------===//
6607getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6608 switch(Entity.getKind()) {
6614 return Sema::AA_Initializing;
6615
6617 if (Entity.getDecl() &&
6618 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6619 return Sema::AA_Sending;
6620
6621 return Sema::AA_Passing;
6622
6624 if (Entity.getDecl() &&
6625 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6626 return Sema::AA_Sending;
6627
6628 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6629
6631 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6632 return Sema::AA_Returning;
6633
6636 // FIXME: Can we tell apart casting vs. converting?
6637 return Sema::AA_Casting;
6638
6640 // This is really initialization, but refer to it as conversion for
6641 // consistency with CheckConvertedConstantExpression.
6642 return Sema::AA_Converting;
6643
6654 return Sema::AA_Initializing;
6655 }
6656
6657 llvm_unreachable("Invalid EntityKind!");
6658}
6659
6660/// Whether we should bind a created object as a temporary when
6661/// initializing the given entity.
6662static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6663 switch (Entity.getKind()) {
6681 return false;
6682
6688 return true;
6689 }
6690
6691 llvm_unreachable("missed an InitializedEntity kind?");
6692}
6693
6694/// Whether the given entity, when initialized with an object
6695/// created for that initialization, requires destruction.
6696static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6697 switch (Entity.getKind()) {
6708 return false;
6709
6722 return true;
6723 }
6724
6725 llvm_unreachable("missed an InitializedEntity kind?");
6726}
6727
6728/// Get the location at which initialization diagnostics should appear.
6730 Expr *Initializer) {
6731 switch (Entity.getKind()) {
6734 return Entity.getReturnLoc();
6735
6737 return Entity.getThrowLoc();
6738
6741 return Entity.getDecl()->getLocation();
6742
6744 return Entity.getCaptureLoc();
6745
6762 return Initializer->getBeginLoc();
6763 }
6764 llvm_unreachable("missed an InitializedEntity kind?");
6765}
6766
6767/// Make a (potentially elidable) temporary copy of the object
6768/// provided by the given initializer by calling the appropriate copy
6769/// constructor.
6770///
6771/// \param S The Sema object used for type-checking.
6772///
6773/// \param T The type of the temporary object, which must either be
6774/// the type of the initializer expression or a superclass thereof.
6775///
6776/// \param Entity The entity being initialized.
6777///
6778/// \param CurInit The initializer expression.
6779///
6780/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6781/// is permitted in C++03 (but not C++0x) when binding a reference to
6782/// an rvalue.
6783///
6784/// \returns An expression that copies the initializer expression into
6785/// a temporary object, or an error expression if a copy could not be
6786/// created.
6788 QualType T,
6789 const InitializedEntity &Entity,
6790 ExprResult CurInit,
6791 bool IsExtraneousCopy) {
6792 if (CurInit.isInvalid())
6793 return CurInit;
6794 // Determine which class type we're copying to.
6795 Expr *CurInitExpr = (Expr *)CurInit.get();
6796 CXXRecordDecl *Class = nullptr;
6797 if (const RecordType *Record = T->getAs<RecordType>())
6798 Class = cast<CXXRecordDecl>(Record->getDecl());
6799 if (!Class)
6800 return CurInit;
6801
6802 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6803
6804 // Make sure that the type we are copying is complete.
6805 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6806 return CurInit;
6807
6808 // Perform overload resolution using the class's constructors. Per
6809 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6810 // is direct-initialization.
6813
6816 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6817 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6818 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6819 /*RequireActualConstructor=*/false,
6820 /*SecondStepOfCopyInit=*/true)) {
6821 case OR_Success:
6822 break;
6823
6825 CandidateSet.NoteCandidates(
6827 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6828 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6829 : diag::err_temp_copy_no_viable)
6830 << (int)Entity.getKind() << CurInitExpr->getType()
6831 << CurInitExpr->getSourceRange()),
6832 S, OCD_AllCandidates, CurInitExpr);
6833 if (!IsExtraneousCopy || S.isSFINAEContext())
6834 return ExprError();
6835 return CurInit;
6836
6837 case OR_Ambiguous:
6838 CandidateSet.NoteCandidates(
6839 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6840 << (int)Entity.getKind()
6841 << CurInitExpr->getType()
6842 << CurInitExpr->getSourceRange()),
6843 S, OCD_AmbiguousCandidates, CurInitExpr);
6844 return ExprError();
6845
6846 case OR_Deleted:
6847 S.Diag(Loc, diag::err_temp_copy_deleted)
6848 << (int)Entity.getKind() << CurInitExpr->getType()
6849 << CurInitExpr->getSourceRange();
6850 S.NoteDeletedFunction(Best->Function);
6851 return ExprError();
6852 }
6853
6854 bool HadMultipleCandidates = CandidateSet.size() > 1;
6855
6856 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6857 SmallVector<Expr*, 8> ConstructorArgs;
6858 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6859
6860 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6861 IsExtraneousCopy);
6862
6863 if (IsExtraneousCopy) {
6864 // If this is a totally extraneous copy for C++03 reference
6865 // binding purposes, just return the original initialization
6866 // expression. We don't generate an (elided) copy operation here
6867 // because doing so would require us to pass down a flag to avoid
6868 // infinite recursion, where each step adds another extraneous,
6869 // elidable copy.
6870
6871 // Instantiate the default arguments of any extra parameters in
6872 // the selected copy constructor, as if we were going to create a
6873 // proper call to the copy constructor.
6874 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6875 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6876 if (S.RequireCompleteType(Loc, Parm->getType(),
6877 diag::err_call_incomplete_argument))
6878 break;
6879
6880 // Build the default argument expression; we don't actually care
6881 // if this succeeds or not, because this routine will complain
6882 // if there was a problem.
6883 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6884 }
6885
6886 return CurInitExpr;
6887 }
6888
6889 // Determine the arguments required to actually perform the
6890 // constructor call (we might have derived-to-base conversions, or
6891 // the copy constructor may have default arguments).
6892 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6893 ConstructorArgs))
6894 return ExprError();
6895
6896 // C++0x [class.copy]p32:
6897 // When certain criteria are met, an implementation is allowed to
6898 // omit the copy/move construction of a class object, even if the
6899 // copy/move constructor and/or destructor for the object have
6900 // side effects. [...]
6901 // - when a temporary class object that has not been bound to a
6902 // reference (12.2) would be copied/moved to a class object
6903 // with the same cv-unqualified type, the copy/move operation
6904 // can be omitted by constructing the temporary object
6905 // directly into the target of the omitted copy/move
6906 //
6907 // Note that the other three bullets are handled elsewhere. Copy
6908 // elision for return statements and throw expressions are handled as part
6909 // of constructor initialization, while copy elision for exception handlers
6910 // is handled by the run-time.
6911 //
6912 // FIXME: If the function parameter is not the same type as the temporary, we
6913 // should still be able to elide the copy, but we don't have a way to
6914 // represent in the AST how much should be elided in this case.
6915 bool Elidable =
6916 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6918 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6919 CurInitExpr->getType());
6920
6921 // Actually perform the constructor call.
6922 CurInit = S.BuildCXXConstructExpr(
6923 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
6924 HadMultipleCandidates,
6925 /*ListInit*/ false,
6926 /*StdInitListInit*/ false,
6927 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
6928
6929 // If we're supposed to bind temporaries, do so.
6930 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6931 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6932 return CurInit;
6933}
6934
6935/// Check whether elidable copy construction for binding a reference to
6936/// a temporary would have succeeded if we were building in C++98 mode, for
6937/// -Wc++98-compat.
6939 const InitializedEntity &Entity,
6940 Expr *CurInitExpr) {
6941 assert(S.getLangOpts().CPlusPlus11);
6942
6943 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6944 if (!Record)
6945 return;
6946
6947 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6948 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6949 return;
6950
6951 // Find constructors which would have been considered.
6954 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6955
6956 // Perform overload resolution.
6959 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6960 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6961 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6962 /*RequireActualConstructor=*/false,
6963 /*SecondStepOfCopyInit=*/true);
6964
6965 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6966 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6967 << CurInitExpr->getSourceRange();
6968
6969 switch (OR) {
6970 case OR_Success:
6971 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6972 Best->FoundDecl, Entity, Diag);
6973 // FIXME: Check default arguments as far as that's possible.
6974 break;
6975
6977 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6978 OCD_AllCandidates, CurInitExpr);
6979 break;
6980
6981 case OR_Ambiguous:
6982 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6983 OCD_AmbiguousCandidates, CurInitExpr);
6984 break;
6985
6986 case OR_Deleted:
6987 S.Diag(Loc, Diag);
6988 S.NoteDeletedFunction(Best->Function);
6989 break;
6990 }
6991}
6992
6993void InitializationSequence::PrintInitLocationNote(Sema &S,
6994 const InitializedEntity &Entity) {
6995 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6996 if (Entity.getDecl()->getLocation().isInvalid())
6997 return;
6998
6999 if (Entity.getDecl()->getDeclName())
7000 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7001 << Entity.getDecl()->getDeclName();
7002 else
7003 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7004 }
7005 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7006 Entity.getMethodDecl())
7007 S.Diag(Entity.getMethodDecl()->getLocation(),
7008 diag::note_method_return_type_change)
7009 << Entity.getMethodDecl()->getDeclName();
7010}
7011
7012/// Returns true if the parameters describe a constructor initialization of
7013/// an explicit temporary object, e.g. "Point(x, y)".
7014static bool isExplicitTemporary(const InitializedEntity &Entity,
7015 const InitializationKind &Kind,
7016 unsigned NumArgs) {
7017 switch (Entity.getKind()) {
7021 break;
7022 default:
7023 return false;
7024 }
7025
7026 switch (Kind.getKind()) {
7028 return true;
7029 // FIXME: Hack to work around cast weirdness.
7032 return NumArgs != 1;
7033 default:
7034 return false;
7035 }
7036}
7037
7038static ExprResult
7040 const InitializedEntity &Entity,
7041 const InitializationKind &Kind,
7042 MultiExprArg Args,
7043 const InitializationSequence::Step& Step,
7044 bool &ConstructorInitRequiresZeroInit,
7045 bool IsListInitialization,
7046 bool IsStdInitListInitialization,
7047 SourceLocation LBraceLoc,
7048 SourceLocation RBraceLoc) {
7049 unsigned NumArgs = Args.size();
7050 CXXConstructorDecl *Constructor
7051 = cast<CXXConstructorDecl>(Step.Function.Function);
7052 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7053
7054 // Build a call to the selected constructor.
7055 SmallVector<Expr*, 8> ConstructorArgs;
7056 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7057 ? Kind.getEqualLoc()
7058 : Kind.getLocation();
7059
7060 if (Kind.getKind() == InitializationKind::IK_Default) {
7061 // Force even a trivial, implicit default constructor to be
7062 // semantically checked. We do this explicitly because we don't build
7063 // the definition for completely trivial constructors.
7064 assert(Constructor->getParent() && "No parent class for constructor.");
7065 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7066 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7067 S.runWithSufficientStackSpace(Loc, [&] {
7068 S.DefineImplicitDefaultConstructor(Loc, Constructor);
7069 });
7070 }
7071 }
7072
7073 ExprResult CurInit((Expr *)nullptr);
7074
7075 // C++ [over.match.copy]p1:
7076 // - When initializing a temporary to be bound to the first parameter
7077 // of a constructor that takes a reference to possibly cv-qualified
7078 // T as its first argument, called with a single argument in the
7079 // context of direct-initialization, explicit conversion functions
7080 // are also considered.
7081 bool AllowExplicitConv =
7082 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7085
7086 // A smart pointer constructed from a nullable pointer is nullable.
7087 if (NumArgs == 1 && !Kind.isExplicitCast())
7089 Entity.getType(), Args.front()->getType(), Kind.getLocation());
7090
7091 // Determine the arguments required to actually perform the constructor
7092 // call.
7093 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7094 ConstructorArgs, AllowExplicitConv,
7095 IsListInitialization))
7096 return ExprError();
7097
7098 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7099 // An explicitly-constructed temporary, e.g., X(1, 2).
7100 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7101 return ExprError();
7102
7103 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7104 if (!TSInfo)
7105 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7106 SourceRange ParenOrBraceRange =
7107 (Kind.getKind() == InitializationKind::IK_DirectList)
7108 ? SourceRange(LBraceLoc, RBraceLoc)
7109 : Kind.getParenOrBraceRange();
7110
7111 CXXConstructorDecl *CalleeDecl = Constructor;
7112 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7113 Step.Function.FoundDecl.getDecl())) {
7114 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7115 }
7116 S.MarkFunctionReferenced(Loc, CalleeDecl);
7117
7118 CurInit = S.CheckForImmediateInvocation(
7120 S.Context, CalleeDecl,
7121 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7122 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7123 IsListInitialization, IsStdInitListInitialization,
7124 ConstructorInitRequiresZeroInit),
7125 CalleeDecl);
7126 } else {
7128
7129 if (Entity.getKind() == InitializedEntity::EK_Base) {
7130 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7133 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7134 ConstructKind = CXXConstructionKind::Delegating;
7135 }
7136
7137 // Only get the parenthesis or brace range if it is a list initialization or
7138 // direct construction.
7139 SourceRange ParenOrBraceRange;
7140 if (IsListInitialization)
7141 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7142 else if (Kind.getKind() == InitializationKind::IK_Direct)
7143 ParenOrBraceRange = Kind.getParenOrBraceRange();
7144
7145 // If the entity allows NRVO, mark the construction as elidable
7146 // unconditionally.
7147 if (Entity.allowsNRVO())
7148 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7149 Step.Function.FoundDecl,
7150 Constructor, /*Elidable=*/true,
7151 ConstructorArgs,
7152 HadMultipleCandidates,
7153 IsListInitialization,
7154 IsStdInitListInitialization,
7155 ConstructorInitRequiresZeroInit,
7156 ConstructKind,
7157 ParenOrBraceRange);
7158 else
7159 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7160 Step.Function.FoundDecl,
7161 Constructor,
7162 ConstructorArgs,
7163 HadMultipleCandidates,
7164 IsListInitialization,
7165 IsStdInitListInitialization,
7166 ConstructorInitRequiresZeroInit,
7167 ConstructKind,
7168 ParenOrBraceRange);
7169 }
7170 if (CurInit.isInvalid())
7171 return ExprError();
7172
7173 // Only check access if all of that succeeded.
7174 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7175 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7176 return ExprError();
7177
7178 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7180 return ExprError();
7181
7182 if (shouldBindAsTemporary(Entity))
7183 CurInit = S.MaybeBindToTemporary(CurInit.get());
7184
7185 return CurInit;
7186}
7187
7188namespace {
7189enum LifetimeKind {
7190 /// The lifetime of a temporary bound to this entity ends at the end of the
7191 /// full-expression, and that's (probably) fine.
7192 LK_FullExpression,
7193
7194 /// The lifetime of a temporary bound to this entity is extended to the
7195 /// lifeitme of the entity itself.
7196 LK_Extended,
7197
7198 /// The lifetime of a temporary bound to this entity probably ends too soon,
7199 /// because the entity is allocated in a new-expression.
7200 LK_New,
7201
7202 /// The lifetime of a temporary bound to this entity ends too soon, because
7203 /// the entity is a return object.
7204 LK_Return,
7205
7206 /// The lifetime of a temporary bound to this entity ends too soon, because
7207 /// the entity is the result of a statement expression.
7208 LK_StmtExprResult,
7209
7210 /// This is a mem-initializer: if it would extend a temporary (other than via
7211 /// a default member initializer), the program is ill-formed.
7212 LK_MemInitializer,
7213};
7214using LifetimeResult =
7215 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7216}
7217
7218/// Determine the declaration which an initialized entity ultimately refers to,
7219/// for the purpose of lifetime-extending a temporary bound to a reference in
7220/// the initialization of \p Entity.
7221static LifetimeResult getEntityLifetime(
7222 const InitializedEntity *Entity,
7223 const InitializedEntity *InitField = nullptr) {
7224 // C++11 [class.temporary]p5:
7225 switch (Entity->getKind()) {
7227 // The temporary [...] persists for the lifetime of the reference
7228 return {Entity, LK_Extended};
7229
7231 // For subobjects, we look at the complete object.
7232 if (Entity->getParent())
7233 return getEntityLifetime(Entity->getParent(), Entity);
7234
7235 // except:
7236 // C++17 [class.base.init]p8:
7237 // A temporary expression bound to a reference member in a
7238 // mem-initializer is ill-formed.
7239 // C++17 [class.base.init]p11:
7240 // A temporary expression bound to a reference member from a
7241 // default member initializer is ill-formed.
7242 //
7243 // The context of p11 and its example suggest that it's only the use of a
7244 // default member initializer from a constructor that makes the program
7245 // ill-formed, not its mere existence, and that it can even be used by
7246 // aggregate initialization.
7247 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7248 : LK_MemInitializer};
7249
7251 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7252 // type.
7253 return {Entity, LK_Extended};
7254
7257 // -- A temporary bound to a reference parameter in a function call
7258 // persists until the completion of the full-expression containing
7259 // the call.
7260 return {nullptr, LK_FullExpression};
7261
7263 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7264 return {nullptr, LK_FullExpression};
7265
7267 // -- The lifetime of a temporary bound to the returned value in a
7268 // function return statement is not extended; the temporary is
7269 // destroyed at the end of the full-expression in the return statement.
7270 return {nullptr, LK_Return};
7271
7273 // FIXME: Should we lifetime-extend through the result of a statement
7274 // expression?
7275 return {nullptr, LK_StmtExprResult};
7276
7278 // -- A temporary bound to a reference in a new-initializer persists
7279 // until the completion of the full-expression containing the
7280 // new-initializer.
7281 return {nullptr, LK_New};
7282
7286 // We don't yet know the storage duration of the surrounding temporary.
7287 // Assume it's got full-expression duration for now, it will patch up our
7288 // storage duration if that's not correct.
7289 return {nullptr, LK_FullExpression};
7290
7292 // For subobjects, we look at the complete object.
7293 return getEntityLifetime(Entity->getParent(), InitField);
7294
7296 // For subobjects, we look at the complete object.
7297 if (Entity->getParent())
7298 return getEntityLifetime(Entity->getParent(), InitField);
7299 return {InitField, LK_MemInitializer};
7300
7302 // We can reach this case for aggregate initialization in a constructor:
7303 // struct A { int &&r; };
7304 // struct B : A { B() : A{0} {} };
7305 // In this case, use the outermost field decl as the context.
7306 return {InitField, LK_MemInitializer};
7307
7313 return {nullptr, LK_FullExpression};
7314
7316 // FIXME: Can we diagnose lifetime problems with exceptions?
7317 return {nullptr, LK_FullExpression};
7318
7320 // -- A temporary object bound to a reference element of an aggregate of
7321 // class type initialized from a parenthesized expression-list
7322 // [dcl.init, 9.3] persists until the completion of the full-expression
7323 // containing the expression-list.
7324 return {nullptr, LK_FullExpression};
7325 }
7326
7327 llvm_unreachable("unknown entity kind");
7328}
7329
7330namespace {
7331enum ReferenceKind {
7332 /// Lifetime would be extended by a reference binding to a temporary.
7333 RK_ReferenceBinding,
7334 /// Lifetime would be extended by a std::initializer_list object binding to
7335 /// its backing array.
7336 RK_StdInitializerList,
7337};
7338
7339/// A temporary or local variable. This will be one of:
7340/// * A MaterializeTemporaryExpr.
7341/// * A DeclRefExpr whose declaration is a local.
7342/// * An AddrLabelExpr.
7343/// * A BlockExpr for a block with captures.
7344using Local = Expr*;
7345
7346/// Expressions we stepped over when looking for the local state. Any steps
7347/// that would inhibit lifetime extension or take us out of subexpressions of
7348/// the initializer are included.
7349struct IndirectLocalPathEntry {
7350 enum EntryKind {
7351 DefaultInit,
7352 AddressOf,
7353 VarInit,
7354 LValToRVal,
7355 LifetimeBoundCall,
7356 TemporaryCopy,
7357 LambdaCaptureInit,
7358 GslReferenceInit,
7359 GslPointerInit
7360 } Kind;
7361 Expr *E;
7362 union {
7363 const Decl *D = nullptr;
7364 const LambdaCapture *Capture;
7365 };
7366 IndirectLocalPathEntry() {}
7367 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7368 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7369 : Kind(K), E(E), D(D) {}
7370 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7371 : Kind(K), E(E), Capture(Capture) {}
7372};
7373
7374using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7375
7376struct RevertToOldSizeRAII {
7377 IndirectLocalPath &Path;
7378 unsigned OldSize = Path.size();
7379 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7380 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7381};
7382
7383using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7384 ReferenceKind RK)>;
7385}
7386
7387static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7388 for (auto E : Path)
7389 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7390 return true;
7391 return false;
7392}
7393
7394static bool pathContainsInit(IndirectLocalPath &Path) {
7395 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7396 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7397 E.Kind == IndirectLocalPathEntry::VarInit;
7398 });
7399}
7400
7401static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7402 Expr *Init, LocalVisitor Visit,
7403 bool RevisitSubinits,
7404 bool EnableLifetimeWarnings);
7405
7406static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7407 Expr *Init, ReferenceKind RK,
7408 LocalVisitor Visit,
7409 bool EnableLifetimeWarnings);
7410
7411template <typename T> static bool isRecordWithAttr(QualType Type) {
7412 if (auto *RD = Type->getAsCXXRecordDecl())
7413 return RD->hasAttr<T>();
7414 return false;
7415}
7416
7417// Decl::isInStdNamespace will return false for iterators in some STL
7418// implementations due to them being defined in a namespace outside of the std
7419// namespace.
7420static bool isInStlNamespace(const Decl *D) {
7421 const DeclContext *DC = D->getDeclContext();
7422 if (!DC)
7423 return false;
7424 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7425 if (const IdentifierInfo *II = ND->getIdentifier()) {
7426 StringRef Name = II->getName();
7427 if (Name.size() >= 2 && Name.front() == '_' &&
7428 (Name[1] == '_' || isUppercase(Name[1])))
7429 return true;
7430 }
7431
7432 return DC->isStdNamespace();
7433}
7434
7436 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7437 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7438 return true;
7439 if (!isInStlNamespace(Callee->getParent()))
7440 return false;
7441 if (!isRecordWithAttr<PointerAttr>(
7442 Callee->getFunctionObjectParameterType()) &&
7443 !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7444 return false;
7445 if (Callee->getReturnType()->isPointerType() ||
7446 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7447 if (!Callee->getIdentifier())
7448 return false;
7449 return llvm::StringSwitch<bool>(Callee->getName())
7450 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7451 .Cases("end", "rend", "cend", "crend", true)
7452 .Cases("c_str", "data", "get", true)
7453 // Map and set types.
7454 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7455 .Default(false);
7456 } else if (Callee->getReturnType()->isReferenceType()) {
7457 if (!Callee->getIdentifier()) {
7458 auto OO = Callee->getOverloadedOperator();
7459 return OO == OverloadedOperatorKind::OO_Subscript ||
7460 OO == OverloadedOperatorKind::OO_Star;
7461 }
7462 return llvm::StringSwitch<bool>(Callee->getName())
7463 .Cases("front", "back", "at", "top", "value", true)
7464 .Default(false);
7465 }
7466 return false;
7467}
7468
7470 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7471 return false;
7472 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7473 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7474 return false;
7475 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7476 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7477 return false;
7478 if (FD->getReturnType()->isPointerType() ||
7479 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7480 return llvm::StringSwitch<bool>(FD->getName())
7481 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7482 .Cases("end", "rend", "cend", "crend", true)
7483 .Case("data", true)
7484 .Default(false);
7485 } else if (FD->getReturnType()->isReferenceType()) {
7486 return llvm::StringSwitch<bool>(FD->getName())
7487 .Cases("get", "any_cast", true)
7488 .Default(false);
7489 }
7490 return false;
7491}
7492
7493static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7494 LocalVisitor Visit) {
7495 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7496 // We are not interested in the temporary base objects of gsl Pointers:
7497 // Temp().ptr; // Here ptr might not dangle.
7498 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7499 return;
7500 // Once we initialized a value with a reference, it can no longer dangle.
7501 if (!Value) {
7502 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7503 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7504 continue;
7505 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7506 return;
7507 break;
7508 }
7509 }
7510 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7511 : IndirectLocalPathEntry::GslReferenceInit,
7512 Arg, D});
7513 if (Arg->isGLValue())
7514 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7515 Visit,
7516 /*EnableLifetimeWarnings=*/true);
7517 else
7518 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7519 /*EnableLifetimeWarnings=*/true);
7520 Path.pop_back();
7521 };
7522
7523 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7524 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7525 if (MD && shouldTrackImplicitObjectArg(MD))
7526 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7527 !MD->getReturnType()->isReferenceType());
7528 return;
7529 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7530 FunctionDecl *Callee = OCE->getDirectCallee();
7531 if (Callee && Callee->isCXXInstanceMember() &&
7532 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7533 VisitPointerArg(Callee, OCE->getArg(0),
7534 !Callee->getReturnType()->isReferenceType());
7535 return;
7536 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7537 FunctionDecl *Callee = CE->getDirectCallee();
7538 if (Callee && shouldTrackFirstArgument(Callee))
7539 VisitPointerArg(Callee, CE->getArg(0),
7540 !Callee->getReturnType()->isReferenceType());
7541 return;
7542 }
7543
7544 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7545 const auto *Ctor = CCE->getConstructor();
7546 const CXXRecordDecl *RD = Ctor->getParent();
7547 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7548 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7549 }
7550}
7551
7553 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7554 if (!TSI)
7555 return false;
7556 // Don't declare this variable in the second operand of the for-statement;
7557 // GCC miscompiles that by ending its lifetime before evaluating the
7558 // third operand. See gcc.gnu.org/PR86769.
7560 for (TypeLoc TL = TSI->getTypeLoc();
7561 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7562 TL = ATL.getModifiedLoc()) {
7563 if (ATL.getAttrAs<LifetimeBoundAttr>())
7564 return true;
7565 }
7566
7567 // Assume that all assignment operators with a "normal" return type return
7568 // *this, that is, an lvalue reference that is the same type as the implicit
7569 // object parameter (or the LHS for a non-member operator$=).
7571 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7572 QualType RetT = FD->getReturnType();
7573 if (RetT->isLValueReferenceType()) {
7574 ASTContext &Ctx = FD->getASTContext();
7575 QualType LHST;
7576 auto *MD = dyn_cast<CXXMethodDecl>(FD);
7577 if (MD && MD->isCXXInstanceMember())
7578 LHST = Ctx.getLValueReferenceType(MD->getFunctionObjectParameterType());
7579 else
7580 LHST = MD->getParamDecl(0)->getType();
7581 if (Ctx.hasSameType(RetT, LHST))
7582 return true;
7583 }
7584 }
7585
7586 return false;
7587}
7588
7589static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7590 LocalVisitor Visit) {
7591 const FunctionDecl *Callee;
7592 ArrayRef<Expr*> Args;
7593
7594 if (auto *CE = dyn_cast<CallExpr>(Call)) {
7595 Callee = CE->getDirectCallee();
7596 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7597 } else {
7598 auto *CCE = cast<CXXConstructExpr>(Call);
7599 Callee = CCE->getConstructor();
7600 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7601 }
7602 if (!Callee)
7603 return;
7604
7605 Expr *ObjectArg = nullptr;
7606 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7607 ObjectArg = Args[0];
7608 Args = Args.slice(1);
7609 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7610 ObjectArg = MCE->getImplicitObjectArgument();
7611 }
7612
7613 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7614 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7615 if (Arg->isGLValue())
7616 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7617 Visit,
7618 /*EnableLifetimeWarnings=*/false);
7619 else
7620 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7621 /*EnableLifetimeWarnings=*/false);
7622 Path.pop_back();
7623 };
7624
7625 bool CheckCoroCall = false;
7626 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7627 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7628 RD->hasAttr<CoroReturnTypeAttr>() &&
7629 !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
7630 }
7631
7632 if (ObjectArg) {
7633 bool CheckCoroObjArg = CheckCoroCall;
7634 // Coroutine lambda objects with empty capture list are not lifetimebound.
7635 if (auto *LE = dyn_cast<LambdaExpr>(ObjectArg->IgnoreImplicit());
7636 LE && LE->captures().empty())
7637 CheckCoroObjArg = false;
7638 // Allow `get_return_object()` as the object param (__promise) is not
7639 // lifetimebound.
7640 if (Sema::CanBeGetReturnObject(Callee))
7641 CheckCoroObjArg = false;
7642 if (implicitObjectParamIsLifetimeBound(Callee) || CheckCoroObjArg)
7643 VisitLifetimeBoundArg(Callee, ObjectArg);
7644 }
7645
7646 for (unsigned I = 0,
7647 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7648 I != N; ++I) {
7649 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7650 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7651 }
7652}
7653
7654/// Visit the locals that would be reachable through a reference bound to the
7655/// glvalue expression \c Init.
7656static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7657 Expr *Init, ReferenceKind RK,
7658 LocalVisitor Visit,
7659 bool EnableLifetimeWarnings) {
7660 RevertToOldSizeRAII RAII(Path);
7661
7662 // Walk past any constructs which we can lifetime-extend across.
7663 Expr *Old;
7664 do {
7665 Old = Init;
7666
7667 if (auto *FE = dyn_cast<FullExpr>(Init))
7668 Init = FE->getSubExpr();
7669
7670 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7671 // If this is just redundant braces around an initializer, step over it.
7672 if (ILE->isTransparent())
7673 Init = ILE->getInit(0);
7674 }
7675
7676 // Step over any subobject adjustments; we may have a materialized
7677 // temporary inside them.
7678 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7679
7680 // Per current approach for DR1376, look through casts to reference type
7681 // when performing lifetime extension.
7682 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7683 if (CE->getSubExpr()->isGLValue())
7684 Init = CE->getSubExpr();
7685
7686 // Per the current approach for DR1299, look through array element access
7687 // on array glvalues when performing lifetime extension.
7688 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7689 Init = ASE->getBase();
7690 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7691 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7692 Init = ICE->getSubExpr();
7693 else
7694 // We can't lifetime extend through this but we might still find some
7695 // retained temporaries.
7696 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7697 EnableLifetimeWarnings);
7698 }
7699
7700 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7701 // constructor inherits one as an implicit mem-initializer.
7702 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7703 Path.push_back(
7704 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7705 Init = DIE->getExpr();
7706 }
7707 } while (Init != Old);
7708
7709 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7710 if (Visit(Path, Local(MTE), RK))
7711 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7712 EnableLifetimeWarnings);
7713 }
7714
7715 if (isa<CallExpr>(Init)) {
7716 if (EnableLifetimeWarnings)
7717 handleGslAnnotatedTypes(Path, Init, Visit);
7718 return visitLifetimeBoundArguments(Path, Init, Visit);
7719 }
7720
7721 switch (Init->getStmtClass()) {
7722 case Stmt::DeclRefExprClass: {
7723 // If we find the name of a local non-reference parameter, we could have a
7724 // lifetime problem.
7725 auto *DRE = cast<DeclRefExpr>(Init);
7726 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7727 if (VD && VD->hasLocalStorage() &&
7728 !DRE->refersToEnclosingVariableOrCapture()) {
7729 if (!VD->getType()->isReferenceType()) {
7730 Visit(Path, Local(DRE), RK);
7731 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7732 // The lifetime of a reference parameter is unknown; assume it's OK
7733 // for now.
7734 break;
7735 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7736 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7737 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7738 RK_ReferenceBinding, Visit,
7739 EnableLifetimeWarnings);
7740 }
7741 }
7742 break;
7743 }
7744
7745 case Stmt::UnaryOperatorClass: {
7746 // The only unary operator that make sense to handle here
7747 // is Deref. All others don't resolve to a "name." This includes
7748 // handling all sorts of rvalues passed to a unary operator.
7749 const UnaryOperator *U = cast<UnaryOperator>(Init);
7750 if (U->getOpcode() == UO_Deref)
7751 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7752 EnableLifetimeWarnings);
7753 break;
7754 }
7755
7756 case Stmt::ArraySectionExprClass: {
7758 cast<ArraySectionExpr>(Init)->getBase(),
7759 Visit, true, EnableLifetimeWarnings);
7760 break;
7761 }
7762
7763 case Stmt::ConditionalOperatorClass:
7764 case Stmt::BinaryConditionalOperatorClass: {
7765 auto *C = cast<AbstractConditionalOperator>(Init);
7766 if (!C->getTrueExpr()->getType()->isVoidType())
7767 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7768 EnableLifetimeWarnings);
7769 if (!C->getFalseExpr()->getType()->isVoidType())
7770 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7771 EnableLifetimeWarnings);
7772 break;
7773 }
7774
7775 case Stmt::CompoundLiteralExprClass: {
7776 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
7777 if (!CLE->isFileScope())
7778 Visit(Path, Local(CLE), RK);
7779 }
7780 break;
7781 }
7782
7783 // FIXME: Visit the left-hand side of an -> or ->*.
7784
7785 default:
7786 break;
7787 }
7788}
7789
7790/// Visit the locals that would be reachable through an object initialized by
7791/// the prvalue expression \c Init.
7792static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7793 Expr *Init, LocalVisitor Visit,
7794 bool RevisitSubinits,
7795 bool EnableLifetimeWarnings) {
7796 RevertToOldSizeRAII RAII(Path);
7797
7798 Expr *Old;
7799 do {
7800 Old = Init;
7801
7802 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7803 // constructor inherits one as an implicit mem-initializer.
7804 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7805 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7806 Init = DIE->getExpr();
7807 }
7808
7809 if (auto *FE = dyn_cast<FullExpr>(Init))
7810 Init = FE->getSubExpr();
7811
7812 // Dig out the expression which constructs the extended temporary.
7813 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7814
7815 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7816 Init = BTE->getSubExpr();
7817
7818 Init = Init->IgnoreParens();
7819
7820 // Step over value-preserving rvalue casts.
7821 if (auto *CE = dyn_cast<CastExpr>(Init)) {
7822 switch (CE->getCastKind()) {
7823 case CK_LValueToRValue:
7824 // If we can match the lvalue to a const object, we can look at its
7825 // initializer.
7826 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7828 Path, Init, RK_ReferenceBinding,
7829 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7830 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7831 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7832 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7833 !isVarOnPath(Path, VD)) {
7834 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7835 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7836 EnableLifetimeWarnings);
7837 }
7838 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7839 if (MTE->getType().isConstQualified())
7840 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7841 true, EnableLifetimeWarnings);
7842 }
7843 return false;
7844 }, EnableLifetimeWarnings);
7845
7846 // We assume that objects can be retained by pointers cast to integers,
7847 // but not if the integer is cast to floating-point type or to _Complex.
7848 // We assume that casts to 'bool' do not preserve enough information to
7849 // retain a local object.
7850 case CK_NoOp:
7851 case CK_BitCast:
7852 case CK_BaseToDerived:
7853 case CK_DerivedToBase:
7854 case CK_UncheckedDerivedToBase:
7855 case CK_Dynamic:
7856 case CK_ToUnion:
7857 case CK_UserDefinedConversion:
7858 case CK_ConstructorConversion:
7859 case CK_IntegralToPointer:
7860 case CK_PointerToIntegral:
7861 case CK_VectorSplat:
7862 case CK_IntegralCast:
7863 case CK_CPointerToObjCPointerCast:
7864 case CK_BlockPointerToObjCPointerCast:
7865 case CK_AnyPointerToBlockPointerCast:
7866 case CK_AddressSpaceConversion:
7867 break;
7868
7869 case CK_ArrayToPointerDecay:
7870 // Model array-to-pointer decay as taking the address of the array
7871 // lvalue.
7872 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7873 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7874 RK_ReferenceBinding, Visit,
7875 EnableLifetimeWarnings);
7876
7877 default:
7878 return;
7879 }
7880
7881 Init = CE->getSubExpr();
7882 }
7883 } while (Old != Init);
7884
7885 // C++17 [dcl.init.list]p6:
7886 // initializing an initializer_list object from the array extends the
7887 // lifetime of the array exactly like binding a reference to a temporary.
7888 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7889 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7890 RK_StdInitializerList, Visit,
7891 EnableLifetimeWarnings);
7892
7893 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7894 // We already visited the elements of this initializer list while
7895 // performing the initialization. Don't visit them again unless we've
7896 // changed the lifetime of the initialized entity.
7897 if (!RevisitSubinits)
7898 return;
7899
7900 if (ILE->isTransparent())
7901 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7902 RevisitSubinits,
7903 EnableLifetimeWarnings);
7904
7905 if (ILE->getType()->isArrayType()) {
7906 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7907 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7908 RevisitSubinits,
7909 EnableLifetimeWarnings);
7910 return;
7911 }
7912
7913 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7914 assert(RD->isAggregate() && "aggregate init on non-aggregate");
7915
7916 // If we lifetime-extend a braced initializer which is initializing an
7917 // aggregate, and that aggregate contains reference members which are
7918 // bound to temporaries, those temporaries are also lifetime-extended.
7919 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7922 RK_ReferenceBinding, Visit,
7923 EnableLifetimeWarnings);
7924 else {
7925 unsigned Index = 0;
7926 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7927 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7928 RevisitSubinits,
7929 EnableLifetimeWarnings);
7930 for (const auto *I : RD->fields()) {
7931 if (Index >= ILE->getNumInits())
7932 break;
7933 if (I->isUnnamedBitField())
7934 continue;
7935 Expr *SubInit = ILE->getInit(Index);
7936 if (I->getType()->isReferenceType())
7938 RK_ReferenceBinding, Visit,
7939 EnableLifetimeWarnings);
7940 else
7941 // This might be either aggregate-initialization of a member or
7942 // initialization of a std::initializer_list object. Regardless,
7943 // we should recursively lifetime-extend that initializer.
7944 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7945 RevisitSubinits,
7946 EnableLifetimeWarnings);
7947 ++Index;
7948 }
7949 }
7950 }
7951 return;
7952 }
7953
7954 // The lifetime of an init-capture is that of the closure object constructed
7955 // by a lambda-expression.
7956 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7957 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7958 for (Expr *E : LE->capture_inits()) {
7959 assert(CapI != LE->capture_end());
7960 const LambdaCapture &Cap = *CapI++;
7961 if (!E)
7962 continue;
7963 if (Cap.capturesVariable())
7964 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7965 if (E->isGLValue())
7966 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7967 Visit, EnableLifetimeWarnings);
7968 else
7969 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7970 EnableLifetimeWarnings);
7971 if (Cap.capturesVariable())
7972 Path.pop_back();
7973 }
7974 }
7975
7976 // Assume that a copy or move from a temporary references the same objects
7977 // that the temporary does.
7978 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7979 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7980 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7981 Expr *Arg = MTE->getSubExpr();
7982 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7983 CCE->getConstructor()});
7984 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7985 /*EnableLifetimeWarnings*/false);
7986 Path.pop_back();
7987 }
7988 }
7989 }
7990
7991 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7992 if (EnableLifetimeWarnings)
7993 handleGslAnnotatedTypes(Path, Init, Visit);
7994 return visitLifetimeBoundArguments(Path, Init, Visit);
7995 }
7996
7997 switch (Init->getStmtClass()) {
7998 case Stmt::UnaryOperatorClass: {
7999 auto *UO = cast<UnaryOperator>(Init);
8000 // If the initializer is the address of a local, we could have a lifetime
8001 // problem.
8002 if (UO->getOpcode() == UO_AddrOf) {
8003 // If this is &rvalue, then it's ill-formed and we have already diagnosed
8004 // it. Don't produce a redundant warning about the lifetime of the
8005 // temporary.
8006 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
8007 return;
8008
8009 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
8010 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
8011 RK_ReferenceBinding, Visit,
8012 EnableLifetimeWarnings);
8013 }
8014 break;
8015 }
8016
8017 case Stmt::BinaryOperatorClass: {
8018 // Handle pointer arithmetic.
8019 auto *BO = cast<BinaryOperator>(Init);
8020 BinaryOperatorKind BOK = BO->getOpcode();
8021 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
8022 break;
8023
8024 if (BO->getLHS()->getType()->isPointerType())
8025 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
8026 EnableLifetimeWarnings);
8027 else if (BO->getRHS()->getType()->isPointerType())
8028 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
8029 EnableLifetimeWarnings);
8030 break;
8031 }
8032
8033 case Stmt::ConditionalOperatorClass:
8034 case Stmt::BinaryConditionalOperatorClass: {
8035 auto *C = cast<AbstractConditionalOperator>(Init);
8036 // In C++, we can have a throw-expression operand, which has 'void' type
8037 // and isn't interesting from a lifetime perspective.
8038 if (!C->getTrueExpr()->getType()->isVoidType())
8039 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
8040 EnableLifetimeWarnings);
8041 if (!C->getFalseExpr()->getType()->isVoidType())
8042 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
8043 EnableLifetimeWarnings);
8044 break;
8045 }
8046
8047 case Stmt::BlockExprClass:
8048 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
8049 // This is a local block, whose lifetime is that of the function.
8050 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
8051 }
8052 break;
8053
8054 case Stmt::AddrLabelExprClass:
8055 // We want to warn if the address of a label would escape the function.
8056 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
8057 break;
8058
8059 default:
8060 break;
8061 }
8062}
8063
8064/// Whether a path to an object supports lifetime extension.
8066 /// Lifetime-extend along this path.
8068 /// We should lifetime-extend, but we don't because (due to technical
8069 /// limitations) we can't. This happens for default member initializers,
8070 /// which we don't clone for every use, so we don't have a unique
8071 /// MaterializeTemporaryExpr to update.
8073 /// Do not lifetime extend along this path.
8074 NoExtend
8076
8077/// Determine whether this is an indirect path to a temporary that we are
8078/// supposed to lifetime-extend along.
8079static PathLifetimeKind
8080shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8081 PathLifetimeKind Kind = PathLifetimeKind::Extend;
8082 for (auto Elem : Path) {
8083 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8084 Kind = PathLifetimeKind::ShouldExtend;
8085 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8086 return PathLifetimeKind::NoExtend;
8087 }
8088 return Kind;
8089}
8090
8091/// Find the range for the first interesting entry in the path at or after I.
8092static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8093 Expr *E) {
8094 for (unsigned N = Path.size(); I != N; ++I) {
8095 switch (Path[I].Kind) {
8096 case IndirectLocalPathEntry::AddressOf:
8097 case IndirectLocalPathEntry::LValToRVal:
8098 case IndirectLocalPathEntry::LifetimeBoundCall:
8099 case IndirectLocalPathEntry::TemporaryCopy:
8100 case IndirectLocalPathEntry::GslReferenceInit:
8101 case IndirectLocalPathEntry::GslPointerInit:
8102 // These exist primarily to mark the path as not permitting or
8103 // supporting lifetime extension.
8104 break;
8105
8106 case IndirectLocalPathEntry::VarInit:
8107 if (cast<VarDecl>(Path[I].D)->isImplicit())
8108 return SourceRange();
8109 [[fallthrough]];
8110 case IndirectLocalPathEntry::DefaultInit:
8111 return Path[I].E->getSourceRange();
8112
8113 case IndirectLocalPathEntry::LambdaCaptureInit:
8114 if (!Path[I].Capture->capturesVariable())
8115 continue;
8116 return Path[I].E->getSourceRange();
8117 }
8118 }
8119 return E->getSourceRange();
8120}
8121
8122static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8123 for (const auto &It : llvm::reverse(Path)) {
8124 if (It.Kind == IndirectLocalPathEntry::VarInit)
8125 continue;
8126 if (It.Kind == IndirectLocalPathEntry::AddressOf)
8127 continue;
8128 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8129 continue;
8130 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8131 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8132 }
8133 return false;
8134}
8135
8137 Expr *Init) {
8138 LifetimeResult LR = getEntityLifetime(&Entity);
8139 LifetimeKind LK = LR.getInt();
8140 const InitializedEntity *ExtendingEntity = LR.getPointer();
8141
8142 // If this entity doesn't have an interesting lifetime, don't bother looking
8143 // for temporaries within its initializer.
8144 if (LK == LK_FullExpression)
8145 return;
8146
8147 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8148 ReferenceKind RK) -> bool {
8149 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8150 SourceLocation DiagLoc = DiagRange.getBegin();
8151
8152 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8153
8154 bool IsGslPtrInitWithGslTempOwner = false;
8155 bool IsLocalGslOwner = false;
8157 if (isa<DeclRefExpr>(L)) {
8158 // We do not want to follow the references when returning a pointer originating
8159 // from a local owner to avoid the following false positive:
8160 // int &p = *localUniquePtr;
8161 // someContainer.add(std::move(localUniquePtr));
8162 // return p;
8163 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8164 if (pathContainsInit(Path) || !IsLocalGslOwner)
8165 return false;
8166 } else {
8167 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8168 isRecordWithAttr<OwnerAttr>(MTE->getType());
8169 // Skipping a chain of initializing gsl::Pointer annotated objects.
8170 // We are looking only for the final source to find out if it was
8171 // a local or temporary owner or the address of a local variable/param.
8172 if (!IsGslPtrInitWithGslTempOwner)
8173 return true;
8174 }
8175 }
8176
8177 switch (LK) {
8178 case LK_FullExpression:
8179 llvm_unreachable("already handled this");
8180
8181 case LK_Extended: {
8182 if (!MTE) {
8183 // The initialized entity has lifetime beyond the full-expression,
8184 // and the local entity does too, so don't warn.
8185 //
8186 // FIXME: We should consider warning if a static / thread storage
8187 // duration variable retains an automatic storage duration local.
8188 return false;
8189 }
8190
8191 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8192 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8193 return false;
8194 }
8195
8196 switch (shouldLifetimeExtendThroughPath(Path)) {
8197 case PathLifetimeKind::Extend:
8198 // Update the storage duration of the materialized temporary.
8199 // FIXME: Rebuild the expression instead of mutating it.
8200 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8201 ExtendingEntity->allocateManglingNumber());
8202 // Also visit the temporaries lifetime-extended by this initializer.
8203 return true;
8204
8205 case PathLifetimeKind::ShouldExtend:
8206 // We're supposed to lifetime-extend the temporary along this path (per
8207 // the resolution of DR1815), but we don't support that yet.
8208 //
8209 // FIXME: Properly handle this situation. Perhaps the easiest approach
8210 // would be to clone the initializer expression on each use that would
8211 // lifetime extend its temporaries.
8212 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8213 << RK << DiagRange;
8214 break;
8215
8216 case PathLifetimeKind::NoExtend:
8217 // If the path goes through the initialization of a variable or field,
8218 // it can't possibly reach a temporary created in this full-expression.
8219 // We will have already diagnosed any problems with the initializer.
8220 if (pathContainsInit(Path))
8221 return false;
8222
8223 Diag(DiagLoc, diag::warn_dangling_variable)
8224 << RK << !Entity.getParent()
8225 << ExtendingEntity->getDecl()->isImplicit()
8226 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8227 break;
8228 }
8229 break;
8230 }
8231
8232 case LK_MemInitializer: {
8233 if (isa<MaterializeTemporaryExpr>(L)) {
8234 // Under C++ DR1696, if a mem-initializer (or a default member
8235 // initializer used by the absence of one) would lifetime-extend a
8236 // temporary, the program is ill-formed.
8237 if (auto *ExtendingDecl =
8238 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8239 if (IsGslPtrInitWithGslTempOwner) {
8240 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8241 << ExtendingDecl << DiagRange;
8242 Diag(ExtendingDecl->getLocation(),
8243 diag::note_ref_or_ptr_member_declared_here)
8244 << true;
8245 return false;
8246 }
8247 bool IsSubobjectMember = ExtendingEntity != &Entity;
8248 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8249 PathLifetimeKind::NoExtend
8250 ? diag::err_dangling_member
8251 : diag::warn_dangling_member)
8252 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8253 // Don't bother adding a note pointing to the field if we're inside
8254 // its default member initializer; our primary diagnostic points to
8255 // the same place in that case.
8256 if (Path.empty() ||
8257 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8258 Diag(ExtendingDecl->getLocation(),
8259 diag::note_lifetime_extending_member_declared_here)
8260 << RK << IsSubobjectMember;
8261 }
8262 } else {
8263 // We have a mem-initializer but no particular field within it; this
8264 // is either a base class or a delegating initializer directly
8265 // initializing the base-class from something that doesn't live long
8266 // enough.
8267 //
8268 // FIXME: Warn on this.
8269 return false;
8270 }
8271 } else {
8272 // Paths via a default initializer can only occur during error recovery
8273 // (there's no other way that a default initializer can refer to a
8274 // local). Don't produce a bogus warning on those cases.
8275 if (pathContainsInit(Path))
8276 return false;
8277
8278 // Suppress false positives for code like the one below:
8279 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8280 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8281 return false;
8282
8283 auto *DRE = dyn_cast<DeclRefExpr>(L);
8284 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8285 if (!VD) {
8286 // A member was initialized to a local block.
8287 // FIXME: Warn on this.
8288 return false;
8289 }
8290
8291 if (auto *Member =
8292 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8293 bool IsPointer = !Member->getType()->isReferenceType();
8294 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8295 : diag::warn_bind_ref_member_to_parameter)
8296 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8297 Diag(Member->getLocation(),
8298 diag::note_ref_or_ptr_member_declared_here)
8299 << (unsigned)IsPointer;
8300 }
8301 }
8302 break;
8303 }
8304
8305 case LK_New:
8306 if (isa<MaterializeTemporaryExpr>(L)) {
8307 if (IsGslPtrInitWithGslTempOwner)
8308 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8309 else
8310 Diag(DiagLoc, RK == RK_ReferenceBinding
8311 ? diag::warn_new_dangling_reference
8312 : diag::warn_new_dangling_initializer_list)
8313 << !Entity.getParent() << DiagRange;
8314 } else {
8315 // We can't determine if the allocation outlives the local declaration.
8316 return false;
8317 }
8318 break;
8319
8320 case LK_Return:
8321 case LK_StmtExprResult:
8322 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8323 // We can't determine if the local variable outlives the statement
8324 // expression.
8325 if (LK == LK_StmtExprResult)
8326 return false;
8327 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8328 << Entity.getType()->isReferenceType() << DRE->getDecl()
8329 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8330 } else if (isa<BlockExpr>(L)) {
8331 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8332 } else if (isa<AddrLabelExpr>(L)) {
8333 // Don't warn when returning a label from a statement expression.
8334 // Leaving the scope doesn't end its lifetime.
8335 if (LK == LK_StmtExprResult)
8336 return false;
8337 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8338 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(L)) {
8339 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8340 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 2
8341 << DiagRange;
8342 } else {
8343 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8344 << Entity.getType()->isReferenceType() << DiagRange;
8345 }
8346 break;
8347 }
8348
8349 for (unsigned I = 0; I != Path.size(); ++I) {
8350 auto Elem = Path[I];
8351
8352 switch (Elem.Kind) {
8353 case IndirectLocalPathEntry::AddressOf:
8354 case IndirectLocalPathEntry::LValToRVal:
8355 // These exist primarily to mark the path as not permitting or
8356 // supporting lifetime extension.
8357 break;
8358
8359 case IndirectLocalPathEntry::LifetimeBoundCall:
8360 case IndirectLocalPathEntry::TemporaryCopy:
8361 case IndirectLocalPathEntry::GslPointerInit:
8362 case IndirectLocalPathEntry::GslReferenceInit:
8363 // FIXME: Consider adding a note for these.
8364 break;
8365
8366 case IndirectLocalPathEntry::DefaultInit: {
8367 auto *FD = cast<FieldDecl>(Elem.D);
8368 Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8369 << FD << nextPathEntryRange(Path, I + 1, L);
8370 break;
8371 }
8372
8373 case IndirectLocalPathEntry::VarInit: {
8374 const VarDecl *VD = cast<VarDecl>(Elem.D);
8375 Diag(VD->getLocation(), diag::note_local_var_initializer)
8376 << VD->getType()->isReferenceType()
8377 << VD->isImplicit() << VD->getDeclName()
8378 << nextPathEntryRange(Path, I + 1, L);
8379 break;
8380 }
8381
8382 case IndirectLocalPathEntry::LambdaCaptureInit:
8383 if (!Elem.Capture->capturesVariable())
8384 break;
8385 // FIXME: We can't easily tell apart an init-capture from a nested
8386 // capture of an init-capture.
8387 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8388 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8389 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8390 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8391 << nextPathEntryRange(Path, I + 1, L);
8392 break;
8393 }
8394 }
8395
8396 // We didn't lifetime-extend, so don't go any further; we don't need more
8397 // warnings or errors on inner temporaries within this one's initializer.
8398 return false;
8399 };
8400
8401 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8402 diag::warn_dangling_lifetime_pointer, SourceLocation());
8404 if (Init->isGLValue())
8405 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8406 TemporaryVisitor,
8407 EnableLifetimeWarnings);
8408 else
8409 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8410 EnableLifetimeWarnings);
8411}
8412
8413static void DiagnoseNarrowingInInitList(Sema &S,
8414 const ImplicitConversionSequence &ICS,
8415 QualType PreNarrowingType,
8416 QualType EntityType,
8417 const Expr *PostInit);
8418
8419static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
8420 QualType ToType, Expr *Init);
8421
8422/// Provide warnings when std::move is used on construction.
8423static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8424 bool IsReturnStmt) {
8425 if (!InitExpr)
8426 return;
8427
8429 return;
8430
8431 QualType DestType = InitExpr->getType();
8432 if (!DestType->isRecordType())
8433 return;
8434
8435 unsigned DiagID = 0;
8436 if (IsReturnStmt) {
8437 const CXXConstructExpr *CCE =
8438 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8439 if (!CCE || CCE->getNumArgs() != 1)
8440 return;
8441
8443 return;
8444
8445 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8446 }
8447
8448 // Find the std::move call and get the argument.
8449 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8450 if (!CE || !CE->isCallToStdMove())
8451 return;
8452
8453 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8454
8455 if (IsReturnStmt) {
8456 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8457 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8458 return;
8459
8460 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8461 if (!VD || !VD->hasLocalStorage())
8462 return;
8463
8464 // __block variables are not moved implicitly.
8465 if (VD->hasAttr<BlocksAttr>())
8466 return;
8467
8468 QualType SourceType = VD->getType();
8469 if (!SourceType->isRecordType())
8470 return;
8471
8472 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8473 return;
8474 }
8475
8476 // If we're returning a function parameter, copy elision
8477 // is not possible.
8478 if (isa<ParmVarDecl>(VD))
8479 DiagID = diag::warn_redundant_move_on_return;
8480 else
8481 DiagID = diag::warn_pessimizing_move_on_return;
8482 } else {
8483 DiagID = diag::warn_pessimizing_move_on_initialization;
8484 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8485 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8486 return;
8487 }
8488
8489 S.Diag(CE->getBeginLoc(), DiagID);
8490
8491 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8492 // is within a macro.
8493 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8494 if (CallBegin.isMacroID())
8495 return;
8496 SourceLocation RParen = CE->getRParenLoc();
8497 if (RParen.isMacroID())
8498 return;
8499 SourceLocation LParen;
8500 SourceLocation ArgLoc = Arg->getBeginLoc();
8501
8502 // Special testing for the argument location. Since the fix-it needs the
8503 // location right before the argument, the argument location can be in a
8504 // macro only if it is at the beginning of the macro.
8505 while (ArgLoc.isMacroID() &&
8508 }
8509
8510 if (LParen.isMacroID())
8511 return;
8512
8513 LParen = ArgLoc.getLocWithOffset(-1);
8514
8515 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8516 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8517 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8518}
8519
8520static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8521 // Check to see if we are dereferencing a null pointer. If so, this is
8522 // undefined behavior, so warn about it. This only handles the pattern
8523 // "*null", which is a very syntactic check.
8524 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8525 if (UO->getOpcode() == UO_Deref &&
8526 UO->getSubExpr()->IgnoreParenCasts()->
8527 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8528 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8529 S.PDiag(diag::warn_binding_null_to_reference)
8530 << UO->getSubExpr()->getSourceRange());
8531 }
8532}
8533
8536 bool BoundToLvalueReference) {
8537 auto MTE = new (Context)
8538 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8539
8540 // Order an ExprWithCleanups for lifetime marks.
8541 //
8542 // TODO: It'll be good to have a single place to check the access of the
8543 // destructor and generate ExprWithCleanups for various uses. Currently these
8544 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8545 // but there may be a chance to merge them.
8548 auto &Record = ExprEvalContexts.back();
8549 Record.ForRangeLifetimeExtendTemps.push_back(MTE);
8550 }
8551 return MTE;
8552}
8553
8555 // In C++98, we don't want to implicitly create an xvalue.
8556 // FIXME: This means that AST consumers need to deal with "prvalues" that
8557 // denote materialized temporaries. Maybe we should add another ValueKind
8558 // for "xvalue pretending to be a prvalue" for C++98 support.
8559 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8560 return E;
8561
8562 // C++1z [conv.rval]/1: T shall be a complete type.
8563 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8564 // If so, we should check for a non-abstract class type here too.
8565 QualType T = E->getType();
8566 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8567 return ExprError();
8568
8569 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8570}
8571
8573 ExprValueKind VK,
8575
8576 CastKind CK = CK_NoOp;
8577
8578 if (VK == VK_PRValue) {
8579 auto PointeeTy = Ty->getPointeeType();
8580 auto ExprPointeeTy = E->getType()->getPointeeType();
8581 if (!PointeeTy.isNull() &&
8582 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8583 CK = CK_AddressSpaceConversion;
8584 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8585 CK = CK_AddressSpaceConversion;
8586 }
8587
8588 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8589}
8590
8592 const InitializedEntity &Entity,
8593 const InitializationKind &Kind,
8594 MultiExprArg Args,
8595 QualType *ResultType) {
8596 if (Failed()) {
8597 Diagnose(S, Entity, Kind, Args);
8598 return ExprError();
8599 }
8600 if (!ZeroInitializationFixit.empty()) {
8601 const Decl *D = Entity.getDecl();
8602 const auto *VD = dyn_cast_or_null<VarDecl>(D);
8603 QualType DestType = Entity.getType();
8604
8605 // The initialization would have succeeded with this fixit. Since the fixit
8606 // is on the error, we need to build a valid AST in this case, so this isn't
8607 // handled in the Failed() branch above.
8608 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8609 // Use a more useful diagnostic for constexpr variables.
8610 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8611 << VD
8612 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8613 ZeroInitializationFixit);
8614 } else {
8615 unsigned DiagID = diag::err_default_init_const;
8616 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8617 DiagID = diag::ext_default_init_const;
8618
8619 S.Diag(Kind.getLocation(), DiagID)
8620 << DestType << (bool)DestType->getAs<RecordType>()
8621 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8622 ZeroInitializationFixit);
8623 }
8624 }
8625
8626 if (getKind() == DependentSequence) {
8627 // If the declaration is a non-dependent, incomplete array type
8628 // that has an initializer, then its type will be completed once
8629 // the initializer is instantiated.
8630 if (ResultType && !Entity.getType()->isDependentType() &&
8631 Args.size() == 1) {
8632 QualType DeclType = Entity.getType();
8633 if (const IncompleteArrayType *ArrayT
8634 = S.Context.getAsIncompleteArrayType(DeclType)) {
8635 // FIXME: We don't currently have the ability to accurately
8636 // compute the length of an initializer list without
8637 // performing full type-checking of the initializer list
8638 // (since we have to determine where braces are implicitly
8639 // introduced and such). So, we fall back to making the array
8640 // type a dependently-sized array type with no specified
8641 // bound.
8642 if (isa<InitListExpr>((Expr *)Args[0])) {
8643 SourceRange Brackets;
8644
8645 // Scavange the location of the brackets from the entity, if we can.
8646 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8647 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8648 TypeLoc TL = TInfo->getTypeLoc();
8649 if (IncompleteArrayTypeLoc ArrayLoc =
8651 Brackets = ArrayLoc.getBracketsRange();
8652 }
8653 }
8654
8655 *ResultType
8656 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8657 /*NumElts=*/nullptr,
8658 ArrayT->getSizeModifier(),
8659 ArrayT->getIndexTypeCVRQualifiers(),
8660 Brackets);
8661 }
8662
8663 }
8664 }
8665 if (Kind.getKind() == InitializationKind::IK_Direct &&
8666 !Kind.isExplicitCast()) {
8667 // Rebuild the ParenListExpr.
8668 SourceRange ParenRange = Kind.getParenOrBraceRange();
8669 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8670 Args);
8671 }
8672 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8673 Kind.isExplicitCast() ||
8674 Kind.getKind() == InitializationKind::IK_DirectList);
8675 return ExprResult(Args[0]);
8676 }
8677
8678 // No steps means no initialization.
8679 if (Steps.empty())
8680 return ExprResult((Expr *)nullptr);
8681
8682 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8683 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8684 !Entity.isParamOrTemplateParamKind()) {
8685 // Produce a C++98 compatibility warning if we are initializing a reference
8686 // from an initializer list. For parameters, we produce a better warning
8687 // elsewhere.
8688 Expr *Init = Args[0];
8689 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8690 << Init->getSourceRange();
8691 }
8692
8693 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8694 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8695 // Produce a Microsoft compatibility warning when initializing from a
8696 // predefined expression since MSVC treats predefined expressions as string
8697 // literals.
8698 Expr *Init = Args[0];
8699 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8700 }
8701
8702 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8703 QualType ETy = Entity.getType();
8704 bool HasGlobalAS = ETy.hasAddressSpace() &&
8706
8707 if (S.getLangOpts().OpenCLVersion >= 200 &&
8708 ETy->isAtomicType() && !HasGlobalAS &&
8709 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8710 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8711 << 1
8712 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8713 return ExprError();
8714 }
8715
8716 QualType DestType = Entity.getType().getNonReferenceType();
8717 // FIXME: Ugly hack around the fact that Entity.getType() is not
8718 // the same as Entity.getDecl()->getType() in cases involving type merging,
8719 // and we want latter when it makes sense.
8720 if (ResultType)
8721 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8722 Entity.getType();
8723
8724 ExprResult CurInit((Expr *)nullptr);
8725 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8726
8727 // HLSL allows vector initialization to function like list initialization, but
8728 // use the syntax of a C++-like constructor.
8729 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8730 isa<InitListExpr>(Args[0]);
8731 (void)IsHLSLVectorInit;
8732
8733 // For initialization steps that start with a single initializer,
8734 // grab the only argument out the Args and place it into the "current"
8735 // initializer.
8736 switch (Steps.front().Kind) {
8741 case SK_BindReference:
8743 case SK_FinalCopy:
8745 case SK_UserConversion:
8754 case SK_UnwrapInitList:
8755 case SK_RewrapInitList:
8756 case SK_CAssignment:
8757 case SK_StringInit:
8759 case SK_ArrayLoopIndex:
8760 case SK_ArrayLoopInit:
8761 case SK_ArrayInit:
8762 case SK_GNUArrayInit:
8768 case SK_OCLSamplerInit:
8769 case SK_OCLZeroOpaqueType: {
8770 assert(Args.size() == 1 || IsHLSLVectorInit);
8771 CurInit = Args[0];
8772 if (!CurInit.get()) return ExprError();
8773 break;
8774 }
8775
8781 break;
8782 }
8783
8784 // Promote from an unevaluated context to an unevaluated list context in
8785 // C++11 list-initialization; we need to instantiate entities usable in
8786 // constant expressions here in order to perform narrowing checks =(
8789 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8790
8791 // C++ [class.abstract]p2:
8792 // no objects of an abstract class can be created except as subobjects
8793 // of a class derived from it
8794 auto checkAbstractType = [&](QualType T) -> bool {
8795 if (Entity.getKind() == InitializedEntity::EK_Base ||
8797 return false;
8798 return S.RequireNonAbstractType(Kind.getLocation(), T,
8799 diag::err_allocation_of_abstract_type);
8800 };
8801
8802 // Walk through the computed steps for the initialization sequence,
8803 // performing the specified conversions along the way.
8804 bool ConstructorInitRequiresZeroInit = false;
8805 for (step_iterator Step = step_begin(), StepEnd = step_end();
8806 Step != StepEnd; ++Step) {
8807 if (CurInit.isInvalid())
8808 return ExprError();
8809
8810 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8811
8812 switch (Step->Kind) {
8814 // Overload resolution determined which function invoke; update the
8815 // initializer to reflect that choice.
8817 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8818 return ExprError();
8819 CurInit = S.FixOverloadedFunctionReference(CurInit,
8822 // We might get back another placeholder expression if we resolved to a
8823 // builtin.
8824 if (!CurInit.isInvalid())
8825 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8826 break;
8827
8831 // We have a derived-to-base cast that produces either an rvalue or an
8832 // lvalue. Perform that cast.
8833
8834 CXXCastPath BasePath;
8835
8836 // Casts to inaccessible base classes are allowed with C-style casts.
8837 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8839 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8840 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8841 return ExprError();
8842
8843 ExprValueKind VK =
8845 ? VK_LValue
8847 : VK_PRValue);
8849 CK_DerivedToBase, CurInit.get(),
8850 &BasePath, VK, FPOptionsOverride());
8851 break;
8852 }
8853
8854 case SK_BindReference:
8855 // Reference binding does not have any corresponding ASTs.
8856
8857 // Check exception specifications
8858 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8859 return ExprError();
8860
8861 // We don't check for e.g. function pointers here, since address
8862 // availability checks should only occur when the function first decays
8863 // into a pointer or reference.
8864 if (CurInit.get()->getType()->isFunctionProtoType()) {
8865 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8866 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8867 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8868 DRE->getBeginLoc()))
8869 return ExprError();
8870 }
8871 }
8872 }
8873
8874 CheckForNullPointerDereference(S, CurInit.get());
8875 break;
8876
8878 // Make sure the "temporary" is actually an rvalue.
8879 assert(CurInit.get()->isPRValue() && "not a temporary");
8880
8881 // Check exception specifications
8882 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8883 return ExprError();
8884
8885 QualType MTETy = Step->Type;
8886
8887 // When this is an incomplete array type (such as when this is
8888 // initializing an array of unknown bounds from an init list), use THAT
8889 // type instead so that we propagate the array bounds.
8890 if (MTETy->isIncompleteArrayType() &&
8891 !CurInit.get()->getType()->isIncompleteArrayType() &&
8894 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8895 MTETy = CurInit.get()->getType();
8896
8897 // Materialize the temporary into memory.
8899 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8900 CurInit = MTE;
8901
8902 // If we're extending this temporary to automatic storage duration -- we
8903 // need to register its cleanup during the full-expression's cleanups.
8904 if (MTE->getStorageDuration() == SD_Automatic &&
8905 MTE->getType().isDestructedType())
8907 break;
8908 }
8909
8910 case SK_FinalCopy:
8911 if (checkAbstractType(Step->Type))
8912 return ExprError();
8913
8914 // If the overall initialization is initializing a temporary, we already
8915 // bound our argument if it was necessary to do so. If not (if we're
8916 // ultimately initializing a non-temporary), our argument needs to be
8917 // bound since it's initializing a function parameter.
8918 // FIXME: This is a mess. Rationalize temporary destruction.
8919 if (!shouldBindAsTemporary(Entity))
8920 CurInit = S.MaybeBindToTemporary(CurInit.get());
8921 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8922 /*IsExtraneousCopy=*/false);
8923 break;
8924
8926 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8927 /*IsExtraneousCopy=*/true);
8928 break;
8929
8930 case SK_UserConversion: {
8931 // We have a user-defined conversion that invokes either a constructor
8932 // or a conversion function.
8936 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8937 bool CreatedObject = false;
8938 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8939 // Build a call to the selected constructor.
8940 SmallVector<Expr*, 8> ConstructorArgs;
8941 SourceLocation Loc = CurInit.get()->getBeginLoc();
8942
8943 // Determine the arguments required to actually perform the constructor
8944 // call.
8945 Expr *Arg = CurInit.get();
8946 if (S.CompleteConstructorCall(Constructor, Step->Type,
8947 MultiExprArg(&Arg, 1), Loc,
8948 ConstructorArgs))
8949 return ExprError();
8950
8951 // Build an expression that constructs a temporary.
8952 CurInit = S.BuildCXXConstructExpr(
8953 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8954 HadMultipleCandidates,
8955 /*ListInit*/ false,
8956 /*StdInitListInit*/ false,
8957 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8958 if (CurInit.isInvalid())
8959 return ExprError();
8960
8961 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8962 Entity);
8963 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8964 return ExprError();
8965
8966 CastKind = CK_ConstructorConversion;
8967 CreatedObject = true;
8968 } else {
8969 // Build a call to the conversion function.
8970 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8971 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8972 FoundFn);
8973 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8974 return ExprError();
8975
8976 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8977 HadMultipleCandidates);
8978 if (CurInit.isInvalid())
8979 return ExprError();
8980
8981 CastKind = CK_UserDefinedConversion;
8982 CreatedObject = Conversion->getReturnType()->isRecordType();
8983 }
8984
8985 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8986 return ExprError();
8987
8988 CurInit = ImplicitCastExpr::Create(
8989 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8990 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8991
8992 if (shouldBindAsTemporary(Entity))
8993 // The overall entity is temporary, so this expression should be
8994 // destroyed at the end of its full-expression.
8995 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8996 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8997 // The object outlasts the full-expression, but we need to prepare for
8998 // a destructor being run on it.
8999 // FIXME: It makes no sense to do this here. This should happen
9000 // regardless of how we initialized the entity.
9001 QualType T = CurInit.get()->getType();
9002 if (const RecordType *Record = T->getAs<RecordType>()) {
9004 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
9006 S.PDiag(diag::err_access_dtor_temp) << T);
9008 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
9009 return ExprError();
9010 }
9011 }
9012 break;
9013 }
9014
9018 // Perform a qualification conversion; these can never go wrong.
9019 ExprValueKind VK =
9021 ? VK_LValue
9023 : VK_PRValue);
9024 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
9025 break;
9026 }
9027
9029 assert(CurInit.get()->isLValue() &&
9030 "function reference should be lvalue");
9031 CurInit =
9032 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
9033 break;
9034
9035 case SK_AtomicConversion: {
9036 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
9037 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9038 CK_NonAtomicToAtomic, VK_PRValue);
9039 break;
9040 }
9041
9044 if (const auto *FromPtrType =
9045 CurInit.get()->getType()->getAs<PointerType>()) {
9046 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
9047 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9048 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9049 // Do not check static casts here because they are checked earlier
9050 // in Sema::ActOnCXXNamedCast()
9051 if (!Kind.isStaticCast()) {
9052 S.Diag(CurInit.get()->getExprLoc(),
9053 diag::warn_noderef_to_dereferenceable_pointer)
9054 << CurInit.get()->getSourceRange();
9055 }
9056 }
9057 }
9058 }
9059
9061 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
9062 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
9063 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
9065 ExprResult CurInitExprRes =
9066 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
9067 getAssignmentAction(Entity), CCK);
9068 if (CurInitExprRes.isInvalid())
9069 return ExprError();
9070
9072
9073 CurInit = CurInitExprRes;
9074
9076 S.getLangOpts().CPlusPlus)
9077 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9078 CurInit.get());
9079
9080 break;
9081 }
9082
9083 case SK_ListInitialization: {
9084 if (checkAbstractType(Step->Type))
9085 return ExprError();
9086
9087 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9088 // If we're not initializing the top-level entity, we need to create an
9089 // InitializeTemporary entity for our target type.
9090 QualType Ty = Step->Type;
9091 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9093 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9094 InitListChecker PerformInitList(S, InitEntity,
9095 InitList, Ty, /*VerifyOnly=*/false,
9096 /*TreatUnavailableAsInvalid=*/false);
9097 if (PerformInitList.HadError())
9098 return ExprError();
9099
9100 // Hack: We must update *ResultType if available in order to set the
9101 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9102 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9103 if (ResultType &&
9104 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9105 if ((*ResultType)->isRValueReferenceType())
9107 else if ((*ResultType)->isLValueReferenceType())
9109 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9110 *ResultType = Ty;
9111 }
9112
9113 InitListExpr *StructuredInitList =
9114 PerformInitList.getFullyStructuredList();
9115 CurInit.get();
9116 CurInit = shouldBindAsTemporary(InitEntity)
9117 ? S.MaybeBindToTemporary(StructuredInitList)
9118 : StructuredInitList;
9119 break;
9120 }
9121
9123 if (checkAbstractType(Step->Type))
9124 return ExprError();
9125
9126 // When an initializer list is passed for a parameter of type "reference
9127 // to object", we don't get an EK_Temporary entity, but instead an
9128 // EK_Parameter entity with reference type.
9129 // FIXME: This is a hack. What we really should do is create a user
9130 // conversion step for this case, but this makes it considerably more
9131 // complicated. For now, this will do.
9133 Entity.getType().getNonReferenceType());
9134 bool UseTemporary = Entity.getType()->isReferenceType();
9135 assert(Args.size() == 1 && "expected a single argument for list init");
9136 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9137 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9138 << InitList->getSourceRange();
9139 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9140 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9141 Entity,
9142 Kind, Arg, *Step,
9143 ConstructorInitRequiresZeroInit,
9144 /*IsListInitialization*/true,
9145 /*IsStdInitListInit*/false,
9146 InitList->getLBraceLoc(),
9147 InitList->getRBraceLoc());
9148 break;
9149 }
9150
9151 case SK_UnwrapInitList:
9152 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9153 break;
9154
9155 case SK_RewrapInitList: {
9156 Expr *E = CurInit.get();
9158 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9159 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9160 ILE->setSyntacticForm(Syntactic);
9161 ILE->setType(E->getType());
9162 ILE->setValueKind(E->getValueKind());
9163 CurInit = ILE;
9164 break;
9165 }
9166
9169 if (checkAbstractType(Step->Type))
9170 return ExprError();
9171
9172 // When an initializer list is passed for a parameter of type "reference
9173 // to object", we don't get an EK_Temporary entity, but instead an
9174 // EK_Parameter entity with reference type.
9175 // FIXME: This is a hack. What we really should do is create a user
9176 // conversion step for this case, but this makes it considerably more
9177 // complicated. For now, this will do.
9179 Entity.getType().getNonReferenceType());
9180 bool UseTemporary = Entity.getType()->isReferenceType();
9181 bool IsStdInitListInit =
9183 Expr *Source = CurInit.get();
9184 SourceRange Range = Kind.hasParenOrBraceRange()
9185 ? Kind.getParenOrBraceRange()
9186 : SourceRange();
9188 S, UseTemporary ? TempEntity : Entity, Kind,
9189 Source ? MultiExprArg(Source) : Args, *Step,
9190 ConstructorInitRequiresZeroInit,
9191 /*IsListInitialization*/ IsStdInitListInit,
9192 /*IsStdInitListInitialization*/ IsStdInitListInit,
9193 /*LBraceLoc*/ Range.getBegin(),
9194 /*RBraceLoc*/ Range.getEnd());
9195 break;
9196 }
9197
9198 case SK_ZeroInitialization: {
9199 step_iterator NextStep = Step;
9200 ++NextStep;
9201 if (NextStep != StepEnd &&
9202 (NextStep->Kind == SK_ConstructorInitialization ||
9203 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9204 // The need for zero-initialization is recorded directly into
9205 // the call to the object's constructor within the next step.
9206 ConstructorInitRequiresZeroInit = true;
9207 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9208 S.getLangOpts().CPlusPlus &&
9209 !Kind.isImplicitValueInit()) {
9210 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9211 if (!TSInfo)
9213 Kind.getRange().getBegin());
9214
9215 CurInit = new (S.Context) CXXScalarValueInitExpr(
9216 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9217 Kind.getRange().getEnd());
9218 } else {
9219 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9220 }
9221 break;
9222 }
9223
9224 case SK_CAssignment: {
9225 QualType SourceType = CurInit.get()->getType();
9226
9227 // Save off the initial CurInit in case we need to emit a diagnostic
9228 ExprResult InitialCurInit = CurInit;
9229 ExprResult Result = CurInit;
9233 if (Result.isInvalid())
9234 return ExprError();
9235 CurInit = Result;
9236
9237 // If this is a call, allow conversion to a transparent union.
9238 ExprResult CurInitExprRes = CurInit;
9239 if (ConvTy != Sema::Compatible &&
9240 Entity.isParameterKind() &&
9243 ConvTy = Sema::Compatible;
9244 if (CurInitExprRes.isInvalid())
9245 return ExprError();
9246 CurInit = CurInitExprRes;
9247
9248 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
9249 CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
9250 CurInit.get());
9251
9252 // C23 6.7.1p6: If an object or subobject declared with storage-class
9253 // specifier constexpr has pointer, integer, or arithmetic type, any
9254 // explicit initializer value for it shall be null, an integer
9255 // constant expression, or an arithmetic constant expression,
9256 // respectively.
9258 if (Entity.getType()->getAs<PointerType>() &&
9259 CurInit.get()->EvaluateAsRValue(ER, S.Context) &&
9260 !ER.Val.isNullPointer()) {
9261 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
9262 }
9263 }
9264
9265 bool Complained;
9266 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9267 Step->Type, SourceType,
9268 InitialCurInit.get(),
9269 getAssignmentAction(Entity, true),
9270 &Complained)) {
9271 PrintInitLocationNote(S, Entity);
9272 return ExprError();
9273 } else if (Complained)
9274 PrintInitLocationNote(S, Entity);
9275 break;
9276 }
9277
9278 case SK_StringInit: {
9279 QualType Ty = Step->Type;
9280 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9281 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9282 S.Context.getAsArrayType(Ty), S,
9283 S.getLangOpts().C23 &&
9285 break;
9286 }
9287
9289 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9290 CK_ObjCObjectLValueCast,
9291 CurInit.get()->getValueKind());
9292 break;
9293
9294 case SK_ArrayLoopIndex: {
9295 Expr *Cur = CurInit.get();
9296 Expr *BaseExpr = new (S.Context)
9297 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9298 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9299 Expr *IndexExpr =
9302 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9303 ArrayLoopCommonExprs.push_back(BaseExpr);
9304 break;
9305 }
9306
9307 case SK_ArrayLoopInit: {
9308 assert(!ArrayLoopCommonExprs.empty() &&
9309 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9310 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9311 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9312 CurInit.get());
9313 break;
9314 }
9315
9316 case SK_GNUArrayInit:
9317 // Okay: we checked everything before creating this step. Note that
9318 // this is a GNU extension.
9319 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9320 << Step->Type << CurInit.get()->getType()
9321 << CurInit.get()->getSourceRange();
9323 [[fallthrough]];
9324 case SK_ArrayInit:
9325 // If the destination type is an incomplete array type, update the
9326 // type accordingly.
9327 if (ResultType) {
9328 if (const IncompleteArrayType *IncompleteDest
9330 if (const ConstantArrayType *ConstantSource
9331 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9332 *ResultType = S.Context.getConstantArrayType(
9333 IncompleteDest->getElementType(), ConstantSource->getSize(),
9334 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9335 }
9336 }
9337 }
9338 break;
9339
9341 // Okay: we checked everything before creating this step. Note that
9342 // this is a GNU extension.
9343 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9344 << CurInit.get()->getSourceRange();
9345 break;
9346
9349 checkIndirectCopyRestoreSource(S, CurInit.get());
9350 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9351 CurInit.get(), Step->Type,
9353 break;
9354
9356 CurInit = ImplicitCastExpr::Create(
9357 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9359 break;
9360
9361 case SK_StdInitializerList: {
9362 S.Diag(CurInit.get()->getExprLoc(),
9363 diag::warn_cxx98_compat_initializer_list_init)
9364 << CurInit.get()->getSourceRange();
9365
9366 // Materialize the temporary into memory.
9368 CurInit.get()->getType(), CurInit.get(),
9369 /*BoundToLvalueReference=*/false);
9370
9371 // Wrap it in a construction of a std::initializer_list<T>.
9372 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9373
9374 // Bind the result, in case the library has given initializer_list a
9375 // non-trivial destructor.
9376 if (shouldBindAsTemporary(Entity))
9377 CurInit = S.MaybeBindToTemporary(CurInit.get());
9378 break;
9379 }
9380
9381 case SK_OCLSamplerInit: {
9382 // Sampler initialization have 5 cases:
9383 // 1. function argument passing
9384 // 1a. argument is a file-scope variable
9385 // 1b. argument is a function-scope variable
9386 // 1c. argument is one of caller function's parameters
9387 // 2. variable initialization
9388 // 2a. initializing a file-scope variable
9389 // 2b. initializing a function-scope variable
9390 //
9391 // For file-scope variables, since they cannot be initialized by function
9392 // call of __translate_sampler_initializer in LLVM IR, their references
9393 // need to be replaced by a cast from their literal initializers to
9394 // sampler type. Since sampler variables can only be used in function
9395 // calls as arguments, we only need to replace them when handling the
9396 // argument passing.
9397 assert(Step->Type->isSamplerT() &&
9398 "Sampler initialization on non-sampler type.");
9399 Expr *Init = CurInit.get()->IgnoreParens();
9400 QualType SourceType = Init->getType();
9401 // Case 1
9402 if (Entity.isParameterKind()) {
9403 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9404 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9405 << SourceType;
9406 break;
9407 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9408 auto Var = cast<VarDecl>(DRE->getDecl());
9409 // Case 1b and 1c
9410 // No cast from integer to sampler is needed.
9411 if (!Var->hasGlobalStorage()) {
9412 CurInit = ImplicitCastExpr::Create(
9413 S.Context, Step->Type, CK_LValueToRValue, Init,
9414 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9415 break;
9416 }
9417 // Case 1a
9418 // For function call with a file-scope sampler variable as argument,
9419 // get the integer literal.
9420 // Do not diagnose if the file-scope variable does not have initializer
9421 // since this has already been diagnosed when parsing the variable
9422 // declaration.
9423 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9424 break;
9425 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9426 Var->getInit()))->getSubExpr();
9427 SourceType = Init->getType();
9428 }
9429 } else {
9430 // Case 2
9431 // Check initializer is 32 bit integer constant.
9432 // If the initializer is taken from global variable, do not diagnose since
9433 // this has already been done when parsing the variable declaration.
9434 if (!Init->isConstantInitializer(S.Context, false))
9435 break;
9436
9437 if (!SourceType->isIntegerType() ||
9438 32 != S.Context.getIntWidth(SourceType)) {
9439 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9440 << SourceType;
9441 break;
9442 }
9443
9444 Expr::EvalResult EVResult;
9445 Init->EvaluateAsInt(EVResult, S.Context);
9446 llvm::APSInt Result = EVResult.Val.getInt();
9447 const uint64_t SamplerValue = Result.getLimitedValue();
9448 // 32-bit value of sampler's initializer is interpreted as
9449 // bit-field with the following structure:
9450 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9451 // |31 6|5 4|3 1| 0|
9452 // This structure corresponds to enum values of sampler properties
9453 // defined in SPIR spec v1.2 and also opencl-c.h
9454 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9455 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9456 if (FilterMode != 1 && FilterMode != 2 &&
9458 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9459 S.Diag(Kind.getLocation(),
9460 diag::warn_sampler_initializer_invalid_bits)
9461 << "Filter Mode";
9462 if (AddressingMode > 4)
9463 S.Diag(Kind.getLocation(),
9464 diag::warn_sampler_initializer_invalid_bits)
9465 << "Addressing Mode";
9466 }
9467
9468 // Cases 1a, 2a and 2b
9469 // Insert cast from integer to sampler.
9471 CK_IntToOCLSampler);
9472 break;
9473 }
9474 case SK_OCLZeroOpaqueType: {
9475 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9477 "Wrong type for initialization of OpenCL opaque type.");
9478
9479 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9480 CK_ZeroToOCLOpaqueType,
9481 CurInit.get()->getValueKind());
9482 break;
9483 }
9485 CurInit = nullptr;
9486 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9487 /*VerifyOnly=*/false, &CurInit);
9488 if (CurInit.get() && ResultType)
9489 *ResultType = CurInit.get()->getType();
9490 if (shouldBindAsTemporary(Entity))
9491 CurInit = S.MaybeBindToTemporary(CurInit.get());
9492 break;
9493 }
9494 }
9495 }
9496
9497 Expr *Init = CurInit.get();
9498 if (!Init)
9499 return ExprError();
9500
9501 // Check whether the initializer has a shorter lifetime than the initialized
9502 // entity, and if not, either lifetime-extend or warn as appropriate.
9503 S.checkInitializerLifetime(Entity, Init);
9504
9505 // Diagnose non-fatal problems with the completed initialization.
9506 if (InitializedEntity::EntityKind EK = Entity.getKind();
9509 cast<FieldDecl>(Entity.getDecl())->isBitField())
9510 S.CheckBitFieldInitialization(Kind.getLocation(),
9511 cast<FieldDecl>(Entity.getDecl()), Init);
9512
9513 // Check for std::move on construction.
9516
9517 return Init;
9518}
9519
9520/// Somewhere within T there is an uninitialized reference subobject.
9521/// Dig it out and diagnose it.
9523 QualType T) {
9524 if (T->isReferenceType()) {
9525 S.Diag(Loc, diag::err_reference_without_init)
9526 << T.getNonReferenceType();
9527 return true;
9528 }
9529
9531 if (!RD || !RD->hasUninitializedReferenceMember())
9532 return false;
9533
9534 for (const auto *FI : RD->fields()) {
9535 if (FI->isUnnamedBitField())
9536 continue;
9537
9538 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9539 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9540 return true;
9541 }
9542 }
9543
9544 for (const auto &BI : RD->bases()) {
9545 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9546 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9547 return true;
9548 }
9549 }
9550
9551 return false;
9552}
9553
9554
9555//===----------------------------------------------------------------------===//
9556// Diagnose initialization failures
9557//===----------------------------------------------------------------------===//
9558
9559/// Emit notes associated with an initialization that failed due to a
9560/// "simple" conversion failure.
9561static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9562 Expr *op) {
9563 QualType destType = entity.getType();
9564 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9566
9567 // Emit a possible note about the conversion failing because the
9568 // operand is a message send with a related result type.
9570
9571 // Emit a possible note about a return failing because we're
9572 // expecting a related result type.
9573 if (entity.getKind() == InitializedEntity::EK_Result)
9575 }
9576 QualType fromType = op->getType();
9577 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9578 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9579 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9580 auto *destDecl = destType->getPointeeCXXRecordDecl();
9581 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9582 destDecl->getDeclKind() == Decl::CXXRecord &&
9583 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9584 !fromDecl->hasDefinition() &&
9585 destPointeeType.getQualifiers().compatiblyIncludes(
9586 fromPointeeType.getQualifiers()))
9587 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9588 << S.getASTContext().getTagDeclType(fromDecl)
9589 << S.getASTContext().getTagDeclType(destDecl);
9590}
9591
9592static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9593 InitListExpr *InitList) {
9594 QualType DestType = Entity.getType();
9595
9596 QualType E;
9597 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9599 E.withConst(),
9600 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9601 InitList->getNumInits()),
9603 InitializedEntity HiddenArray =
9605 return diagnoseListInit(S, HiddenArray, InitList);
9606 }
9607
9608 if (DestType->isReferenceType()) {
9609 // A list-initialization failure for a reference means that we tried to
9610 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9611 // inner initialization failed.
9612 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9614 SourceLocation Loc = InitList->getBeginLoc();
9615 if (auto *D = Entity.getDecl())
9616 Loc = D->getLocation();
9617 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9618 return;
9619 }
9620
9621 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9622 /*VerifyOnly=*/false,
9623 /*TreatUnavailableAsInvalid=*/false);
9624 assert(DiagnoseInitList.HadError() &&
9625 "Inconsistent init list check result.");
9626}
9627
9629 const InitializedEntity &Entity,
9630 const InitializationKind &Kind,
9631 ArrayRef<Expr *> Args) {
9632 if (!Failed())
9633 return false;
9634
9635 // When we want to diagnose only one element of a braced-init-list,
9636 // we need to factor it out.
9637 Expr *OnlyArg;
9638 if (Args.size() == 1) {
9639 auto *List = dyn_cast<InitListExpr>(Args[0]);
9640 if (List && List->getNumInits() == 1)
9641 OnlyArg = List->getInit(0);
9642 else
9643 OnlyArg = Args[0];
9644 }
9645 else
9646 OnlyArg = nullptr;
9647
9648 QualType DestType = Entity.getType();
9649 switch (Failure) {
9651 // FIXME: Customize for the initialized entity?
9652 if (Args.empty()) {
9653 // Dig out the reference subobject which is uninitialized and diagnose it.
9654 // If this is value-initialization, this could be nested some way within
9655 // the target type.
9656 assert(Kind.getKind() == InitializationKind::IK_Value ||
9657 DestType->isReferenceType());
9658 bool Diagnosed =
9659 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9660 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9661 (void)Diagnosed;
9662 } else // FIXME: diagnostic below could be better!
9663 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9664 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9665 break;
9667 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9668 << 1 << Entity.getType() << Args[0]->getSourceRange();
9669 break;
9670
9672 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9673 break;
9675 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9676 break;
9678 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9679 break;
9681 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9682 break;
9684 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9685 break;
9687 S.Diag(Kind.getLocation(),
9688 diag::err_array_init_incompat_wide_string_into_wchar);
9689 break;
9691 S.Diag(Kind.getLocation(),
9692 diag::err_array_init_plain_string_into_char8_t);
9693 S.Diag(Args.front()->getBeginLoc(),
9694 diag::note_array_init_plain_string_into_char8_t)
9695 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9696 break;
9698 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9699 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9700 break;
9703 S.Diag(Kind.getLocation(),
9704 (Failure == FK_ArrayTypeMismatch
9705 ? diag::err_array_init_different_type
9706 : diag::err_array_init_non_constant_array))
9707 << DestType.getNonReferenceType()
9708 << OnlyArg->getType()
9709 << Args[0]->getSourceRange();
9710 break;
9711
9713 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9714 << Args[0]->getSourceRange();
9715 break;
9716
9718 DeclAccessPair Found;
9720 DestType.getNonReferenceType(),
9721 true,
9722 Found);
9723 break;
9724 }
9725
9727 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9728 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9729 OnlyArg->getBeginLoc());
9730 break;
9731 }
9732
9735 switch (FailedOverloadResult) {
9736 case OR_Ambiguous:
9737
9738 FailedCandidateSet.NoteCandidates(
9740 Kind.getLocation(),
9742 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9743 << OnlyArg->getType() << DestType
9744 << Args[0]->getSourceRange())
9745 : (S.PDiag(diag::err_ref_init_ambiguous)
9746 << DestType << OnlyArg->getType()
9747 << Args[0]->getSourceRange())),
9748 S, OCD_AmbiguousCandidates, Args);
9749 break;
9750
9751 case OR_No_Viable_Function: {
9752 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9753 if (!S.RequireCompleteType(Kind.getLocation(),
9754 DestType.getNonReferenceType(),
9755 diag::err_typecheck_nonviable_condition_incomplete,
9756 OnlyArg->getType(), Args[0]->getSourceRange()))
9757 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9758 << (Entity.getKind() == InitializedEntity::EK_Result)
9759 << OnlyArg->getType() << Args[0]->getSourceRange()
9760 << DestType.getNonReferenceType();
9761
9762 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9763 break;
9764 }
9765 case OR_Deleted: {
9768 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9769
9770 StringLiteral *Msg = Best->Function->getDeletedMessage();
9771 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9772 << OnlyArg->getType() << DestType.getNonReferenceType()
9773 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9774 << Args[0]->getSourceRange();
9775 if (Ovl == OR_Deleted) {
9776 S.NoteDeletedFunction(Best->Function);
9777 } else {
9778 llvm_unreachable("Inconsistent overload resolution?");
9779 }
9780 break;
9781 }
9782
9783 case OR_Success:
9784 llvm_unreachable("Conversion did not fail!");
9785 }
9786 break;
9787
9789 if (isa<InitListExpr>(Args[0])) {
9790 S.Diag(Kind.getLocation(),
9791 diag::err_lvalue_reference_bind_to_initlist)
9793 << DestType.getNonReferenceType()
9794 << Args[0]->getSourceRange();
9795 break;
9796 }
9797 [[fallthrough]];
9798
9800 S.Diag(Kind.getLocation(),
9802 ? diag::err_lvalue_reference_bind_to_temporary
9803 : diag::err_lvalue_reference_bind_to_unrelated)
9805 << DestType.getNonReferenceType()
9806 << OnlyArg->getType()
9807 << Args[0]->getSourceRange();
9808 break;
9809
9811 // We don't necessarily have an unambiguous source bit-field.
9812 FieldDecl *BitField = Args[0]->getSourceBitField();
9813 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9814 << DestType.isVolatileQualified()
9815 << (BitField ? BitField->getDeclName() : DeclarationName())
9816 << (BitField != nullptr)
9817 << Args[0]->getSourceRange();
9818 if (BitField)
9819 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9820 break;
9821 }
9822
9824 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9825 << DestType.isVolatileQualified()
9826 << Args[0]->getSourceRange();
9827 break;
9828
9830 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9831 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9832 break;
9833
9835 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9836 << DestType.getNonReferenceType() << OnlyArg->getType()
9837 << Args[0]->getSourceRange();
9838 break;
9839
9841 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9842 << DestType << Args[0]->getSourceRange();
9843 break;
9844
9846 QualType SourceType = OnlyArg->getType();
9847 QualType NonRefType = DestType.getNonReferenceType();
9848 Qualifiers DroppedQualifiers =
9849 SourceType.getQualifiers() - NonRefType.getQualifiers();
9850
9851 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9852 SourceType.getQualifiers()))
9853 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9854 << NonRefType << SourceType << 1 /*addr space*/
9855 << Args[0]->getSourceRange();
9856 else if (DroppedQualifiers.hasQualifiers())
9857 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9858 << NonRefType << SourceType << 0 /*cv quals*/
9859 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9860 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9861 else
9862 // FIXME: Consider decomposing the type and explaining which qualifiers
9863 // were dropped where, or on which level a 'const' is missing, etc.
9864 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9865 << NonRefType << SourceType << 2 /*incompatible quals*/
9866 << Args[0]->getSourceRange();
9867 break;
9868 }
9869
9871 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9872 << DestType.getNonReferenceType()
9873 << DestType.getNonReferenceType()->isIncompleteType()
9874 << OnlyArg->isLValue()
9875 << OnlyArg->getType()
9876 << Args[0]->getSourceRange();
9877 emitBadConversionNotes(S, Entity, Args[0]);
9878 break;
9879
9880 case FK_ConversionFailed: {
9881 QualType FromType = OnlyArg->getType();
9882 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9883 << (int)Entity.getKind()
9884 << DestType
9885 << OnlyArg->isLValue()
9886 << FromType
9887 << Args[0]->getSourceRange();
9888 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9889 S.Diag(Kind.getLocation(), PDiag);
9890 emitBadConversionNotes(S, Entity, Args[0]);
9891 break;
9892 }
9893
9895 // No-op. This error has already been reported.
9896 break;
9897
9899 SourceRange R;
9900
9901 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9902 if (InitList && InitList->getNumInits() >= 1) {
9903 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9904 } else {
9905 assert(Args.size() > 1 && "Expected multiple initializers!");
9906 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9907 }
9908
9910 if (Kind.isCStyleOrFunctionalCast())
9911 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9912 << R;
9913 else
9914 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9915 << /*scalar=*/2 << R;
9916 break;
9917 }
9918
9920 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9921 << 0 << Entity.getType() << Args[0]->getSourceRange();
9922 break;
9923
9925 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9926 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9927 break;
9928
9930 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9931 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9932 break;
9933
9936 SourceRange ArgsRange;
9937 if (Args.size())
9938 ArgsRange =
9939 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9940
9941 if (Failure == FK_ListConstructorOverloadFailed) {
9942 assert(Args.size() == 1 &&
9943 "List construction from other than 1 argument.");
9944 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9945 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9946 }
9947
9948 // FIXME: Using "DestType" for the entity we're printing is probably
9949 // bad.
9950 switch (FailedOverloadResult) {
9951 case OR_Ambiguous:
9952 FailedCandidateSet.NoteCandidates(
9953 PartialDiagnosticAt(Kind.getLocation(),
9954 S.PDiag(diag::err_ovl_ambiguous_init)
9955 << DestType << ArgsRange),
9956 S, OCD_AmbiguousCandidates, Args);
9957 break;
9958
9960 if (Kind.getKind() == InitializationKind::IK_Default &&
9961 (Entity.getKind() == InitializedEntity::EK_Base ||
9964 isa<CXXConstructorDecl>(S.CurContext)) {
9965 // This is implicit default initialization of a member or
9966 // base within a constructor. If no viable function was
9967 // found, notify the user that they need to explicitly
9968 // initialize this base/member.
9969 CXXConstructorDecl *Constructor
9970 = cast<CXXConstructorDecl>(S.CurContext);
9971 const CXXRecordDecl *InheritedFrom = nullptr;
9972 if (auto Inherited = Constructor->getInheritedConstructor())
9973 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9974 if (Entity.getKind() == InitializedEntity::EK_Base) {
9975 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9976 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9977 << S.Context.getTypeDeclType(Constructor->getParent())
9978 << /*base=*/0
9979 << Entity.getType()
9980 << InheritedFrom;
9981
9982 RecordDecl *BaseDecl
9983 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9984 ->getDecl();
9985 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9986 << S.Context.getTagDeclType(BaseDecl);
9987 } else {
9988 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9989 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9990 << S.Context.getTypeDeclType(Constructor->getParent())
9991 << /*member=*/1
9992 << Entity.getName()
9993 << InheritedFrom;
9994 S.Diag(Entity.getDecl()->getLocation(),
9995 diag::note_member_declared_at);
9996
9997 if (const RecordType *Record
9998 = Entity.getType()->getAs<RecordType>())
9999 S.Diag(Record->getDecl()->getLocation(),
10000 diag::note_previous_decl)
10001 << S.Context.getTagDeclType(Record->getDecl());
10002 }
10003 break;
10004 }
10005
10006 FailedCandidateSet.NoteCandidates(
10008 Kind.getLocation(),
10009 S.PDiag(diag::err_ovl_no_viable_function_in_init)
10010 << DestType << ArgsRange),
10011 S, OCD_AllCandidates, Args);
10012 break;
10013
10014 case OR_Deleted: {
10017 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10018 if (Ovl != OR_Deleted) {
10019 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10020 << DestType << ArgsRange;
10021 llvm_unreachable("Inconsistent overload resolution?");
10022 break;
10023 }
10024
10025 // If this is a defaulted or implicitly-declared function, then
10026 // it was implicitly deleted. Make it clear that the deletion was
10027 // implicit.
10028 if (S.isImplicitlyDeleted(Best->Function))
10029 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
10030 << llvm::to_underlying(
10031 S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)))
10032 << DestType << ArgsRange;
10033 else {
10034 StringLiteral *Msg = Best->Function->getDeletedMessage();
10035 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10036 << DestType << (Msg != nullptr)
10037 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
10038 }
10039
10040 S.NoteDeletedFunction(Best->Function);
10041 break;
10042 }
10043
10044 case OR_Success:
10045 llvm_unreachable("Conversion did not fail!");
10046 }
10047 }
10048 break;
10049
10051 if (Entity.getKind() == InitializedEntity::EK_Member &&
10052 isa<CXXConstructorDecl>(S.CurContext)) {
10053 // This is implicit default-initialization of a const member in
10054 // a constructor. Complain that it needs to be explicitly
10055 // initialized.
10056 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
10057 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
10058 << (Constructor->getInheritedConstructor() ? 2 :
10059 Constructor->isImplicit() ? 1 : 0)
10060 << S.Context.getTypeDeclType(Constructor->getParent())
10061 << /*const=*/1
10062 << Entity.getName();
10063 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
10064 << Entity.getName();
10065 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
10066 VD && VD->isConstexpr()) {
10067 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
10068 << VD;
10069 } else {
10070 S.Diag(Kind.getLocation(), diag::err_default_init_const)
10071 << DestType << (bool)DestType->getAs<RecordType>();
10072 }
10073 break;
10074
10075 case FK_Incomplete:
10076 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
10077 diag::err_init_incomplete_type);
10078 break;
10079
10081 // Run the init list checker again to emit diagnostics.
10082 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10083 diagnoseListInit(S, Entity, InitList);
10084 break;
10085 }
10086
10087 case FK_PlaceholderType: {
10088 // FIXME: Already diagnosed!
10089 break;
10090 }
10091
10093 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
10094 << Args[0]->getSourceRange();
10097 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10098 (void)Ovl;
10099 assert(Ovl == OR_Success && "Inconsistent overload resolution");
10100 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10101 S.Diag(CtorDecl->getLocation(),
10102 diag::note_explicit_ctor_deduction_guide_here) << false;
10103 break;
10104 }
10105
10107 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10108 /*VerifyOnly=*/false);
10109 break;
10110
10112 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10113 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10114 << Entity.getType() << InitList->getSourceRange();
10115 break;
10116 }
10117
10118 PrintInitLocationNote(S, Entity);
10119 return true;
10120}
10121
10122void InitializationSequence::dump(raw_ostream &OS) const {
10123 switch (SequenceKind) {
10124 case FailedSequence: {
10125 OS << "Failed sequence: ";
10126 switch (Failure) {
10128 OS << "too many initializers for reference";
10129 break;
10130
10132 OS << "parenthesized list init for reference";
10133 break;
10134
10136 OS << "array requires initializer list";
10137 break;
10138
10140 OS << "address of unaddressable function was taken";
10141 break;
10142
10144 OS << "array requires initializer list or string literal";
10145 break;
10146
10148 OS << "array requires initializer list or wide string literal";
10149 break;
10150
10152 OS << "narrow string into wide char array";
10153 break;
10154
10156 OS << "wide string into char array";
10157 break;
10158
10160 OS << "incompatible wide string into wide char array";
10161 break;
10162
10164 OS << "plain string literal into char8_t array";
10165 break;
10166
10168 OS << "u8 string literal into char array";
10169 break;
10170
10172 OS << "array type mismatch";
10173 break;
10174
10176 OS << "non-constant array initializer";
10177 break;
10178
10180 OS << "address of overloaded function failed";
10181 break;
10182
10184 OS << "overload resolution for reference initialization failed";
10185 break;
10186
10188 OS << "non-const lvalue reference bound to temporary";
10189 break;
10190
10192 OS << "non-const lvalue reference bound to bit-field";
10193 break;
10194
10196 OS << "non-const lvalue reference bound to vector element";
10197 break;
10198
10200 OS << "non-const lvalue reference bound to matrix element";
10201 break;
10202
10204 OS << "non-const lvalue reference bound to unrelated type";
10205 break;
10206
10208 OS << "rvalue reference bound to an lvalue";
10209 break;
10210
10212 OS << "reference initialization drops qualifiers";
10213 break;
10214
10216 OS << "reference with mismatching address space bound to temporary";
10217 break;
10218
10220 OS << "reference initialization failed";
10221 break;
10222
10224 OS << "conversion failed";
10225 break;
10226
10228 OS << "conversion from property failed";
10229 break;
10230
10232 OS << "too many initializers for scalar";
10233 break;
10234
10236 OS << "parenthesized list init for reference";
10237 break;
10238
10240 OS << "referencing binding to initializer list";
10241 break;
10242
10244 OS << "initializer list for non-aggregate, non-scalar type";
10245 break;
10246
10248 OS << "overloading failed for user-defined conversion";
10249 break;
10250
10252 OS << "constructor overloading failed";
10253 break;
10254
10256 OS << "default initialization of a const variable";
10257 break;
10258
10259 case FK_Incomplete:
10260 OS << "initialization of incomplete type";
10261 break;
10262
10264 OS << "list initialization checker failure";
10265 break;
10266
10268 OS << "variable length array has an initializer";
10269 break;
10270
10271 case FK_PlaceholderType:
10272 OS << "initializer expression isn't contextually valid";
10273 break;
10274
10276 OS << "list constructor overloading failed";
10277 break;
10278
10280 OS << "list copy initialization chose explicit constructor";
10281 break;
10282
10284 OS << "parenthesized list initialization failed";
10285 break;
10286
10288 OS << "designated initializer for non-aggregate type";
10289 break;
10290 }
10291 OS << '\n';
10292 return;
10293 }
10294
10295 case DependentSequence:
10296 OS << "Dependent sequence\n";
10297 return;
10298
10299 case NormalSequence:
10300 OS << "Normal sequence: ";
10301 break;
10302 }
10303
10304 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10305 if (S != step_begin()) {
10306 OS << " -> ";
10307 }
10308
10309 switch (S->Kind) {
10311 OS << "resolve address of overloaded function";
10312 break;
10313
10315 OS << "derived-to-base (prvalue)";
10316 break;
10317
10319 OS << "derived-to-base (xvalue)";
10320 break;
10321
10323 OS << "derived-to-base (lvalue)";
10324 break;
10325
10326 case SK_BindReference:
10327 OS << "bind reference to lvalue";
10328 break;
10329
10331 OS << "bind reference to a temporary";
10332 break;
10333
10334 case SK_FinalCopy:
10335 OS << "final copy in class direct-initialization";
10336 break;
10337
10339 OS << "extraneous C++03 copy to temporary";
10340 break;
10341
10342 case SK_UserConversion:
10343 OS << "user-defined conversion via " << *S->Function.Function;
10344 break;
10345
10347 OS << "qualification conversion (prvalue)";
10348 break;
10349
10351 OS << "qualification conversion (xvalue)";
10352 break;
10353
10355 OS << "qualification conversion (lvalue)";
10356 break;
10357
10359 OS << "function reference conversion";
10360 break;
10361
10363 OS << "non-atomic-to-atomic conversion";
10364 break;
10365
10367 OS << "implicit conversion sequence (";
10368 S->ICS->dump(); // FIXME: use OS
10369 OS << ")";
10370 break;
10371
10373 OS << "implicit conversion sequence with narrowing prohibited (";
10374 S->ICS->dump(); // FIXME: use OS
10375 OS << ")";
10376 break;
10377
10379 OS << "list aggregate initialization";
10380 break;
10381
10382 case SK_UnwrapInitList:
10383 OS << "unwrap reference initializer list";
10384 break;
10385
10386 case SK_RewrapInitList:
10387 OS << "rewrap reference initializer list";
10388 break;
10389
10391 OS << "constructor initialization";
10392 break;
10393
10395 OS << "list initialization via constructor";
10396 break;
10397
10399 OS << "zero initialization";
10400 break;
10401
10402 case SK_CAssignment:
10403 OS << "C assignment";
10404 break;
10405
10406 case SK_StringInit:
10407 OS << "string initialization";
10408 break;
10409
10411 OS << "Objective-C object conversion";
10412 break;
10413
10414 case SK_ArrayLoopIndex:
10415 OS << "indexing for array initialization loop";
10416 break;
10417
10418 case SK_ArrayLoopInit:
10419 OS << "array initialization loop";
10420 break;
10421
10422 case SK_ArrayInit:
10423 OS << "array initialization";
10424 break;
10425
10426 case SK_GNUArrayInit:
10427 OS << "array initialization (GNU extension)";
10428 break;
10429
10431 OS << "parenthesized array initialization";
10432 break;
10433
10435 OS << "pass by indirect copy and restore";
10436 break;
10437
10439 OS << "pass by indirect restore";
10440 break;
10441
10443 OS << "Objective-C object retension";
10444 break;
10445
10447 OS << "std::initializer_list from initializer list";
10448 break;
10449
10451 OS << "list initialization from std::initializer_list";
10452 break;
10453
10454 case SK_OCLSamplerInit:
10455 OS << "OpenCL sampler_t from integer constant";
10456 break;
10457
10459 OS << "OpenCL opaque type from zero";
10460 break;
10462 OS << "initialization from a parenthesized list of values";
10463 break;
10464 }
10465
10466 OS << " [" << S->Type << ']';
10467 }
10468
10469 OS << '\n';
10470}
10471
10473 dump(llvm::errs());
10474}
10475
10477 const ImplicitConversionSequence &ICS,
10478 QualType PreNarrowingType,
10479 QualType EntityType,
10480 const Expr *PostInit) {
10481 const StandardConversionSequence *SCS = nullptr;
10482 switch (ICS.getKind()) {
10484 SCS = &ICS.Standard;
10485 break;
10487 SCS = &ICS.UserDefined.After;
10488 break;
10493 return;
10494 }
10495
10496 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
10497 unsigned ConstRefDiagID, unsigned WarnDiagID) {
10498 unsigned DiagID;
10499 auto &L = S.getLangOpts();
10500 if (L.CPlusPlus11 &&
10501 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
10502 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
10503 else
10504 DiagID = WarnDiagID;
10505 return S.Diag(PostInit->getBeginLoc(), DiagID)
10506 << PostInit->getSourceRange();
10507 };
10508
10509 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10510 APValue ConstantValue;
10511 QualType ConstantType;
10512 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10513 ConstantType)) {
10514 case NK_Not_Narrowing:
10516 // No narrowing occurred.
10517 return;
10518
10519 case NK_Type_Narrowing: {
10520 // This was a floating-to-integer conversion, which is always considered a
10521 // narrowing conversion even if the value is a constant and can be
10522 // represented exactly as an integer.
10523 QualType T = EntityType.getNonReferenceType();
10524 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10525 diag::ext_init_list_type_narrowing_const_reference,
10526 diag::warn_init_list_type_narrowing)
10527 << PreNarrowingType.getLocalUnqualifiedType()
10528 << T.getLocalUnqualifiedType();
10529 break;
10530 }
10531
10532 case NK_Constant_Narrowing: {
10533 // A constant value was narrowed.
10534 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10535 diag::ext_init_list_constant_narrowing,
10536 diag::ext_init_list_constant_narrowing_const_reference,
10537 diag::warn_init_list_constant_narrowing)
10538 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10540 break;
10541 }
10542
10543 case NK_Variable_Narrowing: {
10544 // A variable's value may have been narrowed.
10545 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10546 diag::ext_init_list_variable_narrowing,
10547 diag::ext_init_list_variable_narrowing_const_reference,
10548 diag::warn_init_list_variable_narrowing)
10549 << PreNarrowingType.getLocalUnqualifiedType()
10551 break;
10552 }
10553 }
10554
10555 SmallString<128> StaticCast;
10556 llvm::raw_svector_ostream OS(StaticCast);
10557 OS << "static_cast<";
10558 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10559 // It's important to use the typedef's name if there is one so that the
10560 // fixit doesn't break code using types like int64_t.
10561 //
10562 // FIXME: This will break if the typedef requires qualification. But
10563 // getQualifiedNameAsString() includes non-machine-parsable components.
10564 OS << *TT->getDecl();
10565 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10566 OS << BT->getName(S.getLangOpts());
10567 else {
10568 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10569 // with a broken cast.
10570 return;
10571 }
10572 OS << ">(";
10573 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10574 << PostInit->getSourceRange()
10575 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10577 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10578}
10579
10581 QualType ToType, Expr *Init) {
10582 assert(S.getLangOpts().C23);
10584 Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10585 Sema::AllowedExplicit::None,
10586 /*InOverloadResolution*/ false,
10587 /*CStyle*/ false,
10588 /*AllowObjCWritebackConversion=*/false);
10589
10590 if (!ICS.isStandard())
10591 return;
10592
10593 APValue Value;
10594 QualType PreNarrowingType;
10595 // Reuse C++ narrowing check.
10596 switch (ICS.Standard.getNarrowingKind(
10597 S.Context, Init, Value, PreNarrowingType,
10598 /*IgnoreFloatToIntegralConversion*/ false)) {
10599 // The value doesn't fit.
10601 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10602 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10603 return;
10604
10605 // Conversion to a narrower type.
10606 case NK_Type_Narrowing:
10607 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10608 << ToType << FromType;
10609 return;
10610
10611 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10612 // not really interested in these cases.
10615 case NK_Not_Narrowing:
10616 return;
10617 }
10618 llvm_unreachable("unhandled case in switch");
10619}
10620
10622 Sema &SemaRef, QualType &TT) {
10623 assert(SemaRef.getLangOpts().C23);
10624 // character that string literal contains fits into TT - target type.
10625 const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);
10626 QualType CharType = AT->getElementType();
10627 uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);
10628 bool isUnsigned = CharType->isUnsignedIntegerType();
10629 llvm::APSInt Value(BitWidth, isUnsigned);
10630 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10631 int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());
10632 Value = C;
10633 if (Value != C) {
10634 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10635 diag::err_c23_constexpr_init_not_representable)
10636 << C << CharType;
10637 return;
10638 }
10639 }
10640 return;
10641}
10642
10643//===----------------------------------------------------------------------===//
10644// Initialization helper functions
10645//===----------------------------------------------------------------------===//
10646bool
10648 ExprResult Init) {
10649 if (Init.isInvalid())
10650 return false;
10651
10652 Expr *InitE = Init.get();
10653 assert(InitE && "No initialization expression");
10654
10655 InitializationKind Kind =
10657 InitializationSequence Seq(*this, Entity, Kind, InitE);
10658 return !Seq.Failed();
10659}
10660
10663 SourceLocation EqualLoc,
10665 bool TopLevelOfInitList,
10666 bool AllowExplicit) {
10667 if (Init.isInvalid())
10668 return ExprError();
10669
10670 Expr *InitE = Init.get();
10671 assert(InitE && "No initialization expression?");
10672
10673 if (EqualLoc.isInvalid())
10674 EqualLoc = InitE->getBeginLoc();
10675
10677 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10678 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10679
10680 // Prevent infinite recursion when performing parameter copy-initialization.
10681 const bool ShouldTrackCopy =
10682 Entity.isParameterKind() && Seq.isConstructorInitialization();
10683 if (ShouldTrackCopy) {
10684 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10685 Seq.SetOverloadFailure(
10688
10689 // Try to give a meaningful diagnostic note for the problematic
10690 // constructor.
10691 const auto LastStep = Seq.step_end() - 1;
10692 assert(LastStep->Kind ==
10694 const FunctionDecl *Function = LastStep->Function.Function;
10695 auto Candidate =
10696 llvm::find_if(Seq.getFailedCandidateSet(),
10697 [Function](const OverloadCandidate &Candidate) -> bool {
10698 return Candidate.Viable &&
10699 Candidate.Function == Function &&
10700 Candidate.Conversions.size() > 0;
10701 });
10702 if (Candidate != Seq.getFailedCandidateSet().end() &&
10703 Function->getNumParams() > 0) {
10704 Candidate->Viable = false;
10707 InitE,
10708 Function->getParamDecl(0)->getType());
10709 }
10710 }
10711 CurrentParameterCopyTypes.push_back(Entity.getType());
10712 }
10713
10714 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10715
10716 if (ShouldTrackCopy)
10717 CurrentParameterCopyTypes.pop_back();
10718
10719 return Result;
10720}
10721
10722/// Determine whether RD is, or is derived from, a specialization of CTD.
10724 ClassTemplateDecl *CTD) {
10725 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10726 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10727 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10728 };
10729 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10730}
10731
10733 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10734 const InitializationKind &Kind, MultiExprArg Inits) {
10735 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10736 TSInfo->getType()->getContainedDeducedType());
10737 assert(DeducedTST && "not a deduced template specialization type");
10738
10739 auto TemplateName = DeducedTST->getTemplateName();
10741 return SubstAutoTypeDependent(TSInfo->getType());
10742
10743 // We can only perform deduction for class templates or alias templates.
10744 auto *Template =
10745 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10746 TemplateDecl *LookupTemplateDecl = Template;
10747 if (!Template) {
10748 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10750 Diag(Kind.getLocation(),
10751 diag::warn_cxx17_compat_ctad_for_alias_templates);
10752 LookupTemplateDecl = AliasTemplate;
10753 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10754 ->getUnderlyingType()
10755 .getCanonicalType();
10756 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10757 // of the form
10758 // [typename] [nested-name-specifier] [template] simple-template-id
10759 if (const auto *TST =
10760 UnderlyingType->getAs<TemplateSpecializationType>()) {
10761 Template = dyn_cast_or_null<ClassTemplateDecl>(
10762 TST->getTemplateName().getAsTemplateDecl());
10763 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10764 // Cases where template arguments in the RHS of the alias are not
10765 // dependent. e.g.
10766 // using AliasFoo = Foo<bool>;
10767 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
10768 RT->getAsCXXRecordDecl()))
10769 Template = CTSD->getSpecializedTemplate();
10770 }
10771 }
10772 }
10773 if (!Template) {
10774 Diag(Kind.getLocation(),
10775 diag::err_deduced_non_class_or_alias_template_specialization_type)
10777 if (auto *TD = TemplateName.getAsTemplateDecl())
10779 return QualType();
10780 }
10781
10782 // Can't deduce from dependent arguments.
10784 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10785 diag::warn_cxx14_compat_class_template_argument_deduction)
10786 << TSInfo->getTypeLoc().getSourceRange() << 0;
10787 return SubstAutoTypeDependent(TSInfo->getType());
10788 }
10789
10790 // FIXME: Perform "exact type" matching first, per CWG discussion?
10791 // Or implement this via an implied 'T(T) -> T' deduction guide?
10792
10793 // FIXME: Do we need/want a std::initializer_list<T> special case?
10794
10795 // Look up deduction guides, including those synthesized from constructors.
10796 //
10797 // C++1z [over.match.class.deduct]p1:
10798 // A set of functions and function templates is formed comprising:
10799 // - For each constructor of the class template designated by the
10800 // template-name, a function template [...]
10801 // - For each deduction-guide, a function or function template [...]
10802 DeclarationNameInfo NameInfo(
10804 TSInfo->getTypeLoc().getEndLoc());
10805 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10806 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10807
10808 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10809 // clear on this, but they're not found by name so access does not apply.
10810 Guides.suppressDiagnostics();
10811
10812 // Figure out if this is list-initialization.
10814 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10815 ? dyn_cast<InitListExpr>(Inits[0])
10816 : nullptr;
10817
10818 // C++1z [over.match.class.deduct]p1:
10819 // Initialization and overload resolution are performed as described in
10820 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10821 // (as appropriate for the type of initialization performed) for an object
10822 // of a hypothetical class type, where the selected functions and function
10823 // templates are considered to be the constructors of that class type
10824 //
10825 // Since we know we're initializing a class type of a type unrelated to that
10826 // of the initializer, this reduces to something fairly reasonable.
10827 OverloadCandidateSet Candidates(Kind.getLocation(),
10830
10831 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10832
10833 // Return true if the candidate is added successfully, false otherwise.
10834 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10836 DeclAccessPair FoundDecl,
10837 bool OnlyListConstructors,
10838 bool AllowAggregateDeductionCandidate) {
10839 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10840 // For copy-initialization, the candidate functions are all the
10841 // converting constructors (12.3.1) of that class.
10842 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10843 // The converting constructors of T are candidate functions.
10844 if (!AllowExplicit) {
10845 // Overload resolution checks whether the deduction guide is declared
10846 // explicit for us.
10847
10848 // When looking for a converting constructor, deduction guides that
10849 // could never be called with one argument are not interesting to
10850 // check or note.
10851 if (GD->getMinRequiredArguments() > 1 ||
10852 (GD->getNumParams() == 0 && !GD->isVariadic()))
10853 return;
10854 }
10855
10856 // C++ [over.match.list]p1.1: (first phase list initialization)
10857 // Initially, the candidate functions are the initializer-list
10858 // constructors of the class T
10859 if (OnlyListConstructors && !isInitListConstructor(GD))
10860 return;
10861
10862 if (!AllowAggregateDeductionCandidate &&
10863 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10864 return;
10865
10866 // C++ [over.match.list]p1.2: (second phase list initialization)
10867 // the candidate functions are all the constructors of the class T
10868 // C++ [over.match.ctor]p1: (all other cases)
10869 // the candidate functions are all the constructors of the class of
10870 // the object being initialized
10871
10872 // C++ [over.best.ics]p4:
10873 // When [...] the constructor [...] is a candidate by
10874 // - [over.match.copy] (in all cases)
10875 // FIXME: The "second phase of [over.match.list] case can also
10876 // theoretically happen here, but it's not clear whether we can
10877 // ever have a parameter of the right type.
10878 bool SuppressUserConversions = Kind.isCopyInit();
10879
10880 if (TD) {
10881 SmallVector<Expr *, 8> TmpInits;
10882 for (Expr *E : Inits)
10883 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10884 TmpInits.push_back(DI->getInit());
10885 else
10886 TmpInits.push_back(E);
10888 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10889 SuppressUserConversions,
10890 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10891 /*PO=*/{}, AllowAggregateDeductionCandidate);
10892 } else {
10893 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10894 SuppressUserConversions,
10895 /*PartialOverloading=*/false, AllowExplicit);
10896 }
10897 };
10898
10899 bool FoundDeductionGuide = false;
10900
10901 auto TryToResolveOverload =
10902 [&](bool OnlyListConstructors) -> OverloadingResult {
10904 bool HasAnyDeductionGuide = false;
10905
10906 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10907 auto *Pattern = Template;
10908 while (Pattern->getInstantiatedFromMemberTemplate()) {
10909 if (Pattern->isMemberSpecialization())
10910 break;
10911 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10912 }
10913
10914 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10915 if (!(RD->getDefinition() && RD->isAggregate()))
10916 return;
10918 SmallVector<QualType, 8> ElementTypes;
10919
10920 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10921 if (!CheckInitList.HadError()) {
10922 // C++ [over.match.class.deduct]p1.8:
10923 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10924 // rvalue reference to the declared type of e_i and
10925 // C++ [over.match.class.deduct]p1.9:
10926 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10927 // lvalue reference to the const-qualified declared type of e_i and
10928 // C++ [over.match.class.deduct]p1.10:
10929 // otherwise, T_i is the declared type of e_i
10930 for (int I = 0, E = ListInit->getNumInits();
10931 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10932 if (ElementTypes[I]->isArrayType()) {
10933 if (isa<InitListExpr>(ListInit->getInit(I)))
10934 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10935 else if (isa<StringLiteral>(
10936 ListInit->getInit(I)->IgnoreParenImpCasts()))
10937 ElementTypes[I] =
10938 Context.getLValueReferenceType(ElementTypes[I].withConst());
10939 }
10940
10941 if (FunctionTemplateDecl *TD =
10943 LookupTemplateDecl, ElementTypes,
10944 TSInfo->getTypeLoc().getEndLoc())) {
10945 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10946 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10947 OnlyListConstructors,
10948 /*AllowAggregateDeductionCandidate=*/true);
10949 HasAnyDeductionGuide = true;
10950 }
10951 }
10952 };
10953
10954 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10955 NamedDecl *D = (*I)->getUnderlyingDecl();
10956 if (D->isInvalidDecl())
10957 continue;
10958
10959 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10960 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10961 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10962 if (!GD)
10963 continue;
10964
10965 if (!GD->isImplicit())
10966 HasAnyDeductionGuide = true;
10967
10968 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10969 /*AllowAggregateDeductionCandidate=*/false);
10970 }
10971
10972 // C++ [over.match.class.deduct]p1.4:
10973 // if C is defined and its definition satisfies the conditions for an
10974 // aggregate class ([dcl.init.aggr]) with the assumption that any
10975 // dependent base class has no virtual functions and no virtual base
10976 // classes, and the initializer is a non-empty braced-init-list or
10977 // parenthesized expression-list, and there are no deduction-guides for
10978 // C, the set contains an additional function template, called the
10979 // aggregate deduction candidate, defined as follows.
10980 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10981 if (ListInit && ListInit->getNumInits()) {
10982 SynthesizeAggrGuide(ListInit);
10983 } else if (Inits.size()) { // parenthesized expression-list
10984 // Inits are expressions inside the parentheses. We don't have
10985 // the parentheses source locations, use the begin/end of Inits as the
10986 // best heuristic.
10987 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10988 Inits, Inits.back()->getEndLoc());
10989 SynthesizeAggrGuide(&TempListInit);
10990 }
10991 }
10992
10993 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10994
10995 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10996 };
10997
10999
11000 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
11001 // try initializer-list constructors.
11002 if (ListInit) {
11003 bool TryListConstructors = true;
11004
11005 // Try list constructors unless the list is empty and the class has one or
11006 // more default constructors, in which case those constructors win.
11007 if (!ListInit->getNumInits()) {
11008 for (NamedDecl *D : Guides) {
11009 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
11010 if (FD && FD->getMinRequiredArguments() == 0) {
11011 TryListConstructors = false;
11012 break;
11013 }
11014 }
11015 } else if (ListInit->getNumInits() == 1) {
11016 // C++ [over.match.class.deduct]:
11017 // As an exception, the first phase in [over.match.list] (considering
11018 // initializer-list constructors) is omitted if the initializer list
11019 // consists of a single expression of type cv U, where U is a
11020 // specialization of C or a class derived from a specialization of C.
11021 Expr *E = ListInit->getInit(0);
11022 auto *RD = E->getType()->getAsCXXRecordDecl();
11023 if (!isa<InitListExpr>(E) && RD &&
11024 isCompleteType(Kind.getLocation(), E->getType()) &&
11026 TryListConstructors = false;
11027 }
11028
11029 if (TryListConstructors)
11030 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
11031 // Then unwrap the initializer list and try again considering all
11032 // constructors.
11033 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
11034 }
11035
11036 // If list-initialization fails, or if we're doing any other kind of
11037 // initialization, we (eventually) consider constructors.
11039 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
11040
11041 switch (Result) {
11042 case OR_Ambiguous:
11043 // FIXME: For list-initialization candidates, it'd usually be better to
11044 // list why they were not viable when given the initializer list itself as
11045 // an argument.
11046 Candidates.NoteCandidates(
11048 Kind.getLocation(),
11049 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
11050 << TemplateName),
11051 *this, OCD_AmbiguousCandidates, Inits);
11052 return QualType();
11053
11054 case OR_No_Viable_Function: {
11055 CXXRecordDecl *Primary =
11056 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
11057 bool Complete =
11058 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
11059 Candidates.NoteCandidates(
11061 Kind.getLocation(),
11062 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
11063 : diag::err_deduced_class_template_incomplete)
11064 << TemplateName << !Guides.empty()),
11065 *this, OCD_AllCandidates, Inits);
11066 return QualType();
11067 }
11068
11069 case OR_Deleted: {
11070 // FIXME: There are no tests for this diagnostic, and it doesn't seem
11071 // like we ever get here; attempts to trigger this seem to yield a
11072 // generic c'all to deleted function' diagnostic instead.
11073 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
11074 << TemplateName;
11075 NoteDeletedFunction(Best->Function);
11076 return QualType();
11077 }
11078
11079 case OR_Success:
11080 // C++ [over.match.list]p1:
11081 // In copy-list-initialization, if an explicit constructor is chosen, the
11082 // initialization is ill-formed.
11083 if (Kind.isCopyInit() && ListInit &&
11084 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
11085 bool IsDeductionGuide = !Best->Function->isImplicit();
11086 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
11087 << TemplateName << IsDeductionGuide;
11088 Diag(Best->Function->getLocation(),
11089 diag::note_explicit_ctor_deduction_guide_here)
11090 << IsDeductionGuide;
11091 return QualType();
11092 }
11093
11094 // Make sure we didn't select an unusable deduction guide, and mark it
11095 // as referenced.
11096 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
11097 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
11098 break;
11099 }
11100
11101 // C++ [dcl.type.class.deduct]p1:
11102 // The placeholder is replaced by the return type of the function selected
11103 // by overload resolution for class template deduction.
11105 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
11106 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11107 diag::warn_cxx14_compat_class_template_argument_deduction)
11108 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
11109
11110 // Warn if CTAD was used on a type that does not have any user-defined
11111 // deduction guides.
11112 if (!FoundDeductionGuide) {
11113 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11114 diag::warn_ctad_maybe_unsupported)
11115 << TemplateName;
11116 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
11117 }
11118
11119 return DeducedType;
11120}
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:31
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:569
static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
Definition: SemaInit.cpp:7552
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E)
Tries to get a FunctionDecl out of E.
Definition: SemaInit.cpp:6124
static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee)
Definition: SemaInit.cpp:7435
static void updateStringLiteralType(Expr *E, QualType Ty)
Update the type of a string literal, including any surrounding parentheses, to match the type of the ...
Definition: SemaInit.cpp:173
static void updateGNUCompoundLiteralRValue(Expr *E)
Fix a compound literal initializing an array so it's correctly marked as an rvalue.
Definition: SemaInit.cpp:185
static bool initializingConstexprVariable(const InitializedEntity &Entity)
Definition: SemaInit.cpp:194
static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7589
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:6696
static SourceLocation getInitializationLoc(const InitializedEntity &Entity, Expr *Initializer)
Get the location at which initialization diagnostics should appear.
Definition: SemaInit.cpp:6729
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:6006
static DesignatedInitExpr * CloneDesignatedInitExpr(Sema &SemaRef, DesignatedInitExpr *DIE)
Definition: SemaInit.cpp:2499
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:6787
static Sema::AssignmentAction getAssignmentAction(const InitializedEntity &Entity, bool Diagnose=false)
Definition: SemaInit.cpp:6607
static void TryOrBuildParenListInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args, InitializationSequence &Sequence, bool VerifyOnly, ExprResult *Result=nullptr)
Definition: SemaInit.cpp:5451
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, bool IsReturnStmt)
Provide warnings when std::move is used on construction.
Definition: SemaInit.cpp:8423
static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, Sema &SemaRef, QualType &TT)
Definition: SemaInit.cpp:10621
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:6938
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, ClassTemplateDecl *CTD)
Determine whether RD is, or is derived from, a specialization of CTD.
Definition: SemaInit.cpp:10723
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:4072
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:73
StringInitFailureKind
Definition: SemaInit.cpp:59
@ SIF_None
Definition: SemaInit.cpp:60
@ SIF_PlainStringIntoUTF8Char
Definition: SemaInit.cpp:65
@ SIF_IncompatWideStringIntoWideChar
Definition: SemaInit.cpp:63
@ SIF_UTF8StringIntoPlainChar
Definition: SemaInit.cpp:64
@ SIF_NarrowStringIntoWideChar
Definition: SemaInit.cpp:61
@ SIF_Other
Definition: SemaInit.cpp:66
@ SIF_WideStringIntoChar
Definition: SemaInit.cpp:62
static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, LocalVisitor Visit)
Definition: SemaInit.cpp:7493
static void TryDefaultInitialization(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, InitializationSequence &Sequence)
Attempt default initialization (C++ [dcl.init]p6).
Definition: SemaInit.cpp:5413
static bool TryOCLSamplerInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6053
static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path)
Definition: SemaInit.cpp:8122
static bool isInStlNamespace(const Decl *D)
Definition: SemaInit.cpp:7420
static bool maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, const InitializedEntity &Entity)
Tries to add a zero initializer. Returns true if that worked.
Definition: SemaInit.cpp:4012
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:3351
static bool canPerformArrayCopy(const InitializedEntity &Entity)
Determine whether we can perform an elementwise array copy for this kind of entity.
Definition: SemaInit.cpp:6135
static bool IsZeroInitializer(Expr *Initializer, Sema &S)
Definition: SemaInit.cpp:6066
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:5002
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:8080
static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, QualType ToType, Expr *Init)
Definition: SemaInit.cpp:10580
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:2471
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:5335
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:5703
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:4120
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:7221
static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD)
Definition: SemaInit.cpp:7387
static bool shouldTrackFirstArgument(const FunctionDecl *FD)
Definition: SemaInit.cpp:7469
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:4562
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:5326
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:4964
static void DiagnoseNarrowingInInitList(Sema &S, const ImplicitConversionSequence &ICS, QualType PreNarrowingType, QualType EntityType, const Expr *PostInit)
Definition: SemaInit.cpp:10476
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:5990
static bool pathContainsInit(IndirectLocalPath &Path)
Definition: SemaInit.cpp:7394
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, Sema &S, bool CheckC23ConstexprInit=false)
Definition: SemaInit.cpp:212
static bool isRecordWithAttr(QualType Type)
Definition: SemaInit.cpp:7411
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:7014
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:4993
PathLifetimeKind
Whether a path to an object supports lifetime extension.
Definition: SemaInit.cpp:8065
@ ShouldExtend
We should lifetime-extend, but we don't because (due to technical limitations) we can't.
Definition: SemaInit.cpp:8072
@ NoExtend
Do not lifetime extend along this path.
Definition: SemaInit.cpp:8074
@ Extend
Lifetime-extend along this path.
Definition: SemaInit.cpp:8067
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, InitializationSequence &Sequence, QualType DestType, Expr *Initializer)
Definition: SemaInit.cpp:6071
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:49
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, InitListExpr *InitList)
Definition: SemaInit.cpp:9592
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:4779
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:4234
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:9561
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:4032
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:8092
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src)
Check whether the given expression is a valid operand for an indirect copy/restore.
Definition: SemaInit.cpp:5972
static bool shouldBindAsTemporary(const InitializedEntity &Entity)
Whether we should bind a created object as a temporary when initializing the given entity.
Definition: SemaInit.cpp:6662
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:7656
static bool ResolveOverloadedFunctionForReferenceBinding(Sema &S, Expr *Initializer, QualType &SourceType, QualType &UnqualifiedSourceType, QualType UnqualifiedTargetType, InitializationSequence &Sequence)
Definition: SemaInit.cpp:4414
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:7792
InvalidICRKind
The non-zero enum values here are indexes into diagnostic alternatives.
Definition: SemaInit.cpp:5902
@ IIK_okay
Definition: SemaInit.cpp:5902
@ IIK_nonlocal
Definition: SemaInit.cpp:5902
@ IIK_nonscalar
Definition: SemaInit.cpp:5902
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:7039
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:4459
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:5890
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:4107
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, QualType T)
Somewhere within T there is an uninitialized reference subobject.
Definition: SemaInit.cpp:9522
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, bool isAddressOf, bool &isWeakAccess)
Determines whether this expression is an acceptable ICR source.
Definition: SemaInit.cpp:5905
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:946
bool isNullPointer() const
Definition: APValue.cpp:1010
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
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:648
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:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
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:1098
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:2773
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:1590
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:775
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:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
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:1119
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:2617
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:2340
CanQualType OCLSamplerTy
Definition: ASTContext.h:1127
CanQualType VoidTy
Definition: ASTContext.h:1091
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:2770
CanQualType Char32Ty
Definition: ASTContext.h:1099
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:757
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:1793
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:2344
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:5564
Represents a loop initializing the elements of an array.
Definition: Expr.h:5511
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
QualType getElementType() const
Definition: Type.h:3526
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:2977
Kind getKind() const
Definition: Type.h:3019
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:1485
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1683
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1680
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2777
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2614
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2773
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1952
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
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:1162
bool allowConstDefaultInit() const
Determine whether declaring a const variable with this type is ok per core issue 253.
Definition: DeclCXX.h:1392
base_class_range bases()
Definition: DeclCXX.h:619
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1833
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
llvm::iterator_range< base_class_iterator > base_class_range
Definition: DeclCXX.h:615
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:617
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:2175
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:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
bool isCallToStdMove() const
Definition: Expr.cpp:3510
Expr * getCallee()
Definition: Expr.h:2970
SourceLocation getRParenLoc() const
Definition: Expr.h:3130
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:3483
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:3082
QualType getElementType() const
Definition: Type.h:3092
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3552
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:218
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3628
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
virtual std::unique_ptr< CorrectionCandidateCallback > clone()=0
Clone this CorrectionCandidateCallback.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2279
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
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:1957
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
bool isStdNamespace() const
Definition: DeclBase.cpp:1248
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
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:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
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:599
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasAttr() const
Definition: DeclBase.h:583
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:5943
Represents a single C99 designator.
Definition: Expr.h:5135
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:5297
void setFieldDecl(FieldDecl *FD)
Definition: Expr.h:5233
FieldDecl * getFieldDecl() const
Definition: Expr.h:5226
SourceLocation getFieldLoc() const
Definition: Expr.h:5243
const IdentifierInfo * getFieldName() const
Definition: Expr.cpp:4540
SourceLocation getDotLoc() const
Definition: Expr.h:5238
SourceLocation getLBracketLoc() const
Definition: Expr.h:5279
Represents a C99 designated initializer expression.
Definition: Expr.h:5092
bool isDirectInit() const
Whether this designated initializer should result in direct-initialization of the designated subobjec...
Definition: Expr.h:5352
Expr * getArrayRangeEnd(const Designator &D) const
Definition: Expr.cpp:4649
void setInit(Expr *init)
Definition: Expr.h:5364
Expr * getSubExpr(unsigned Idx) const
Definition: Expr.h:5374
llvm::MutableArrayRef< Designator > designators()
Definition: Expr.h:5325
bool usesGNUSyntax() const
Determines whether this designated initializer used the deprecated GNU syntax for designated initiali...
Definition: Expr.h:5356
Expr * getArrayRangeStart(const Designator &D) const
Definition: Expr.cpp:4644
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:4656
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4582
Expr * getArrayIndex(const Designator &D) const
Definition: Expr.cpp:4639
Designator * getDesignator(unsigned Idx)
Definition: Expr.h:5333
Expr * getInit() const
Retrieve the initializer value.
Definition: Expr.h:5360
unsigned size() const
Returns the number of designators in this initializer.
Definition: Expr.h:5322
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:4618
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:4635
SourceLocation getEqualOrColonLoc() const
Retrieve the location of the '=' that precedes the initializer value itself, if present.
Definition: Expr.h:5347
unsigned getNumSubExprs() const
Retrieve the total number of subexpressions in this designated initializer expression,...
Definition: Expr.h:5372
InitListExpr * getUpdater() const
Definition: Expr.h:5479
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:5571
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:3064
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:4133
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:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
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:3279
@ 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:3556
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
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:3193
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:3918
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:4057
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3058
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3219
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4646
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4668
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3152
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:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
QualType getReturnType() const
Definition: Decl.h:2755
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2348
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
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:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:594
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
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:742
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5600
Represents a C array with an unspecified size.
Definition: Type.h:3699
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
chain_iterator chain_end() const
Definition: Decl.h:3368
chain_iterator chain_begin() const
Definition: Decl.h:3367
ArrayRef< NamedDecl * >::const_iterator chain_iterator
Definition: Decl.h:3362
Describes an C or C++ initializer list.
Definition: Expr.h:4847
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition: Expr.h:4951
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:5017
void markError()
Mark the semantic form of the InitListExpr as error when the semantic analysis fails.
Definition: Expr.h:4913
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4954
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2432
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition: Expr.cpp:2392
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:4966
unsigned getNumInits() const
Definition: Expr.h:4877
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2466
void setInit(unsigned Init, Expr *expr)
Definition: Expr.h:4903
SourceLocation getLBraceLoc() const
Definition: Expr.h:5001
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:2396
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2408
InitListExpr * getSyntacticForm() const
Definition: Expr.h:5013
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4941
SourceLocation getRBraceLoc() const
Definition: Expr.h:5003
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition: Expr.cpp:2455
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2484
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:4972
bool isSyntacticForm() const
Definition: Expr.h:5010
void setRBraceLoc(SourceLocation Loc)
Definition: Expr.h:5004
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:5027
Expr ** getInits()
Retrieve the set of initializers.
Definition: Expr.h:4880
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:3866
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:8591
void AddStringInitStep(QualType T)
Add a string init step.
Definition: SemaInit.cpp:3901
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
Definition: SemaInit.cpp:3956
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
Definition: SemaInit.cpp:3873
@ 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:3809
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:6113
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
Definition: SemaInit.cpp:3822
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
Definition: SemaInit.cpp:3841
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
Definition: SemaInit.cpp:3772
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:6169
void AddParenthesizedListInitStep(QualType T)
Definition: SemaInit.cpp:3977
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:3700
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:3970
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:3794
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:3908
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
Definition: SemaInit.cpp:3999
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
Definition: SemaInit.cpp:3933
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:3801
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:3963
void AddCAssignmentStep(QualType T)
Add a C assignment step.
Definition: SemaInit.cpp:3894
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
Definition: SemaInit.cpp:3940
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:3984
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:9628
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:3848
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
Definition: SemaInit.cpp:10472
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
Definition: SemaInit.cpp:3855
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
Definition: SemaInit.cpp:3887
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
Definition: SemaInit.cpp:3949
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:3786
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:3689
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
Definition: SemaInit.cpp:3922
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:3760
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
Definition: SemaInit.cpp:3915
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3754
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:3470
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:3482
unsigned allocateManglingNumber() const
QualType getType() const
Retrieve type being initialized.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
Definition: SemaInit.cpp:3520
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:3554
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
Definition: SemaInit.cpp:3635
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:6217
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3420
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:362
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4686
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4711
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:5420
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:980
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void setDestAS(LangAS AS)
Definition: Overload.h:1215
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1001
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:996
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:1761
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
QualType withConst() const
Definition: Type.h:1154
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
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:7556
QualType getCanonicalType() const
Definition: Type.h:7407
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7428
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7476
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
void addAddressSpace(LangAS space)
Definition: Type.h:583
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
bool hasConst() const
Definition: Type.h:443
bool hasQualifiers() const
Return true if the set contains any qualifiers.
Definition: Type.h:632
bool hasAddressSpace() const
Definition: Type.h:556
Qualifiers withoutAddressSpace() const
Definition: Type.h:524
void removeAddressSpace()
Definition: Type.h:582
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:421
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
bool hasVolatile() const
Definition: Type.h:453
bool hasObjCLifetime() const
Definition: Type.h:530
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3438
Represents a struct/union/class.
Definition: Decl.h:4169
bool hasFlexibleArrayMember() const
Definition: Decl.h:4202
field_iterator field_end() const
Definition: Decl.h:4378
field_range fields() const
Definition: Decl.h:4375
bool isRandomized() const
Definition: Decl.h:4319
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4360
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4372
bool field_empty() const
Definition: Decl.h:4383
field_iterator field_begin() const
Definition: Decl.cpp:5071
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
bool isSpelledAsLValue() const
Definition: Type.h:3389
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4638
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
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)
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:167
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
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:8139
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8142
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8148
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8146
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17458
ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init)
Definition: SemaInit.cpp:3368
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1420
ASTContext & Context
Definition: Sema.h:858
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition: Sema.cpp:582
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
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:5792
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:762
ASTContext & getASTContext() const
Definition: Sema.h:527
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9967
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
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:8151
llvm::SmallVector< QualType, 4 > CurrentParameterCopyTypes
Stack of types that correspond to the parameter entities that are currently being copy-initialized.
Definition: Sema.h:7059
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:520
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
ExprResult PerformQualificationConversion(Expr *E, QualType Ty, ExprValueKind VK=VK_PRValue, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
Definition: SemaInit.cpp:8572
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17795
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8554
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:71
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5188
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:10019
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:10732
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:6295
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8535
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:6091
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6093
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6172
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1309
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21227
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10484
SourceManager & getSourceManager() const
Definition: Sema.h:525
AssignmentAction
Definition: Sema.h:5196
@ AA_Returning
Definition: Sema.h:5199
@ AA_Passing_CFAudited
Definition: Sema.h:5204
@ AA_Initializing
Definition: Sema.h:5201
@ AA_Converting
Definition: Sema.h:5200
@ AA_Passing
Definition: Sema.h:5198
@ AA_Casting
Definition: Sema.h:5203
@ AA_Sending
Definition: Sema.h:5202
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:20505
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5714
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11707
@ CTK_ErrorRecovery
Definition: Sema.h:7605
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3334
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:120
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5356
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:9276
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:8136
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6438
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
Definition: SemaType.cpp:9217
SourceManager & SourceMgr
Definition: Sema.h:861
DiagnosticsEngine & Diags
Definition: Sema.h:860
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:521
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16075
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5788
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:520
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:17125
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:18360
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:17051
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:10647
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:267
void setFromType(QualType T)
Definition: Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
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:364
QualType getToType(unsigned Idx) const
Definition: Overload.h:374
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
StringRef getString() const
Definition: Expr.h:1850
bool isUnion() const
Definition: Decl.h:3791
bool isBigEndian() const
Definition: TargetInfo.h:1629
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:6085
const Type * getTypeForDecl() const
Definition: Decl.h:3415
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:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7326
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:7337
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isVoidType() const
Definition: Type.h:7901
bool isBooleanType() const
Definition: Type.h:8029
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8076
bool isIncompleteArrayType() const
Definition: Type.h:7682
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool isRValueReferenceType() const
Definition: Type.h:7628
bool isConstantArrayType() const
Definition: Type.h:7678
bool isArrayType() const
Definition: Type.h:7674
bool isCharType() const
Definition: Type.cpp:2077
bool isPointerType() const
Definition: Type.h:7608
bool isArrayParameterType() const
Definition: Type.h:7690
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7941
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isScalarType() const
Definition: Type.h:8000
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:1855
bool isChar8Type() const
Definition: Type.cpp:2093
bool isSizelessBuiltinType() const
Definition: Type.cpp:2421
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isExtVectorType() const
Definition: Type.h:7718
bool isOCLIntelSubgroupAVCType() const
Definition: Type.h:7846
bool isLValueReferenceType() const
Definition: Type.h:7624
bool isOpenCLSpecificType() const
Definition: Type.h:7861
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2326
bool isAnyComplexType() const
Definition: Type.h:7710
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1999
bool isQueueT() const
Definition: Type.h:7817
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8069
bool isAtomicType() const
Definition: Type.h:7753
bool isFunctionProtoType() const
Definition: Type.h:2490
bool isObjCObjectType() const
Definition: Type.h:7744
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8172
bool isEventT() const
Definition: Type.h:7809
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool isVectorType() const
Definition: Type.h:7714
bool isFloatingType() const
Definition: Type.cpp:2237
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:2184
bool isSamplerT() const
Definition: Type.h:7805
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
bool isObjCRetainableType() const
Definition: Type.cpp:4862
bool isUnionType() const
Definition: Type.cpp:660
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:2183
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:5373
Represents a variable declaration or definition.
Definition: Decl.h:918
const Expr * getInit() const
Definition: Decl.h:1355
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3743
Represents a GCC generic vector type.
Definition: Type.h:3965
unsigned getNumElements() const
Definition: Type.h:3980
VectorKind getVectorKind() const
Definition: Type.h:3985
QualType getElementType() const
Definition: Type.h:3979
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:1867
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:59
@ CPlusPlus11
Definition: LangStandard.h:56
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
bool isCompoundAssignmentOperator(OverloadedOperatorKind Kind)
Determine if this is a compound assignment operator.
Definition: OperatorKinds.h:53
@ ovl_fail_bad_conversion
Definition: Overload.h:777
@ 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:1532
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:326
@ 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
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1241
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Braces
New-expression has a C++11 list-initializer.
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:442
@ Implicit
An implicit conversion.
@ CStyleCast
A C-style cast.
@ OtherCast
A cast other than a C-style cast.
@ FunctionalCast
A functional-style cast.
@ AS_public
Definition: Specifiers.h: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:1233
DeclAccessPair FoundDecl
Definition: Overload.h:1232
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:848
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:877
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:911
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:871
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8156
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427