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