Bug Summary

File:tools/clang/lib/Sema/SemaInit.cpp
Warning:line 5151, column 8
Called C++ object pointer is null

Annotated Source Code

1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Sema/Designator.h"
21#include "clang/Sema/Initialization.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
35/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
61 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
62 return SIF_Other;
63
64 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
66
67 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
69 return SIF_None;
70
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
73 if (!SL)
74 return SIF_Other;
75
76 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
78
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
84 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
94 case StringLiteral::UTF16:
95 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
102 case StringLiteral::UTF32:
103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
110 case StringLiteral::Wide:
111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
118 }
119
120 llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 120)
;
121}
122
123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
125 const ArrayType *arrayType = Context.getAsArrayType(declType);
126 if (!arrayType)
127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
129}
130
131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
134 while (true) {
135 E->setType(Ty);
136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 145)
;
146 }
147}
148
149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
151 // Get the length of the string as parsed.
152 auto *ConstantArrayTy =
153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
154 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
155
156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
157 // C99 6.7.8p14. We have an array of character type with unknown size
158 // being initialized to a string literal.
159 llvm::APInt ConstVal(32, StrLength);
160 // Return a new array type (C99 6.7.8p22).
161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
164 updateStringLiteralType(Str, DeclT);
165 return;
166 }
167
168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
169
170 // We have an array of character type with known size. However,
171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
173 if (S.getLangOpts().CPlusPlus) {
174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
185 S.Diag(Str->getLocStart(),
186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
191 S.Diag(Str->getLocStart(),
192 diag::ext_initializer_string_for_char_array_too_long)
193 << Str->getSourceRange();
194 }
195
196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
200 updateStringLiteralType(Str, DeclT);
201}
202
203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
207namespace {
208
209/// @brief Semantic checking for initializer lists.
210///
211/// The InitListChecker class contains a set of routines that each
212/// handle the initialization of a certain kind of entity, e.g.,
213/// arrays, vectors, struct/union types, scalars, etc. The
214/// InitListChecker itself performs a recursive walk of the subobject
215/// structure of the type to be initialized, while stepping through
216/// the initializer list one element at a time. The IList and Index
217/// parameters to each of the Check* routines contain the active
218/// (syntactic) initializer list and the index into that initializer
219/// list that represents the current initializer. Each routine is
220/// responsible for moving that Index forward as it consumes elements.
221///
222/// Each Check* routine also has a StructuredList/StructuredIndex
223/// arguments, which contains the current "structured" (semantic)
224/// initializer list and the index into that initializer list where we
225/// are copying initializers as we map them over to the semantic
226/// list. Once we have completed our recursive walk of the subobject
227/// structure, we will have constructed a full semantic initializer
228/// list.
229///
230/// C99 designators cause changes in the initializer list traversal,
231/// because they make the initialization "jump" into a specific
232/// subobject and then continue the initialization from that
233/// point. CheckDesignatedInitializer() recursively steps into the
234/// designated subobject and manages backing out the recursion to
235/// initialize the subobjects after the one designated.
236class InitListChecker {
237 Sema &SemaRef;
238 bool hadError;
239 bool VerifyOnly; // no diagnostics, no structure building
240 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
241 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
242 InitListExpr *FullyStructuredList;
243
244 void CheckImplicitInitList(const InitializedEntity &Entity,
245 InitListExpr *ParentIList, QualType T,
246 unsigned &Index, InitListExpr *StructuredList,
247 unsigned &StructuredIndex);
248 void CheckExplicitInitList(const InitializedEntity &Entity,
249 InitListExpr *IList, QualType &T,
250 InitListExpr *StructuredList,
251 bool TopLevelObject = false);
252 void CheckListElementTypes(const InitializedEntity &Entity,
253 InitListExpr *IList, QualType &DeclType,
254 bool SubobjectIsDesignatorContext,
255 unsigned &Index,
256 InitListExpr *StructuredList,
257 unsigned &StructuredIndex,
258 bool TopLevelObject = false);
259 void CheckSubElementType(const InitializedEntity &Entity,
260 InitListExpr *IList, QualType ElemType,
261 unsigned &Index,
262 InitListExpr *StructuredList,
263 unsigned &StructuredIndex);
264 void CheckComplexType(const InitializedEntity &Entity,
265 InitListExpr *IList, QualType DeclType,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
269 void CheckScalarType(const InitializedEntity &Entity,
270 InitListExpr *IList, QualType DeclType,
271 unsigned &Index,
272 InitListExpr *StructuredList,
273 unsigned &StructuredIndex);
274 void CheckReferenceType(const InitializedEntity &Entity,
275 InitListExpr *IList, QualType DeclType,
276 unsigned &Index,
277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
279 void CheckVectorType(const InitializedEntity &Entity,
280 InitListExpr *IList, QualType DeclType, unsigned &Index,
281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
283 void CheckStructUnionTypes(const InitializedEntity &Entity,
284 InitListExpr *IList, QualType DeclType,
285 CXXRecordDecl::base_class_range Bases,
286 RecordDecl::field_iterator Field,
287 bool SubobjectIsDesignatorContext, unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
291 void CheckArrayType(const InitializedEntity &Entity,
292 InitListExpr *IList, QualType &DeclType,
293 llvm::APSInt elementIndex,
294 bool SubobjectIsDesignatorContext, unsigned &Index,
295 InitListExpr *StructuredList,
296 unsigned &StructuredIndex);
297 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
298 InitListExpr *IList, DesignatedInitExpr *DIE,
299 unsigned DesigIdx,
300 QualType &CurrentObjectType,
301 RecordDecl::field_iterator *NextField,
302 llvm::APSInt *NextElementIndex,
303 unsigned &Index,
304 InitListExpr *StructuredList,
305 unsigned &StructuredIndex,
306 bool FinishSubobjectInit,
307 bool TopLevelObject);
308 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
309 QualType CurrentObjectType,
310 InitListExpr *StructuredList,
311 unsigned StructuredIndex,
312 SourceRange InitRange,
313 bool IsFullyOverwritten = false);
314 void UpdateStructuredListElement(InitListExpr *StructuredList,
315 unsigned &StructuredIndex,
316 Expr *expr);
317 int numArrayElements(QualType DeclType);
318 int numStructUnionElements(QualType DeclType);
319
320 static ExprResult PerformEmptyInit(Sema &SemaRef,
321 SourceLocation Loc,
322 const InitializedEntity &Entity,
323 bool VerifyOnly,
324 bool TreatUnavailableAsInvalid);
325
326 // Explanation on the "FillWithNoInit" mode:
327 //
328 // Assume we have the following definitions (Case#1):
329 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
330 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
331 //
332 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
333 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
334 //
335 // But if we have (Case#2):
336 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
337 //
338 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
339 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
340 //
341 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
342 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
343 // initializers but with special "NoInitExpr" place holders, which tells the
344 // CodeGen not to generate any initializers for these parts.
345 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
346 const InitializedEntity &ParentEntity,
347 InitListExpr *ILE, bool &RequiresSecondPass,
348 bool FillWithNoInit);
349 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
350 const InitializedEntity &ParentEntity,
351 InitListExpr *ILE, bool &RequiresSecondPass,
352 bool FillWithNoInit = false);
353 void FillInEmptyInitializations(const InitializedEntity &Entity,
354 InitListExpr *ILE, bool &RequiresSecondPass,
355 bool FillWithNoInit = false);
356 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
357 Expr *InitExpr, FieldDecl *Field,
358 bool TopLevelObject);
359 void CheckEmptyInitializable(const InitializedEntity &Entity,
360 SourceLocation Loc);
361
362public:
363 InitListChecker(Sema &S, const InitializedEntity &Entity,
364 InitListExpr *IL, QualType &T, bool VerifyOnly,
365 bool TreatUnavailableAsInvalid);
366 bool HadError() { return hadError; }
367
368 // @brief Retrieves the fully-structured initializer list used for
369 // semantic analysis and code generation.
370 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
371};
372
373} // end anonymous namespace
374
375ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
376 SourceLocation Loc,
377 const InitializedEntity &Entity,
378 bool VerifyOnly,
379 bool TreatUnavailableAsInvalid) {
380 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
381 true);
382 MultiExprArg SubInit;
383 Expr *InitExpr;
384 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
385
386 // C++ [dcl.init.aggr]p7:
387 // If there are fewer initializer-clauses in the list than there are
388 // members in the aggregate, then each member not explicitly initialized
389 // ...
390 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
391 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
392 if (EmptyInitList) {
393 // C++1y / DR1070:
394 // shall be initialized [...] from an empty initializer list.
395 //
396 // We apply the resolution of this DR to C++11 but not C++98, since C++98
397 // does not have useful semantics for initialization from an init list.
398 // We treat this as copy-initialization, because aggregate initialization
399 // always performs copy-initialization on its elements.
400 //
401 // Only do this if we're initializing a class type, to avoid filling in
402 // the initializer list where possible.
403 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
404 InitListExpr(SemaRef.Context, Loc, None, Loc);
405 InitExpr->setType(SemaRef.Context.VoidTy);
406 SubInit = InitExpr;
407 Kind = InitializationKind::CreateCopy(Loc, Loc);
408 } else {
409 // C++03:
410 // shall be value-initialized.
411 }
412
413 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
414 // libstdc++4.6 marks the vector default constructor as explicit in
415 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
416 // stlport does so too. Look for std::__debug for libstdc++, and for
417 // std:: for stlport. This is effectively a compiler-side implementation of
418 // LWG2193.
419 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
420 InitializationSequence::FK_ExplicitConstructor) {
421 OverloadCandidateSet::iterator Best;
422 OverloadingResult O =
423 InitSeq.getFailedCandidateSet()
424 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
425 (void)O;
426 assert(O == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (O == OR_Success && "Inconsistent overload resolution"
) ? void (0) : __assert_fail ("O == OR_Success && \"Inconsistent overload resolution\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 426, __extension__ __PRETTY_FUNCTION__))
;
427 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
428 CXXRecordDecl *R = CtorDecl->getParent();
429
430 if (CtorDecl->getMinRequiredArguments() == 0 &&
431 CtorDecl->isExplicit() && R->getDeclName() &&
432 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
433 bool IsInStd = false;
434 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
435 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
436 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
437 IsInStd = true;
438 }
439
440 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
441 .Cases("basic_string", "deque", "forward_list", true)
442 .Cases("list", "map", "multimap", "multiset", true)
443 .Cases("priority_queue", "queue", "set", "stack", true)
444 .Cases("unordered_map", "unordered_set", "vector", true)
445 .Default(false)) {
446 InitSeq.InitializeFrom(
447 SemaRef, Entity,
448 InitializationKind::CreateValue(Loc, Loc, Loc, true),
449 MultiExprArg(), /*TopLevelOfInitList=*/false,
450 TreatUnavailableAsInvalid);
451 // Emit a warning for this. System header warnings aren't shown
452 // by default, but people working on system headers should see it.
453 if (!VerifyOnly) {
454 SemaRef.Diag(CtorDecl->getLocation(),
455 diag::warn_invalid_initializer_from_system_header);
456 if (Entity.getKind() == InitializedEntity::EK_Member)
457 SemaRef.Diag(Entity.getDecl()->getLocation(),
458 diag::note_used_in_initialization_here);
459 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
460 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
461 }
462 }
463 }
464 }
465 if (!InitSeq) {
466 if (!VerifyOnly) {
467 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
468 if (Entity.getKind() == InitializedEntity::EK_Member)
469 SemaRef.Diag(Entity.getDecl()->getLocation(),
470 diag::note_in_omitted_aggregate_initializer)
471 << /*field*/1 << Entity.getDecl();
472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
473 bool IsTrailingArrayNewMember =
474 Entity.getParent() &&
475 Entity.getParent()->isVariableLengthArrayNew();
476 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
477 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
478 << Entity.getElementIndex();
479 }
480 }
481 return ExprError();
482 }
483
484 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
485 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
486}
487
488void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
489 SourceLocation Loc) {
490 assert(VerifyOnly &&(static_cast <bool> (VerifyOnly && "CheckEmptyInitializable is only inteded for verification mode."
) ? void (0) : __assert_fail ("VerifyOnly && \"CheckEmptyInitializable is only inteded for verification mode.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 491, __extension__ __PRETTY_FUNCTION__))
491 "CheckEmptyInitializable is only inteded for verification mode.")(static_cast <bool> (VerifyOnly && "CheckEmptyInitializable is only inteded for verification mode."
) ? void (0) : __assert_fail ("VerifyOnly && \"CheckEmptyInitializable is only inteded for verification mode.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 491, __extension__ __PRETTY_FUNCTION__))
;
492 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
493 TreatUnavailableAsInvalid).isInvalid())
494 hadError = true;
495}
496
497void InitListChecker::FillInEmptyInitForBase(
498 unsigned Init, const CXXBaseSpecifier &Base,
499 const InitializedEntity &ParentEntity, InitListExpr *ILE,
500 bool &RequiresSecondPass, bool FillWithNoInit) {
501 assert(Init < ILE->getNumInits() && "should have been expanded")(static_cast <bool> (Init < ILE->getNumInits() &&
"should have been expanded") ? void (0) : __assert_fail ("Init < ILE->getNumInits() && \"should have been expanded\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 501, __extension__ __PRETTY_FUNCTION__))
;
502
503 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
504 SemaRef.Context, &Base, false, &ParentEntity);
505
506 if (!ILE->getInit(Init)) {
507 ExprResult BaseInit =
508 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
509 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
510 /*VerifyOnly*/ false,
511 TreatUnavailableAsInvalid);
512 if (BaseInit.isInvalid()) {
513 hadError = true;
514 return;
515 }
516
517 ILE->setInit(Init, BaseInit.getAs<Expr>());
518 } else if (InitListExpr *InnerILE =
519 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
520 FillInEmptyInitializations(BaseEntity, InnerILE,
521 RequiresSecondPass, FillWithNoInit);
522 } else if (DesignatedInitUpdateExpr *InnerDIUE =
523 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
524 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
525 RequiresSecondPass, /*FillWithNoInit =*/true);
526 }
527}
528
529void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
530 const InitializedEntity &ParentEntity,
531 InitListExpr *ILE,
532 bool &RequiresSecondPass,
533 bool FillWithNoInit) {
534 SourceLocation Loc = ILE->getLocEnd();
535 unsigned NumInits = ILE->getNumInits();
536 InitializedEntity MemberEntity
537 = InitializedEntity::InitializeMember(Field, &ParentEntity);
538
539 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
540 if (!RType->getDecl()->isUnion())
541 assert(Init < NumInits && "This ILE should have been expanded")(static_cast <bool> (Init < NumInits && "This ILE should have been expanded"
) ? void (0) : __assert_fail ("Init < NumInits && \"This ILE should have been expanded\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 541, __extension__ __PRETTY_FUNCTION__))
;
542
543 if (Init >= NumInits || !ILE->getInit(Init)) {
544 if (FillWithNoInit) {
545 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
546 if (Init < NumInits)
547 ILE->setInit(Init, Filler);
548 else
549 ILE->updateInit(SemaRef.Context, Init, Filler);
550 return;
551 }
552 // C++1y [dcl.init.aggr]p7:
553 // If there are fewer initializer-clauses in the list than there are
554 // members in the aggregate, then each member not explicitly initialized
555 // shall be initialized from its brace-or-equal-initializer [...]
556 if (Field->hasInClassInitializer()) {
557 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
558 if (DIE.isInvalid()) {
559 hadError = true;
560 return;
561 }
562 if (Init < NumInits)
563 ILE->setInit(Init, DIE.get());
564 else {
565 ILE->updateInit(SemaRef.Context, Init, DIE.get());
566 RequiresSecondPass = true;
567 }
568 return;
569 }
570
571 if (Field->getType()->isReferenceType()) {
572 // C++ [dcl.init.aggr]p9:
573 // If an incomplete or empty initializer-list leaves a
574 // member of reference type uninitialized, the program is
575 // ill-formed.
576 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
577 << Field->getType()
578 << ILE->getSyntacticForm()->getSourceRange();
579 SemaRef.Diag(Field->getLocation(),
580 diag::note_uninit_reference_member);
581 hadError = true;
582 return;
583 }
584
585 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
586 /*VerifyOnly*/false,
587 TreatUnavailableAsInvalid);
588 if (MemberInit.isInvalid()) {
589 hadError = true;
590 return;
591 }
592
593 if (hadError) {
594 // Do nothing
595 } else if (Init < NumInits) {
596 ILE->setInit(Init, MemberInit.getAs<Expr>());
597 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
598 // Empty initialization requires a constructor call, so
599 // extend the initializer list to include the constructor
600 // call and make a note that we'll need to take another pass
601 // through the initializer list.
602 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
603 RequiresSecondPass = true;
604 }
605 } else if (InitListExpr *InnerILE
606 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
607 FillInEmptyInitializations(MemberEntity, InnerILE,
608 RequiresSecondPass, FillWithNoInit);
609 else if (DesignatedInitUpdateExpr *InnerDIUE
610 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
611 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
612 RequiresSecondPass, /*FillWithNoInit =*/ true);
613}
614
615/// Recursively replaces NULL values within the given initializer list
616/// with expressions that perform value-initialization of the
617/// appropriate type.
618void
619InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
620 InitListExpr *ILE,
621 bool &RequiresSecondPass,
622 bool FillWithNoInit) {
623 assert((ILE->getType() != SemaRef.Context.VoidTy) &&(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 624, __extension__ __PRETTY_FUNCTION__))
624 "Should not have void type")(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 624, __extension__ __PRETTY_FUNCTION__))
;
625
626 // A transparent ILE is not performing aggregate initialization and should
627 // not be filled in.
628 if (ILE->isTransparent())
629 return;
630
631 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
632 const RecordDecl *RDecl = RType->getDecl();
633 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
634 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
635 Entity, ILE, RequiresSecondPass, FillWithNoInit);
636 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
637 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
638 for (auto *Field : RDecl->fields()) {
639 if (Field->hasInClassInitializer()) {
640 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
641 FillWithNoInit);
642 break;
643 }
644 }
645 } else {
646 // The fields beyond ILE->getNumInits() are default initialized, so in
647 // order to leave them uninitialized, the ILE is expanded and the extra
648 // fields are then filled with NoInitExpr.
649 unsigned NumElems = numStructUnionElements(ILE->getType());
650 if (RDecl->hasFlexibleArrayMember())
651 ++NumElems;
652 if (ILE->getNumInits() < NumElems)
653 ILE->resizeInits(SemaRef.Context, NumElems);
654
655 unsigned Init = 0;
656
657 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
658 for (auto &Base : CXXRD->bases()) {
659 if (hadError)
660 return;
661
662 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
663 FillWithNoInit);
664 ++Init;
665 }
666 }
667
668 for (auto *Field : RDecl->fields()) {
669 if (Field->isUnnamedBitfield())
670 continue;
671
672 if (hadError)
673 return;
674
675 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
676 FillWithNoInit);
677 if (hadError)
678 return;
679
680 ++Init;
681
682 // Only look at the first initialization of a union.
683 if (RDecl->isUnion())
684 break;
685 }
686 }
687
688 return;
689 }
690
691 QualType ElementType;
692
693 InitializedEntity ElementEntity = Entity;
694 unsigned NumInits = ILE->getNumInits();
695 unsigned NumElements = NumInits;
696 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
697 ElementType = AType->getElementType();
698 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
699 NumElements = CAType->getSize().getZExtValue();
700 // For an array new with an unknown bound, ask for one additional element
701 // in order to populate the array filler.
702 if (Entity.isVariableLengthArrayNew())
703 ++NumElements;
704 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
705 0, Entity);
706 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
707 ElementType = VType->getElementType();
708 NumElements = VType->getNumElements();
709 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
710 0, Entity);
711 } else
712 ElementType = ILE->getType();
713
714 for (unsigned Init = 0; Init != NumElements; ++Init) {
715 if (hadError)
716 return;
717
718 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
719 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
720 ElementEntity.setElementIndex(Init);
721
722 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
723 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
724 ILE->setInit(Init, ILE->getArrayFiller());
725 else if (!InitExpr && !ILE->hasArrayFiller()) {
726 Expr *Filler = nullptr;
727
728 if (FillWithNoInit)
729 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
730 else {
731 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
732 ElementEntity,
733 /*VerifyOnly*/false,
734 TreatUnavailableAsInvalid);
735 if (ElementInit.isInvalid()) {
736 hadError = true;
737 return;
738 }
739
740 Filler = ElementInit.getAs<Expr>();
741 }
742
743 if (hadError) {
744 // Do nothing
745 } else if (Init < NumInits) {
746 // For arrays, just set the expression used for value-initialization
747 // of the "holes" in the array.
748 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
749 ILE->setArrayFiller(Filler);
750 else
751 ILE->setInit(Init, Filler);
752 } else {
753 // For arrays, just set the expression used for value-initialization
754 // of the rest of elements and exit.
755 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
756 ILE->setArrayFiller(Filler);
757 return;
758 }
759
760 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
761 // Empty initialization requires a constructor call, so
762 // extend the initializer list to include the constructor
763 // call and make a note that we'll need to take another pass
764 // through the initializer list.
765 ILE->updateInit(SemaRef.Context, Init, Filler);
766 RequiresSecondPass = true;
767 }
768 }
769 } else if (InitListExpr *InnerILE
770 = dyn_cast_or_null<InitListExpr>(InitExpr))
771 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
772 FillWithNoInit);
773 else if (DesignatedInitUpdateExpr *InnerDIUE
774 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
775 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
776 RequiresSecondPass, /*FillWithNoInit =*/ true);
777 }
778}
779
780InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
781 InitListExpr *IL, QualType &T,
782 bool VerifyOnly,
783 bool TreatUnavailableAsInvalid)
784 : SemaRef(S), VerifyOnly(VerifyOnly),
785 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
786 // FIXME: Check that IL isn't already the semantic form of some other
787 // InitListExpr. If it is, we'd create a broken AST.
788
789 hadError = false;
790
791 FullyStructuredList =
792 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
793 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
794 /*TopLevelObject=*/true);
795
796 if (!hadError && !VerifyOnly) {
797 bool RequiresSecondPass = false;
798 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
799 if (RequiresSecondPass && !hadError)
800 FillInEmptyInitializations(Entity, FullyStructuredList,
801 RequiresSecondPass);
802 }
803}
804
805int InitListChecker::numArrayElements(QualType DeclType) {
806 // FIXME: use a proper constant
807 int maxElements = 0x7FFFFFFF;
808 if (const ConstantArrayType *CAT =
809 SemaRef.Context.getAsConstantArrayType(DeclType)) {
810 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
811 }
812 return maxElements;
813}
814
815int InitListChecker::numStructUnionElements(QualType DeclType) {
816 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
817 int InitializableMembers = 0;
818 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
819 InitializableMembers += CXXRD->getNumBases();
820 for (const auto *Field : structDecl->fields())
821 if (!Field->isUnnamedBitfield())
822 ++InitializableMembers;
823
824 if (structDecl->isUnion())
825 return std::min(InitializableMembers, 1);
826 return InitializableMembers - structDecl->hasFlexibleArrayMember();
827}
828
829/// Determine whether Entity is an entity for which it is idiomatic to elide
830/// the braces in aggregate initialization.
831static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
832 // Recursive initialization of the one and only field within an aggregate
833 // class is considered idiomatic. This case arises in particular for
834 // initialization of std::array, where the C++ standard suggests the idiom of
835 //
836 // std::array<T, N> arr = {1, 2, 3};
837 //
838 // (where std::array is an aggregate struct containing a single array field.
839
840 // FIXME: Should aggregate initialization of a struct with a single
841 // base class and no members also suppress the warning?
842 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
843 return false;
844
845 auto *ParentRD =
846 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
847 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
848 if (CXXRD->getNumBases())
849 return false;
850
851 auto FieldIt = ParentRD->field_begin();
852 assert(FieldIt != ParentRD->field_end() &&(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 853, __extension__ __PRETTY_FUNCTION__))
853 "no fields but have initializer for member?")(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 853, __extension__ __PRETTY_FUNCTION__))
;
854 return ++FieldIt == ParentRD->field_end();
855}
856
857/// Check whether the range of the initializer \p ParentIList from element
858/// \p Index onwards can be used to initialize an object of type \p T. Update
859/// \p Index to indicate how many elements of the list were consumed.
860///
861/// This also fills in \p StructuredList, from element \p StructuredIndex
862/// onwards, with the fully-braced, desugared form of the initialization.
863void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
864 InitListExpr *ParentIList,
865 QualType T, unsigned &Index,
866 InitListExpr *StructuredList,
867 unsigned &StructuredIndex) {
868 int maxElements = 0;
869
870 if (T->isArrayType())
871 maxElements = numArrayElements(T);
872 else if (T->isRecordType())
873 maxElements = numStructUnionElements(T);
874 else if (T->isVectorType())
875 maxElements = T->getAs<VectorType>()->getNumElements();
876 else
877 llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 877)
;
878
879 if (maxElements == 0) {
880 if (!VerifyOnly)
881 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
882 diag::err_implicit_empty_initializer);
883 ++Index;
884 hadError = true;
885 return;
886 }
887
888 // Build a structured initializer list corresponding to this subobject.
889 InitListExpr *StructuredSubobjectInitList
890 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
891 StructuredIndex,
892 SourceRange(ParentIList->getInit(Index)->getLocStart(),
893 ParentIList->getSourceRange().getEnd()));
894 unsigned StructuredSubobjectInitIndex = 0;
895
896 // Check the element types and build the structural subobject.
897 unsigned StartIndex = Index;
898 CheckListElementTypes(Entity, ParentIList, T,
899 /*SubobjectIsDesignatorContext=*/false, Index,
900 StructuredSubobjectInitList,
901 StructuredSubobjectInitIndex);
902
903 if (!VerifyOnly) {
904 StructuredSubobjectInitList->setType(T);
905
906 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
907 // Update the structured sub-object initializer so that it's ending
908 // range corresponds with the end of the last initializer it used.
909 if (EndIndex < ParentIList->getNumInits() &&
910 ParentIList->getInit(EndIndex)) {
911 SourceLocation EndLoc
912 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
913 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
914 }
915
916 // Complain about missing braces.
917 if ((T->isArrayType() || T->isRecordType()) &&
918 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
919 !isIdiomaticBraceElisionEntity(Entity)) {
920 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
921 diag::warn_missing_braces)
922 << StructuredSubobjectInitList->getSourceRange()
923 << FixItHint::CreateInsertion(
924 StructuredSubobjectInitList->getLocStart(), "{")
925 << FixItHint::CreateInsertion(
926 SemaRef.getLocForEndOfToken(
927 StructuredSubobjectInitList->getLocEnd()),
928 "}");
929 }
930 }
931}
932
933/// Warn that \p Entity was of scalar type and was initialized by a
934/// single-element braced initializer list.
935static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
936 SourceRange Braces) {
937 // Don't warn during template instantiation. If the initialization was
938 // non-dependent, we warned during the initial parse; otherwise, the
939 // type might not be scalar in some uses of the template.
940 if (S.inTemplateInstantiation())
941 return;
942
943 unsigned DiagID = 0;
944
945 switch (Entity.getKind()) {
946 case InitializedEntity::EK_VectorElement:
947 case InitializedEntity::EK_ComplexElement:
948 case InitializedEntity::EK_ArrayElement:
949 case InitializedEntity::EK_Parameter:
950 case InitializedEntity::EK_Parameter_CF_Audited:
951 case InitializedEntity::EK_Result:
952 // Extra braces here are suspicious.
953 DiagID = diag::warn_braces_around_scalar_init;
954 break;
955
956 case InitializedEntity::EK_Member:
957 // Warn on aggregate initialization but not on ctor init list or
958 // default member initializer.
959 if (Entity.getParent())
960 DiagID = diag::warn_braces_around_scalar_init;
961 break;
962
963 case InitializedEntity::EK_Variable:
964 case InitializedEntity::EK_LambdaCapture:
965 // No warning, might be direct-list-initialization.
966 // FIXME: Should we warn for copy-list-initialization in these cases?
967 break;
968
969 case InitializedEntity::EK_New:
970 case InitializedEntity::EK_Temporary:
971 case InitializedEntity::EK_CompoundLiteralInit:
972 // No warning, braces are part of the syntax of the underlying construct.
973 break;
974
975 case InitializedEntity::EK_RelatedResult:
976 // No warning, we already warned when initializing the result.
977 break;
978
979 case InitializedEntity::EK_Exception:
980 case InitializedEntity::EK_Base:
981 case InitializedEntity::EK_Delegating:
982 case InitializedEntity::EK_BlockElement:
983 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
984 case InitializedEntity::EK_Binding:
985 llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 985)
;
986 }
987
988 if (DiagID) {
989 S.Diag(Braces.getBegin(), DiagID)
990 << Braces
991 << FixItHint::CreateRemoval(Braces.getBegin())
992 << FixItHint::CreateRemoval(Braces.getEnd());
993 }
994}
995
996/// Check whether the initializer \p IList (that was written with explicit
997/// braces) can be used to initialize an object of type \p T.
998///
999/// This also fills in \p StructuredList with the fully-braced, desugared
1000/// form of the initialization.
1001void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1002 InitListExpr *IList, QualType &T,
1003 InitListExpr *StructuredList,
1004 bool TopLevelObject) {
1005 if (!VerifyOnly) {
1006 SyntacticToSemantic[IList] = StructuredList;
1007 StructuredList->setSyntacticForm(IList);
1008 }
1009
1010 unsigned Index = 0, StructuredIndex = 0;
1011 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1012 Index, StructuredList, StructuredIndex, TopLevelObject);
1013 if (!VerifyOnly) {
1014 QualType ExprTy = T;
1015 if (!ExprTy->isArrayType())
1016 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1017 IList->setType(ExprTy);
1018 StructuredList->setType(ExprTy);
1019 }
1020 if (hadError)
1021 return;
1022
1023 if (Index < IList->getNumInits()) {
1024 // We have leftover initializers
1025 if (VerifyOnly) {
1026 if (SemaRef.getLangOpts().CPlusPlus ||
1027 (SemaRef.getLangOpts().OpenCL &&
1028 IList->getType()->isVectorType())) {
1029 hadError = true;
1030 }
1031 return;
1032 }
1033
1034 if (StructuredIndex == 1 &&
1035 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1036 SIF_None) {
1037 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1038 if (SemaRef.getLangOpts().CPlusPlus) {
1039 DK = diag::err_excess_initializers_in_char_array_initializer;
1040 hadError = true;
1041 }
1042 // Special-case
1043 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1044 << IList->getInit(Index)->getSourceRange();
1045 } else if (!T->isIncompleteType()) {
1046 // Don't complain for incomplete types, since we'll get an error
1047 // elsewhere
1048 QualType CurrentObjectType = StructuredList->getType();
1049 int initKind =
1050 CurrentObjectType->isArrayType()? 0 :
1051 CurrentObjectType->isVectorType()? 1 :
1052 CurrentObjectType->isScalarType()? 2 :
1053 CurrentObjectType->isUnionType()? 3 :
1054 4;
1055
1056 unsigned DK = diag::ext_excess_initializers;
1057 if (SemaRef.getLangOpts().CPlusPlus) {
1058 DK = diag::err_excess_initializers;
1059 hadError = true;
1060 }
1061 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1062 DK = diag::err_excess_initializers;
1063 hadError = true;
1064 }
1065
1066 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1067 << initKind << IList->getInit(Index)->getSourceRange();
1068 }
1069 }
1070
1071 if (!VerifyOnly && T->isScalarType() &&
1072 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1073 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1074}
1075
1076void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1077 InitListExpr *IList,
1078 QualType &DeclType,
1079 bool SubobjectIsDesignatorContext,
1080 unsigned &Index,
1081 InitListExpr *StructuredList,
1082 unsigned &StructuredIndex,
1083 bool TopLevelObject) {
1084 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1085 // Explicitly braced initializer for complex type can be real+imaginary
1086 // parts.
1087 CheckComplexType(Entity, IList, DeclType, Index,
1088 StructuredList, StructuredIndex);
1089 } else if (DeclType->isScalarType()) {
1090 CheckScalarType(Entity, IList, DeclType, Index,
1091 StructuredList, StructuredIndex);
1092 } else if (DeclType->isVectorType()) {
1093 CheckVectorType(Entity, IList, DeclType, Index,
1094 StructuredList, StructuredIndex);
1095 } else if (DeclType->isRecordType()) {
1096 assert(DeclType->isAggregateType() &&(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1097, __extension__ __PRETTY_FUNCTION__))
1097 "non-aggregate records should be handed in CheckSubElementType")(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1097, __extension__ __PRETTY_FUNCTION__))
;
1098 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1099 auto Bases =
1100 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1101 CXXRecordDecl::base_class_iterator());
1102 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1103 Bases = CXXRD->bases();
1104 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1105 SubobjectIsDesignatorContext, Index, StructuredList,
1106 StructuredIndex, TopLevelObject);
1107 } else if (DeclType->isArrayType()) {
1108 llvm::APSInt Zero(
1109 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1110 false);
1111 CheckArrayType(Entity, IList, DeclType, Zero,
1112 SubobjectIsDesignatorContext, Index,
1113 StructuredList, StructuredIndex);
1114 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1115 // This type is invalid, issue a diagnostic.
1116 ++Index;
1117 if (!VerifyOnly)
1118 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1119 << DeclType;
1120 hadError = true;
1121 } else if (DeclType->isReferenceType()) {
1122 CheckReferenceType(Entity, IList, DeclType, Index,
1123 StructuredList, StructuredIndex);
1124 } else if (DeclType->isObjCObjectType()) {
1125 if (!VerifyOnly)
1126 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1127 << DeclType;
1128 hadError = true;
1129 } else {
1130 if (!VerifyOnly)
1131 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1132 << DeclType;
1133 hadError = true;
1134 }
1135}
1136
1137void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1138 InitListExpr *IList,
1139 QualType ElemType,
1140 unsigned &Index,
1141 InitListExpr *StructuredList,
1142 unsigned &StructuredIndex) {
1143 Expr *expr = IList->getInit(Index);
1144
1145 if (ElemType->isReferenceType())
1146 return CheckReferenceType(Entity, IList, ElemType, Index,
1147 StructuredList, StructuredIndex);
1148
1149 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1150 if (SubInitList->getNumInits() == 1 &&
1151 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1152 SIF_None) {
1153 expr = SubInitList->getInit(0);
1154 } else if (!SemaRef.getLangOpts().CPlusPlus) {
1155 InitListExpr *InnerStructuredList
1156 = getStructuredSubobjectInit(IList, Index, ElemType,
1157 StructuredList, StructuredIndex,
1158 SubInitList->getSourceRange(), true);
1159 CheckExplicitInitList(Entity, SubInitList, ElemType,
1160 InnerStructuredList);
1161
1162 if (!hadError && !VerifyOnly) {
1163 bool RequiresSecondPass = false;
1164 FillInEmptyInitializations(Entity, InnerStructuredList,
1165 RequiresSecondPass);
1166 if (RequiresSecondPass && !hadError)
1167 FillInEmptyInitializations(Entity, InnerStructuredList,
1168 RequiresSecondPass);
1169 }
1170 ++StructuredIndex;
1171 ++Index;
1172 return;
1173 }
1174 // C++ initialization is handled later.
1175 } else if (isa<ImplicitValueInitExpr>(expr)) {
1176 // This happens during template instantiation when we see an InitListExpr
1177 // that we've already checked once.
1178 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1179, __extension__ __PRETTY_FUNCTION__))
1179 "found implicit initialization for the wrong type")(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1179, __extension__ __PRETTY_FUNCTION__))
;
1180 if (!VerifyOnly)
1181 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1182 ++Index;
1183 return;
1184 }
1185
1186 if (SemaRef.getLangOpts().CPlusPlus) {
1187 // C++ [dcl.init.aggr]p2:
1188 // Each member is copy-initialized from the corresponding
1189 // initializer-clause.
1190
1191 // FIXME: Better EqualLoc?
1192 InitializationKind Kind =
1193 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1194 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1195 /*TopLevelOfInitList*/ true);
1196
1197 // C++14 [dcl.init.aggr]p13:
1198 // If the assignment-expression can initialize a member, the member is
1199 // initialized. Otherwise [...] brace elision is assumed
1200 //
1201 // Brace elision is never performed if the element is not an
1202 // assignment-expression.
1203 if (Seq || isa<InitListExpr>(expr)) {
1204 if (!VerifyOnly) {
1205 ExprResult Result =
1206 Seq.Perform(SemaRef, Entity, Kind, expr);
1207 if (Result.isInvalid())
1208 hadError = true;
1209
1210 UpdateStructuredListElement(StructuredList, StructuredIndex,
1211 Result.getAs<Expr>());
1212 } else if (!Seq)
1213 hadError = true;
1214 ++Index;
1215 return;
1216 }
1217
1218 // Fall through for subaggregate initialization
1219 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1220 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1221 return CheckScalarType(Entity, IList, ElemType, Index,
1222 StructuredList, StructuredIndex);
1223 } else if (const ArrayType *arrayType =
1224 SemaRef.Context.getAsArrayType(ElemType)) {
1225 // arrayType can be incomplete if we're initializing a flexible
1226 // array member. There's nothing we can do with the completed
1227 // type here, though.
1228
1229 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1230 if (!VerifyOnly) {
1231 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1232 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1233 }
1234 ++Index;
1235 return;
1236 }
1237
1238 // Fall through for subaggregate initialization.
1239
1240 } else {
1241 assert((ElemType->isRecordType() || ElemType->isVectorType() ||(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1242, __extension__ __PRETTY_FUNCTION__))
1242 ElemType->isOpenCLSpecificType()) && "Unexpected type")(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1242, __extension__ __PRETTY_FUNCTION__))
;
1243
1244 // C99 6.7.8p13:
1245 //
1246 // The initializer for a structure or union object that has
1247 // automatic storage duration shall be either an initializer
1248 // list as described below, or a single expression that has
1249 // compatible structure or union type. In the latter case, the
1250 // initial value of the object, including unnamed members, is
1251 // that of the expression.
1252 ExprResult ExprRes = expr;
1253 if (SemaRef.CheckSingleAssignmentConstraints(
1254 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1255 if (ExprRes.isInvalid())
1256 hadError = true;
1257 else {
1258 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1259 if (ExprRes.isInvalid())
1260 hadError = true;
1261 }
1262 UpdateStructuredListElement(StructuredList, StructuredIndex,
1263 ExprRes.getAs<Expr>());
1264 ++Index;
1265 return;
1266 }
1267 ExprRes.get();
1268 // Fall through for subaggregate initialization
1269 }
1270
1271 // C++ [dcl.init.aggr]p12:
1272 //
1273 // [...] Otherwise, if the member is itself a non-empty
1274 // subaggregate, brace elision is assumed and the initializer is
1275 // considered for the initialization of the first member of
1276 // the subaggregate.
1277 // OpenCL vector initializer is handled elsewhere.
1278 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1279 ElemType->isAggregateType()) {
1280 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1281 StructuredIndex);
1282 ++StructuredIndex;
1283 } else {
1284 if (!VerifyOnly) {
1285 // We cannot initialize this element, so let
1286 // PerformCopyInitialization produce the appropriate diagnostic.
1287 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1288 /*TopLevelOfInitList=*/true);
1289 }
1290 hadError = true;
1291 ++Index;
1292 ++StructuredIndex;
1293 }
1294}
1295
1296void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1297 InitListExpr *IList, QualType DeclType,
1298 unsigned &Index,
1299 InitListExpr *StructuredList,
1300 unsigned &StructuredIndex) {
1301 assert(Index == 0 && "Index in explicit init list must be zero")(static_cast <bool> (Index == 0 && "Index in explicit init list must be zero"
) ? void (0) : __assert_fail ("Index == 0 && \"Index in explicit init list must be zero\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1301, __extension__ __PRETTY_FUNCTION__))
;
1302
1303 // As an extension, clang supports complex initializers, which initialize
1304 // a complex number component-wise. When an explicit initializer list for
1305 // a complex number contains two two initializers, this extension kicks in:
1306 // it exepcts the initializer list to contain two elements convertible to
1307 // the element type of the complex type. The first element initializes
1308 // the real part, and the second element intitializes the imaginary part.
1309
1310 if (IList->getNumInits() != 2)
1311 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1312 StructuredIndex);
1313
1314 // This is an extension in C. (The builtin _Complex type does not exist
1315 // in the C++ standard.)
1316 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1317 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1318 << IList->getSourceRange();
1319
1320 // Initialize the complex number.
1321 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1322 InitializedEntity ElementEntity =
1323 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1324
1325 for (unsigned i = 0; i < 2; ++i) {
1326 ElementEntity.setElementIndex(Index);
1327 CheckSubElementType(ElementEntity, IList, elementType, Index,
1328 StructuredList, StructuredIndex);
1329 }
1330}
1331
1332void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1333 InitListExpr *IList, QualType DeclType,
1334 unsigned &Index,
1335 InitListExpr *StructuredList,
1336 unsigned &StructuredIndex) {
1337 if (Index >= IList->getNumInits()) {
1338 if (!VerifyOnly)
1339 SemaRef.Diag(IList->getLocStart(),
1340 SemaRef.getLangOpts().CPlusPlus11 ?
1341 diag::warn_cxx98_compat_empty_scalar_initializer :
1342 diag::err_empty_scalar_initializer)
1343 << IList->getSourceRange();
1344 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1345 ++Index;
1346 ++StructuredIndex;
1347 return;
1348 }
1349
1350 Expr *expr = IList->getInit(Index);
1351 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1352 // FIXME: This is invalid, and accepting it causes overload resolution
1353 // to pick the wrong overload in some corner cases.
1354 if (!VerifyOnly)
1355 SemaRef.Diag(SubIList->getLocStart(),
1356 diag::ext_many_braces_around_scalar_init)
1357 << SubIList->getSourceRange();
1358
1359 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1360 StructuredIndex);
1361 return;
1362 } else if (isa<DesignatedInitExpr>(expr)) {
1363 if (!VerifyOnly)
1364 SemaRef.Diag(expr->getLocStart(),
1365 diag::err_designator_for_scalar_init)
1366 << DeclType << expr->getSourceRange();
1367 hadError = true;
1368 ++Index;
1369 ++StructuredIndex;
1370 return;
1371 }
1372
1373 if (VerifyOnly) {
1374 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1375 hadError = true;
1376 ++Index;
1377 return;
1378 }
1379
1380 ExprResult Result =
1381 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1382 /*TopLevelOfInitList=*/true);
1383
1384 Expr *ResultExpr = nullptr;
1385
1386 if (Result.isInvalid())
1387 hadError = true; // types weren't compatible.
1388 else {
1389 ResultExpr = Result.getAs<Expr>();
1390
1391 if (ResultExpr != expr) {
1392 // The type was promoted, update initializer list.
1393 IList->setInit(Index, ResultExpr);
1394 }
1395 }
1396 if (hadError)
1397 ++StructuredIndex;
1398 else
1399 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1400 ++Index;
1401}
1402
1403void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1404 InitListExpr *IList, QualType DeclType,
1405 unsigned &Index,
1406 InitListExpr *StructuredList,
1407 unsigned &StructuredIndex) {
1408 if (Index >= IList->getNumInits()) {
1409 // FIXME: It would be wonderful if we could point at the actual member. In
1410 // general, it would be useful to pass location information down the stack,
1411 // so that we know the location (or decl) of the "current object" being
1412 // initialized.
1413 if (!VerifyOnly)
1414 SemaRef.Diag(IList->getLocStart(),
1415 diag::err_init_reference_member_uninitialized)
1416 << DeclType
1417 << IList->getSourceRange();
1418 hadError = true;
1419 ++Index;
1420 ++StructuredIndex;
1421 return;
1422 }
1423
1424 Expr *expr = IList->getInit(Index);
1425 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1426 if (!VerifyOnly)
1427 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1428 << DeclType << IList->getSourceRange();
1429 hadError = true;
1430 ++Index;
1431 ++StructuredIndex;
1432 return;
1433 }
1434
1435 if (VerifyOnly) {
1436 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1437 hadError = true;
1438 ++Index;
1439 return;
1440 }
1441
1442 ExprResult Result =
1443 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1444 /*TopLevelOfInitList=*/true);
1445
1446 if (Result.isInvalid())
1447 hadError = true;
1448
1449 expr = Result.getAs<Expr>();
1450 IList->setInit(Index, expr);
1451
1452 if (hadError)
1453 ++StructuredIndex;
1454 else
1455 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1456 ++Index;
1457}
1458
1459void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1460 InitListExpr *IList, QualType DeclType,
1461 unsigned &Index,
1462 InitListExpr *StructuredList,
1463 unsigned &StructuredIndex) {
1464 const VectorType *VT = DeclType->getAs<VectorType>();
1465 unsigned maxElements = VT->getNumElements();
1466 unsigned numEltsInit = 0;
1467 QualType elementType = VT->getElementType();
1468
1469 if (Index >= IList->getNumInits()) {
1470 // Make sure the element type can be value-initialized.
1471 if (VerifyOnly)
1472 CheckEmptyInitializable(
1473 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1474 IList->getLocEnd());
1475 return;
1476 }
1477
1478 if (!SemaRef.getLangOpts().OpenCL) {
1479 // If the initializing element is a vector, try to copy-initialize
1480 // instead of breaking it apart (which is doomed to failure anyway).
1481 Expr *Init = IList->getInit(Index);
1482 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1483 if (VerifyOnly) {
1484 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1485 hadError = true;
1486 ++Index;
1487 return;
1488 }
1489
1490 ExprResult Result =
1491 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1492 /*TopLevelOfInitList=*/true);
1493
1494 Expr *ResultExpr = nullptr;
1495 if (Result.isInvalid())
1496 hadError = true; // types weren't compatible.
1497 else {
1498 ResultExpr = Result.getAs<Expr>();
1499
1500 if (ResultExpr != Init) {
1501 // The type was promoted, update initializer list.
1502 IList->setInit(Index, ResultExpr);
1503 }
1504 }
1505 if (hadError)
1506 ++StructuredIndex;
1507 else
1508 UpdateStructuredListElement(StructuredList, StructuredIndex,
1509 ResultExpr);
1510 ++Index;
1511 return;
1512 }
1513
1514 InitializedEntity ElementEntity =
1515 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1516
1517 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1518 // Don't attempt to go past the end of the init list
1519 if (Index >= IList->getNumInits()) {
1520 if (VerifyOnly)
1521 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1522 break;
1523 }
1524
1525 ElementEntity.setElementIndex(Index);
1526 CheckSubElementType(ElementEntity, IList, elementType, Index,
1527 StructuredList, StructuredIndex);
1528 }
1529
1530 if (VerifyOnly)
1531 return;
1532
1533 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1534 const VectorType *T = Entity.getType()->getAs<VectorType>();
1535 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1536 T->getVectorKind() == VectorType::NeonPolyVector)) {
1537 // The ability to use vector initializer lists is a GNU vector extension
1538 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1539 // endian machines it works fine, however on big endian machines it
1540 // exhibits surprising behaviour:
1541 //
1542 // uint32x2_t x = {42, 64};
1543 // return vget_lane_u32(x, 0); // Will return 64.
1544 //
1545 // Because of this, explicitly call out that it is non-portable.
1546 //
1547 SemaRef.Diag(IList->getLocStart(),
1548 diag::warn_neon_vector_initializer_non_portable);
1549
1550 const char *typeCode;
1551 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1552
1553 if (elementType->isFloatingType())
1554 typeCode = "f";
1555 else if (elementType->isSignedIntegerType())
1556 typeCode = "s";
1557 else if (elementType->isUnsignedIntegerType())
1558 typeCode = "u";
1559 else
1560 llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 1560)
;
1561
1562 SemaRef.Diag(IList->getLocStart(),
1563 SemaRef.Context.getTypeSize(VT) > 64 ?
1564 diag::note_neon_vector_initializer_non_portable_q :
1565 diag::note_neon_vector_initializer_non_portable)
1566 << typeCode << typeSize;
1567 }
1568
1569 return;
1570 }
1571
1572 InitializedEntity ElementEntity =
1573 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1574
1575 // OpenCL initializers allows vectors to be constructed from vectors.
1576 for (unsigned i = 0; i < maxElements; ++i) {
1577 // Don't attempt to go past the end of the init list
1578 if (Index >= IList->getNumInits())
1579 break;
1580
1581 ElementEntity.setElementIndex(Index);
1582
1583 QualType IType = IList->getInit(Index)->getType();
1584 if (!IType->isVectorType()) {
1585 CheckSubElementType(ElementEntity, IList, elementType, Index,
1586 StructuredList, StructuredIndex);
1587 ++numEltsInit;
1588 } else {
1589 QualType VecType;
1590 const VectorType *IVT = IType->getAs<VectorType>();
1591 unsigned numIElts = IVT->getNumElements();
1592
1593 if (IType->isExtVectorType())
1594 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1595 else
1596 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1597 IVT->getVectorKind());
1598 CheckSubElementType(ElementEntity, IList, VecType, Index,
1599 StructuredList, StructuredIndex);
1600 numEltsInit += numIElts;
1601 }
1602 }
1603
1604 // OpenCL requires all elements to be initialized.
1605 if (numEltsInit != maxElements) {
1606 if (!VerifyOnly)
1607 SemaRef.Diag(IList->getLocStart(),
1608 diag::err_vector_incorrect_num_initializers)
1609 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1610 hadError = true;
1611 }
1612}
1613
1614void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1615 InitListExpr *IList, QualType &DeclType,
1616 llvm::APSInt elementIndex,
1617 bool SubobjectIsDesignatorContext,
1618 unsigned &Index,
1619 InitListExpr *StructuredList,
1620 unsigned &StructuredIndex) {
1621 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1622
1623 // Check for the special-case of initializing an array with a string.
1624 if (Index < IList->getNumInits()) {
1625 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1626 SIF_None) {
1627 // We place the string literal directly into the resulting
1628 // initializer list. This is the only place where the structure
1629 // of the structured initializer list doesn't match exactly,
1630 // because doing so would involve allocating one character
1631 // constant for each string.
1632 if (!VerifyOnly) {
1633 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1634 UpdateStructuredListElement(StructuredList, StructuredIndex,
1635 IList->getInit(Index));
1636 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1637 }
1638 ++Index;
1639 return;
1640 }
1641 }
1642 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1643 // Check for VLAs; in standard C it would be possible to check this
1644 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1645 // them in all sorts of strange places).
1646 if (!VerifyOnly)
1647 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1648 diag::err_variable_object_no_init)
1649 << VAT->getSizeExpr()->getSourceRange();
1650 hadError = true;
1651 ++Index;
1652 ++StructuredIndex;
1653 return;
1654 }
1655
1656 // We might know the maximum number of elements in advance.
1657 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1658 elementIndex.isUnsigned());
1659 bool maxElementsKnown = false;
1660 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1661 maxElements = CAT->getSize();
1662 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1663 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1664 maxElementsKnown = true;
1665 }
1666
1667 QualType elementType = arrayType->getElementType();
1668 while (Index < IList->getNumInits()) {
1669 Expr *Init = IList->getInit(Index);
1670 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1671 // If we're not the subobject that matches up with the '{' for
1672 // the designator, we shouldn't be handling the
1673 // designator. Return immediately.
1674 if (!SubobjectIsDesignatorContext)
1675 return;
1676
1677 // Handle this designated initializer. elementIndex will be
1678 // updated to be the next array element we'll initialize.
1679 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1680 DeclType, nullptr, &elementIndex, Index,
1681 StructuredList, StructuredIndex, true,
1682 false)) {
1683 hadError = true;
1684 continue;
1685 }
1686
1687 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1688 maxElements = maxElements.extend(elementIndex.getBitWidth());
1689 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1690 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1691 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1692
1693 // If the array is of incomplete type, keep track of the number of
1694 // elements in the initializer.
1695 if (!maxElementsKnown && elementIndex > maxElements)
1696 maxElements = elementIndex;
1697
1698 continue;
1699 }
1700
1701 // If we know the maximum number of elements, and we've already
1702 // hit it, stop consuming elements in the initializer list.
1703 if (maxElementsKnown && elementIndex == maxElements)
1704 break;
1705
1706 InitializedEntity ElementEntity =
1707 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1708 Entity);
1709 // Check this element.
1710 CheckSubElementType(ElementEntity, IList, elementType, Index,
1711 StructuredList, StructuredIndex);
1712 ++elementIndex;
1713
1714 // If the array is of incomplete type, keep track of the number of
1715 // elements in the initializer.
1716 if (!maxElementsKnown && elementIndex > maxElements)
1717 maxElements = elementIndex;
1718 }
1719 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1720 // If this is an incomplete array type, the actual type needs to
1721 // be calculated here.
1722 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1723 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1724 // Sizing an array implicitly to zero is not allowed by ISO C,
1725 // but is supported by GNU.
1726 SemaRef.Diag(IList->getLocStart(),
1727 diag::ext_typecheck_zero_array_size);
1728 }
1729
1730 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1731 ArrayType::Normal, 0);
1732 }
1733 if (!hadError && VerifyOnly) {
1734 // If there are any members of the array that get value-initialized, check
1735 // that is possible. That happens if we know the bound and don't have
1736 // enough elements, or if we're performing an array new with an unknown
1737 // bound.
1738 // FIXME: This needs to detect holes left by designated initializers too.
1739 if ((maxElementsKnown && elementIndex < maxElements) ||
1740 Entity.isVariableLengthArrayNew())
1741 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1742 SemaRef.Context, 0, Entity),
1743 IList->getLocEnd());
1744 }
1745}
1746
1747bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1748 Expr *InitExpr,
1749 FieldDecl *Field,
1750 bool TopLevelObject) {
1751 // Handle GNU flexible array initializers.
1752 unsigned FlexArrayDiag;
1753 if (isa<InitListExpr>(InitExpr) &&
1754 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1755 // Empty flexible array init always allowed as an extension
1756 FlexArrayDiag = diag::ext_flexible_array_init;
1757 } else if (SemaRef.getLangOpts().CPlusPlus) {
1758 // Disallow flexible array init in C++; it is not required for gcc
1759 // compatibility, and it needs work to IRGen correctly in general.
1760 FlexArrayDiag = diag::err_flexible_array_init;
1761 } else if (!TopLevelObject) {
1762 // Disallow flexible array init on non-top-level object
1763 FlexArrayDiag = diag::err_flexible_array_init;
1764 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1765 // Disallow flexible array init on anything which is not a variable.
1766 FlexArrayDiag = diag::err_flexible_array_init;
1767 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1768 // Disallow flexible array init on local variables.
1769 FlexArrayDiag = diag::err_flexible_array_init;
1770 } else {
1771 // Allow other cases.
1772 FlexArrayDiag = diag::ext_flexible_array_init;
1773 }
1774
1775 if (!VerifyOnly) {
1776 SemaRef.Diag(InitExpr->getLocStart(),
1777 FlexArrayDiag)
1778 << InitExpr->getLocStart();
1779 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1780 << Field;
1781 }
1782
1783 return FlexArrayDiag != diag::ext_flexible_array_init;
1784}
1785
1786void InitListChecker::CheckStructUnionTypes(
1787 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1788 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1789 bool SubobjectIsDesignatorContext, unsigned &Index,
1790 InitListExpr *StructuredList, unsigned &StructuredIndex,
1791 bool TopLevelObject) {
1792 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1793
1794 // If the record is invalid, some of it's members are invalid. To avoid
1795 // confusion, we forgo checking the intializer for the entire record.
1796 if (structDecl->isInvalidDecl()) {
1797 // Assume it was supposed to consume a single initializer.
1798 ++Index;
1799 hadError = true;
1800 return;
1801 }
1802
1803 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1804 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1805
1806 // If there's a default initializer, use it.
1807 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1808 if (VerifyOnly)
1809 return;
1810 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1811 Field != FieldEnd; ++Field) {
1812 if (Field->hasInClassInitializer()) {
1813 StructuredList->setInitializedFieldInUnion(*Field);
1814 // FIXME: Actually build a CXXDefaultInitExpr?
1815 return;
1816 }
1817 }
1818 }
1819
1820 // Value-initialize the first member of the union that isn't an unnamed
1821 // bitfield.
1822 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1823 Field != FieldEnd; ++Field) {
1824 if (!Field->isUnnamedBitfield()) {
1825 if (VerifyOnly)
1826 CheckEmptyInitializable(
1827 InitializedEntity::InitializeMember(*Field, &Entity),
1828 IList->getLocEnd());
1829 else
1830 StructuredList->setInitializedFieldInUnion(*Field);
1831 break;
1832 }
1833 }
1834 return;
1835 }
1836
1837 bool InitializedSomething = false;
1838
1839 // If we have any base classes, they are initialized prior to the fields.
1840 for (auto &Base : Bases) {
1841 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1842 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1843
1844 // Designated inits always initialize fields, so if we see one, all
1845 // remaining base classes have no explicit initializer.
1846 if (Init && isa<DesignatedInitExpr>(Init))
1847 Init = nullptr;
1848
1849 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1850 SemaRef.Context, &Base, false, &Entity);
1851 if (Init) {
1852 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1853 StructuredList, StructuredIndex);
1854 InitializedSomething = true;
1855 } else if (VerifyOnly) {
1856 CheckEmptyInitializable(BaseEntity, InitLoc);
1857 }
1858 }
1859
1860 // If structDecl is a forward declaration, this loop won't do
1861 // anything except look at designated initializers; That's okay,
1862 // because an error should get printed out elsewhere. It might be
1863 // worthwhile to skip over the rest of the initializer, though.
1864 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1865 RecordDecl::field_iterator FieldEnd = RD->field_end();
1866 bool CheckForMissingFields =
1867 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1868
1869 while (Index < IList->getNumInits()) {
1870 Expr *Init = IList->getInit(Index);
1871
1872 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1873 // If we're not the subobject that matches up with the '{' for
1874 // the designator, we shouldn't be handling the
1875 // designator. Return immediately.
1876 if (!SubobjectIsDesignatorContext)
1877 return;
1878
1879 // Handle this designated initializer. Field will be updated to
1880 // the next field that we'll be initializing.
1881 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1882 DeclType, &Field, nullptr, Index,
1883 StructuredList, StructuredIndex,
1884 true, TopLevelObject))
1885 hadError = true;
1886
1887 InitializedSomething = true;
1888
1889 // Disable check for missing fields when designators are used.
1890 // This matches gcc behaviour.
1891 CheckForMissingFields = false;
1892 continue;
1893 }
1894
1895 if (Field == FieldEnd) {
1896 // We've run out of fields. We're done.
1897 break;
1898 }
1899
1900 // We've already initialized a member of a union. We're done.
1901 if (InitializedSomething && DeclType->isUnionType())
1902 break;
1903
1904 // If we've hit the flexible array member at the end, we're done.
1905 if (Field->getType()->isIncompleteArrayType())
1906 break;
1907
1908 if (Field->isUnnamedBitfield()) {
1909 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1910 ++Field;
1911 continue;
1912 }
1913
1914 // Make sure we can use this declaration.
1915 bool InvalidUse;
1916 if (VerifyOnly)
1917 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
1918 else
1919 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1920 IList->getInit(Index)->getLocStart());
1921 if (InvalidUse) {
1922 ++Index;
1923 ++Field;
1924 hadError = true;
1925 continue;
1926 }
1927
1928 InitializedEntity MemberEntity =
1929 InitializedEntity::InitializeMember(*Field, &Entity);
1930 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1931 StructuredList, StructuredIndex);
1932 InitializedSomething = true;
1933
1934 if (DeclType->isUnionType() && !VerifyOnly) {
1935 // Initialize the first field within the union.
1936 StructuredList->setInitializedFieldInUnion(*Field);
1937 }
1938
1939 ++Field;
1940 }
1941
1942 // Emit warnings for missing struct field initializers.
1943 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1944 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1945 !DeclType->isUnionType()) {
1946 // It is possible we have one or more unnamed bitfields remaining.
1947 // Find first (if any) named field and emit warning.
1948 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1949 it != end; ++it) {
1950 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1951 SemaRef.Diag(IList->getSourceRange().getEnd(),
1952 diag::warn_missing_field_initializers) << *it;
1953 break;
1954 }
1955 }
1956 }
1957
1958 // Check that any remaining fields can be value-initialized.
1959 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1960 !Field->getType()->isIncompleteArrayType()) {
1961 // FIXME: Should check for holes left by designated initializers too.
1962 for (; Field != FieldEnd && !hadError; ++Field) {
1963 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1964 CheckEmptyInitializable(
1965 InitializedEntity::InitializeMember(*Field, &Entity),
1966 IList->getLocEnd());
1967 }
1968 }
1969
1970 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1971 Index >= IList->getNumInits())
1972 return;
1973
1974 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1975 TopLevelObject)) {
1976 hadError = true;
1977 ++Index;
1978 return;
1979 }
1980
1981 InitializedEntity MemberEntity =
1982 InitializedEntity::InitializeMember(*Field, &Entity);
1983
1984 if (isa<InitListExpr>(IList->getInit(Index)))
1985 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1986 StructuredList, StructuredIndex);
1987 else
1988 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1989 StructuredList, StructuredIndex);
1990}
1991
1992/// \brief Expand a field designator that refers to a member of an
1993/// anonymous struct or union into a series of field designators that
1994/// refers to the field within the appropriate subobject.
1995///
1996static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1997 DesignatedInitExpr *DIE,
1998 unsigned DesigIdx,
1999 IndirectFieldDecl *IndirectField) {
2000 typedef DesignatedInitExpr::Designator Designator;
2001
2002 // Build the replacement designators.
2003 SmallVector<Designator, 4> Replacements;
2004 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2005 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2006 if (PI + 1 == PE)
2007 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2008 DIE->getDesignator(DesigIdx)->getDotLoc(),
2009 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2010 else
2011 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2012 SourceLocation(), SourceLocation()));
2013 assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(*PI)", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2013, __extension__ __PRETTY_FUNCTION__))
;
2014 Replacements.back().setField(cast<FieldDecl>(*PI));
2015 }
2016
2017 // Expand the current designator into the set of replacement
2018 // designators, so we have a full subobject path down to where the
2019 // member of the anonymous struct/union is actually stored.
2020 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2021 &Replacements[0] + Replacements.size());
2022}
2023
2024static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2025 DesignatedInitExpr *DIE) {
2026 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2027 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2028 for (unsigned I = 0; I < NumIndexExprs; ++I)
2029 IndexExprs[I] = DIE->getSubExpr(I + 1);
2030 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2031 IndexExprs,
2032 DIE->getEqualOrColonLoc(),
2033 DIE->usesGNUSyntax(), DIE->getInit());
2034}
2035
2036namespace {
2037
2038// Callback to only accept typo corrections that are for field members of
2039// the given struct or union.
2040class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2041 public:
2042 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2043 : Record(RD) {}
2044
2045 bool ValidateCandidate(const TypoCorrection &candidate) override {
2046 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2047 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2048 }
2049
2050 private:
2051 RecordDecl *Record;
2052};
2053
2054} // end anonymous namespace
2055
2056/// @brief Check the well-formedness of a C99 designated initializer.
2057///
2058/// Determines whether the designated initializer @p DIE, which
2059/// resides at the given @p Index within the initializer list @p
2060/// IList, is well-formed for a current object of type @p DeclType
2061/// (C99 6.7.8). The actual subobject that this designator refers to
2062/// within the current subobject is returned in either
2063/// @p NextField or @p NextElementIndex (whichever is appropriate).
2064///
2065/// @param IList The initializer list in which this designated
2066/// initializer occurs.
2067///
2068/// @param DIE The designated initializer expression.
2069///
2070/// @param DesigIdx The index of the current designator.
2071///
2072/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2073/// into which the designation in @p DIE should refer.
2074///
2075/// @param NextField If non-NULL and the first designator in @p DIE is
2076/// a field, this will be set to the field declaration corresponding
2077/// to the field named by the designator.
2078///
2079/// @param NextElementIndex If non-NULL and the first designator in @p
2080/// DIE is an array designator or GNU array-range designator, this
2081/// will be set to the last index initialized by this designator.
2082///
2083/// @param Index Index into @p IList where the designated initializer
2084/// @p DIE occurs.
2085///
2086/// @param StructuredList The initializer list expression that
2087/// describes all of the subobject initializers in the order they'll
2088/// actually be initialized.
2089///
2090/// @returns true if there was an error, false otherwise.
2091bool
2092InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2093 InitListExpr *IList,
2094 DesignatedInitExpr *DIE,
2095 unsigned DesigIdx,
2096 QualType &CurrentObjectType,
2097 RecordDecl::field_iterator *NextField,
2098 llvm::APSInt *NextElementIndex,
2099 unsigned &Index,
2100 InitListExpr *StructuredList,
2101 unsigned &StructuredIndex,
2102 bool FinishSubobjectInit,
2103 bool TopLevelObject) {
2104 if (DesigIdx == DIE->size()) {
2105 // Check the actual initialization for the designated object type.
2106 bool prevHadError = hadError;
2107
2108 // Temporarily remove the designator expression from the
2109 // initializer list that the child calls see, so that we don't try
2110 // to re-process the designator.
2111 unsigned OldIndex = Index;
2112 IList->setInit(OldIndex, DIE->getInit());
2113
2114 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2115 StructuredList, StructuredIndex);
2116
2117 // Restore the designated initializer expression in the syntactic
2118 // form of the initializer list.
2119 if (IList->getInit(OldIndex) != DIE->getInit())
2120 DIE->setInit(IList->getInit(OldIndex));
2121 IList->setInit(OldIndex, DIE);
2122
2123 return hadError && !prevHadError;
2124 }
2125
2126 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2127 bool IsFirstDesignator = (DesigIdx == 0);
2128 if (!VerifyOnly) {
2129 assert((IsFirstDesignator || StructuredList) &&(static_cast <bool> ((IsFirstDesignator || StructuredList
) && "Need a non-designated initializer list to start from"
) ? void (0) : __assert_fail ("(IsFirstDesignator || StructuredList) && \"Need a non-designated initializer list to start from\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2130, __extension__ __PRETTY_FUNCTION__))
2130 "Need a non-designated initializer list to start from")(static_cast <bool> ((IsFirstDesignator || StructuredList
) && "Need a non-designated initializer list to start from"
) ? void (0) : __assert_fail ("(IsFirstDesignator || StructuredList) && \"Need a non-designated initializer list to start from\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2130, __extension__ __PRETTY_FUNCTION__))
;
2131
2132 // Determine the structural initializer list that corresponds to the
2133 // current subobject.
2134 if (IsFirstDesignator)
2135 StructuredList = SyntacticToSemantic.lookup(IList);
2136 else {
2137 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2138 StructuredList->getInit(StructuredIndex) : nullptr;
2139 if (!ExistingInit && StructuredList->hasArrayFiller())
2140 ExistingInit = StructuredList->getArrayFiller();
2141
2142 if (!ExistingInit)
2143 StructuredList =
2144 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2145 StructuredList, StructuredIndex,
2146 SourceRange(D->getLocStart(),
2147 DIE->getLocEnd()));
2148 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2149 StructuredList = Result;
2150 else {
2151 if (DesignatedInitUpdateExpr *E =
2152 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2153 StructuredList = E->getUpdater();
2154 else {
2155 DesignatedInitUpdateExpr *DIUE =
2156 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2157 D->getLocStart(), ExistingInit,
2158 DIE->getLocEnd());
2159 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2160 StructuredList = DIUE->getUpdater();
2161 }
2162
2163 // We need to check on source range validity because the previous
2164 // initializer does not have to be an explicit initializer. e.g.,
2165 //
2166 // struct P { int a, b; };
2167 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2168 //
2169 // There is an overwrite taking place because the first braced initializer
2170 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2171 if (ExistingInit->getSourceRange().isValid()) {
2172 // We are creating an initializer list that initializes the
2173 // subobjects of the current object, but there was already an
2174 // initialization that completely initialized the current
2175 // subobject, e.g., by a compound literal:
2176 //
2177 // struct X { int a, b; };
2178 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2179 //
2180 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2181 // designated initializer re-initializes the whole
2182 // subobject [0], overwriting previous initializers.
2183 SemaRef.Diag(D->getLocStart(),
2184 diag::warn_subobject_initializer_overrides)
2185 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2186
2187 SemaRef.Diag(ExistingInit->getLocStart(),
2188 diag::note_previous_initializer)
2189 << /*FIXME:has side effects=*/0
2190 << ExistingInit->getSourceRange();
2191 }
2192 }
2193 }
2194 assert(StructuredList && "Expected a structured initializer list")(static_cast <bool> (StructuredList && "Expected a structured initializer list"
) ? void (0) : __assert_fail ("StructuredList && \"Expected a structured initializer list\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2194, __extension__ __PRETTY_FUNCTION__))
;
2195 }
2196
2197 if (D->isFieldDesignator()) {
2198 // C99 6.7.8p7:
2199 //
2200 // If a designator has the form
2201 //
2202 // . identifier
2203 //
2204 // then the current object (defined below) shall have
2205 // structure or union type and the identifier shall be the
2206 // name of a member of that type.
2207 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2208 if (!RT) {
2209 SourceLocation Loc = D->getDotLoc();
2210 if (Loc.isInvalid())
2211 Loc = D->getFieldLoc();
2212 if (!VerifyOnly)
2213 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2214 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2215 ++Index;
2216 return true;
2217 }
2218
2219 FieldDecl *KnownField = D->getField();
2220 if (!KnownField) {
2221 IdentifierInfo *FieldName = D->getFieldName();
2222 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2223 for (NamedDecl *ND : Lookup) {
2224 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2225 KnownField = FD;
2226 break;
2227 }
2228 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2229 // In verify mode, don't modify the original.
2230 if (VerifyOnly)
2231 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2232 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2233 D = DIE->getDesignator(DesigIdx);
2234 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2235 break;
2236 }
2237 }
2238 if (!KnownField) {
2239 if (VerifyOnly) {
2240 ++Index;
2241 return true; // No typo correction when just trying this out.
2242 }
2243
2244 // Name lookup found something, but it wasn't a field.
2245 if (!Lookup.empty()) {
2246 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2247 << FieldName;
2248 SemaRef.Diag(Lookup.front()->getLocation(),
2249 diag::note_field_designator_found);
2250 ++Index;
2251 return true;
2252 }
2253
2254 // Name lookup didn't find anything.
2255 // Determine whether this was a typo for another field name.
2256 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2257 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2258 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2259 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2260 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2261 SemaRef.diagnoseTypo(
2262 Corrected,
2263 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2264 << FieldName << CurrentObjectType);
2265 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2266 hadError = true;
2267 } else {
2268 // Typo correction didn't find anything.
2269 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2270 << FieldName << CurrentObjectType;
2271 ++Index;
2272 return true;
2273 }
2274 }
2275 }
2276
2277 unsigned FieldIndex = 0;
2278
2279 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2280 FieldIndex = CXXRD->getNumBases();
2281
2282 for (auto *FI : RT->getDecl()->fields()) {
2283 if (FI->isUnnamedBitfield())
2284 continue;
2285 if (declaresSameEntity(KnownField, FI)) {
2286 KnownField = FI;
2287 break;
2288 }
2289 ++FieldIndex;
2290 }
2291
2292 RecordDecl::field_iterator Field =
2293 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2294
2295 // All of the fields of a union are located at the same place in
2296 // the initializer list.
2297 if (RT->getDecl()->isUnion()) {
2298 FieldIndex = 0;
2299 if (!VerifyOnly) {
2300 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2301 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2302 assert(StructuredList->getNumInits() == 1(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
2303 && "A union should never have more than one initializer!")(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
;
2304
2305 Expr *ExistingInit = StructuredList->getInit(0);
2306 if (ExistingInit) {
2307 // We're about to throw away an initializer, emit warning.
2308 SemaRef.Diag(D->getFieldLoc(),
2309 diag::warn_initializer_overrides)
2310 << D->getSourceRange();
2311 SemaRef.Diag(ExistingInit->getLocStart(),
2312 diag::note_previous_initializer)
2313 << /*FIXME:has side effects=*/0
2314 << ExistingInit->getSourceRange();
2315 }
2316
2317 // remove existing initializer
2318 StructuredList->resizeInits(SemaRef.Context, 0);
2319 StructuredList->setInitializedFieldInUnion(nullptr);
2320 }
2321
2322 StructuredList->setInitializedFieldInUnion(*Field);
2323 }
2324 }
2325
2326 // Make sure we can use this declaration.
2327 bool InvalidUse;
2328 if (VerifyOnly)
2329 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2330 else
2331 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2332 if (InvalidUse) {
2333 ++Index;
2334 return true;
2335 }
2336
2337 if (!VerifyOnly) {
2338 // Update the designator with the field declaration.
2339 D->setField(*Field);
2340
2341 // Make sure that our non-designated initializer list has space
2342 // for a subobject corresponding to this field.
2343 if (FieldIndex >= StructuredList->getNumInits())
2344 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2345 }
2346
2347 // This designator names a flexible array member.
2348 if (Field->getType()->isIncompleteArrayType()) {
2349 bool Invalid = false;
2350 if ((DesigIdx + 1) != DIE->size()) {
2351 // We can't designate an object within the flexible array
2352 // member (because GCC doesn't allow it).
2353 if (!VerifyOnly) {
2354 DesignatedInitExpr::Designator *NextD
2355 = DIE->getDesignator(DesigIdx + 1);
2356 SemaRef.Diag(NextD->getLocStart(),
2357 diag::err_designator_into_flexible_array_member)
2358 << SourceRange(NextD->getLocStart(),
2359 DIE->getLocEnd());
2360 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2361 << *Field;
2362 }
2363 Invalid = true;
2364 }
2365
2366 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2367 !isa<StringLiteral>(DIE->getInit())) {
2368 // The initializer is not an initializer list.
2369 if (!VerifyOnly) {
2370 SemaRef.Diag(DIE->getInit()->getLocStart(),
2371 diag::err_flexible_array_init_needs_braces)
2372 << DIE->getInit()->getSourceRange();
2373 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2374 << *Field;
2375 }
2376 Invalid = true;
2377 }
2378
2379 // Check GNU flexible array initializer.
2380 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2381 TopLevelObject))
2382 Invalid = true;
2383
2384 if (Invalid) {
2385 ++Index;
2386 return true;
2387 }
2388
2389 // Initialize the array.
2390 bool prevHadError = hadError;
2391 unsigned newStructuredIndex = FieldIndex;
2392 unsigned OldIndex = Index;
2393 IList->setInit(Index, DIE->getInit());
2394
2395 InitializedEntity MemberEntity =
2396 InitializedEntity::InitializeMember(*Field, &Entity);
2397 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2398 StructuredList, newStructuredIndex);
2399
2400 IList->setInit(OldIndex, DIE);
2401 if (hadError && !prevHadError) {
2402 ++Field;
2403 ++FieldIndex;
2404 if (NextField)
2405 *NextField = Field;
2406 StructuredIndex = FieldIndex;
2407 return true;
2408 }
2409 } else {
2410 // Recurse to check later designated subobjects.
2411 QualType FieldType = Field->getType();
2412 unsigned newStructuredIndex = FieldIndex;
2413
2414 InitializedEntity MemberEntity =
2415 InitializedEntity::InitializeMember(*Field, &Entity);
2416 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2417 FieldType, nullptr, nullptr, Index,
2418 StructuredList, newStructuredIndex,
2419 FinishSubobjectInit, false))
2420 return true;
2421 }
2422
2423 // Find the position of the next field to be initialized in this
2424 // subobject.
2425 ++Field;
2426 ++FieldIndex;
2427
2428 // If this the first designator, our caller will continue checking
2429 // the rest of this struct/class/union subobject.
2430 if (IsFirstDesignator) {
2431 if (NextField)
2432 *NextField = Field;
2433 StructuredIndex = FieldIndex;
2434 return false;
2435 }
2436
2437 if (!FinishSubobjectInit)
2438 return false;
2439
2440 // We've already initialized something in the union; we're done.
2441 if (RT->getDecl()->isUnion())
2442 return hadError;
2443
2444 // Check the remaining fields within this class/struct/union subobject.
2445 bool prevHadError = hadError;
2446
2447 auto NoBases =
2448 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2449 CXXRecordDecl::base_class_iterator());
2450 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2451 false, Index, StructuredList, FieldIndex);
2452 return hadError && !prevHadError;
2453 }
2454
2455 // C99 6.7.8p6:
2456 //
2457 // If a designator has the form
2458 //
2459 // [ constant-expression ]
2460 //
2461 // then the current object (defined below) shall have array
2462 // type and the expression shall be an integer constant
2463 // expression. If the array is of unknown size, any
2464 // nonnegative value is valid.
2465 //
2466 // Additionally, cope with the GNU extension that permits
2467 // designators of the form
2468 //
2469 // [ constant-expression ... constant-expression ]
2470 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2471 if (!AT) {
2472 if (!VerifyOnly)
2473 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2474 << CurrentObjectType;
2475 ++Index;
2476 return true;
2477 }
2478
2479 Expr *IndexExpr = nullptr;
2480 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2481 if (D->isArrayDesignator()) {
2482 IndexExpr = DIE->getArrayIndex(*D);
2483 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2484 DesignatedEndIndex = DesignatedStartIndex;
2485 } else {
2486 assert(D->isArrayRangeDesignator() && "Need array-range designator")(static_cast <bool> (D->isArrayRangeDesignator() &&
"Need array-range designator") ? void (0) : __assert_fail ("D->isArrayRangeDesignator() && \"Need array-range designator\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2486, __extension__ __PRETTY_FUNCTION__))
;
2487
2488 DesignatedStartIndex =
2489 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2490 DesignatedEndIndex =
2491 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2492 IndexExpr = DIE->getArrayRangeEnd(*D);
2493
2494 // Codegen can't handle evaluating array range designators that have side
2495 // effects, because we replicate the AST value for each initialized element.
2496 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2497 // elements with something that has a side effect, so codegen can emit an
2498 // "error unsupported" error instead of miscompiling the app.
2499 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2500 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2501 FullyStructuredList->sawArrayRangeDesignator();
2502 }
2503
2504 if (isa<ConstantArrayType>(AT)) {
2505 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2506 DesignatedStartIndex
2507 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2508 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2509 DesignatedEndIndex
2510 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2511 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2512 if (DesignatedEndIndex >= MaxElements) {
2513 if (!VerifyOnly)
2514 SemaRef.Diag(IndexExpr->getLocStart(),
2515 diag::err_array_designator_too_large)
2516 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2517 << IndexExpr->getSourceRange();
2518 ++Index;
2519 return true;
2520 }
2521 } else {
2522 unsigned DesignatedIndexBitWidth =
2523 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2524 DesignatedStartIndex =
2525 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2526 DesignatedEndIndex =
2527 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2528 DesignatedStartIndex.setIsUnsigned(true);
2529 DesignatedEndIndex.setIsUnsigned(true);
2530 }
2531
2532 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2533 // We're modifying a string literal init; we have to decompose the string
2534 // so we can modify the individual characters.
2535 ASTContext &Context = SemaRef.Context;
2536 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2537
2538 // Compute the character type
2539 QualType CharTy = AT->getElementType();
2540
2541 // Compute the type of the integer literals.
2542 QualType PromotedCharTy = CharTy;
2543 if (CharTy->isPromotableIntegerType())
2544 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2545 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2546
2547 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2548 // Get the length of the string.
2549 uint64_t StrLen = SL->getLength();
2550 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2551 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2552 StructuredList->resizeInits(Context, StrLen);
2553
2554 // Build a literal for each character in the string, and put them into
2555 // the init list.
2556 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2557 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2558 Expr *Init = new (Context) IntegerLiteral(
2559 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2560 if (CharTy != PromotedCharTy)
2561 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2562 Init, nullptr, VK_RValue);
2563 StructuredList->updateInit(Context, i, Init);
2564 }
2565 } else {
2566 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2567 std::string Str;
2568 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2569
2570 // Get the length of the string.
2571 uint64_t StrLen = Str.size();
2572 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2573 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2574 StructuredList->resizeInits(Context, StrLen);
2575
2576 // Build a literal for each character in the string, and put them into
2577 // the init list.
2578 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2579 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2580 Expr *Init = new (Context) IntegerLiteral(
2581 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2582 if (CharTy != PromotedCharTy)
2583 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2584 Init, nullptr, VK_RValue);
2585 StructuredList->updateInit(Context, i, Init);
2586 }
2587 }
2588 }
2589
2590 // Make sure that our non-designated initializer list has space
2591 // for a subobject corresponding to this array element.
2592 if (!VerifyOnly &&
2593 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2594 StructuredList->resizeInits(SemaRef.Context,
2595 DesignatedEndIndex.getZExtValue() + 1);
2596
2597 // Repeatedly perform subobject initializations in the range
2598 // [DesignatedStartIndex, DesignatedEndIndex].
2599
2600 // Move to the next designator
2601 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2602 unsigned OldIndex = Index;
2603
2604 InitializedEntity ElementEntity =
2605 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2606
2607 while (DesignatedStartIndex <= DesignatedEndIndex) {
2608 // Recurse to check later designated subobjects.
2609 QualType ElementType = AT->getElementType();
2610 Index = OldIndex;
2611
2612 ElementEntity.setElementIndex(ElementIndex);
2613 if (CheckDesignatedInitializer(
2614 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2615 nullptr, Index, StructuredList, ElementIndex,
2616 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2617 false))
2618 return true;
2619
2620 // Move to the next index in the array that we'll be initializing.
2621 ++DesignatedStartIndex;
2622 ElementIndex = DesignatedStartIndex.getZExtValue();
2623 }
2624
2625 // If this the first designator, our caller will continue checking
2626 // the rest of this array subobject.
2627 if (IsFirstDesignator) {
2628 if (NextElementIndex)
2629 *NextElementIndex = DesignatedStartIndex;
2630 StructuredIndex = ElementIndex;
2631 return false;
2632 }
2633
2634 if (!FinishSubobjectInit)
2635 return false;
2636
2637 // Check the remaining elements within this array subobject.
2638 bool prevHadError = hadError;
2639 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2640 /*SubobjectIsDesignatorContext=*/false, Index,
2641 StructuredList, ElementIndex);
2642 return hadError && !prevHadError;
2643}
2644
2645// Get the structured initializer list for a subobject of type
2646// @p CurrentObjectType.
2647InitListExpr *
2648InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2649 QualType CurrentObjectType,
2650 InitListExpr *StructuredList,
2651 unsigned StructuredIndex,
2652 SourceRange InitRange,
2653 bool IsFullyOverwritten) {
2654 if (VerifyOnly)
2655 return nullptr; // No structured list in verification-only mode.
2656 Expr *ExistingInit = nullptr;
2657 if (!StructuredList)
2658 ExistingInit = SyntacticToSemantic.lookup(IList);
2659 else if (StructuredIndex < StructuredList->getNumInits())
2660 ExistingInit = StructuredList->getInit(StructuredIndex);
2661
2662 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2663 // There might have already been initializers for subobjects of the current
2664 // object, but a subsequent initializer list will overwrite the entirety
2665 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2666 //
2667 // struct P { char x[6]; };
2668 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2669 //
2670 // The first designated initializer is ignored, and l.x is just "f".
2671 if (!IsFullyOverwritten)
2672 return Result;
2673
2674 if (ExistingInit) {
2675 // We are creating an initializer list that initializes the
2676 // subobjects of the current object, but there was already an
2677 // initialization that completely initialized the current
2678 // subobject, e.g., by a compound literal:
2679 //
2680 // struct X { int a, b; };
2681 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2682 //
2683 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2684 // designated initializer re-initializes the whole
2685 // subobject [0], overwriting previous initializers.
2686 SemaRef.Diag(InitRange.getBegin(),
2687 diag::warn_subobject_initializer_overrides)
2688 << InitRange;
2689 SemaRef.Diag(ExistingInit->getLocStart(),
2690 diag::note_previous_initializer)
2691 << /*FIXME:has side effects=*/0
2692 << ExistingInit->getSourceRange();
2693 }
2694
2695 InitListExpr *Result
2696 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2697 InitRange.getBegin(), None,
2698 InitRange.getEnd());
2699
2700 QualType ResultType = CurrentObjectType;
2701 if (!ResultType->isArrayType())
2702 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2703 Result->setType(ResultType);
2704
2705 // Pre-allocate storage for the structured initializer list.
2706 unsigned NumElements = 0;
2707 unsigned NumInits = 0;
2708 bool GotNumInits = false;
2709 if (!StructuredList) {
2710 NumInits = IList->getNumInits();
2711 GotNumInits = true;
2712 } else if (Index < IList->getNumInits()) {
2713 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2714 NumInits = SubList->getNumInits();
2715 GotNumInits = true;
2716 }
2717 }
2718
2719 if (const ArrayType *AType
2720 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2721 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2722 NumElements = CAType->getSize().getZExtValue();
2723 // Simple heuristic so that we don't allocate a very large
2724 // initializer with many empty entries at the end.
2725 if (GotNumInits && NumElements > NumInits)
2726 NumElements = 0;
2727 }
2728 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2729 NumElements = VType->getNumElements();
2730 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2731 RecordDecl *RDecl = RType->getDecl();
2732 if (RDecl->isUnion())
2733 NumElements = 1;
2734 else
2735 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2736 }
2737
2738 Result->reserveInits(SemaRef.Context, NumElements);
2739
2740 // Link this new initializer list into the structured initializer
2741 // lists.
2742 if (StructuredList)
2743 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2744 else {
2745 Result->setSyntacticForm(IList);
2746 SyntacticToSemantic[IList] = Result;
2747 }
2748
2749 return Result;
2750}
2751
2752/// Update the initializer at index @p StructuredIndex within the
2753/// structured initializer list to the value @p expr.
2754void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2755 unsigned &StructuredIndex,
2756 Expr *expr) {
2757 // No structured initializer list to update
2758 if (!StructuredList)
2759 return;
2760
2761 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2762 StructuredIndex, expr)) {
2763 // This initializer overwrites a previous initializer. Warn.
2764 // We need to check on source range validity because the previous
2765 // initializer does not have to be an explicit initializer.
2766 // struct P { int a, b; };
2767 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2768 // There is an overwrite taking place because the first braced initializer
2769 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2770 if (PrevInit->getSourceRange().isValid()) {
2771 SemaRef.Diag(expr->getLocStart(),
2772 diag::warn_initializer_overrides)
2773 << expr->getSourceRange();
2774
2775 SemaRef.Diag(PrevInit->getLocStart(),
2776 diag::note_previous_initializer)
2777 << /*FIXME:has side effects=*/0
2778 << PrevInit->getSourceRange();
2779 }
2780 }
2781
2782 ++StructuredIndex;
2783}
2784
2785/// Check that the given Index expression is a valid array designator
2786/// value. This is essentially just a wrapper around
2787/// VerifyIntegerConstantExpression that also checks for negative values
2788/// and produces a reasonable diagnostic if there is a
2789/// failure. Returns the index expression, possibly with an implicit cast
2790/// added, on success. If everything went okay, Value will receive the
2791/// value of the constant expression.
2792static ExprResult
2793CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2794 SourceLocation Loc = Index->getLocStart();
2795
2796 // Make sure this is an integer constant expression.
2797 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2798 if (Result.isInvalid())
2799 return Result;
2800
2801 if (Value.isSigned() && Value.isNegative())
2802 return S.Diag(Loc, diag::err_array_designator_negative)
2803 << Value.toString(10) << Index->getSourceRange();
2804
2805 Value.setIsUnsigned(true);
2806 return Result;
2807}
2808
2809ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2810 SourceLocation Loc,
2811 bool GNUSyntax,
2812 ExprResult Init) {
2813 typedef DesignatedInitExpr::Designator ASTDesignator;
2814
2815 bool Invalid = false;
2816 SmallVector<ASTDesignator, 32> Designators;
2817 SmallVector<Expr *, 32> InitExpressions;
2818
2819 // Build designators and check array designator expressions.
2820 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2821 const Designator &D = Desig.getDesignator(Idx);
2822 switch (D.getKind()) {
2823 case Designator::FieldDesignator:
2824 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2825 D.getFieldLoc()));
2826 break;
2827
2828 case Designator::ArrayDesignator: {
2829 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2830 llvm::APSInt IndexValue;
2831 if (!Index->isTypeDependent() && !Index->isValueDependent())
2832 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2833 if (!Index)
2834 Invalid = true;
2835 else {
2836 Designators.push_back(ASTDesignator(InitExpressions.size(),
2837 D.getLBracketLoc(),
2838 D.getRBracketLoc()));
2839 InitExpressions.push_back(Index);
2840 }
2841 break;
2842 }
2843
2844 case Designator::ArrayRangeDesignator: {
2845 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2846 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2847 llvm::APSInt StartValue;
2848 llvm::APSInt EndValue;
2849 bool StartDependent = StartIndex->isTypeDependent() ||
2850 StartIndex->isValueDependent();
2851 bool EndDependent = EndIndex->isTypeDependent() ||
2852 EndIndex->isValueDependent();
2853 if (!StartDependent)
2854 StartIndex =
2855 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2856 if (!EndDependent)
2857 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2858
2859 if (!StartIndex || !EndIndex)
2860 Invalid = true;
2861 else {
2862 // Make sure we're comparing values with the same bit width.
2863 if (StartDependent || EndDependent) {
2864 // Nothing to compute.
2865 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2866 EndValue = EndValue.extend(StartValue.getBitWidth());
2867 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2868 StartValue = StartValue.extend(EndValue.getBitWidth());
2869
2870 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2871 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2872 << StartValue.toString(10) << EndValue.toString(10)
2873 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2874 Invalid = true;
2875 } else {
2876 Designators.push_back(ASTDesignator(InitExpressions.size(),
2877 D.getLBracketLoc(),
2878 D.getEllipsisLoc(),
2879 D.getRBracketLoc()));
2880 InitExpressions.push_back(StartIndex);
2881 InitExpressions.push_back(EndIndex);
2882 }
2883 }
2884 break;
2885 }
2886 }
2887 }
2888
2889 if (Invalid || Init.isInvalid())
2890 return ExprError();
2891
2892 // Clear out the expressions within the designation.
2893 Desig.ClearExprs(*this);
2894
2895 DesignatedInitExpr *DIE
2896 = DesignatedInitExpr::Create(Context,
2897 Designators,
2898 InitExpressions, Loc, GNUSyntax,
2899 Init.getAs<Expr>());
2900
2901 if (!getLangOpts().C99)
2902 Diag(DIE->getLocStart(), diag::ext_designated_init)
2903 << DIE->getSourceRange();
2904
2905 return DIE;
2906}
2907
2908//===----------------------------------------------------------------------===//
2909// Initialization entity
2910//===----------------------------------------------------------------------===//
2911
2912InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2913 const InitializedEntity &Parent)
2914 : Parent(&Parent), Index(Index)
2915{
2916 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2917 Kind = EK_ArrayElement;
2918 Type = AT->getElementType();
2919 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2920 Kind = EK_VectorElement;
2921 Type = VT->getElementType();
2922 } else {
2923 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2924 assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ?
void (0) : __assert_fail ("CT && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2924, __extension__ __PRETTY_FUNCTION__))
;
2925 Kind = EK_ComplexElement;
2926 Type = CT->getElementType();
2927 }
2928}
2929
2930InitializedEntity
2931InitializedEntity::InitializeBase(ASTContext &Context,
2932 const CXXBaseSpecifier *Base,
2933 bool IsInheritedVirtualBase,
2934 const InitializedEntity *Parent) {
2935 InitializedEntity Result;
2936 Result.Kind = EK_Base;
2937 Result.Parent = Parent;
2938 Result.Base = reinterpret_cast<uintptr_t>(Base);
2939 if (IsInheritedVirtualBase)
2940 Result.Base |= 0x01;
2941
2942 Result.Type = Base->getType();
2943 return Result;
2944}
2945
2946DeclarationName InitializedEntity::getName() const {
2947 switch (getKind()) {
2948 case EK_Parameter:
2949 case EK_Parameter_CF_Audited: {
2950 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2951 return (D ? D->getDeclName() : DeclarationName());
2952 }
2953
2954 case EK_Variable:
2955 case EK_Member:
2956 case EK_Binding:
2957 return Variable.VariableOrMember->getDeclName();
2958
2959 case EK_LambdaCapture:
2960 return DeclarationName(Capture.VarID);
2961
2962 case EK_Result:
2963 case EK_Exception:
2964 case EK_New:
2965 case EK_Temporary:
2966 case EK_Base:
2967 case EK_Delegating:
2968 case EK_ArrayElement:
2969 case EK_VectorElement:
2970 case EK_ComplexElement:
2971 case EK_BlockElement:
2972 case EK_LambdaToBlockConversionBlockElement:
2973 case EK_CompoundLiteralInit:
2974 case EK_RelatedResult:
2975 return DeclarationName();
2976 }
2977
2978 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 2978)
;
2979}
2980
2981ValueDecl *InitializedEntity::getDecl() const {
2982 switch (getKind()) {
2983 case EK_Variable:
2984 case EK_Member:
2985 case EK_Binding:
2986 return Variable.VariableOrMember;
2987
2988 case EK_Parameter:
2989 case EK_Parameter_CF_Audited:
2990 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2991
2992 case EK_Result:
2993 case EK_Exception:
2994 case EK_New:
2995 case EK_Temporary:
2996 case EK_Base:
2997 case EK_Delegating:
2998 case EK_ArrayElement:
2999 case EK_VectorElement:
3000 case EK_ComplexElement:
3001 case EK_BlockElement:
3002 case EK_LambdaToBlockConversionBlockElement:
3003 case EK_LambdaCapture:
3004 case EK_CompoundLiteralInit:
3005 case EK_RelatedResult:
3006 return nullptr;
3007 }
3008
3009 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3009)
;
3010}
3011
3012bool InitializedEntity::allowsNRVO() const {
3013 switch (getKind()) {
3014 case EK_Result:
3015 case EK_Exception:
3016 return LocAndNRVO.NRVO;
3017
3018 case EK_Variable:
3019 case EK_Parameter:
3020 case EK_Parameter_CF_Audited:
3021 case EK_Member:
3022 case EK_Binding:
3023 case EK_New:
3024 case EK_Temporary:
3025 case EK_CompoundLiteralInit:
3026 case EK_Base:
3027 case EK_Delegating:
3028 case EK_ArrayElement:
3029 case EK_VectorElement:
3030 case EK_ComplexElement:
3031 case EK_BlockElement:
3032 case EK_LambdaToBlockConversionBlockElement:
3033 case EK_LambdaCapture:
3034 case EK_RelatedResult:
3035 break;
3036 }
3037
3038 return false;
3039}
3040
3041unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3042 assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail
("getParent() != this", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3042, __extension__ __PRETTY_FUNCTION__))
;
3043 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3044 for (unsigned I = 0; I != Depth; ++I)
3045 OS << "`-";
3046
3047 switch (getKind()) {
3048 case EK_Variable: OS << "Variable"; break;
3049 case EK_Parameter: OS << "Parameter"; break;
3050 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3051 break;
3052 case EK_Result: OS << "Result"; break;
3053 case EK_Exception: OS << "Exception"; break;
3054 case EK_Member: OS << "Member"; break;
3055 case EK_Binding: OS << "Binding"; break;
3056 case EK_New: OS << "New"; break;
3057 case EK_Temporary: OS << "Temporary"; break;
3058 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3059 case EK_RelatedResult: OS << "RelatedResult"; break;
3060 case EK_Base: OS << "Base"; break;
3061 case EK_Delegating: OS << "Delegating"; break;
3062 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3063 case EK_VectorElement: OS << "VectorElement " << Index; break;
3064 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3065 case EK_BlockElement: OS << "Block"; break;
3066 case EK_LambdaToBlockConversionBlockElement:
3067 OS << "Block (lambda)";
3068 break;
3069 case EK_LambdaCapture:
3070 OS << "LambdaCapture ";
3071 OS << DeclarationName(Capture.VarID);
3072 break;
3073 }
3074
3075 if (auto *D = getDecl()) {
3076 OS << " ";
3077 D->printQualifiedName(OS);
3078 }
3079
3080 OS << " '" << getType().getAsString() << "'\n";
3081
3082 return Depth + 1;
3083}
3084
3085LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const {
3086 dumpImpl(llvm::errs());
3087}
3088
3089//===----------------------------------------------------------------------===//
3090// Initialization sequence
3091//===----------------------------------------------------------------------===//
3092
3093void InitializationSequence::Step::Destroy() {
3094 switch (Kind) {
3095 case SK_ResolveAddressOfOverloadedFunction:
3096 case SK_CastDerivedToBaseRValue:
3097 case SK_CastDerivedToBaseXValue:
3098 case SK_CastDerivedToBaseLValue:
3099 case SK_BindReference:
3100 case SK_BindReferenceToTemporary:
3101 case SK_FinalCopy:
3102 case SK_ExtraneousCopyToTemporary:
3103 case SK_UserConversion:
3104 case SK_QualificationConversionRValue:
3105 case SK_QualificationConversionXValue:
3106 case SK_QualificationConversionLValue:
3107 case SK_AtomicConversion:
3108 case SK_LValueToRValue:
3109 case SK_ListInitialization:
3110 case SK_UnwrapInitList:
3111 case SK_RewrapInitList:
3112 case SK_ConstructorInitialization:
3113 case SK_ConstructorInitializationFromList:
3114 case SK_ZeroInitialization:
3115 case SK_CAssignment:
3116 case SK_StringInit:
3117 case SK_ObjCObjectConversion:
3118 case SK_ArrayLoopIndex:
3119 case SK_ArrayLoopInit:
3120 case SK_ArrayInit:
3121 case SK_GNUArrayInit:
3122 case SK_ParenthesizedArrayInit:
3123 case SK_PassByIndirectCopyRestore:
3124 case SK_PassByIndirectRestore:
3125 case SK_ProduceObjCObject:
3126 case SK_StdInitializerList:
3127 case SK_StdInitializerListConstructorCall:
3128 case SK_OCLSamplerInit:
3129 case SK_OCLZeroEvent:
3130 case SK_OCLZeroQueue:
3131 break;
3132
3133 case SK_ConversionSequence:
3134 case SK_ConversionSequenceNoNarrowing:
3135 delete ICS;
3136 }
3137}
3138
3139bool InitializationSequence::isDirectReferenceBinding() const {
3140 // There can be some lvalue adjustments after the SK_BindReference step.
3141 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3142 if (I->Kind == SK_BindReference)
3143 return true;
3144 if (I->Kind == SK_BindReferenceToTemporary)
3145 return false;
3146 }
3147 return false;
3148}
3149
3150bool InitializationSequence::isAmbiguous() const {
3151 if (!Failed())
3152 return false;
3153
3154 switch (getFailureKind()) {
3155 case FK_TooManyInitsForReference:
3156 case FK_ParenthesizedListInitForReference:
3157 case FK_ArrayNeedsInitList:
3158 case FK_ArrayNeedsInitListOrStringLiteral:
3159 case FK_ArrayNeedsInitListOrWideStringLiteral:
3160 case FK_NarrowStringIntoWideCharArray:
3161 case FK_WideStringIntoCharArray:
3162 case FK_IncompatWideStringIntoWideChar:
3163 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3164 case FK_NonConstLValueReferenceBindingToTemporary:
3165 case FK_NonConstLValueReferenceBindingToBitfield:
3166 case FK_NonConstLValueReferenceBindingToVectorElement:
3167 case FK_NonConstLValueReferenceBindingToUnrelated:
3168 case FK_RValueReferenceBindingToLValue:
3169 case FK_ReferenceInitDropsQualifiers:
3170 case FK_ReferenceInitFailed:
3171 case FK_ConversionFailed:
3172 case FK_ConversionFromPropertyFailed:
3173 case FK_TooManyInitsForScalar:
3174 case FK_ParenthesizedListInitForScalar:
3175 case FK_ReferenceBindingToInitList:
3176 case FK_InitListBadDestinationType:
3177 case FK_DefaultInitOfConst:
3178 case FK_Incomplete:
3179 case FK_ArrayTypeMismatch:
3180 case FK_NonConstantArrayInit:
3181 case FK_ListInitializationFailed:
3182 case FK_VariableLengthArrayHasInitializer:
3183 case FK_PlaceholderType:
3184 case FK_ExplicitConstructor:
3185 case FK_AddressOfUnaddressableFunction:
3186 return false;
3187
3188 case FK_ReferenceInitOverloadFailed:
3189 case FK_UserConversionOverloadFailed:
3190 case FK_ConstructorOverloadFailed:
3191 case FK_ListConstructorOverloadFailed:
3192 return FailedOverloadResult == OR_Ambiguous;
3193 }
3194
3195 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3195)
;
3196}
3197
3198bool InitializationSequence::isConstructorInitialization() const {
3199 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3200}
3201
3202void
3203InitializationSequence
3204::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3205 DeclAccessPair Found,
3206 bool HadMultipleCandidates) {
3207 Step S;
3208 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3209 S.Type = Function->getType();
3210 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3211 S.Function.Function = Function;
3212 S.Function.FoundDecl = Found;
3213 Steps.push_back(S);
3214}
3215
3216void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3217 ExprValueKind VK) {
3218 Step S;
3219 switch (VK) {
3220 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3221 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3222 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3223 }
3224 S.Type = BaseType;
3225 Steps.push_back(S);
3226}
3227
3228void InitializationSequence::AddReferenceBindingStep(QualType T,
3229 bool BindingTemporary) {
3230 Step S;
3231 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3232 S.Type = T;
3233 Steps.push_back(S);
3234}
3235
3236void InitializationSequence::AddFinalCopy(QualType T) {
3237 Step S;
3238 S.Kind = SK_FinalCopy;
3239 S.Type = T;
3240 Steps.push_back(S);
3241}
3242
3243void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3244 Step S;
3245 S.Kind = SK_ExtraneousCopyToTemporary;
3246 S.Type = T;
3247 Steps.push_back(S);
3248}
3249
3250void
3251InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3252 DeclAccessPair FoundDecl,
3253 QualType T,
3254 bool HadMultipleCandidates) {
3255 Step S;
3256 S.Kind = SK_UserConversion;
3257 S.Type = T;
3258 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3259 S.Function.Function = Function;
3260 S.Function.FoundDecl = FoundDecl;
3261 Steps.push_back(S);
3262}
3263
3264void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3265 ExprValueKind VK) {
3266 Step S;
3267 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3268 switch (VK) {
3269 case VK_RValue:
3270 S.Kind = SK_QualificationConversionRValue;
3271 break;
3272 case VK_XValue:
3273 S.Kind = SK_QualificationConversionXValue;
3274 break;
3275 case VK_LValue:
3276 S.Kind = SK_QualificationConversionLValue;
3277 break;
3278 }
3279 S.Type = Ty;
3280 Steps.push_back(S);
3281}
3282
3283void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3284 Step S;
3285 S.Kind = SK_AtomicConversion;
3286 S.Type = Ty;
3287 Steps.push_back(S);
3288}
3289
3290void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3291 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers")(static_cast <bool> (!Ty.hasQualifiers() && "rvalues may not have qualifiers"
) ? void (0) : __assert_fail ("!Ty.hasQualifiers() && \"rvalues may not have qualifiers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3291, __extension__ __PRETTY_FUNCTION__))
;
3292
3293 Step S;
3294 S.Kind = SK_LValueToRValue;
3295 S.Type = Ty;
3296 Steps.push_back(S);
3297}
3298
3299void InitializationSequence::AddConversionSequenceStep(
3300 const ImplicitConversionSequence &ICS, QualType T,
3301 bool TopLevelOfInitList) {
3302 Step S;
3303 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3304 : SK_ConversionSequence;
3305 S.Type = T;
3306 S.ICS = new ImplicitConversionSequence(ICS);
3307 Steps.push_back(S);
3308}
3309
3310void InitializationSequence::AddListInitializationStep(QualType T) {
3311 Step S;
3312 S.Kind = SK_ListInitialization;
3313 S.Type = T;
3314 Steps.push_back(S);
3315}
3316
3317void InitializationSequence::AddConstructorInitializationStep(
3318 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3319 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3320 Step S;
3321 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3322 : SK_ConstructorInitializationFromList
3323 : SK_ConstructorInitialization;
3324 S.Type = T;
3325 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3326 S.Function.Function = Constructor;
3327 S.Function.FoundDecl = FoundDecl;
3328 Steps.push_back(S);
3329}
3330
3331void InitializationSequence::AddZeroInitializationStep(QualType T) {
3332 Step S;
3333 S.Kind = SK_ZeroInitialization;
3334 S.Type = T;
3335 Steps.push_back(S);
3336}
3337
3338void InitializationSequence::AddCAssignmentStep(QualType T) {
3339 Step S;
3340 S.Kind = SK_CAssignment;
3341 S.Type = T;
3342 Steps.push_back(S);
3343}
3344
3345void InitializationSequence::AddStringInitStep(QualType T) {
3346 Step S;
3347 S.Kind = SK_StringInit;
3348 S.Type = T;
3349 Steps.push_back(S);
3350}
3351
3352void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3353 Step S;
3354 S.Kind = SK_ObjCObjectConversion;
3355 S.Type = T;
3356 Steps.push_back(S);
3357}
3358
3359void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3360 Step S;
3361 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3362 S.Type = T;
3363 Steps.push_back(S);
3364}
3365
3366void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3367 Step S;
3368 S.Kind = SK_ArrayLoopIndex;
3369 S.Type = EltT;
3370 Steps.insert(Steps.begin(), S);
3371
3372 S.Kind = SK_ArrayLoopInit;
3373 S.Type = T;
3374 Steps.push_back(S);
3375}
3376
3377void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3378 Step S;
3379 S.Kind = SK_ParenthesizedArrayInit;
3380 S.Type = T;
3381 Steps.push_back(S);
3382}
3383
3384void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3385 bool shouldCopy) {
3386 Step s;
3387 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3388 : SK_PassByIndirectRestore);
3389 s.Type = type;
3390 Steps.push_back(s);
3391}
3392
3393void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3394 Step S;
3395 S.Kind = SK_ProduceObjCObject;
3396 S.Type = T;
3397 Steps.push_back(S);
3398}
3399
3400void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3401 Step S;
3402 S.Kind = SK_StdInitializerList;
3403 S.Type = T;
3404 Steps.push_back(S);
3405}
3406
3407void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3408 Step S;
3409 S.Kind = SK_OCLSamplerInit;
3410 S.Type = T;
3411 Steps.push_back(S);
3412}
3413
3414void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3415 Step S;
3416 S.Kind = SK_OCLZeroEvent;
3417 S.Type = T;
3418 Steps.push_back(S);
3419}
3420
3421void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3422 Step S;
3423 S.Kind = SK_OCLZeroQueue;
3424 S.Type = T;
3425 Steps.push_back(S);
3426}
3427
3428void InitializationSequence::RewrapReferenceInitList(QualType T,
3429 InitListExpr *Syntactic) {
3430 assert(Syntactic->getNumInits() == 1 &&(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3431, __extension__ __PRETTY_FUNCTION__))
3431 "Can only rewrap trivial init lists.")(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3431, __extension__ __PRETTY_FUNCTION__))
;
3432 Step S;
3433 S.Kind = SK_UnwrapInitList;
3434 S.Type = Syntactic->getInit(0)->getType();
3435 Steps.insert(Steps.begin(), S);
3436
3437 S.Kind = SK_RewrapInitList;
3438 S.Type = T;
3439 S.WrappingSyntacticList = Syntactic;
3440 Steps.push_back(S);
3441}
3442
3443void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3444 OverloadingResult Result) {
3445 setSequenceKind(FailedSequence);
3446 this->Failure = Failure;
3447 this->FailedOverloadResult = Result;
3448}
3449
3450//===----------------------------------------------------------------------===//
3451// Attempt initialization
3452//===----------------------------------------------------------------------===//
3453
3454/// Tries to add a zero initializer. Returns true if that worked.
3455static bool
3456maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3457 const InitializedEntity &Entity) {
3458 if (Entity.getKind() != InitializedEntity::EK_Variable)
3459 return false;
3460
3461 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3462 if (VD->getInit() || VD->getLocEnd().isMacroID())
3463 return false;
3464
3465 QualType VariableTy = VD->getType().getCanonicalType();
3466 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3467 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3468 if (!Init.empty()) {
3469 Sequence.AddZeroInitializationStep(Entity.getType());
3470 Sequence.SetZeroInitializationFixit(Init, Loc);
3471 return true;
3472 }
3473 return false;
3474}
3475
3476static void MaybeProduceObjCObject(Sema &S,
3477 InitializationSequence &Sequence,
3478 const InitializedEntity &Entity) {
3479 if (!S.getLangOpts().ObjCAutoRefCount) return;
3480
3481 /// When initializing a parameter, produce the value if it's marked
3482 /// __attribute__((ns_consumed)).
3483 if (Entity.isParameterKind()) {
3484 if (!Entity.isParameterConsumed())
3485 return;
3486
3487 assert(Entity.getType()->isObjCRetainableType() &&(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3488, __extension__ __PRETTY_FUNCTION__))
3488 "consuming an object of unretainable type?")(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3488, __extension__ __PRETTY_FUNCTION__))
;
3489 Sequence.AddProduceObjCObjectStep(Entity.getType());
3490
3491 /// When initializing a return value, if the return type is a
3492 /// retainable type, then returns need to immediately retain the
3493 /// object. If an autorelease is required, it will be done at the
3494 /// last instant.
3495 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3496 if (!Entity.getType()->isObjCRetainableType())
3497 return;
3498
3499 Sequence.AddProduceObjCObjectStep(Entity.getType());
3500 }
3501}
3502
3503static void TryListInitialization(Sema &S,
3504 const InitializedEntity &Entity,
3505 const InitializationKind &Kind,
3506 InitListExpr *InitList,
3507 InitializationSequence &Sequence,
3508 bool TreatUnavailableAsInvalid);
3509
3510/// \brief When initializing from init list via constructor, handle
3511/// initialization of an object of type std::initializer_list<T>.
3512///
3513/// \return true if we have handled initialization of an object of type
3514/// std::initializer_list<T>, false otherwise.
3515static bool TryInitializerListConstruction(Sema &S,
3516 InitListExpr *List,
3517 QualType DestType,
3518 InitializationSequence &Sequence,
3519 bool TreatUnavailableAsInvalid) {
3520 QualType E;
3521 if (!S.isStdInitializerList(DestType, &E))
3522 return false;
3523
3524 if (!S.isCompleteType(List->getExprLoc(), E)) {
3525 Sequence.setIncompleteTypeFailure(E);
3526 return true;
3527 }
3528
3529 // Try initializing a temporary array from the init list.
3530 QualType ArrayType = S.Context.getConstantArrayType(
3531 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3532 List->getNumInits()),
3533 clang::ArrayType::Normal, 0);
3534 InitializedEntity HiddenArray =
3535 InitializedEntity::InitializeTemporary(ArrayType);
3536 InitializationKind Kind =
3537 InitializationKind::CreateDirectList(List->getExprLoc());
3538 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3539 TreatUnavailableAsInvalid);
3540 if (Sequence)
3541 Sequence.AddStdInitializerListConstructionStep(DestType);
3542 return true;
3543}
3544
3545/// Determine if the constructor has the signature of a copy or move
3546/// constructor for the type T of the class in which it was found. That is,
3547/// determine if its first parameter is of type T or reference to (possibly
3548/// cv-qualified) T.
3549static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3550 const ConstructorInfo &Info) {
3551 if (Info.Constructor->getNumParams() == 0)
3552 return false;
3553
3554 QualType ParmT =
3555 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3556 QualType ClassT =
3557 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3558
3559 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3560}
3561
3562static OverloadingResult
3563ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3564 MultiExprArg Args,
3565 OverloadCandidateSet &CandidateSet,
3566 QualType DestType,
3567 DeclContext::lookup_result Ctors,
3568 OverloadCandidateSet::iterator &Best,
3569 bool CopyInitializing, bool AllowExplicit,
3570 bool OnlyListConstructors, bool IsListInit,
3571 bool SecondStepOfCopyInit = false) {
3572 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3573
3574 for (NamedDecl *D : Ctors) {
3575 auto Info = getConstructorInfo(D);
3576 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3577 continue;
3578
3579 if (!AllowExplicit && Info.Constructor->isExplicit())
3580 continue;
3581
3582 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3583 continue;
3584
3585 // C++11 [over.best.ics]p4:
3586 // ... and the constructor or user-defined conversion function is a
3587 // candidate by
3588 // - 13.3.1.3, when the argument is the temporary in the second step
3589 // of a class copy-initialization, or
3590 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3591 // - the second phase of 13.3.1.7 when the initializer list has exactly
3592 // one element that is itself an initializer list, and the target is
3593 // the first parameter of a constructor of class X, and the conversion
3594 // is to X or reference to (possibly cv-qualified X),
3595 // user-defined conversion sequences are not considered.
3596 bool SuppressUserConversions =
3597 SecondStepOfCopyInit ||
3598 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3599 hasCopyOrMoveCtorParam(S.Context, Info));
3600
3601 if (Info.ConstructorTmpl)
3602 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3603 /*ExplicitArgs*/ nullptr, Args,
3604 CandidateSet, SuppressUserConversions);
3605 else {
3606 // C++ [over.match.copy]p1:
3607 // - When initializing a temporary to be bound to the first parameter
3608 // of a constructor [for type T] that takes a reference to possibly
3609 // cv-qualified T as its first argument, called with a single
3610 // argument in the context of direct-initialization, explicit
3611 // conversion functions are also considered.
3612 // FIXME: What if a constructor template instantiates to such a signature?
3613 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3614 Args.size() == 1 &&
3615 hasCopyOrMoveCtorParam(S.Context, Info);
3616 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3617 CandidateSet, SuppressUserConversions,
3618 /*PartialOverloading=*/false,
3619 /*AllowExplicit=*/AllowExplicitConv);
3620 }
3621 }
3622
3623 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3624 //
3625 // When initializing an object of class type T by constructor
3626 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3627 // from a single expression of class type U, conversion functions of
3628 // U that convert to the non-reference type cv T are candidates.
3629 // Explicit conversion functions are only candidates during
3630 // direct-initialization.
3631 //
3632 // Note: SecondStepOfCopyInit is only ever true in this case when
3633 // evaluating whether to produce a C++98 compatibility warning.
3634 if (S.getLangOpts().CPlusPlus1z && Args.size() == 1 &&
3635 !SecondStepOfCopyInit) {
3636 Expr *Initializer = Args[0];
3637 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3638 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3639 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3640 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3641 NamedDecl *D = *I;
3642 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3643 D = D->getUnderlyingDecl();
3644
3645 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3646 CXXConversionDecl *Conv;
3647 if (ConvTemplate)
3648 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3649 else
3650 Conv = cast<CXXConversionDecl>(D);
3651
3652 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3653 if (ConvTemplate)
3654 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3655 ActingDC, Initializer, DestType,
3656 CandidateSet, AllowExplicit,
3657 /*AllowResultConversion*/false);
3658 else
3659 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3660 DestType, CandidateSet, AllowExplicit,
3661 /*AllowResultConversion*/false);
3662 }
3663 }
3664 }
3665 }
3666
3667 // Perform overload resolution and return the result.
3668 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3669}
3670
3671/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3672/// enumerates the constructors of the initialized entity and performs overload
3673/// resolution to select the best.
3674/// \param DestType The destination class type.
3675/// \param DestArrayType The destination type, which is either DestType or
3676/// a (possibly multidimensional) array of DestType.
3677/// \param IsListInit Is this list-initialization?
3678/// \param IsInitListCopy Is this non-list-initialization resulting from a
3679/// list-initialization from {x} where x is the same
3680/// type as the entity?
3681static void TryConstructorInitialization(Sema &S,
3682 const InitializedEntity &Entity,
3683 const InitializationKind &Kind,
3684 MultiExprArg Args, QualType DestType,
3685 QualType DestArrayType,
3686 InitializationSequence &Sequence,
3687 bool IsListInit = false,
3688 bool IsInitListCopy = false) {
3689 assert(((!IsListInit && !IsInitListCopy) ||(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3692, __extension__ __PRETTY_FUNCTION__))
3690 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3692, __extension__ __PRETTY_FUNCTION__))
3691 "IsListInit/IsInitListCopy must come with a single initializer list "(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3692, __extension__ __PRETTY_FUNCTION__))
3692 "argument.")(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3692, __extension__ __PRETTY_FUNCTION__))
;
3693 InitListExpr *ILE =
3694 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3695 MultiExprArg UnwrappedArgs =
3696 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3697
3698 // The type we're constructing needs to be complete.
3699 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3700 Sequence.setIncompleteTypeFailure(DestType);
3701 return;
3702 }
3703
3704 // C++1z [dcl.init]p17:
3705 // - If the initializer expression is a prvalue and the cv-unqualified
3706 // version of the source type is the same class as the class of the
3707 // destination, the initializer expression is used to initialize the
3708 // destination object.
3709 // Per DR (no number yet), this does not apply when initializing a base
3710 // class or delegating to another constructor from a mem-initializer.
3711 // ObjC++: Lambda captured by the block in the lambda to block conversion
3712 // should avoid copy elision.
3713 if (S.getLangOpts().CPlusPlus1z &&
3714 Entity.getKind() != InitializedEntity::EK_Base &&
3715 Entity.getKind() != InitializedEntity::EK_Delegating &&
3716 Entity.getKind() !=
3717 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3718 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3719 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3720 // Convert qualifications if necessary.
3721 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3722 if (ILE)
3723 Sequence.RewrapReferenceInitList(DestType, ILE);
3724 return;
3725 }
3726
3727 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3728 assert(DestRecordType && "Constructor initialization requires record type")(static_cast <bool> (DestRecordType && "Constructor initialization requires record type"
) ? void (0) : __assert_fail ("DestRecordType && \"Constructor initialization requires record type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3728, __extension__ __PRETTY_FUNCTION__))
;
3729 CXXRecordDecl *DestRecordDecl
3730 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3731
3732 // Build the candidate set directly in the initialization sequence
3733 // structure, so that it will persist if we fail.
3734 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3735
3736 // Determine whether we are allowed to call explicit constructors or
3737 // explicit conversion operators.
3738 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3739 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3740
3741 // - Otherwise, if T is a class type, constructors are considered. The
3742 // applicable constructors are enumerated, and the best one is chosen
3743 // through overload resolution.
3744 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3745
3746 OverloadingResult Result = OR_No_Viable_Function;
3747 OverloadCandidateSet::iterator Best;
3748 bool AsInitializerList = false;
3749
3750 // C++11 [over.match.list]p1, per DR1467:
3751 // When objects of non-aggregate type T are list-initialized, such that
3752 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3753 // according to the rules in this section, overload resolution selects
3754 // the constructor in two phases:
3755 //
3756 // - Initially, the candidate functions are the initializer-list
3757 // constructors of the class T and the argument list consists of the
3758 // initializer list as a single argument.
3759 if (IsListInit) {
3760 AsInitializerList = true;
3761
3762 // If the initializer list has no elements and T has a default constructor,
3763 // the first phase is omitted.
3764 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3765 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3766 CandidateSet, DestType, Ctors, Best,
3767 CopyInitialization, AllowExplicit,
3768 /*OnlyListConstructor=*/true,
3769 IsListInit);
3770 }
3771
3772 // C++11 [over.match.list]p1:
3773 // - If no viable initializer-list constructor is found, overload resolution
3774 // is performed again, where the candidate functions are all the
3775 // constructors of the class T and the argument list consists of the
3776 // elements of the initializer list.
3777 if (Result == OR_No_Viable_Function) {
3778 AsInitializerList = false;
3779 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3780 CandidateSet, DestType, Ctors, Best,
3781 CopyInitialization, AllowExplicit,
3782 /*OnlyListConstructors=*/false,
3783 IsListInit);
3784 }
3785 if (Result) {
3786 Sequence.SetOverloadFailure(IsListInit ?
3787 InitializationSequence::FK_ListConstructorOverloadFailed :
3788 InitializationSequence::FK_ConstructorOverloadFailed,
3789 Result);
3790 return;
3791 }
3792
3793 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3794
3795 // In C++17, ResolveConstructorOverload can select a conversion function
3796 // instead of a constructor.
3797 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3798 // Add the user-defined conversion step that calls the conversion function.
3799 QualType ConvType = CD->getConversionType();
3800 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3801, __extension__ __PRETTY_FUNCTION__))
3801 "should not have selected this conversion function")(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 3801, __extension__ __PRETTY_FUNCTION__))
;
3802 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3803 HadMultipleCandidates);
3804 if (!S.Context.hasSameType(ConvType, DestType))
3805 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3806 if (IsListInit)
3807 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3808 return;
3809 }
3810
3811 // C++11 [dcl.init]p6:
3812 // If a program calls for the default initialization of an object
3813 // of a const-qualified type T, T shall be a class type with a
3814 // user-provided default constructor.
3815 // C++ core issue 253 proposal:
3816 // If the implicit default constructor initializes all subobjects, no
3817 // initializer should be required.
3818 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3819 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3820 if (Kind.getKind() == InitializationKind::IK_Default &&
3821 Entity.getType().isConstQualified()) {
3822 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3823 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3824 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3825 return;
3826 }
3827 }
3828
3829 // C++11 [over.match.list]p1:
3830 // In copy-list-initialization, if an explicit constructor is chosen, the
3831 // initializer is ill-formed.
3832 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3833 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3834 return;
3835 }
3836
3837 // Add the constructor initialization step. Any cv-qualification conversion is
3838 // subsumed by the initialization.
3839 Sequence.AddConstructorInitializationStep(
3840 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
3841 IsListInit | IsInitListCopy, AsInitializerList);
3842}
3843
3844static bool
3845ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3846 Expr *Initializer,
3847 QualType &SourceType,
3848 QualType &UnqualifiedSourceType,
3849 QualType UnqualifiedTargetType,
3850 InitializationSequence &Sequence) {
3851 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3852 S.Context.OverloadTy) {
3853 DeclAccessPair Found;
3854 bool HadMultipleCandidates = false;
3855 if (FunctionDecl *Fn
3856 = S.ResolveAddressOfOverloadedFunction(Initializer,
3857 UnqualifiedTargetType,
3858 false, Found,
3859 &HadMultipleCandidates)) {
3860 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3861 HadMultipleCandidates);
3862 SourceType = Fn->getType();
3863 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3864 } else if (!UnqualifiedTargetType->isRecordType()) {
3865 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3866 return true;
3867 }
3868 }
3869 return false;
3870}
3871
3872static void TryReferenceInitializationCore(Sema &S,
3873 const InitializedEntity &Entity,
3874 const InitializationKind &Kind,
3875 Expr *Initializer,
3876 QualType cv1T1, QualType T1,
3877 Qualifiers T1Quals,
3878 QualType cv2T2, QualType T2,
3879 Qualifiers T2Quals,
3880 InitializationSequence &Sequence);
3881
3882static void TryValueInitialization(Sema &S,
3883 const InitializedEntity &Entity,
3884 const InitializationKind &Kind,
3885 InitializationSequence &Sequence,
3886 InitListExpr *InitList = nullptr);
3887
3888/// \brief Attempt list initialization of a reference.
3889static void TryReferenceListInitialization(Sema &S,
3890 const InitializedEntity &Entity,
3891 const InitializationKind &Kind,
3892 InitListExpr *InitList,
3893 InitializationSequence &Sequence,
3894 bool TreatUnavailableAsInvalid) {
3895 // First, catch C++03 where this isn't possible.
3896 if (!S.getLangOpts().CPlusPlus11) {
3897 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3898 return;
3899 }
3900 // Can't reference initialize a compound literal.
3901 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3902 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3903 return;
3904 }
3905
3906 QualType DestType = Entity.getType();
3907 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3908 Qualifiers T1Quals;
3909 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3910
3911 // Reference initialization via an initializer list works thus:
3912 // If the initializer list consists of a single element that is
3913 // reference-related to the referenced type, bind directly to that element
3914 // (possibly creating temporaries).
3915 // Otherwise, initialize a temporary with the initializer list and
3916 // bind to that.
3917 if (InitList->getNumInits() == 1) {
3918 Expr *Initializer = InitList->getInit(0);
3919 QualType cv2T2 = Initializer->getType();
3920 Qualifiers T2Quals;
3921 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3922
3923 // If this fails, creating a temporary wouldn't work either.
3924 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3925 T1, Sequence))
3926 return;
3927
3928 SourceLocation DeclLoc = Initializer->getLocStart();
3929 bool dummy1, dummy2, dummy3;
3930 Sema::ReferenceCompareResult RefRelationship
3931 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3932 dummy2, dummy3);
3933 if (RefRelationship >= Sema::Ref_Related) {
3934 // Try to bind the reference here.
3935 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3936 T1Quals, cv2T2, T2, T2Quals, Sequence);
3937 if (Sequence)
3938 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3939 return;
3940 }
3941
3942 // Update the initializer if we've resolved an overloaded function.
3943 if (Sequence.step_begin() != Sequence.step_end())
3944 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3945 }
3946
3947 // Not reference-related. Create a temporary and bind to that.
3948 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3949
3950 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3951 TreatUnavailableAsInvalid);
3952 if (Sequence) {
3953 if (DestType->isRValueReferenceType() ||
3954 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3955 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3956 else
3957 Sequence.SetFailed(
3958 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3959 }
3960}
3961
3962/// \brief Attempt list initialization (C++0x [dcl.init.list])
3963static void TryListInitialization(Sema &S,
3964 const InitializedEntity &Entity,
3965 const InitializationKind &Kind,
3966 InitListExpr *InitList,
3967 InitializationSequence &Sequence,
3968 bool TreatUnavailableAsInvalid) {
3969 QualType DestType = Entity.getType();
3970
3971 // C++ doesn't allow scalar initialization with more than one argument.
3972 // But C99 complex numbers are scalars and it makes sense there.
3973 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3974 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3975 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3976 return;
3977 }
3978 if (DestType->isReferenceType()) {
3979 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3980 TreatUnavailableAsInvalid);
3981 return;
3982 }
3983
3984 if (DestType->isRecordType() &&
3985 !S.isCompleteType(InitList->getLocStart(), DestType)) {
3986 Sequence.setIncompleteTypeFailure(DestType);
3987 return;
3988 }
3989
3990 // C++11 [dcl.init.list]p3, per DR1467:
3991 // - If T is a class type and the initializer list has a single element of
3992 // type cv U, where U is T or a class derived from T, the object is
3993 // initialized from that element (by copy-initialization for
3994 // copy-list-initialization, or by direct-initialization for
3995 // direct-list-initialization).
3996 // - Otherwise, if T is a character array and the initializer list has a
3997 // single element that is an appropriately-typed string literal
3998 // (8.5.2 [dcl.init.string]), initialization is performed as described
3999 // in that section.
4000 // - Otherwise, if T is an aggregate, [...] (continue below).
4001 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4002 if (DestType->isRecordType()) {
4003 QualType InitType = InitList->getInit(0)->getType();
4004 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4005 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
4006 Expr *InitListAsExpr = InitList;
4007 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4008 DestType, Sequence,
4009 /*InitListSyntax*/false,
4010 /*IsInitListCopy*/true);
4011 return;
4012 }
4013 }
4014 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4015 Expr *SubInit[1] = {InitList->getInit(0)};
4016 if (!isa<VariableArrayType>(DestAT) &&
4017 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4018 InitializationKind SubKind =
4019 Kind.getKind() == InitializationKind::IK_DirectList
4020 ? InitializationKind::CreateDirect(Kind.getLocation(),
4021 InitList->getLBraceLoc(),
4022 InitList->getRBraceLoc())
4023 : Kind;
4024 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4025 /*TopLevelOfInitList*/ true,
4026 TreatUnavailableAsInvalid);
4027
4028 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4029 // the element is not an appropriately-typed string literal, in which
4030 // case we should proceed as in C++11 (below).
4031 if (Sequence) {
4032 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4033 return;
4034 }
4035 }
4036 }
4037 }
4038
4039 // C++11 [dcl.init.list]p3:
4040 // - If T is an aggregate, aggregate initialization is performed.
4041 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4042 (S.getLangOpts().CPlusPlus11 &&
4043 S.isStdInitializerList(DestType, nullptr))) {
4044 if (S.getLangOpts().CPlusPlus11) {
4045 // - Otherwise, if the initializer list has no elements and T is a
4046 // class type with a default constructor, the object is
4047 // value-initialized.
4048 if (InitList->getNumInits() == 0) {
4049 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4050 if (RD->hasDefaultConstructor()) {
4051 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4052 return;
4053 }
4054 }
4055
4056 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4057 // an initializer_list object constructed [...]
4058 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4059 TreatUnavailableAsInvalid))
4060 return;
4061
4062 // - Otherwise, if T is a class type, constructors are considered.
4063 Expr *InitListAsExpr = InitList;
4064 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4065 DestType, Sequence, /*InitListSyntax*/true);
4066 } else
4067 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4068 return;
4069 }
4070
4071 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4072 InitList->getNumInits() == 1) {
4073 Expr *E = InitList->getInit(0);
4074
4075 // - Otherwise, if T is an enumeration with a fixed underlying type,
4076 // the initializer-list has a single element v, and the initialization
4077 // is direct-list-initialization, the object is initialized with the
4078 // value T(v); if a narrowing conversion is required to convert v to
4079 // the underlying type of T, the program is ill-formed.
4080 auto *ET = DestType->getAs<EnumType>();
4081 if (S.getLangOpts().CPlusPlus1z &&
4082 Kind.getKind() == InitializationKind::IK_DirectList &&
4083 ET && ET->getDecl()->isFixed() &&
4084 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4085 (E->getType()->isIntegralOrEnumerationType() ||
4086 E->getType()->isFloatingType())) {
4087 // There are two ways that T(v) can work when T is an enumeration type.
4088 // If there is either an implicit conversion sequence from v to T or
4089 // a conversion function that can convert from v to T, then we use that.
4090 // Otherwise, if v is of integral, enumeration, or floating-point type,
4091 // it is converted to the enumeration type via its underlying type.
4092 // There is no overlap possible between these two cases (except when the
4093 // source value is already of the destination type), and the first
4094 // case is handled by the general case for single-element lists below.
4095 ImplicitConversionSequence ICS;
4096 ICS.setStandard();
4097 ICS.Standard.setAsIdentityConversion();
4098 if (!E->isRValue())
4099 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4100 // If E is of a floating-point type, then the conversion is ill-formed
4101 // due to narrowing, but go through the motions in order to produce the
4102 // right diagnostic.
4103 ICS.Standard.Second = E->getType()->isFloatingType()
4104 ? ICK_Floating_Integral
4105 : ICK_Integral_Conversion;
4106 ICS.Standard.setFromType(E->getType());
4107 ICS.Standard.setToType(0, E->getType());
4108 ICS.Standard.setToType(1, DestType);
4109 ICS.Standard.setToType(2, DestType);
4110 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4111 /*TopLevelOfInitList*/true);
4112 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4113 return;
4114 }
4115
4116 // - Otherwise, if the initializer list has a single element of type E
4117 // [...references are handled above...], the object or reference is
4118 // initialized from that element (by copy-initialization for
4119 // copy-list-initialization, or by direct-initialization for
4120 // direct-list-initialization); if a narrowing conversion is required
4121 // to convert the element to T, the program is ill-formed.
4122 //
4123 // Per core-24034, this is direct-initialization if we were performing
4124 // direct-list-initialization and copy-initialization otherwise.
4125 // We can't use InitListChecker for this, because it always performs
4126 // copy-initialization. This only matters if we might use an 'explicit'
4127 // conversion operator, so we only need to handle the cases where the source
4128 // is of record type.
4129 if (InitList->getInit(0)->getType()->isRecordType()) {
4130 InitializationKind SubKind =
4131 Kind.getKind() == InitializationKind::IK_DirectList
4132 ? InitializationKind::CreateDirect(Kind.getLocation(),
4133 InitList->getLBraceLoc(),
4134 InitList->getRBraceLoc())
4135 : Kind;
4136 Expr *SubInit[1] = { InitList->getInit(0) };
4137 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4138 /*TopLevelOfInitList*/true,
4139 TreatUnavailableAsInvalid);
4140 if (Sequence)
4141 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4142 return;
4143 }
4144 }
4145
4146 InitListChecker CheckInitList(S, Entity, InitList,
4147 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4148 if (CheckInitList.HadError()) {
4149 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4150 return;
4151 }
4152
4153 // Add the list initialization step with the built init list.
4154 Sequence.AddListInitializationStep(DestType);
4155}
4156
4157/// \brief Try a reference initialization that involves calling a conversion
4158/// function.
4159static OverloadingResult TryRefInitWithConversionFunction(
4160 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4161 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4162 InitializationSequence &Sequence) {
4163 QualType DestType = Entity.getType();
4164 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4165 QualType T1 = cv1T1.getUnqualifiedType();
4166 QualType cv2T2 = Initializer->getType();
4167 QualType T2 = cv2T2.getUnqualifiedType();
4168
4169 bool DerivedToBase;
4170 bool ObjCConversion;
4171 bool ObjCLifetimeConversion;
4172 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion
) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion) && \"Must have incompatible references when binding via conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4176, __extension__ __PRETTY_FUNCTION__))
4173 T1, T2, DerivedToBase,(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion
) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion) && \"Must have incompatible references when binding via conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4176, __extension__ __PRETTY_FUNCTION__))
4174 ObjCConversion,(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion
) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion) && \"Must have incompatible references when binding via conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4176, __extension__ __PRETTY_FUNCTION__))
4175 ObjCLifetimeConversion) &&(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion
) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion) && \"Must have incompatible references when binding via conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4176, __extension__ __PRETTY_FUNCTION__))
4176 "Must have incompatible references when binding via conversion")(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion
) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getLocStart(), T1, T2, DerivedToBase, ObjCConversion, ObjCLifetimeConversion) && \"Must have incompatible references when binding via conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4176, __extension__ __PRETTY_FUNCTION__))
;
4177 (void)DerivedToBase;
4178 (void)ObjCConversion;
4179 (void)ObjCLifetimeConversion;
4180
4181 // Build the candidate set directly in the initialization sequence
4182 // structure, so that it will persist if we fail.
4183 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4184 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4185
4186 // Determine whether we are allowed to call explicit constructors or
4187 // explicit conversion operators.
4188 bool AllowExplicit = Kind.AllowExplicit();
4189 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4190
4191 const RecordType *T1RecordType = nullptr;
4192 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4193 S.isCompleteType(Kind.getLocation(), T1)) {
4194 // The type we're converting to is a class type. Enumerate its constructors
4195 // to see if there is a suitable conversion.
4196 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4197
4198 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4199 auto Info = getConstructorInfo(D);
4200 if (!Info.Constructor)
4201 continue;
4202
4203 if (!Info.Constructor->isInvalidDecl() &&
4204 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4205 if (Info.ConstructorTmpl)
4206 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4207 /*ExplicitArgs*/ nullptr,
4208 Initializer, CandidateSet,
4209 /*SuppressUserConversions=*/true);
4210 else
4211 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4212 Initializer, CandidateSet,
4213 /*SuppressUserConversions=*/true);
4214 }
4215 }
4216 }
4217 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4218 return OR_No_Viable_Function;
4219
4220 const RecordType *T2RecordType = nullptr;
4221 if ((T2RecordType = T2->getAs<RecordType>()) &&
4222 S.isCompleteType(Kind.getLocation(), T2)) {
4223 // The type we're converting from is a class type, enumerate its conversion
4224 // functions.
4225 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4226
4227 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4228 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4229 NamedDecl *D = *I;
4230 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4231 if (isa<UsingShadowDecl>(D))
4232 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4233
4234 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4235 CXXConversionDecl *Conv;
4236 if (ConvTemplate)
4237 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4238 else
4239 Conv = cast<CXXConversionDecl>(D);
4240
4241 // If the conversion function doesn't return a reference type,
4242 // it can't be considered for this conversion unless we're allowed to
4243 // consider rvalues.
4244 // FIXME: Do we need to make sure that we only consider conversion
4245 // candidates with reference-compatible results? That might be needed to
4246 // break recursion.
4247 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4248 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4249 if (ConvTemplate)
4250 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4251 ActingDC, Initializer,
4252 DestType, CandidateSet,
4253 /*AllowObjCConversionOnExplicit=*/
4254 false);
4255 else
4256 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4257 Initializer, DestType, CandidateSet,
4258 /*AllowObjCConversionOnExplicit=*/false);
4259 }
4260 }
4261 }
4262 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4263 return OR_No_Viable_Function;
4264
4265 SourceLocation DeclLoc = Initializer->getLocStart();
4266
4267 // Perform overload resolution. If it fails, return the failed result.
4268 OverloadCandidateSet::iterator Best;
4269 if (OverloadingResult Result
4270 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4271 return Result;
4272
4273 FunctionDecl *Function = Best->Function;
4274 // This is the overload that will be used for this initialization step if we
4275 // use this initialization. Mark it as referenced.
4276 Function->setReferenced();
4277
4278 // Compute the returned type and value kind of the conversion.
4279 QualType cv3T3;
4280 if (isa<CXXConversionDecl>(Function))
4281 cv3T3 = Function->getReturnType();
4282 else
4283 cv3T3 = T1;
4284
4285 ExprValueKind VK = VK_RValue;
4286 if (cv3T3->isLValueReferenceType())
4287 VK = VK_LValue;
4288 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4289 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4290 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4291
4292 // Add the user-defined conversion step.
4293 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4294 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4295 HadMultipleCandidates);
4296
4297 // Determine whether we'll need to perform derived-to-base adjustments or
4298 // other conversions.
4299 bool NewDerivedToBase = false;
4300 bool NewObjCConversion = false;
4301 bool NewObjCLifetimeConversion = false;
4302 Sema::ReferenceCompareResult NewRefRelationship
4303 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4304 NewDerivedToBase, NewObjCConversion,
4305 NewObjCLifetimeConversion);
4306
4307 // Add the final conversion sequence, if necessary.
4308 if (NewRefRelationship == Sema::Ref_Incompatible) {
4309 assert(!isa<CXXConstructorDecl>(Function) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4310, __extension__ __PRETTY_FUNCTION__))
4310 "should not have conversion after constructor")(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4310, __extension__ __PRETTY_FUNCTION__))
;
4311
4312 ImplicitConversionSequence ICS;
4313 ICS.setStandard();
4314 ICS.Standard = Best->FinalConversion;
4315 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4316
4317 // Every implicit conversion results in a prvalue, except for a glvalue
4318 // derived-to-base conversion, which we handle below.
4319 cv3T3 = ICS.Standard.getToType(2);
4320 VK = VK_RValue;
4321 }
4322
4323 // If the converted initializer is a prvalue, its type T4 is adjusted to
4324 // type "cv1 T4" and the temporary materialization conversion is applied.
4325 //
4326 // We adjust the cv-qualifications to match the reference regardless of
4327 // whether we have a prvalue so that the AST records the change. In this
4328 // case, T4 is "cv3 T3".
4329 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4330 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4331 Sequence.AddQualificationConversionStep(cv1T4, VK);
4332 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4333 VK = IsLValueRef ? VK_LValue : VK_XValue;
4334
4335 if (NewDerivedToBase)
4336 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4337 else if (NewObjCConversion)
4338 Sequence.AddObjCObjectConversionStep(cv1T1);
4339
4340 return OR_Success;
4341}
4342
4343static void CheckCXX98CompatAccessibleCopy(Sema &S,
4344 const InitializedEntity &Entity,
4345 Expr *CurInitExpr);
4346
4347/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4348static void TryReferenceInitialization(Sema &S,
4349 const InitializedEntity &Entity,
4350 const InitializationKind &Kind,
4351 Expr *Initializer,
4352 InitializationSequence &Sequence) {
4353 QualType DestType = Entity.getType();
4354 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4355 Qualifiers T1Quals;
4356 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4357 QualType cv2T2 = Initializer->getType();
4358 Qualifiers T2Quals;
4359 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4360
4361 // If the initializer is the address of an overloaded function, try
4362 // to resolve the overloaded function. If all goes well, T2 is the
4363 // type of the resulting function.
4364 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4365 T1, Sequence))
4366 return;
4367
4368 // Delegate everything else to a subfunction.
4369 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4370 T1Quals, cv2T2, T2, T2Quals, Sequence);
4371}
4372
4373/// Determine whether an expression is a non-referenceable glvalue (one to
4374/// which a reference can never bind). Attemting to bind a reference to
4375/// such a glvalue will always create a temporary.
4376static bool isNonReferenceableGLValue(Expr *E) {
4377 return E->refersToBitField() || E->refersToVectorElement();
4378}
4379
4380/// \brief Reference initialization without resolving overloaded functions.
4381static void TryReferenceInitializationCore(Sema &S,
4382 const InitializedEntity &Entity,
4383 const InitializationKind &Kind,
4384 Expr *Initializer,
4385 QualType cv1T1, QualType T1,
4386 Qualifiers T1Quals,
4387 QualType cv2T2, QualType T2,
4388 Qualifiers T2Quals,
4389 InitializationSequence &Sequence) {
4390 QualType DestType = Entity.getType();
4391 SourceLocation DeclLoc = Initializer->getLocStart();
4392 // Compute some basic properties of the types and the initializer.
4393 bool isLValueRef = DestType->isLValueReferenceType();
4394 bool isRValueRef = !isLValueRef;
4395 bool DerivedToBase = false;
4396 bool ObjCConversion = false;
4397 bool ObjCLifetimeConversion = false;
4398 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4399 Sema::ReferenceCompareResult RefRelationship
4400 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4401 ObjCConversion, ObjCLifetimeConversion);
4402
4403 // C++0x [dcl.init.ref]p5:
4404 // A reference to type "cv1 T1" is initialized by an expression of type
4405 // "cv2 T2" as follows:
4406 //
4407 // - If the reference is an lvalue reference and the initializer
4408 // expression
4409 // Note the analogous bullet points for rvalue refs to functions. Because
4410 // there are no function rvalues in C++, rvalue refs to functions are treated
4411 // like lvalue refs.
4412 OverloadingResult ConvOvlResult = OR_Success;
4413 bool T1Function = T1->isFunctionType();
4414 if (isLValueRef || T1Function) {
4415 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4416 (RefRelationship == Sema::Ref_Compatible ||
4417 (Kind.isCStyleOrFunctionalCast() &&
4418 RefRelationship == Sema::Ref_Related))) {
4419 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4420 // reference-compatible with "cv2 T2," or
4421 if (T1Quals != T2Quals)
4422 // Convert to cv1 T2. This should only add qualifiers unless this is a
4423 // c-style cast. The removal of qualifiers in that case notionally
4424 // happens after the reference binding, but that doesn't matter.
4425 Sequence.AddQualificationConversionStep(
4426 S.Context.getQualifiedType(T2, T1Quals),
4427 Initializer->getValueKind());
4428 if (DerivedToBase)
4429 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4430 else if (ObjCConversion)
4431 Sequence.AddObjCObjectConversionStep(cv1T1);
4432
4433 // We only create a temporary here when binding a reference to a
4434 // bit-field or vector element. Those cases are't supposed to be
4435 // handled by this bullet, but the outcome is the same either way.
4436 Sequence.AddReferenceBindingStep(cv1T1, false);
4437 return;
4438 }
4439
4440 // - has a class type (i.e., T2 is a class type), where T1 is not
4441 // reference-related to T2, and can be implicitly converted to an
4442 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4443 // with "cv3 T3" (this conversion is selected by enumerating the
4444 // applicable conversion functions (13.3.1.6) and choosing the best
4445 // one through overload resolution (13.3)),
4446 // If we have an rvalue ref to function type here, the rhs must be
4447 // an rvalue. DR1287 removed the "implicitly" here.
4448 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4449 (isLValueRef || InitCategory.isRValue())) {
4450 ConvOvlResult = TryRefInitWithConversionFunction(
4451 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4452 /*IsLValueRef*/ isLValueRef, Sequence);
4453 if (ConvOvlResult == OR_Success)
4454 return;
4455 if (ConvOvlResult != OR_No_Viable_Function)
4456 Sequence.SetOverloadFailure(
4457 InitializationSequence::FK_ReferenceInitOverloadFailed,
4458 ConvOvlResult);
4459 }
4460 }
4461
4462 // - Otherwise, the reference shall be an lvalue reference to a
4463 // non-volatile const type (i.e., cv1 shall be const), or the reference
4464 // shall be an rvalue reference.
4465 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4466 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4467 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4468 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4469 Sequence.SetOverloadFailure(
4470 InitializationSequence::FK_ReferenceInitOverloadFailed,
4471 ConvOvlResult);
4472 else if (!InitCategory.isLValue())
4473 Sequence.SetFailed(
4474 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4475 else {
4476 InitializationSequence::FailureKind FK;
4477 switch (RefRelationship) {
4478 case Sema::Ref_Compatible:
4479 if (Initializer->refersToBitField())
4480 FK = InitializationSequence::
4481 FK_NonConstLValueReferenceBindingToBitfield;
4482 else if (Initializer->refersToVectorElement())
4483 FK = InitializationSequence::
4484 FK_NonConstLValueReferenceBindingToVectorElement;
4485 else
4486 llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4486)
;
4487 break;
4488 case Sema::Ref_Related:
4489 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4490 break;
4491 case Sema::Ref_Incompatible:
4492 FK = InitializationSequence::
4493 FK_NonConstLValueReferenceBindingToUnrelated;
4494 break;
4495 }
4496 Sequence.SetFailed(FK);
4497 }
4498 return;
4499 }
4500
4501 // - If the initializer expression
4502 // - is an
4503 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4504 // [1z] rvalue (but not a bit-field) or
4505 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4506 //
4507 // Note: functions are handled above and below rather than here...
4508 if (!T1Function &&
4509 (RefRelationship == Sema::Ref_Compatible ||
4510 (Kind.isCStyleOrFunctionalCast() &&
4511 RefRelationship == Sema::Ref_Related)) &&
4512 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4513 (InitCategory.isPRValue() &&
4514 (S.getLangOpts().CPlusPlus1z || T2->isRecordType() ||
4515 T2->isArrayType())))) {
4516 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4517 if (InitCategory.isPRValue() && T2->isRecordType()) {
4518 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4519 // compiler the freedom to perform a copy here or bind to the
4520 // object, while C++0x requires that we bind directly to the
4521 // object. Hence, we always bind to the object without making an
4522 // extra copy. However, in C++03 requires that we check for the
4523 // presence of a suitable copy constructor:
4524 //
4525 // The constructor that would be used to make the copy shall
4526 // be callable whether or not the copy is actually done.
4527 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4528 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4529 else if (S.getLangOpts().CPlusPlus11)
4530 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4531 }
4532
4533 // C++1z [dcl.init.ref]/5.2.1.2:
4534 // If the converted initializer is a prvalue, its type T4 is adjusted
4535 // to type "cv1 T4" and the temporary materialization conversion is
4536 // applied.
4537 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4538 if (T1Quals != T2Quals)
4539 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4540 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4541 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4542
4543 // In any case, the reference is bound to the resulting glvalue (or to
4544 // an appropriate base class subobject).
4545 if (DerivedToBase)
4546 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4547 else if (ObjCConversion)
4548 Sequence.AddObjCObjectConversionStep(cv1T1);
4549 return;
4550 }
4551
4552 // - has a class type (i.e., T2 is a class type), where T1 is not
4553 // reference-related to T2, and can be implicitly converted to an
4554 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4555 // where "cv1 T1" is reference-compatible with "cv3 T3",
4556 //
4557 // DR1287 removes the "implicitly" here.
4558 if (T2->isRecordType()) {
4559 if (RefRelationship == Sema::Ref_Incompatible) {
4560 ConvOvlResult = TryRefInitWithConversionFunction(
4561 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4562 /*IsLValueRef*/ isLValueRef, Sequence);
4563 if (ConvOvlResult)
4564 Sequence.SetOverloadFailure(
4565 InitializationSequence::FK_ReferenceInitOverloadFailed,
4566 ConvOvlResult);
4567
4568 return;
4569 }
4570
4571 if (RefRelationship == Sema::Ref_Compatible &&
4572 isRValueRef && InitCategory.isLValue()) {
4573 Sequence.SetFailed(
4574 InitializationSequence::FK_RValueReferenceBindingToLValue);
4575 return;
4576 }
4577
4578 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4579 return;
4580 }
4581
4582 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4583 // from the initializer expression using the rules for a non-reference
4584 // copy-initialization (8.5). The reference is then bound to the
4585 // temporary. [...]
4586
4587 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4588
4589 // FIXME: Why do we use an implicit conversion here rather than trying
4590 // copy-initialization?
4591 ImplicitConversionSequence ICS
4592 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4593 /*SuppressUserConversions=*/false,
4594 /*AllowExplicit=*/false,
4595 /*FIXME:InOverloadResolution=*/false,
4596 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4597 /*AllowObjCWritebackConversion=*/false);
4598
4599 if (ICS.isBad()) {
4600 // FIXME: Use the conversion function set stored in ICS to turn
4601 // this into an overloading ambiguity diagnostic. However, we need
4602 // to keep that set as an OverloadCandidateSet rather than as some
4603 // other kind of set.
4604 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4605 Sequence.SetOverloadFailure(
4606 InitializationSequence::FK_ReferenceInitOverloadFailed,
4607 ConvOvlResult);
4608 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4609 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4610 else
4611 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4612 return;
4613 } else {
4614 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4615 }
4616
4617 // [...] If T1 is reference-related to T2, cv1 must be the
4618 // same cv-qualification as, or greater cv-qualification
4619 // than, cv2; otherwise, the program is ill-formed.
4620 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4621 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4622 if (RefRelationship == Sema::Ref_Related &&
4623 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4624 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4625 return;
4626 }
4627
4628 // [...] If T1 is reference-related to T2 and the reference is an rvalue
4629 // reference, the initializer expression shall not be an lvalue.
4630 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4631 InitCategory.isLValue()) {
4632 Sequence.SetFailed(
4633 InitializationSequence::FK_RValueReferenceBindingToLValue);
4634 return;
4635 }
4636
4637 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4638}
4639
4640/// \brief Attempt character array initialization from a string literal
4641/// (C++ [dcl.init.string], C99 6.7.8).
4642static void TryStringLiteralInitialization(Sema &S,
4643 const InitializedEntity &Entity,
4644 const InitializationKind &Kind,
4645 Expr *Initializer,
4646 InitializationSequence &Sequence) {
4647 Sequence.AddStringInitStep(Entity.getType());
4648}
4649
4650/// \brief Attempt value initialization (C++ [dcl.init]p7).
4651static void TryValueInitialization(Sema &S,
4652 const InitializedEntity &Entity,
4653 const InitializationKind &Kind,
4654 InitializationSequence &Sequence,
4655 InitListExpr *InitList) {
4656 assert((!InitList || InitList->getNumInits() == 0) &&(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4657, __extension__ __PRETTY_FUNCTION__))
4657 "Shouldn't use value-init for non-empty init lists")(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4657, __extension__ __PRETTY_FUNCTION__))
;
4658
4659 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4660 //
4661 // To value-initialize an object of type T means:
4662 QualType T = Entity.getType();
4663
4664 // -- if T is an array type, then each element is value-initialized;
4665 T = S.Context.getBaseElementType(T);
4666
4667 if (const RecordType *RT = T->getAs<RecordType>()) {
4668 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4669 bool NeedZeroInitialization = true;
4670 // C++98:
4671 // -- if T is a class type (clause 9) with a user-declared constructor
4672 // (12.1), then the default constructor for T is called (and the
4673 // initialization is ill-formed if T has no accessible default
4674 // constructor);
4675 // C++11:
4676 // -- if T is a class type (clause 9) with either no default constructor
4677 // (12.1 [class.ctor]) or a default constructor that is user-provided
4678 // or deleted, then the object is default-initialized;
4679 //
4680 // Note that the C++11 rule is the same as the C++98 rule if there are no
4681 // defaulted or deleted constructors, so we just use it unconditionally.
4682 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4683 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4684 NeedZeroInitialization = false;
4685
4686 // -- if T is a (possibly cv-qualified) non-union class type without a
4687 // user-provided or deleted default constructor, then the object is
4688 // zero-initialized and, if T has a non-trivial default constructor,
4689 // default-initialized;
4690 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4691 // constructor' part was removed by DR1507.
4692 if (NeedZeroInitialization)
4693 Sequence.AddZeroInitializationStep(Entity.getType());
4694
4695 // C++03:
4696 // -- if T is a non-union class type without a user-declared constructor,
4697 // then every non-static data member and base class component of T is
4698 // value-initialized;
4699 // [...] A program that calls for [...] value-initialization of an
4700 // entity of reference type is ill-formed.
4701 //
4702 // C++11 doesn't need this handling, because value-initialization does not
4703 // occur recursively there, and the implicit default constructor is
4704 // defined as deleted in the problematic cases.
4705 if (!S.getLangOpts().CPlusPlus11 &&
4706 ClassDecl->hasUninitializedReferenceMember()) {
4707 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4708 return;
4709 }
4710
4711 // If this is list-value-initialization, pass the empty init list on when
4712 // building the constructor call. This affects the semantics of a few
4713 // things (such as whether an explicit default constructor can be called).
4714 Expr *InitListAsExpr = InitList;
4715 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4716 bool InitListSyntax = InitList;
4717
4718 // FIXME: Instead of creating a CXXConstructExpr of array type here,
4719 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4720 return TryConstructorInitialization(
4721 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4722 }
4723 }
4724
4725 Sequence.AddZeroInitializationStep(Entity.getType());
4726}
4727
4728/// \brief Attempt default initialization (C++ [dcl.init]p6).
4729static void TryDefaultInitialization(Sema &S,
4730 const InitializedEntity &Entity,
4731 const InitializationKind &Kind,
4732 InitializationSequence &Sequence) {
4733 assert(Kind.getKind() == InitializationKind::IK_Default)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Default) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Default"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4733, __extension__ __PRETTY_FUNCTION__))
;
4734
4735 // C++ [dcl.init]p6:
4736 // To default-initialize an object of type T means:
4737 // - if T is an array type, each element is default-initialized;
4738 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4739
4740 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4741 // constructor for T is called (and the initialization is ill-formed if
4742 // T has no accessible default constructor);
4743 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4744 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4745 Entity.getType(), Sequence);
4746 return;
4747 }
4748
4749 // - otherwise, no initialization is performed.
4750
4751 // If a program calls for the default initialization of an object of
4752 // a const-qualified type T, T shall be a class type with a user-provided
4753 // default constructor.
4754 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4755 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4756 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4757 return;
4758 }
4759
4760 // If the destination type has a lifetime property, zero-initialize it.
4761 if (DestType.getQualifiers().hasObjCLifetime()) {
4762 Sequence.AddZeroInitializationStep(Entity.getType());
4763 return;
4764 }
4765}
4766
4767/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4768/// which enumerates all conversion functions and performs overload resolution
4769/// to select the best.
4770static void TryUserDefinedConversion(Sema &S,
4771 QualType DestType,
4772 const InitializationKind &Kind,
4773 Expr *Initializer,
4774 InitializationSequence &Sequence,
4775 bool TopLevelOfInitList) {
4776 assert(!DestType->isReferenceType() && "References are handled elsewhere")(static_cast <bool> (!DestType->isReferenceType() &&
"References are handled elsewhere") ? void (0) : __assert_fail
("!DestType->isReferenceType() && \"References are handled elsewhere\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4776, __extension__ __PRETTY_FUNCTION__))
;
4777 QualType SourceType = Initializer->getType();
4778 assert((DestType->isRecordType() || SourceType->isRecordType()) &&(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4779, __extension__ __PRETTY_FUNCTION__))
4779 "Must have a class type to perform a user-defined conversion")(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 4779, __extension__ __PRETTY_FUNCTION__))
;
4780
4781 // Build the candidate set directly in the initialization sequence
4782 // structure, so that it will persist if we fail.
4783 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4784 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4785
4786 // Determine whether we are allowed to call explicit constructors or
4787 // explicit conversion operators.
4788 bool AllowExplicit = Kind.AllowExplicit();
4789
4790 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4791 // The type we're converting to is a class type. Enumerate its constructors
4792 // to see if there is a suitable conversion.
4793 CXXRecordDecl *DestRecordDecl
4794 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4795
4796 // Try to complete the type we're converting to.
4797 if (S.isCompleteType(Kind.getLocation(), DestType)) {
4798 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
4799 auto Info = getConstructorInfo(D);
4800 if (!Info.Constructor)
4801 continue;
4802
4803 if (!Info.Constructor->isInvalidDecl() &&
4804 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4805 if (Info.ConstructorTmpl)
4806 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4807 /*ExplicitArgs*/ nullptr,
4808 Initializer, CandidateSet,
4809 /*SuppressUserConversions=*/true);
4810 else
4811 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4812 Initializer, CandidateSet,
4813 /*SuppressUserConversions=*/true);
4814 }
4815 }
4816 }
4817 }
4818
4819 SourceLocation DeclLoc = Initializer->getLocStart();
4820
4821 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4822 // The type we're converting from is a class type, enumerate its conversion
4823 // functions.
4824
4825 // We can only enumerate the conversion functions for a complete type; if
4826 // the type isn't complete, simply skip this step.
4827 if (S.isCompleteType(DeclLoc, SourceType)) {
4828 CXXRecordDecl *SourceRecordDecl
4829 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4830
4831 const auto &Conversions =
4832 SourceRecordDecl->getVisibleConversionFunctions();
4833 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4834 NamedDecl *D = *I;
4835 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4836 if (isa<UsingShadowDecl>(D))
4837 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4838
4839 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4840 CXXConversionDecl *Conv;
4841 if (ConvTemplate)
4842 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4843 else
4844 Conv = cast<CXXConversionDecl>(D);
4845
4846 if (AllowExplicit || !Conv->isExplicit()) {
4847 if (ConvTemplate)
4848 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4849 ActingDC, Initializer, DestType,
4850 CandidateSet, AllowExplicit);
4851 else
4852 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4853 Initializer, DestType, CandidateSet,
4854 AllowExplicit);
4855 }
4856 }
4857 }
4858 }
4859
4860 // Perform overload resolution. If it fails, return the failed result.
4861 OverloadCandidateSet::iterator Best;
4862 if (OverloadingResult Result
4863 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4864 Sequence.SetOverloadFailure(
4865 InitializationSequence::FK_UserConversionOverloadFailed,
4866 Result);
4867 return;
4868 }
4869
4870 FunctionDecl *Function = Best->Function;
4871 Function->setReferenced();
4872 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4873
4874 if (isa<CXXConstructorDecl>(Function)) {
4875 // Add the user-defined conversion step. Any cv-qualification conversion is
4876 // subsumed by the initialization. Per DR5, the created temporary is of the
4877 // cv-unqualified type of the destination.
4878 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4879 DestType.getUnqualifiedType(),
4880 HadMultipleCandidates);
4881
4882 // C++14 and before:
4883 // - if the function is a constructor, the call initializes a temporary
4884 // of the cv-unqualified version of the destination type. The [...]
4885 // temporary [...] is then used to direct-initialize, according to the
4886 // rules above, the object that is the destination of the
4887 // copy-initialization.
4888 // Note that this just performs a simple object copy from the temporary.
4889 //
4890 // C++1z:
4891 // - if the function is a constructor, the call is a prvalue of the
4892 // cv-unqualified version of the destination type whose return object
4893 // is initialized by the constructor. The call is used to
4894 // direct-initialize, according to the rules above, the object that
4895 // is the destination of the copy-initialization.
4896 // Therefore we need to do nothing further.
4897 //
4898 // FIXME: Mark this copy as extraneous.
4899 if (!S.getLangOpts().CPlusPlus1z)
4900 Sequence.AddFinalCopy(DestType);
4901 else if (DestType.hasQualifiers())
4902 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4903 return;
4904 }
4905
4906 // Add the user-defined conversion step that calls the conversion function.
4907 QualType ConvType = Function->getCallResultType();
4908 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4909 HadMultipleCandidates);
4910
4911 if (ConvType->getAs<RecordType>()) {
4912 // The call is used to direct-initialize [...] the object that is the
4913 // destination of the copy-initialization.
4914 //
4915 // In C++1z, this does not call a constructor if we enter /17.6.1:
4916 // - If the initializer expression is a prvalue and the cv-unqualified
4917 // version of the source type is the same as the class of the
4918 // destination [... do not make an extra copy]
4919 //
4920 // FIXME: Mark this copy as extraneous.
4921 if (!S.getLangOpts().CPlusPlus1z ||
4922 Function->getReturnType()->isReferenceType() ||
4923 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4924 Sequence.AddFinalCopy(DestType);
4925 else if (!S.Context.hasSameType(ConvType, DestType))
4926 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4927 return;
4928 }
4929
4930 // If the conversion following the call to the conversion function
4931 // is interesting, add it as a separate step.
4932 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4933 Best->FinalConversion.Third) {
4934 ImplicitConversionSequence ICS;
4935 ICS.setStandard();
4936 ICS.Standard = Best->FinalConversion;
4937 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4938 }
4939}
4940
4941/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4942/// a function with a pointer return type contains a 'return false;' statement.
4943/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4944/// code using that header.
4945///
4946/// Work around this by treating 'return false;' as zero-initializing the result
4947/// if it's used in a pointer-returning function in a system header.
4948static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4949 const InitializedEntity &Entity,
4950 const Expr *Init) {
4951 return S.getLangOpts().CPlusPlus11 &&
4952 Entity.getKind() == InitializedEntity::EK_Result &&
4953 Entity.getType()->isPointerType() &&
4954 isa<CXXBoolLiteralExpr>(Init) &&
4955 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4956 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4957}
4958
4959/// The non-zero enum values here are indexes into diagnostic alternatives.
4960enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4961
4962/// Determines whether this expression is an acceptable ICR source.
4963static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4964 bool isAddressOf, bool &isWeakAccess) {
4965 // Skip parens.
4966 e = e->IgnoreParens();
4967
4968 // Skip address-of nodes.
4969 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4970 if (op->getOpcode() == UO_AddrOf)
4971 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4972 isWeakAccess);
4973
4974 // Skip certain casts.
4975 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4976 switch (ce->getCastKind()) {
4977 case CK_Dependent:
4978 case CK_BitCast:
4979 case CK_LValueBitCast:
4980 case CK_NoOp:
4981 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4982
4983 case CK_ArrayToPointerDecay:
4984 return IIK_nonscalar;
4985
4986 case CK_NullToPointer:
4987 return IIK_okay;
4988
4989 default:
4990 break;
4991 }
4992
4993 // If we have a declaration reference, it had better be a local variable.
4994 } else if (isa<DeclRefExpr>(e)) {
4995 // set isWeakAccess to true, to mean that there will be an implicit
4996 // load which requires a cleanup.
4997 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4998 isWeakAccess = true;
4999
5000 if (!isAddressOf) return IIK_nonlocal;
5001
5002 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5003 if (!var) return IIK_nonlocal;
5004
5005 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5006
5007 // If we have a conditional operator, check both sides.
5008 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5009 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5010 isWeakAccess))
5011 return iik;
5012
5013 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5014
5015 // These are never scalar.
5016 } else if (isa<ArraySubscriptExpr>(e)) {
5017 return IIK_nonscalar;
5018
5019 // Otherwise, it needs to be a null pointer constant.
5020 } else {
5021 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5022 ? IIK_okay : IIK_nonlocal);
5023 }
5024
5025 return IIK_nonlocal;
5026}
5027
5028/// Check whether the given expression is a valid operand for an
5029/// indirect copy/restore.
5030static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5031 assert(src->isRValue())(static_cast <bool> (src->isRValue()) ? void (0) : __assert_fail
("src->isRValue()", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5031, __extension__ __PRETTY_FUNCTION__))
;
5032 bool isWeakAccess = false;
5033 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5034 // If isWeakAccess to true, there will be an implicit
5035 // load which requires a cleanup.
5036 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5037 S.Cleanup.setExprNeedsCleanups(true);
5038
5039 if (iik == IIK_okay) return;
5040
5041 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5042 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5043 << src->getSourceRange();
5044}
5045
5046/// \brief Determine whether we have compatible array types for the
5047/// purposes of GNU by-copy array initialization.
5048static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5049 const ArrayType *Source) {
5050 // If the source and destination array types are equivalent, we're
5051 // done.
5052 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5053 return true;
5054
5055 // Make sure that the element types are the same.
5056 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5057 return false;
5058
5059 // The only mismatch we allow is when the destination is an
5060 // incomplete array type and the source is a constant array type.
5061 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5062}
5063
5064static bool tryObjCWritebackConversion(Sema &S,
5065 InitializationSequence &Sequence,
5066 const InitializedEntity &Entity,
5067 Expr *Initializer) {
5068 bool ArrayDecay = false;
5069 QualType ArgType = Initializer->getType();
5070 QualType ArgPointee;
5071 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5072 ArrayDecay = true;
5073 ArgPointee = ArgArrayType->getElementType();
5074 ArgType = S.Context.getPointerType(ArgPointee);
5075 }
5076
5077 // Handle write-back conversion.
5078 QualType ConvertedArgType;
5079 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5080 ConvertedArgType))
5081 return false;
5082
5083 // We should copy unless we're passing to an argument explicitly
5084 // marked 'out'.
5085 bool ShouldCopy = true;
5086 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5087 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5088
5089 // Do we need an lvalue conversion?
5090 if (ArrayDecay || Initializer->isGLValue()) {
5091 ImplicitConversionSequence ICS;
5092 ICS.setStandard();
5093 ICS.Standard.setAsIdentityConversion();
5094
5095 QualType ResultType;
5096 if (ArrayDecay) {
5097 ICS.Standard.First = ICK_Array_To_Pointer;
5098 ResultType = S.Context.getPointerType(ArgPointee);
5099 } else {
5100 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5101 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5102 }
5103
5104 Sequence.AddConversionSequenceStep(ICS, ResultType);
5105 }
5106
5107 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5108 return true;
5109}
5110
5111static bool TryOCLSamplerInitialization(Sema &S,
5112 InitializationSequence &Sequence,
5113 QualType DestType,
5114 Expr *Initializer) {
5115 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5116 (!Initializer->isIntegerConstantExpr(S.Context) &&
5117 !Initializer->getType()->isSamplerT()))
5118 return false;
5119
5120 Sequence.AddOCLSamplerInitStep(DestType);
5121 return true;
5122}
5123
5124//
5125// OpenCL 1.2 spec, s6.12.10
5126//
5127// The event argument can also be used to associate the
5128// async_work_group_copy with a previous async copy allowing
5129// an event to be shared by multiple async copies; otherwise
5130// event should be zero.
5131//
5132static bool TryOCLZeroEventInitialization(Sema &S,
5133 InitializationSequence &Sequence,
5134 QualType DestType,
5135 Expr *Initializer) {
5136 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5137 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5138 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5139 return false;
5140
5141 Sequence.AddOCLZeroEventStep(DestType);
5142 return true;
5143}
5144
5145static bool TryOCLZeroQueueInitialization(Sema &S,
5146 InitializationSequence &Sequence,
5147 QualType DestType,
5148 Expr *Initializer) {
5149 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
23
Assuming the condition is false
5150 !DestType->isQueueT() ||
5151 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
24
Called C++ object pointer is null
5152 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5153 return false;
5154
5155 Sequence.AddOCLZeroQueueStep(DestType);
5156 return true;
5157}
5158
5159InitializationSequence::InitializationSequence(Sema &S,
5160 const InitializedEntity &Entity,
5161 const InitializationKind &Kind,
5162 MultiExprArg Args,
5163 bool TopLevelOfInitList,
5164 bool TreatUnavailableAsInvalid)
5165 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5166 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5167 TreatUnavailableAsInvalid);
5168}
5169
5170/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5171/// address of that function, this returns true. Otherwise, it returns false.
5172static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5173 auto *DRE = dyn_cast<DeclRefExpr>(E);
5174 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5175 return false;
5176
5177 return !S.checkAddressOfFunctionIsAvailable(
5178 cast<FunctionDecl>(DRE->getDecl()));
5179}
5180
5181/// Determine whether we can perform an elementwise array copy for this kind
5182/// of entity.
5183static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5184 switch (Entity.getKind()) {
5185 case InitializedEntity::EK_LambdaCapture:
5186 // C++ [expr.prim.lambda]p24:
5187 // For array members, the array elements are direct-initialized in
5188 // increasing subscript order.
5189 return true;
5190
5191 case InitializedEntity::EK_Variable:
5192 // C++ [dcl.decomp]p1:
5193 // [...] each element is copy-initialized or direct-initialized from the
5194 // corresponding element of the assignment-expression [...]
5195 return isa<DecompositionDecl>(Entity.getDecl());
5196
5197 case InitializedEntity::EK_Member:
5198 // C++ [class.copy.ctor]p14:
5199 // - if the member is an array, each element is direct-initialized with
5200 // the corresponding subobject of x
5201 return Entity.isImplicitMemberInitializer();
5202
5203 case InitializedEntity::EK_ArrayElement:
5204 // All the above cases are intended to apply recursively, even though none
5205 // of them actually say that.
5206 if (auto *E = Entity.getParent())
5207 return canPerformArrayCopy(*E);
5208 break;
5209
5210 default:
5211 break;
5212 }
5213
5214 return false;
5215}
5216
5217void InitializationSequence::InitializeFrom(Sema &S,
5218 const InitializedEntity &Entity,
5219 const InitializationKind &Kind,
5220 MultiExprArg Args,
5221 bool TopLevelOfInitList,
5222 bool TreatUnavailableAsInvalid) {
5223 ASTContext &Context = S.Context;
5224
5225 // Eliminate non-overload placeholder types in the arguments. We
5226 // need to do this before checking whether types are dependent
5227 // because lowering a pseudo-object expression might well give us
5228 // something of dependent type.
5229 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1
Assuming 'I' is equal to 'E'
2
Loop condition is false. Execution continues on line 5246
5230 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5231 // FIXME: should we be doing this here?
5232 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5233 if (result.isInvalid()) {
5234 SetFailed(FK_PlaceholderType);
5235 return;
5236 }
5237 Args[I] = result.get();
5238 }
5239
5240 // C++0x [dcl.init]p16:
5241 // The semantics of initializers are as follows. The destination type is
5242 // the type of the object or reference being initialized and the source
5243 // type is the type of the initializer expression. The source type is not
5244 // defined when the initializer is a braced-init-list or when it is a
5245 // parenthesized list of expressions.
5246 QualType DestType = Entity.getType();
5247
5248 if (DestType->isDependentType() ||
4
Taking false branch
5249 Expr::hasAnyTypeDependentArguments(Args)) {
3
Assuming the condition is false
5250 SequenceKind = DependentSequence;
5251 return;
5252 }
5253
5254 // Almost everything is a normal sequence.
5255 setSequenceKind(NormalSequence);
5256
5257 QualType SourceType;
5258 Expr *Initializer = nullptr;
5
'Initializer' initialized to a null pointer value
5259 if (Args.size() == 1) {
6
Assuming the condition is false
7
Taking false branch
5260 Initializer = Args[0];
5261 if (S.getLangOpts().ObjC1) {
5262 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5263 DestType, Initializer->getType(),
5264 Initializer) ||
5265 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5266 Args[0] = Initializer;
5267 }
5268 if (!isa<InitListExpr>(Initializer))
5269 SourceType = Initializer->getType();
5270 }
5271
5272 // - If the initializer is a (non-parenthesized) braced-init-list, the
5273 // object is list-initialized (8.5.4).
5274 if (Kind.getKind() != InitializationKind::IK_Direct) {
8
Assuming the condition is false
9
Taking false branch
5275 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5276 TryListInitialization(S, Entity, Kind, InitList, *this,
5277 TreatUnavailableAsInvalid);
5278 return;
5279 }
5280 }
5281
5282 // - If the destination type is a reference type, see 8.5.3.
5283 if (DestType->isReferenceType()) {
10
Taking false branch
5284 // C++0x [dcl.init.ref]p1:
5285 // A variable declared to be a T& or T&&, that is, "reference to type T"
5286 // (8.3.2), shall be initialized by an object, or function, of type T or
5287 // by an object that can be converted into a T.
5288 // (Therefore, multiple arguments are not permitted.)
5289 if (Args.size() != 1)
5290 SetFailed(FK_TooManyInitsForReference);
5291 // C++17 [dcl.init.ref]p5:
5292 // A reference [...] is initialized by an expression [...] as follows:
5293 // If the initializer is not an expression, presumably we should reject,
5294 // but the standard fails to actually say so.
5295 else if (isa<InitListExpr>(Args[0]))
5296 SetFailed(FK_ParenthesizedListInitForReference);
5297 else
5298 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5299 return;
5300 }
5301
5302 // - If the initializer is (), the object is value-initialized.
5303 if (Kind.getKind() == InitializationKind::IK_Value ||
12
Taking false branch
5304 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
11
Assuming the condition is false
5305 TryValueInitialization(S, Entity, Kind, *this);
5306 return;
5307 }
5308
5309 // Handle default initialization.
5310 if (Kind.getKind() == InitializationKind::IK_Default) {
13
Taking false branch
5311 TryDefaultInitialization(S, Entity, Kind, *this);
5312 return;
5313 }
5314
5315 // - If the destination type is an array of characters, an array of
5316 // char16_t, an array of char32_t, or an array of wchar_t, and the
5317 // initializer is a string literal, see 8.5.2.
5318 // - Otherwise, if the destination type is an array, the program is
5319 // ill-formed.
5320 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
14
Assuming 'DestAT' is null
15
Taking false branch
5321 if (Initializer && isa<VariableArrayType>(DestAT)) {
5322 SetFailed(FK_VariableLengthArrayHasInitializer);
5323 return;
5324 }
5325
5326 if (Initializer) {
5327 switch (IsStringInit(Initializer, DestAT, Context)) {
5328 case SIF_None:
5329 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5330 return;
5331 case SIF_NarrowStringIntoWideChar:
5332 SetFailed(FK_NarrowStringIntoWideCharArray);
5333 return;
5334 case SIF_WideStringIntoChar:
5335 SetFailed(FK_WideStringIntoCharArray);
5336 return;
5337 case SIF_IncompatWideStringIntoWideChar:
5338 SetFailed(FK_IncompatWideStringIntoWideChar);
5339 return;
5340 case SIF_Other:
5341 break;
5342 }
5343 }
5344
5345 // Some kinds of initialization permit an array to be initialized from
5346 // another array of the same type, and perform elementwise initialization.
5347 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5348 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5349 Entity.getType()) &&
5350 canPerformArrayCopy(Entity)) {
5351 // If source is a prvalue, use it directly.
5352 if (Initializer->getValueKind() == VK_RValue) {
5353 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5354 return;
5355 }
5356
5357 // Emit element-at-a-time copy loop.
5358 InitializedEntity Element =
5359 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5360 QualType InitEltT =
5361 Context.getAsArrayType(Initializer->getType())->getElementType();
5362 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5363 Initializer->getValueKind(),
5364 Initializer->getObjectKind());
5365 Expr *OVEAsExpr = &OVE;
5366 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5367 TreatUnavailableAsInvalid);
5368 if (!Failed())
5369 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5370 return;
5371 }
5372
5373 // Note: as an GNU C extension, we allow initialization of an
5374 // array from a compound literal that creates an array of the same
5375 // type, so long as the initializer has no side effects.
5376 if (!S.getLangOpts().CPlusPlus && Initializer &&
5377 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5378 Initializer->getType()->isArrayType()) {
5379 const ArrayType *SourceAT
5380 = Context.getAsArrayType(Initializer->getType());
5381 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5382 SetFailed(FK_ArrayTypeMismatch);
5383 else if (Initializer->HasSideEffects(S.Context))
5384 SetFailed(FK_NonConstantArrayInit);
5385 else {
5386 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5387 }
5388 }
5389 // Note: as a GNU C++ extension, we allow list-initialization of a
5390 // class member of array type from a parenthesized initializer list.
5391 else if (S.getLangOpts().CPlusPlus &&
5392 Entity.getKind() == InitializedEntity::EK_Member &&
5393 Initializer && isa<InitListExpr>(Initializer)) {
5394 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5395 *this, TreatUnavailableAsInvalid);
5396 AddParenthesizedArrayInitStep(DestType);
5397 } else if (DestAT->getElementType()->isCharType())
5398 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5399 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5400 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5401 else
5402 SetFailed(FK_ArrayNeedsInitList);
5403
5404 return;
5405 }
5406
5407 // Determine whether we should consider writeback conversions for
5408 // Objective-C ARC.
5409 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
16
Assuming the condition is false
5410 Entity.isParameterKind();
5411
5412 // We're at the end of the line for C: it's either a write-back conversion
5413 // or it's a C assignment. There's no need to check anything else.
5414 if (!S.getLangOpts().CPlusPlus) {
17
Assuming the condition is true
18
Taking true branch
5415 // If allowed, check whether this is an Objective-C writeback conversion.
5416 if (allowObjCWritebackConversion &&
5417 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5418 return;
5419 }
5420
5421 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
19
Taking false branch
5422 return;
5423
5424 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
20
Taking false branch
5425 return;
5426
5427 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
21
Passing null pointer value via 4th parameter 'Initializer'
22
Calling 'TryOCLZeroQueueInitialization'
5428 return;
5429
5430 // Handle initialization in C
5431 AddCAssignmentStep(DestType);
5432 MaybeProduceObjCObject(S, *this, Entity);
5433 return;
5434 }
5435
5436 assert(S.getLangOpts().CPlusPlus)(static_cast <bool> (S.getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("S.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5436, __extension__ __PRETTY_FUNCTION__))
;
5437
5438 // - If the destination type is a (possibly cv-qualified) class type:
5439 if (DestType->isRecordType()) {
5440 // - If the initialization is direct-initialization, or if it is
5441 // copy-initialization where the cv-unqualified version of the
5442 // source type is the same class as, or a derived class of, the
5443 // class of the destination, constructors are considered. [...]
5444 if (Kind.getKind() == InitializationKind::IK_Direct ||
5445 (Kind.getKind() == InitializationKind::IK_Copy &&
5446 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5447 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
5448 TryConstructorInitialization(S, Entity, Kind, Args,
5449 DestType, DestType, *this);
5450 // - Otherwise (i.e., for the remaining copy-initialization cases),
5451 // user-defined conversion sequences that can convert from the source
5452 // type to the destination type or (when a conversion function is
5453 // used) to a derived class thereof are enumerated as described in
5454 // 13.3.1.4, and the best one is chosen through overload resolution
5455 // (13.3).
5456 else
5457 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5458 TopLevelOfInitList);
5459 return;
5460 }
5461
5462 assert(Args.size() >= 1 && "Zero-argument case handled above")(static_cast <bool> (Args.size() >= 1 && "Zero-argument case handled above"
) ? void (0) : __assert_fail ("Args.size() >= 1 && \"Zero-argument case handled above\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5462, __extension__ __PRETTY_FUNCTION__))
;
5463
5464 // The remaining cases all need a source type.
5465 if (Args.size() > 1) {
5466 SetFailed(FK_TooManyInitsForScalar);
5467 return;
5468 } else if (isa<InitListExpr>(Args[0])) {
5469 SetFailed(FK_ParenthesizedListInitForScalar);
5470 return;
5471 }
5472
5473 // - Otherwise, if the source type is a (possibly cv-qualified) class
5474 // type, conversion functions are considered.
5475 if (!SourceType.isNull() && SourceType->isRecordType()) {
5476 // For a conversion to _Atomic(T) from either T or a class type derived
5477 // from T, initialize the T object then convert to _Atomic type.
5478 bool NeedAtomicConversion = false;
5479 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5480 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5481 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5482 Atomic->getValueType())) {
5483 DestType = Atomic->getValueType();
5484 NeedAtomicConversion = true;
5485 }
5486 }
5487
5488 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5489 TopLevelOfInitList);
5490 MaybeProduceObjCObject(S, *this, Entity);
5491 if (!Failed() && NeedAtomicConversion)
5492 AddAtomicConversionStep(Entity.getType());
5493 return;
5494 }
5495
5496 // - Otherwise, the initial value of the object being initialized is the
5497 // (possibly converted) value of the initializer expression. Standard
5498 // conversions (Clause 4) will be used, if necessary, to convert the
5499 // initializer expression to the cv-unqualified version of the
5500 // destination type; no user-defined conversions are considered.
5501
5502 ImplicitConversionSequence ICS
5503 = S.TryImplicitConversion(Initializer, DestType,
5504 /*SuppressUserConversions*/true,
5505 /*AllowExplicitConversions*/ false,
5506 /*InOverloadResolution*/ false,
5507 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5508 allowObjCWritebackConversion);
5509
5510 if (ICS.isStandard() &&
5511 ICS.Standard.Second == ICK_Writeback_Conversion) {
5512 // Objective-C ARC writeback conversion.
5513
5514 // We should copy unless we're passing to an argument explicitly
5515 // marked 'out'.
5516 bool ShouldCopy = true;
5517 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5518 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5519
5520 // If there was an lvalue adjustment, add it as a separate conversion.
5521 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5522 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5523 ImplicitConversionSequence LvalueICS;
5524 LvalueICS.setStandard();
5525 LvalueICS.Standard.setAsIdentityConversion();
5526 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5527 LvalueICS.Standard.First = ICS.Standard.First;
5528 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5529 }
5530
5531 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5532 } else if (ICS.isBad()) {
5533 DeclAccessPair dap;
5534 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5535 AddZeroInitializationStep(Entity.getType());
5536 } else if (Initializer->getType() == Context.OverloadTy &&
5537 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5538 false, dap))
5539 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5540 else if (Initializer->getType()->isFunctionType() &&
5541 isExprAnUnaddressableFunction(S, Initializer))
5542 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
5543 else
5544 SetFailed(InitializationSequence::FK_ConversionFailed);
5545 } else {
5546 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5547
5548 MaybeProduceObjCObject(S, *this, Entity);
5549 }
5550}
5551
5552InitializationSequence::~InitializationSequence() {
5553 for (auto &S : Steps)
5554 S.Destroy();
5555}
5556
5557//===----------------------------------------------------------------------===//
5558// Perform initialization
5559//===----------------------------------------------------------------------===//
5560static Sema::AssignmentAction
5561getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5562 switch(Entity.getKind()) {
5563 case InitializedEntity::EK_Variable:
5564 case InitializedEntity::EK_New:
5565 case InitializedEntity::EK_Exception:
5566 case InitializedEntity::EK_Base:
5567 case InitializedEntity::EK_Delegating:
5568 return Sema::AA_Initializing;
5569
5570 case InitializedEntity::EK_Parameter:
5571 if (Entity.getDecl() &&
5572 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5573 return Sema::AA_Sending;
5574
5575 return Sema::AA_Passing;
5576
5577 case InitializedEntity::EK_Parameter_CF_Audited:
5578 if (Entity.getDecl() &&
5579 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5580 return Sema::AA_Sending;
5581
5582 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5583
5584 case InitializedEntity::EK_Result:
5585 return Sema::AA_Returning;
5586
5587 case InitializedEntity::EK_Temporary:
5588 case InitializedEntity::EK_RelatedResult:
5589 // FIXME: Can we tell apart casting vs. converting?
5590 return Sema::AA_Casting;
5591
5592 case InitializedEntity::EK_Member:
5593 case InitializedEntity::EK_Binding:
5594 case InitializedEntity::EK_ArrayElement:
5595 case InitializedEntity::EK_VectorElement:
5596 case InitializedEntity::EK_ComplexElement:
5597 case InitializedEntity::EK_BlockElement:
5598 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5599 case InitializedEntity::EK_LambdaCapture:
5600 case InitializedEntity::EK_CompoundLiteralInit:
5601 return Sema::AA_Initializing;
5602 }
5603
5604 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5604)
;
5605}
5606
5607/// \brief Whether we should bind a created object as a temporary when
5608/// initializing the given entity.
5609static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5610 switch (Entity.getKind()) {
5611 case InitializedEntity::EK_ArrayElement:
5612 case InitializedEntity::EK_Member:
5613 case InitializedEntity::EK_Result:
5614 case InitializedEntity::EK_New:
5615 case InitializedEntity::EK_Variable:
5616 case InitializedEntity::EK_Base:
5617 case InitializedEntity::EK_Delegating:
5618 case InitializedEntity::EK_VectorElement:
5619 case InitializedEntity::EK_ComplexElement:
5620 case InitializedEntity::EK_Exception:
5621 case InitializedEntity::EK_BlockElement:
5622 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5623 case InitializedEntity::EK_LambdaCapture:
5624 case InitializedEntity::EK_CompoundLiteralInit:
5625 return false;
5626
5627 case InitializedEntity::EK_Parameter:
5628 case InitializedEntity::EK_Parameter_CF_Audited:
5629 case InitializedEntity::EK_Temporary:
5630 case InitializedEntity::EK_RelatedResult:
5631 case InitializedEntity::EK_Binding:
5632 return true;
5633 }
5634
5635 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5635)
;
5636}
5637
5638/// \brief Whether the given entity, when initialized with an object
5639/// created for that initialization, requires destruction.
5640static bool shouldDestroyEntity(const InitializedEntity &Entity) {
5641 switch (Entity.getKind()) {
5642 case InitializedEntity::EK_Result:
5643 case InitializedEntity::EK_New:
5644 case InitializedEntity::EK_Base:
5645 case InitializedEntity::EK_Delegating:
5646 case InitializedEntity::EK_VectorElement:
5647 case InitializedEntity::EK_ComplexElement:
5648 case InitializedEntity::EK_BlockElement:
5649 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5650 case InitializedEntity::EK_LambdaCapture:
5651 return false;
5652
5653 case InitializedEntity::EK_Member:
5654 case InitializedEntity::EK_Binding:
5655 case InitializedEntity::EK_Variable:
5656 case InitializedEntity::EK_Parameter:
5657 case InitializedEntity::EK_Parameter_CF_Audited:
5658 case InitializedEntity::EK_Temporary:
5659 case InitializedEntity::EK_ArrayElement:
5660 case InitializedEntity::EK_Exception:
5661 case InitializedEntity::EK_CompoundLiteralInit:
5662 case InitializedEntity::EK_RelatedResult:
5663 return true;
5664 }
5665
5666 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5666)
;
5667}
5668
5669/// \brief Get the location at which initialization diagnostics should appear.
5670static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5671 Expr *Initializer) {
5672 switch (Entity.getKind()) {
5673 case InitializedEntity::EK_Result:
5674 return Entity.getReturnLoc();
5675
5676 case InitializedEntity::EK_Exception:
5677 return Entity.getThrowLoc();
5678
5679 case InitializedEntity::EK_Variable:
5680 case InitializedEntity::EK_Binding:
5681 return Entity.getDecl()->getLocation();
5682
5683 case InitializedEntity::EK_LambdaCapture:
5684 return Entity.getCaptureLoc();
5685
5686 case InitializedEntity::EK_ArrayElement:
5687 case InitializedEntity::EK_Member:
5688 case InitializedEntity::EK_Parameter:
5689 case InitializedEntity::EK_Parameter_CF_Audited:
5690 case InitializedEntity::EK_Temporary:
5691 case InitializedEntity::EK_New:
5692 case InitializedEntity::EK_Base:
5693 case InitializedEntity::EK_Delegating:
5694 case InitializedEntity::EK_VectorElement:
5695 case InitializedEntity::EK_ComplexElement:
5696 case InitializedEntity::EK_BlockElement:
5697 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5698 case InitializedEntity::EK_CompoundLiteralInit:
5699 case InitializedEntity::EK_RelatedResult:
5700 return Initializer->getLocStart();
5701 }
5702 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5702)
;
5703}
5704
5705/// \brief Make a (potentially elidable) temporary copy of the object
5706/// provided by the given initializer by calling the appropriate copy
5707/// constructor.
5708///
5709/// \param S The Sema object used for type-checking.
5710///
5711/// \param T The type of the temporary object, which must either be
5712/// the type of the initializer expression or a superclass thereof.
5713///
5714/// \param Entity The entity being initialized.
5715///
5716/// \param CurInit The initializer expression.
5717///
5718/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5719/// is permitted in C++03 (but not C++0x) when binding a reference to
5720/// an rvalue.
5721///
5722/// \returns An expression that copies the initializer expression into
5723/// a temporary object, or an error expression if a copy could not be
5724/// created.
5725static ExprResult CopyObject(Sema &S,
5726 QualType T,
5727 const InitializedEntity &Entity,
5728 ExprResult CurInit,
5729 bool IsExtraneousCopy) {
5730 if (CurInit.isInvalid())
5731 return CurInit;
5732 // Determine which class type we're copying to.
5733 Expr *CurInitExpr = (Expr *)CurInit.get();
5734 CXXRecordDecl *Class = nullptr;
5735 if (const RecordType *Record = T->getAs<RecordType>())
5736 Class = cast<CXXRecordDecl>(Record->getDecl());
5737 if (!Class)
5738 return CurInit;
5739
5740 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5741
5742 // Make sure that the type we are copying is complete.
5743 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5744 return CurInit;
5745
5746 // Perform overload resolution using the class's constructors. Per
5747 // C++11 [dcl.init]p16, second bullet for class types, this initialization
5748 // is direct-initialization.
5749 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5750 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
5751
5752 OverloadCandidateSet::iterator Best;
5753 switch (ResolveConstructorOverload(
5754 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
5755 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5756 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5757 /*SecondStepOfCopyInit=*/true)) {
5758 case OR_Success:
5759 break;
5760
5761 case OR_No_Viable_Function:
5762 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5763 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5764 : diag::err_temp_copy_no_viable)
5765 << (int)Entity.getKind() << CurInitExpr->getType()
5766 << CurInitExpr->getSourceRange();
5767 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5768 if (!IsExtraneousCopy || S.isSFINAEContext())
5769 return ExprError();
5770 return CurInit;
5771
5772 case OR_Ambiguous:
5773 S.Diag(Loc, diag::err_temp_copy_ambiguous)
5774 << (int)Entity.getKind() << CurInitExpr->getType()
5775 << CurInitExpr->getSourceRange();
5776 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5777 return ExprError();
5778
5779 case OR_Deleted:
5780 S.Diag(Loc, diag::err_temp_copy_deleted)
5781 << (int)Entity.getKind() << CurInitExpr->getType()
5782 << CurInitExpr->getSourceRange();
5783 S.NoteDeletedFunction(Best->Function);
5784 return ExprError();
5785 }
5786
5787 bool HadMultipleCandidates = CandidateSet.size() > 1;
5788
5789 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5790 SmallVector<Expr*, 8> ConstructorArgs;
5791 CurInit.get(); // Ownership transferred into MultiExprArg, below.
5792
5793 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5794 IsExtraneousCopy);
5795
5796 if (IsExtraneousCopy) {
5797 // If this is a totally extraneous copy for C++03 reference
5798 // binding purposes, just return the original initialization
5799 // expression. We don't generate an (elided) copy operation here
5800 // because doing so would require us to pass down a flag to avoid
5801 // infinite recursion, where each step adds another extraneous,
5802 // elidable copy.
5803
5804 // Instantiate the default arguments of any extra parameters in
5805 // the selected copy constructor, as if we were going to create a
5806 // proper call to the copy constructor.
5807 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5808 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5809 if (S.RequireCompleteType(Loc, Parm->getType(),
5810 diag::err_call_incomplete_argument))
5811 break;
5812
5813 // Build the default argument expression; we don't actually care
5814 // if this succeeds or not, because this routine will complain
5815 // if there was a problem.
5816 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5817 }
5818
5819 return CurInitExpr;
5820 }
5821
5822 // Determine the arguments required to actually perform the
5823 // constructor call (we might have derived-to-base conversions, or
5824 // the copy constructor may have default arguments).
5825 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5826 return ExprError();
5827
5828 // C++0x [class.copy]p32:
5829 // When certain criteria are met, an implementation is allowed to
5830 // omit the copy/move construction of a class object, even if the
5831 // copy/move constructor and/or destructor for the object have
5832 // side effects. [...]
5833 // - when a temporary class object that has not been bound to a
5834 // reference (12.2) would be copied/moved to a class object
5835 // with the same cv-unqualified type, the copy/move operation
5836 // can be omitted by constructing the temporary object
5837 // directly into the target of the omitted copy/move
5838 //
5839 // Note that the other three bullets are handled elsewhere. Copy
5840 // elision for return statements and throw expressions are handled as part
5841 // of constructor initialization, while copy elision for exception handlers
5842 // is handled by the run-time.
5843 //
5844 // FIXME: If the function parameter is not the same type as the temporary, we
5845 // should still be able to elide the copy, but we don't have a way to
5846 // represent in the AST how much should be elided in this case.
5847 bool Elidable =
5848 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5849 S.Context.hasSameUnqualifiedType(
5850 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5851 CurInitExpr->getType());
5852
5853 // Actually perform the constructor call.
5854 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5855 Elidable,
5856 ConstructorArgs,
5857 HadMultipleCandidates,
5858 /*ListInit*/ false,
5859 /*StdInitListInit*/ false,
5860 /*ZeroInit*/ false,
5861 CXXConstructExpr::CK_Complete,
5862 SourceRange());
5863
5864 // If we're supposed to bind temporaries, do so.
5865 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5866 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5867 return CurInit;
5868}
5869
5870/// \brief Check whether elidable copy construction for binding a reference to
5871/// a temporary would have succeeded if we were building in C++98 mode, for
5872/// -Wc++98-compat.
5873static void CheckCXX98CompatAccessibleCopy(Sema &S,
5874 const InitializedEntity &Entity,
5875 Expr *CurInitExpr) {
5876 assert(S.getLangOpts().CPlusPlus11)(static_cast <bool> (S.getLangOpts().CPlusPlus11) ? void
(0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5876, __extension__ __PRETTY_FUNCTION__))
;
5877
5878 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5879 if (!Record)
5880 return;
5881
5882 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5883 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5884 return;
5885
5886 // Find constructors which would have been considered.
5887 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5888 DeclContext::lookup_result Ctors =
5889 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
5890
5891 // Perform overload resolution.
5892 OverloadCandidateSet::iterator Best;
5893 OverloadingResult OR = ResolveConstructorOverload(
5894 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
5895 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5896 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5897 /*SecondStepOfCopyInit=*/true);
5898
5899 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5900 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5901 << CurInitExpr->getSourceRange();
5902
5903 switch (OR) {
5904 case OR_Success:
5905 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5906 Best->FoundDecl, Entity, Diag);
5907 // FIXME: Check default arguments as far as that's possible.
5908 break;
5909
5910 case OR_No_Viable_Function:
5911 S.Diag(Loc, Diag);
5912 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5913 break;
5914
5915 case OR_Ambiguous:
5916 S.Diag(Loc, Diag);
5917 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5918 break;
5919
5920 case OR_Deleted:
5921 S.Diag(Loc, Diag);
5922 S.NoteDeletedFunction(Best->Function);
5923 break;
5924 }
5925}
5926
5927void InitializationSequence::PrintInitLocationNote(Sema &S,
5928 const InitializedEntity &Entity) {
5929 if (Entity.isParameterKind() && Entity.getDecl()) {
5930 if (Entity.getDecl()->getLocation().isInvalid())
5931 return;
5932
5933 if (Entity.getDecl()->getDeclName())
5934 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5935 << Entity.getDecl()->getDeclName();
5936 else
5937 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5938 }
5939 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5940 Entity.getMethodDecl())
5941 S.Diag(Entity.getMethodDecl()->getLocation(),
5942 diag::note_method_return_type_change)
5943 << Entity.getMethodDecl()->getDeclName();
5944}
5945
5946/// Returns true if the parameters describe a constructor initialization of
5947/// an explicit temporary object, e.g. "Point(x, y)".
5948static bool isExplicitTemporary(const InitializedEntity &Entity,
5949 const InitializationKind &Kind,
5950 unsigned NumArgs) {
5951 switch (Entity.getKind()) {
5952 case InitializedEntity::EK_Temporary:
5953 case InitializedEntity::EK_CompoundLiteralInit:
5954 case InitializedEntity::EK_RelatedResult:
5955 break;
5956 default:
5957 return false;
5958 }
5959
5960 switch (Kind.getKind()) {
5961 case InitializationKind::IK_DirectList:
5962 return true;
5963 // FIXME: Hack to work around cast weirdness.
5964 case InitializationKind::IK_Direct:
5965 case InitializationKind::IK_Value:
5966 return NumArgs != 1;
5967 default:
5968 return false;
5969 }
5970}
5971
5972static ExprResult
5973PerformConstructorInitialization(Sema &S,
5974 const InitializedEntity &Entity,
5975 const InitializationKind &Kind,
5976 MultiExprArg Args,
5977 const InitializationSequence::Step& Step,
5978 bool &ConstructorInitRequiresZeroInit,
5979 bool IsListInitialization,
5980 bool IsStdInitListInitialization,
5981 SourceLocation LBraceLoc,
5982 SourceLocation RBraceLoc) {
5983 unsigned NumArgs = Args.size();
5984 CXXConstructorDecl *Constructor
5985 = cast<CXXConstructorDecl>(Step.Function.Function);
5986 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5987
5988 // Build a call to the selected constructor.
5989 SmallVector<Expr*, 8> ConstructorArgs;
5990 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5991 ? Kind.getEqualLoc()
5992 : Kind.getLocation();
5993
5994 if (Kind.getKind() == InitializationKind::IK_Default) {
5995 // Force even a trivial, implicit default constructor to be
5996 // semantically checked. We do this explicitly because we don't build
5997 // the definition for completely trivial constructors.
5998 assert(Constructor->getParent() && "No parent class for constructor.")(static_cast <bool> (Constructor->getParent() &&
"No parent class for constructor.") ? void (0) : __assert_fail
("Constructor->getParent() && \"No parent class for constructor.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 5998, __extension__ __PRETTY_FUNCTION__))
;
5999 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6000 Constructor->isTrivial() && !Constructor->isUsed(false))
6001 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6002 }
6003
6004 ExprResult CurInit((Expr *)nullptr);
6005
6006 // C++ [over.match.copy]p1:
6007 // - When initializing a temporary to be bound to the first parameter
6008 // of a constructor that takes a reference to possibly cv-qualified
6009 // T as its first argument, called with a single argument in the
6010 // context of direct-initialization, explicit conversion functions
6011 // are also considered.
6012 bool AllowExplicitConv =
6013 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6014 hasCopyOrMoveCtorParam(S.Context,
6015 getConstructorInfo(Step.Function.FoundDecl));
6016
6017 // Determine the arguments required to actually perform the constructor
6018 // call.
6019 if (S.CompleteConstructorCall(Constructor, Args,
6020 Loc, ConstructorArgs,
6021 AllowExplicitConv,
6022 IsListInitialization))
6023 return ExprError();
6024
6025
6026 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6027 // An explicitly-constructed temporary, e.g., X(1, 2).
6028 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6029 return ExprError();
6030
6031 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6032 if (!TSInfo)
6033 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6034 SourceRange ParenOrBraceRange =
6035 (Kind.getKind() == InitializationKind::IK_DirectList)
6036 ? SourceRange(LBraceLoc, RBraceLoc)
6037 : Kind.getParenRange();
6038
6039 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6040 Step.Function.FoundDecl.getDecl())) {
6041 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
6042 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6043 return ExprError();
6044 }
6045 S.MarkFunctionReferenced(Loc, Constructor);
6046
6047 CurInit = new (S.Context) CXXTemporaryObjectExpr(
6048 S.Context, Constructor,
6049 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6050 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6051 IsListInitialization, IsStdInitListInitialization,
6052 ConstructorInitRequiresZeroInit);
6053 } else {
6054 CXXConstructExpr::ConstructionKind ConstructKind =
6055 CXXConstructExpr::CK_Complete;
6056
6057 if (Entity.getKind() == InitializedEntity::EK_Base) {
6058 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6059 CXXConstructExpr::CK_VirtualBase :
6060 CXXConstructExpr::CK_NonVirtualBase;
6061 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6062 ConstructKind = CXXConstructExpr::CK_Delegating;
6063 }
6064
6065 // Only get the parenthesis or brace range if it is a list initialization or
6066 // direct construction.
6067 SourceRange ParenOrBraceRange;
6068 if (IsListInitialization)
6069 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6070 else if (Kind.getKind() == InitializationKind::IK_Direct)
6071 ParenOrBraceRange = Kind.getParenRange();
6072
6073 // If the entity allows NRVO, mark the construction as elidable
6074 // unconditionally.
6075 if (Entity.allowsNRVO())
6076 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6077 Step.Function.FoundDecl,
6078 Constructor, /*Elidable=*/true,
6079 ConstructorArgs,
6080 HadMultipleCandidates,
6081 IsListInitialization,
6082 IsStdInitListInitialization,
6083 ConstructorInitRequiresZeroInit,
6084 ConstructKind,
6085 ParenOrBraceRange);
6086 else
6087 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6088 Step.Function.FoundDecl,
6089 Constructor,
6090 ConstructorArgs,
6091 HadMultipleCandidates,
6092 IsListInitialization,
6093 IsStdInitListInitialization,
6094 ConstructorInitRequiresZeroInit,
6095 ConstructKind,
6096 ParenOrBraceRange);
6097 }
6098 if (CurInit.isInvalid())
6099 return ExprError();
6100
6101 // Only check access if all of that succeeded.
6102 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
6103 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6104 return ExprError();
6105
6106 if (shouldBindAsTemporary(Entity))
6107 CurInit = S.MaybeBindToTemporary(CurInit.get());
6108
6109 return CurInit;
6110}
6111
6112/// Determine whether the specified InitializedEntity definitely has a lifetime
6113/// longer than the current full-expression. Conservatively returns false if
6114/// it's unclear.
6115static bool
6116InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6117 const InitializedEntity *Top = &Entity;
6118 while (Top->getParent())
6119 Top = Top->getParent();
6120
6121 switch (Top->getKind()) {
6122 case InitializedEntity::EK_Variable:
6123 case InitializedEntity::EK_Result:
6124 case InitializedEntity::EK_Exception:
6125 case InitializedEntity::EK_Member:
6126 case InitializedEntity::EK_Binding:
6127 case InitializedEntity::EK_New:
6128 case InitializedEntity::EK_Base:
6129 case InitializedEntity::EK_Delegating:
6130 return true;
6131
6132 case InitializedEntity::EK_ArrayElement:
6133 case InitializedEntity::EK_VectorElement:
6134 case InitializedEntity::EK_BlockElement:
6135 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6136 case InitializedEntity::EK_ComplexElement:
6137 // Could not determine what the full initialization is. Assume it might not
6138 // outlive the full-expression.
6139 return false;
6140
6141 case InitializedEntity::EK_Parameter:
6142 case InitializedEntity::EK_Parameter_CF_Audited:
6143 case InitializedEntity::EK_Temporary:
6144 case InitializedEntity::EK_LambdaCapture:
6145 case InitializedEntity::EK_CompoundLiteralInit:
6146 case InitializedEntity::EK_RelatedResult:
6147 // The entity being initialized might not outlive the full-expression.
6148 return false;
6149 }
6150
6151 llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6151)
;
6152}
6153
6154/// Determine the declaration which an initialized entity ultimately refers to,
6155/// for the purpose of lifetime-extending a temporary bound to a reference in
6156/// the initialization of \p Entity.
6157static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6158 const InitializedEntity *Entity,
6159 const InitializedEntity *FallbackDecl = nullptr) {
6160 // C++11 [class.temporary]p5:
6161 switch (Entity->getKind()) {
6162 case InitializedEntity::EK_Variable:
6163 // The temporary [...] persists for the lifetime of the reference
6164 return Entity;
6165
6166 case InitializedEntity::EK_Member:
6167 // For subobjects, we look at the complete object.
6168 if (Entity->getParent())
6169 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6170 Entity);
6171
6172 // except:
6173 // -- A temporary bound to a reference member in a constructor's
6174 // ctor-initializer persists until the constructor exits.
6175 return Entity;
6176
6177 case InitializedEntity::EK_Binding:
6178 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6179 // type.
6180 return Entity;
6181
6182 case InitializedEntity::EK_Parameter:
6183 case InitializedEntity::EK_Parameter_CF_Audited:
6184 // -- A temporary bound to a reference parameter in a function call
6185 // persists until the completion of the full-expression containing
6186 // the call.
6187 case InitializedEntity::EK_Result:
6188 // -- The lifetime of a temporary bound to the returned value in a
6189 // function return statement is not extended; the temporary is
6190 // destroyed at the end of the full-expression in the return statement.
6191 case InitializedEntity::EK_New:
6192 // -- A temporary bound to a reference in a new-initializer persists
6193 // until the completion of the full-expression containing the
6194 // new-initializer.
6195 return nullptr;
6196
6197 case InitializedEntity::EK_Temporary:
6198 case InitializedEntity::EK_CompoundLiteralInit:
6199 case InitializedEntity::EK_RelatedResult:
6200 // We don't yet know the storage duration of the surrounding temporary.
6201 // Assume it's got full-expression duration for now, it will patch up our
6202 // storage duration if that's not correct.
6203 return nullptr;
6204
6205 case InitializedEntity::EK_ArrayElement:
6206 // For subobjects, we look at the complete object.
6207 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6208 FallbackDecl);
6209
6210 case InitializedEntity::EK_Base:
6211 // For subobjects, we look at the complete object.
6212 if (Entity->getParent())
6213 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6214 Entity);
6215 // Fall through.
6216 case InitializedEntity::EK_Delegating:
6217 // We can reach this case for aggregate initialization in a constructor:
6218 // struct A { int &&r; };
6219 // struct B : A { B() : A{0} {} };
6220 // In this case, use the innermost field decl as the context.
6221 return FallbackDecl;
6222
6223 case InitializedEntity::EK_BlockElement:
6224 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6225 case InitializedEntity::EK_LambdaCapture:
6226 case InitializedEntity::EK_Exception:
6227 case InitializedEntity::EK_VectorElement:
6228 case InitializedEntity::EK_ComplexElement:
6229 return nullptr;
6230 }
6231 llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6231)
;
6232}
6233
6234static void performLifetimeExtension(Expr *Init,
6235 const InitializedEntity *ExtendingEntity);
6236
6237/// Update a glvalue expression that is used as the initializer of a reference
6238/// to note that its lifetime is extended.
6239/// \return \c true if any temporary had its lifetime extended.
6240static bool
6241performReferenceExtension(Expr *Init,
6242 const InitializedEntity *ExtendingEntity) {
6243 // Walk past any constructs which we can lifetime-extend across.
6244 Expr *Old;
6245 do {
6246 Old = Init;
6247
6248 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6249 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6250 // This is just redundant braces around an initializer. Step over it.
6251 Init = ILE->getInit(0);
6252 }
6253 }
6254
6255 // Step over any subobject adjustments; we may have a materialized
6256 // temporary inside them.
6257 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6258
6259 // Per current approach for DR1376, look through casts to reference type
6260 // when performing lifetime extension.
6261 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6262 if (CE->getSubExpr()->isGLValue())
6263 Init = CE->getSubExpr();
6264
6265 // Per the current approach for DR1299, look through array element access
6266 // when performing lifetime extension.
6267 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6268 Init = ASE->getBase();
6269 } while (Init != Old);
6270
6271 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6272 // Update the storage duration of the materialized temporary.
6273 // FIXME: Rebuild the expression instead of mutating it.
6274 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6275 ExtendingEntity->allocateManglingNumber());
6276 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
6277 return true;
6278 }
6279
6280 return false;
6281}
6282
6283/// Update a prvalue expression that is going to be materialized as a
6284/// lifetime-extended temporary.
6285static void performLifetimeExtension(Expr *Init,
6286 const InitializedEntity *ExtendingEntity) {
6287 // Dig out the expression which constructs the extended temporary.
6288 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6289
6290 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6291 Init = BTE->getSubExpr();
6292
6293 if (CXXStdInitializerListExpr *ILE =
6294 dyn_cast<CXXStdInitializerListExpr>(Init)) {
6295 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
6296 return;
6297 }
6298
6299 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6300 if (ILE->getType()->isArrayType()) {
6301 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
6302 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
6303 return;
6304 }
6305
6306 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
6307 assert(RD->isAggregate() && "aggregate init on non-aggregate")(static_cast <bool> (RD->isAggregate() && "aggregate init on non-aggregate"
) ? void (0) : __assert_fail ("RD->isAggregate() && \"aggregate init on non-aggregate\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6307, __extension__ __PRETTY_FUNCTION__))
;
6308
6309 // If we lifetime-extend a braced initializer which is initializing an
6310 // aggregate, and that aggregate contains reference members which are
6311 // bound to temporaries, those temporaries are also lifetime-extended.
6312 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6313 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
6314 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
6315 else {
6316 unsigned Index = 0;
6317 for (const auto *I : RD->fields()) {
6318 if (Index >= ILE->getNumInits())
6319 break;
6320 if (I->isUnnamedBitfield())
6321 continue;
6322 Expr *SubInit = ILE->getInit(Index);
6323 if (I->getType()->isReferenceType())
6324 performReferenceExtension(SubInit, ExtendingEntity);
6325 else if (isa<InitListExpr>(SubInit) ||
6326 isa<CXXStdInitializerListExpr>(SubInit))
6327 // This may be either aggregate-initialization of a member or
6328 // initialization of a std::initializer_list object. Either way,
6329 // we should recursively lifetime-extend that initializer.
6330 performLifetimeExtension(SubInit, ExtendingEntity);
6331 ++Index;
6332 }
6333 }
6334 }
6335 }
6336}
6337
6338static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6339 const Expr *Init, bool IsInitializerList,
6340 const ValueDecl *ExtendingDecl) {
6341 // Warn if a field lifetime-extends a temporary.
6342 if (isa<FieldDecl>(ExtendingDecl)) {
6343 if (IsInitializerList) {
6344 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6345 << /*at end of constructor*/true;
6346 return;
6347 }
6348
6349 bool IsSubobjectMember = false;
6350 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6351 Ent = Ent->getParent()) {
6352 if (Ent->getKind() != InitializedEntity::EK_Base) {
6353 IsSubobjectMember = true;
6354 break;
6355 }
6356 }
6357 S.Diag(Init->getExprLoc(),
6358 diag::warn_bind_ref_member_to_temporary)
6359 << ExtendingDecl << Init->getSourceRange()
6360 << IsSubobjectMember << IsInitializerList;
6361 if (IsSubobjectMember)
6362 S.Diag(ExtendingDecl->getLocation(),
6363 diag::note_ref_subobject_of_member_declared_here);
6364 else
6365 S.Diag(ExtendingDecl->getLocation(),
6366 diag::note_ref_or_ptr_member_declared_here)
6367 << /*is pointer*/false;
6368 }
6369}
6370
6371static void DiagnoseNarrowingInInitList(Sema &S,
6372 const ImplicitConversionSequence &ICS,
6373 QualType PreNarrowingType,
6374 QualType EntityType,
6375 const Expr *PostInit);
6376
6377/// Provide warnings when std::move is used on construction.
6378static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6379 bool IsReturnStmt) {
6380 if (!InitExpr)
6381 return;
6382
6383 if (S.inTemplateInstantiation())
6384 return;
6385
6386 QualType DestType = InitExpr->getType();
6387 if (!DestType->isRecordType())
6388 return;
6389
6390 unsigned DiagID = 0;
6391 if (IsReturnStmt) {
6392 const CXXConstructExpr *CCE =
6393 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6394 if (!CCE || CCE->getNumArgs() != 1)
6395 return;
6396
6397 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6398 return;
6399
6400 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
6401 }
6402
6403 // Find the std::move call and get the argument.
6404 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6405 if (!CE || CE->getNumArgs() != 1)
6406 return;
6407
6408 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6409 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6410 !MoveFunction->getIdentifier() ||
6411 !MoveFunction->getIdentifier()->isStr("move"))
6412 return;
6413
6414 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6415
6416 if (IsReturnStmt) {
6417 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6418 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6419 return;
6420
6421 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6422 if (!VD || !VD->hasLocalStorage())
6423 return;
6424
6425 // __block variables are not moved implicitly.
6426 if (VD->hasAttr<BlocksAttr>())
6427 return;
6428
6429 QualType SourceType = VD->getType();
6430 if (!SourceType->isRecordType())
6431 return;
6432
6433 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
6434 return;
6435 }
6436
6437 // If we're returning a function parameter, copy elision
6438 // is not possible.
6439 if (isa<ParmVarDecl>(VD))
6440 DiagID = diag::warn_redundant_move_on_return;
6441 else
6442 DiagID = diag::warn_pessimizing_move_on_return;
6443 } else {
6444 DiagID = diag::warn_pessimizing_move_on_initialization;
6445 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6446 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6447 return;
6448 }
6449
6450 S.Diag(CE->getLocStart(), DiagID);
6451
6452 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6453 // is within a macro.
6454 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6455 if (CallBegin.isMacroID())
6456 return;
6457 SourceLocation RParen = CE->getRParenLoc();
6458 if (RParen.isMacroID())
6459 return;
6460 SourceLocation LParen;
6461 SourceLocation ArgLoc = Arg->getLocStart();
6462
6463 // Special testing for the argument location. Since the fix-it needs the
6464 // location right before the argument, the argument location can be in a
6465 // macro only if it is at the beginning of the macro.
6466 while (ArgLoc.isMacroID() &&
6467 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6468 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6469 }
6470
6471 if (LParen.isMacroID())
6472 return;
6473
6474 LParen = ArgLoc.getLocWithOffset(-1);
6475
6476 S.Diag(CE->getLocStart(), diag::note_remove_move)
6477 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6478 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6479}
6480
6481static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6482 // Check to see if we are dereferencing a null pointer. If so, this is
6483 // undefined behavior, so warn about it. This only handles the pattern
6484 // "*null", which is a very syntactic check.
6485 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6486 if (UO->getOpcode() == UO_Deref &&
6487 UO->getSubExpr()->IgnoreParenCasts()->
6488 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6489 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6490 S.PDiag(diag::warn_binding_null_to_reference)
6491 << UO->getSubExpr()->getSourceRange());
6492 }
6493}
6494
6495MaterializeTemporaryExpr *
6496Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6497 bool BoundToLvalueReference) {
6498 auto MTE = new (Context)
6499 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6500
6501 // Order an ExprWithCleanups for lifetime marks.
6502 //
6503 // TODO: It'll be good to have a single place to check the access of the
6504 // destructor and generate ExprWithCleanups for various uses. Currently these
6505 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6506 // but there may be a chance to merge them.
6507 Cleanup.setExprNeedsCleanups(false);
6508 return MTE;
6509}
6510
6511ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6512 // In C++98, we don't want to implicitly create an xvalue.
6513 // FIXME: This means that AST consumers need to deal with "prvalues" that
6514 // denote materialized temporaries. Maybe we should add another ValueKind
6515 // for "xvalue pretending to be a prvalue" for C++98 support.
6516 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6517 return E;
6518
6519 // C++1z [conv.rval]/1: T shall be a complete type.
6520 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6521 // If so, we should check for a non-abstract class type here too.
6522 QualType T = E->getType();
6523 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6524 return ExprError();
6525
6526 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6527}
6528
6529ExprResult
6530InitializationSequence::Perform(Sema &S,
6531 const InitializedEntity &Entity,
6532 const InitializationKind &Kind,
6533 MultiExprArg Args,
6534 QualType *ResultType) {
6535 if (Failed()) {
6536 Diagnose(S, Entity, Kind, Args);
6537 return ExprError();
6538 }
6539 if (!ZeroInitializationFixit.empty()) {
6540 unsigned DiagID = diag::err_default_init_const;
6541 if (Decl *D = Entity.getDecl())
6542 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6543 DiagID = diag::ext_default_init_const;
6544
6545 // The initialization would have succeeded with this fixit. Since the fixit
6546 // is on the error, we need to build a valid AST in this case, so this isn't
6547 // handled in the Failed() branch above.
6548 QualType DestType = Entity.getType();
6549 S.Diag(Kind.getLocation(), DiagID)
6550 << DestType << (bool)DestType->getAs<RecordType>()
6551 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6552 ZeroInitializationFixit);
6553 }
6554
6555 if (getKind() == DependentSequence) {
6556 // If the declaration is a non-dependent, incomplete array type
6557 // that has an initializer, then its type will be completed once
6558 // the initializer is instantiated.
6559 if (ResultType && !Entity.getType()->isDependentType() &&
6560 Args.size() == 1) {
6561 QualType DeclType = Entity.getType();
6562 if (const IncompleteArrayType *ArrayT
6563 = S.Context.getAsIncompleteArrayType(DeclType)) {
6564 // FIXME: We don't currently have the ability to accurately
6565 // compute the length of an initializer list without
6566 // performing full type-checking of the initializer list
6567 // (since we have to determine where braces are implicitly
6568 // introduced and such). So, we fall back to making the array
6569 // type a dependently-sized array type with no specified
6570 // bound.
6571 if (isa<InitListExpr>((Expr *)Args[0])) {
6572 SourceRange Brackets;
6573
6574 // Scavange the location of the brackets from the entity, if we can.
6575 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
6576 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6577 TypeLoc TL = TInfo->getTypeLoc();
6578 if (IncompleteArrayTypeLoc ArrayLoc =
6579 TL.getAs<IncompleteArrayTypeLoc>())
6580 Brackets = ArrayLoc.getBracketsRange();
6581 }
6582 }
6583
6584 *ResultType
6585 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
6586 /*NumElts=*/nullptr,
6587 ArrayT->getSizeModifier(),
6588 ArrayT->getIndexTypeCVRQualifiers(),
6589 Brackets);
6590 }
6591
6592 }
6593 }
6594 if (Kind.getKind() == InitializationKind::IK_Direct &&
6595 !Kind.isExplicitCast()) {
6596 // Rebuild the ParenListExpr.
6597 SourceRange ParenRange = Kind.getParenRange();
6598 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
6599 Args);
6600 }
6601 assert(Kind.getKind() == InitializationKind::IK_Copy ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6603, __extension__ __PRETTY_FUNCTION__))
6602 Kind.isExplicitCast() ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6603, __extension__ __PRETTY_FUNCTION__))
6603 Kind.getKind() == InitializationKind::IK_DirectList)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6603, __extension__ __PRETTY_FUNCTION__))
;
6604 return ExprResult(Args[0]);
6605 }
6606
6607 // No steps means no initialization.
6608 if (Steps.empty())
6609 return ExprResult((Expr *)nullptr);
6610
6611 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
6612 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
6613 !Entity.isParameterKind()) {
6614 // Produce a C++98 compatibility warning if we are initializing a reference
6615 // from an initializer list. For parameters, we produce a better warning
6616 // elsewhere.
6617 Expr *Init = Args[0];
6618 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6619 << Init->getSourceRange();
6620 }
6621
6622 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6623 QualType ETy = Entity.getType();
6624 Qualifiers TyQualifiers = ETy.getQualifiers();
6625 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6626 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6627
6628 if (S.getLangOpts().OpenCLVersion >= 200 &&
6629 ETy->isAtomicType() && !HasGlobalAS &&
6630 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6631 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6632 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6633 return ExprError();
6634 }
6635
6636 // Diagnose cases where we initialize a pointer to an array temporary, and the
6637 // pointer obviously outlives the temporary.
6638 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
6639 Entity.getType()->isPointerType() &&
6640 InitializedEntityOutlivesFullExpression(Entity)) {
6641 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6642 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6643 Init = MTE->GetTemporaryExpr();
6644 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6645 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6646 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6647 << Init->getSourceRange();
6648 }
6649
6650 QualType DestType = Entity.getType().getNonReferenceType();
6651 // FIXME: Ugly hack around the fact that Entity.getType() is not
6652 // the same as Entity.getDecl()->getType() in cases involving type merging,
6653 // and we want latter when it makes sense.
6654 if (ResultType)
6655 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
6656 Entity.getType();
6657
6658 ExprResult CurInit((Expr *)nullptr);
6659 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
6660
6661 // For initialization steps that start with a single initializer,
6662 // grab the only argument out the Args and place it into the "current"
6663 // initializer.
6664 switch (Steps.front().Kind) {
6665 case SK_ResolveAddressOfOverloadedFunction:
6666 case SK_CastDerivedToBaseRValue:
6667 case SK_CastDerivedToBaseXValue:
6668 case SK_CastDerivedToBaseLValue:
6669 case SK_BindReference:
6670 case SK_BindReferenceToTemporary:
6671 case SK_FinalCopy:
6672 case SK_ExtraneousCopyToTemporary:
6673 case SK_UserConversion:
6674 case SK_QualificationConversionLValue:
6675 case SK_QualificationConversionXValue:
6676 case SK_QualificationConversionRValue:
6677 case SK_AtomicConversion:
6678 case SK_LValueToRValue:
6679 case SK_ConversionSequence:
6680 case SK_ConversionSequenceNoNarrowing:
6681 case SK_ListInitialization:
6682 case SK_UnwrapInitList:
6683 case SK_RewrapInitList:
6684 case SK_CAssignment:
6685 case SK_StringInit:
6686 case SK_ObjCObjectConversion:
6687 case SK_ArrayLoopIndex:
6688 case SK_ArrayLoopInit:
6689 case SK_ArrayInit:
6690 case SK_GNUArrayInit:
6691 case SK_ParenthesizedArrayInit:
6692 case SK_PassByIndirectCopyRestore:
6693 case SK_PassByIndirectRestore:
6694 case SK_ProduceObjCObject:
6695 case SK_StdInitializerList:
6696 case SK_OCLSamplerInit:
6697 case SK_OCLZeroEvent:
6698 case SK_OCLZeroQueue: {
6699 assert(Args.size() == 1)(static_cast <bool> (Args.size() == 1) ? void (0) : __assert_fail
("Args.size() == 1", "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6699, __extension__ __PRETTY_FUNCTION__))
;
6700 CurInit = Args[0];
6701 if (!CurInit.get()) return ExprError();
6702 break;
6703 }
6704
6705 case SK_ConstructorInitialization:
6706 case SK_ConstructorInitializationFromList:
6707 case SK_StdInitializerListConstructorCall:
6708 case SK_ZeroInitialization:
6709 break;
6710 }
6711
6712 // Promote from an unevaluated context to an unevaluated list context in
6713 // C++11 list-initialization; we need to instantiate entities usable in
6714 // constant expressions here in order to perform narrowing checks =(
6715 EnterExpressionEvaluationContext Evaluated(
6716 S, EnterExpressionEvaluationContext::InitList,
6717 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6718
6719 // C++ [class.abstract]p2:
6720 // no objects of an abstract class can be created except as subobjects
6721 // of a class derived from it
6722 auto checkAbstractType = [&](QualType T) -> bool {
6723 if (Entity.getKind() == InitializedEntity::EK_Base ||
6724 Entity.getKind() == InitializedEntity::EK_Delegating)
6725 return false;
6726 return S.RequireNonAbstractType(Kind.getLocation(), T,
6727 diag::err_allocation_of_abstract_type);
6728 };
6729
6730 // Walk through the computed steps for the initialization sequence,
6731 // performing the specified conversions along the way.
6732 bool ConstructorInitRequiresZeroInit = false;
6733 for (step_iterator Step = step_begin(), StepEnd = step_end();
6734 Step != StepEnd; ++Step) {
6735 if (CurInit.isInvalid())
6736 return ExprError();
6737
6738 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
6739
6740 switch (Step->Kind) {
6741 case SK_ResolveAddressOfOverloadedFunction:
6742 // Overload resolution determined which function invoke; update the
6743 // initializer to reflect that choice.
6744 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
6745 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6746 return ExprError();
6747 CurInit = S.FixOverloadedFunctionReference(CurInit,
6748 Step->Function.FoundDecl,
6749 Step->Function.Function);
6750 break;
6751
6752 case SK_CastDerivedToBaseRValue:
6753 case SK_CastDerivedToBaseXValue:
6754 case SK_CastDerivedToBaseLValue: {
6755 // We have a derived-to-base cast that produces either an rvalue or an
6756 // lvalue. Perform that cast.
6757
6758 CXXCastPath BasePath;
6759
6760 // Casts to inaccessible base classes are allowed with C-style casts.
6761 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6762 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
6763 CurInit.get()->getLocStart(),
6764 CurInit.get()->getSourceRange(),
6765 &BasePath, IgnoreBaseAccess))
6766 return ExprError();
6767
6768 ExprValueKind VK =
6769 Step->Kind == SK_CastDerivedToBaseLValue ?
6770 VK_LValue :
6771 (Step->Kind == SK_CastDerivedToBaseXValue ?
6772 VK_XValue :
6773 VK_RValue);
6774 CurInit =
6775 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6776 CurInit.get(), &BasePath, VK);
6777 break;
6778 }
6779
6780 case SK_BindReference:
6781 // Reference binding does not have any corresponding ASTs.
6782
6783 // Check exception specifications
6784 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6785 return ExprError();
6786
6787 // We don't check for e.g. function pointers here, since address
6788 // availability checks should only occur when the function first decays
6789 // into a pointer or reference.
6790 if (CurInit.get()->getType()->isFunctionProtoType()) {
6791 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6792 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6793 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6794 DRE->getLocStart()))
6795 return ExprError();
6796 }
6797 }
6798 }
6799
6800 // Even though we didn't materialize a temporary, the binding may still
6801 // extend the lifetime of a temporary. This happens if we bind a reference
6802 // to the result of a cast to reference type.
6803 if (const InitializedEntity *ExtendingEntity =
6804 getEntityForTemporaryLifetimeExtension(&Entity))
6805 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6806 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6807 /*IsInitializerList=*/false,
6808 ExtendingEntity->getDecl());
6809
6810 CheckForNullPointerDereference(S, CurInit.get());
6811 break;
6812
6813 case SK_BindReferenceToTemporary: {
6814 // Make sure the "temporary" is actually an rvalue.
6815 assert(CurInit.get()->isRValue() && "not a temporary")(static_cast <bool> (CurInit.get()->isRValue() &&
"not a temporary") ? void (0) : __assert_fail ("CurInit.get()->isRValue() && \"not a temporary\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6815, __extension__ __PRETTY_FUNCTION__))
;
6816
6817 // Check exception specifications
6818 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6819 return ExprError();
6820
6821 // Materialize the temporary into memory.
6822 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
6823 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
6824
6825 // Maybe lifetime-extend the temporary's subobjects to match the
6826 // entity's lifetime.
6827 if (const InitializedEntity *ExtendingEntity =
6828 getEntityForTemporaryLifetimeExtension(&Entity))
6829 if (performReferenceExtension(MTE, ExtendingEntity))
6830 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6831 /*IsInitializerList=*/false,
6832 ExtendingEntity->getDecl());
6833
6834 // If we're extending this temporary to automatic storage duration -- we
6835 // need to register its cleanup during the full-expression's cleanups.
6836 if (MTE->getStorageDuration() == SD_Automatic &&
6837 MTE->getType().isDestructedType())
6838 S.Cleanup.setExprNeedsCleanups(true);
6839
6840 CurInit = MTE;
6841 break;
6842 }
6843
6844 case SK_FinalCopy:
6845 if (checkAbstractType(Step->Type))
6846 return ExprError();
6847
6848 // If the overall initialization is initializing a temporary, we already
6849 // bound our argument if it was necessary to do so. If not (if we're
6850 // ultimately initializing a non-temporary), our argument needs to be
6851 // bound since it's initializing a function parameter.
6852 // FIXME: This is a mess. Rationalize temporary destruction.
6853 if (!shouldBindAsTemporary(Entity))
6854 CurInit = S.MaybeBindToTemporary(CurInit.get());
6855 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6856 /*IsExtraneousCopy=*/false);
6857 break;
6858
6859 case SK_ExtraneousCopyToTemporary:
6860 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6861 /*IsExtraneousCopy=*/true);
6862 break;
6863
6864 case SK_UserConversion: {
6865 // We have a user-defined conversion that invokes either a constructor
6866 // or a conversion function.
6867 CastKind CastKind;
6868 FunctionDecl *Fn = Step->Function.Function;
6869 DeclAccessPair FoundFn = Step->Function.FoundDecl;
6870 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
6871 bool CreatedObject = false;
6872 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
6873 // Build a call to the selected constructor.
6874 SmallVector<Expr*, 8> ConstructorArgs;
6875 SourceLocation Loc = CurInit.get()->getLocStart();
6876
6877 // Determine the arguments required to actually perform the constructor
6878 // call.
6879 Expr *Arg = CurInit.get();
6880 if (S.CompleteConstructorCall(Constructor,
6881 MultiExprArg(&Arg, 1),
6882 Loc, ConstructorArgs))
6883 return ExprError();
6884
6885 // Build an expression that constructs a temporary.
6886 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6887 FoundFn, Constructor,
6888 ConstructorArgs,
6889 HadMultipleCandidates,
6890 /*ListInit*/ false,
6891 /*StdInitListInit*/ false,
6892 /*ZeroInit*/ false,
6893 CXXConstructExpr::CK_Complete,
6894 SourceRange());
6895 if (CurInit.isInvalid())
6896 return ExprError();
6897
6898 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6899 Entity);
6900 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6901 return ExprError();
6902
6903 CastKind = CK_ConstructorConversion;
6904 CreatedObject = true;
6905 } else {
6906 // Build a call to the conversion function.
6907 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
6908 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
6909 FoundFn);
6910 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6911 return ExprError();
6912
6913 // FIXME: Should we move this initialization into a separate
6914 // derived-to-base conversion? I believe the answer is "no", because
6915 // we don't want to turn off access control here for c-style casts.
6916 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6917 /*Qualifier=*/nullptr,
6918 FoundFn, Conversion);
6919 if (CurInit.isInvalid())
6920 return ExprError();
6921
6922 // Build the actual call to the conversion function.
6923 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6924 HadMultipleCandidates);
6925 if (CurInit.isInvalid())
6926 return ExprError();
6927
6928 CastKind = CK_UserDefinedConversion;
6929 CreatedObject = Conversion->getReturnType()->isRecordType();
6930 }
6931
6932 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6933 return ExprError();
6934
6935 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6936 CastKind, CurInit.get(), nullptr,
6937 CurInit.get()->getValueKind());
6938
6939 if (shouldBindAsTemporary(Entity))
6940 // The overall entity is temporary, so this expression should be
6941 // destroyed at the end of its full-expression.
6942 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6943 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6944 // The object outlasts the full-expression, but we need to prepare for
6945 // a destructor being run on it.
6946 // FIXME: It makes no sense to do this here. This should happen
6947 // regardless of how we initialized the entity.
6948 QualType T = CurInit.get()->getType();
6949 if (const RecordType *Record = T->getAs<RecordType>()) {
6950 CXXDestructorDecl *Destructor
6951 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
6952 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
6953 S.PDiag(diag::err_access_dtor_temp) << T);
6954 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
6955 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6956 return ExprError();
6957 }
6958 }
6959 break;
6960 }
6961
6962 case SK_QualificationConversionLValue:
6963 case SK_QualificationConversionXValue:
6964 case SK_QualificationConversionRValue: {
6965 // Perform a qualification conversion; these can never go wrong.
6966 ExprValueKind VK =
6967 Step->Kind == SK_QualificationConversionLValue ?
6968 VK_LValue :
6969 (Step->Kind == SK_QualificationConversionXValue ?
6970 VK_XValue :
6971 VK_RValue);
6972 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
6973 break;
6974 }
6975
6976 case SK_AtomicConversion: {
6977 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic")(static_cast <bool> (CurInit.get()->isRValue() &&
"cannot convert glvalue to atomic") ? void (0) : __assert_fail
("CurInit.get()->isRValue() && \"cannot convert glvalue to atomic\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6977, __extension__ __PRETTY_FUNCTION__))
;
6978 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6979 CK_NonAtomicToAtomic, VK_RValue);
6980 break;
6981 }
6982
6983 case SK_LValueToRValue: {
6984 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue")(static_cast <bool> (CurInit.get()->isGLValue() &&
"cannot load from a prvalue") ? void (0) : __assert_fail ("CurInit.get()->isGLValue() && \"cannot load from a prvalue\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 6984, __extension__ __PRETTY_FUNCTION__))
;
6985 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6986 CK_LValueToRValue, CurInit.get(),
6987 /*BasePath=*/nullptr, VK_RValue);
6988 break;
6989 }
6990
6991 case SK_ConversionSequence:
6992 case SK_ConversionSequenceNoNarrowing: {
6993 Sema::CheckedConversionKind CCK
6994 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6995 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
6996 : Kind.isExplicitCast()? Sema::CCK_OtherCast
6997 : Sema::CCK_ImplicitConversion;
6998 ExprResult CurInitExprRes =
6999 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
7000 getAssignmentAction(Entity), CCK);
7001 if (CurInitExprRes.isInvalid())
7002 return ExprError();
7003
7004 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7005
7006 CurInit = CurInitExprRes;
7007
7008 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
7009 S.getLangOpts().CPlusPlus)
7010 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7011 CurInit.get());
7012
7013 break;
7014 }
7015
7016 case SK_ListInitialization: {
7017 if (checkAbstractType(Step->Type))
7018 return ExprError();
7019
7020 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
7021 // If we're not initializing the top-level entity, we need to create an
7022 // InitializeTemporary entity for our target type.
7023 QualType Ty = Step->Type;
7024 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
7025 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
7026 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7027 InitListChecker PerformInitList(S, InitEntity,
7028 InitList, Ty, /*VerifyOnly=*/false,
7029 /*TreatUnavailableAsInvalid=*/false);
7030 if (PerformInitList.HadError())
7031 return ExprError();
7032
7033 // Hack: We must update *ResultType if available in order to set the
7034 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7035 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7036 if (ResultType &&
7037 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
7038 if ((*ResultType)->isRValueReferenceType())
7039 Ty = S.Context.getRValueReferenceType(Ty);
7040 else if ((*ResultType)->isLValueReferenceType())
7041 Ty = S.Context.getLValueReferenceType(Ty,
7042 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7043 *ResultType = Ty;
7044 }
7045
7046 InitListExpr *StructuredInitList =
7047 PerformInitList.getFullyStructuredList();
7048 CurInit.get();
7049 CurInit = shouldBindAsTemporary(InitEntity)
7050 ? S.MaybeBindToTemporary(StructuredInitList)
7051 : StructuredInitList;
7052 break;
7053 }
7054
7055 case SK_ConstructorInitializationFromList: {
7056 if (checkAbstractType(Step->Type))
7057 return ExprError();
7058
7059 // When an initializer list is passed for a parameter of type "reference
7060 // to object", we don't get an EK_Temporary entity, but instead an
7061 // EK_Parameter entity with reference type.
7062 // FIXME: This is a hack. What we really should do is create a user
7063 // conversion step for this case, but this makes it considerably more
7064 // complicated. For now, this will do.
7065 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7066 Entity.getType().getNonReferenceType());
7067 bool UseTemporary = Entity.getType()->isReferenceType();
7068 assert(Args.size() == 1 && "expected a single argument for list init")(static_cast <bool> (Args.size() == 1 && "expected a single argument for list init"
) ? void (0) : __assert_fail ("Args.size() == 1 && \"expected a single argument for list init\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7068, __extension__ __PRETTY_FUNCTION__))
;
7069 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7070 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7071 << InitList->getSourceRange();
7072 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
7073 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7074 Entity,
7075 Kind, Arg, *Step,
7076 ConstructorInitRequiresZeroInit,
7077 /*IsListInitialization*/true,
7078 /*IsStdInitListInit*/false,
7079 InitList->getLBraceLoc(),
7080 InitList->getRBraceLoc());
7081 break;
7082 }
7083
7084 case SK_UnwrapInitList:
7085 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
7086 break;
7087
7088 case SK_RewrapInitList: {
7089 Expr *E = CurInit.get();
7090 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7091 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
7092 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
7093 ILE->setSyntacticForm(Syntactic);
7094 ILE->setType(E->getType());
7095 ILE->setValueKind(E->getValueKind());
7096 CurInit = ILE;
7097 break;
7098 }
7099
7100 case SK_ConstructorInitialization:
7101 case SK_StdInitializerListConstructorCall: {
7102 if (checkAbstractType(Step->Type))
7103 return ExprError();
7104
7105 // When an initializer list is passed for a parameter of type "reference
7106 // to object", we don't get an EK_Temporary entity, but instead an
7107 // EK_Parameter entity with reference type.
7108 // FIXME: This is a hack. What we really should do is create a user
7109 // conversion step for this case, but this makes it considerably more
7110 // complicated. For now, this will do.
7111 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7112 Entity.getType().getNonReferenceType());
7113 bool UseTemporary = Entity.getType()->isReferenceType();
7114 bool IsStdInitListInit =
7115 Step->Kind == SK_StdInitializerListConstructorCall;
7116 Expr *Source = CurInit.get();
7117 CurInit = PerformConstructorInitialization(
7118 S, UseTemporary ? TempEntity : Entity, Kind,
7119 Source ? MultiExprArg(Source) : Args, *Step,
7120 ConstructorInitRequiresZeroInit,
7121 /*IsListInitialization*/ IsStdInitListInit,
7122 /*IsStdInitListInitialization*/ IsStdInitListInit,
7123 /*LBraceLoc*/ SourceLocation(),
7124 /*RBraceLoc*/ SourceLocation());
7125 break;
7126 }
7127
7128 case SK_ZeroInitialization: {
7129 step_iterator NextStep = Step;
7130 ++NextStep;
7131 if (NextStep != StepEnd &&
7132 (NextStep->Kind == SK_ConstructorInitialization ||
7133 NextStep->Kind == SK_ConstructorInitializationFromList)) {
7134 // The need for zero-initialization is recorded directly into
7135 // the call to the object's constructor within the next step.
7136 ConstructorInitRequiresZeroInit = true;
7137 } else if (Kind.getKind() == InitializationKind::IK_Value &&
7138 S.getLangOpts().CPlusPlus &&
7139 !Kind.isImplicitValueInit()) {
7140 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7141 if (!TSInfo)
7142 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
7143 Kind.getRange().getBegin());
7144
7145 CurInit = new (S.Context) CXXScalarValueInitExpr(
7146 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7147 Kind.getRange().getEnd());
7148 } else {
7149 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
7150 }
7151 break;
7152 }
7153
7154 case SK_CAssignment: {
7155 QualType SourceType = CurInit.get()->getType();
7156 // Save off the initial CurInit in case we need to emit a diagnostic
7157 ExprResult InitialCurInit = CurInit;
7158 ExprResult Result = CurInit;
7159 Sema::AssignConvertType ConvTy =
7160 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7161 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
7162 if (Result.isInvalid())
7163 return ExprError();
7164 CurInit = Result;
7165
7166 // If this is a call, allow conversion to a transparent union.
7167 ExprResult CurInitExprRes = CurInit;
7168 if (ConvTy != Sema::Compatible &&
7169 Entity.isParameterKind() &&
7170 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
7171 == Sema::Compatible)
7172 ConvTy = Sema::Compatible;
7173 if (CurInitExprRes.isInvalid())
7174 return ExprError();
7175 CurInit = CurInitExprRes;
7176
7177 bool Complained;
7178 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7179 Step->Type, SourceType,
7180 InitialCurInit.get(),
7181 getAssignmentAction(Entity, true),
7182 &Complained)) {
7183 PrintInitLocationNote(S, Entity);
7184 return ExprError();
7185 } else if (Complained)
7186 PrintInitLocationNote(S, Entity);
7187 break;
7188 }
7189
7190 case SK_StringInit: {
7191 QualType Ty = Step->Type;
7192 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
7193 S.Context.getAsArrayType(Ty), S);
7194 break;
7195 }
7196
7197 case SK_ObjCObjectConversion:
7198 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7199 CK_ObjCObjectLValueCast,
7200 CurInit.get()->getValueKind());
7201 break;
7202
7203 case SK_ArrayLoopIndex: {
7204 Expr *Cur = CurInit.get();
7205 Expr *BaseExpr = new (S.Context)
7206 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7207 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7208 Expr *IndexExpr =
7209 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7210 CurInit = S.CreateBuiltinArraySubscriptExpr(
7211 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7212 ArrayLoopCommonExprs.push_back(BaseExpr);
7213 break;
7214 }
7215
7216 case SK_ArrayLoopInit: {
7217 assert(!ArrayLoopCommonExprs.empty() &&(static_cast <bool> (!ArrayLoopCommonExprs.empty() &&
"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void (
0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7218, __extension__ __PRETTY_FUNCTION__))
7218 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit")(static_cast <bool> (!ArrayLoopCommonExprs.empty() &&
"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void (
0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7218, __extension__ __PRETTY_FUNCTION__))
;
7219 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7220 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7221 CurInit.get());
7222 break;
7223 }
7224
7225 case SK_GNUArrayInit:
7226 // Okay: we checked everything before creating this step. Note that
7227 // this is a GNU extension.
7228 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
7229 << Step->Type << CurInit.get()->getType()
7230 << CurInit.get()->getSourceRange();
7231 LLVM_FALLTHROUGH[[clang::fallthrough]];
7232 case SK_ArrayInit:
7233 // If the destination type is an incomplete array type, update the
7234 // type accordingly.
7235 if (ResultType) {
7236 if (const IncompleteArrayType *IncompleteDest
7237 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7238 if (const ConstantArrayType *ConstantSource
7239 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
7240 *ResultType = S.Context.getConstantArrayType(
7241 IncompleteDest->getElementType(),
7242 ConstantSource->getSize(),
7243 ArrayType::Normal, 0);
7244 }
7245 }
7246 }
7247 break;
7248
7249 case SK_ParenthesizedArrayInit:
7250 // Okay: we checked everything before creating this step. Note that
7251 // this is a GNU extension.
7252 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7253 << CurInit.get()->getSourceRange();
7254 break;
7255
7256 case SK_PassByIndirectCopyRestore:
7257 case SK_PassByIndirectRestore:
7258 checkIndirectCopyRestoreSource(S, CurInit.get());
7259 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7260 CurInit.get(), Step->Type,
7261 Step->Kind == SK_PassByIndirectCopyRestore);
7262 break;
7263
7264 case SK_ProduceObjCObject:
7265 CurInit =
7266 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7267 CurInit.get(), nullptr, VK_RValue);
7268 break;
7269
7270 case SK_StdInitializerList: {
7271 S.Diag(CurInit.get()->getExprLoc(),
7272 diag::warn_cxx98_compat_initializer_list_init)
7273 << CurInit.get()->getSourceRange();
7274
7275 // Materialize the temporary into memory.
7276 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7277 CurInit.get()->getType(), CurInit.get(),
7278 /*BoundToLvalueReference=*/false);
7279
7280 // Maybe lifetime-extend the array temporary's subobjects to match the
7281 // entity's lifetime.
7282 if (const InitializedEntity *ExtendingEntity =
7283 getEntityForTemporaryLifetimeExtension(&Entity))
7284 if (performReferenceExtension(MTE, ExtendingEntity))
7285 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7286 /*IsInitializerList=*/true,
7287 ExtendingEntity->getDecl());
7288
7289 // Wrap it in a construction of a std::initializer_list<T>.
7290 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
7291
7292 // Bind the result, in case the library has given initializer_list a
7293 // non-trivial destructor.
7294 if (shouldBindAsTemporary(Entity))
7295 CurInit = S.MaybeBindToTemporary(CurInit.get());
7296 break;
7297 }
7298
7299 case SK_OCLSamplerInit: {
7300 // Sampler initialzation have 5 cases:
7301 // 1. function argument passing
7302 // 1a. argument is a file-scope variable
7303 // 1b. argument is a function-scope variable
7304 // 1c. argument is one of caller function's parameters
7305 // 2. variable initialization
7306 // 2a. initializing a file-scope variable
7307 // 2b. initializing a function-scope variable
7308 //
7309 // For file-scope variables, since they cannot be initialized by function
7310 // call of __translate_sampler_initializer in LLVM IR, their references
7311 // need to be replaced by a cast from their literal initializers to
7312 // sampler type. Since sampler variables can only be used in function
7313 // calls as arguments, we only need to replace them when handling the
7314 // argument passing.
7315 assert(Step->Type->isSamplerT() &&(static_cast <bool> (Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.") ? void (0) : __assert_fail
("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7316, __extension__ __PRETTY_FUNCTION__))
7316 "Sampler initialization on non-sampler type.")(static_cast <bool> (Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.") ? void (0) : __assert_fail
("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7316, __extension__ __PRETTY_FUNCTION__))
;
7317 Expr *Init = CurInit.get();
7318 QualType SourceType = Init->getType();
7319 // Case 1
7320 if (Entity.isParameterKind()) {
7321 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
7322 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7323 << SourceType;
7324 break;
7325 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7326 auto Var = cast<VarDecl>(DRE->getDecl());
7327 // Case 1b and 1c
7328 // No cast from integer to sampler is needed.
7329 if (!Var->hasGlobalStorage()) {
7330 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7331 CK_LValueToRValue, Init,
7332 /*BasePath=*/nullptr, VK_RValue);
7333 break;
7334 }
7335 // Case 1a
7336 // For function call with a file-scope sampler variable as argument,
7337 // get the integer literal.
7338 // Do not diagnose if the file-scope variable does not have initializer
7339 // since this has already been diagnosed when parsing the variable
7340 // declaration.
7341 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7342 break;
7343 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7344 Var->getInit()))->getSubExpr();
7345 SourceType = Init->getType();
7346 }
7347 } else {
7348 // Case 2
7349 // Check initializer is 32 bit integer constant.
7350 // If the initializer is taken from global variable, do not diagnose since
7351 // this has already been done when parsing the variable declaration.
7352 if (!Init->isConstantInitializer(S.Context, false))
7353 break;
7354
7355 if (!SourceType->isIntegerType() ||
7356 32 != S.Context.getIntWidth(SourceType)) {
7357 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7358 << SourceType;
7359 break;
7360 }
7361
7362 llvm::APSInt Result;
7363 Init->EvaluateAsInt(Result, S.Context);
7364 const uint64_t SamplerValue = Result.getLimitedValue();
7365 // 32-bit value of sampler's initializer is interpreted as
7366 // bit-field with the following structure:
7367 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7368 // |31 6|5 4|3 1| 0|
7369 // This structure corresponds to enum values of sampler properties
7370 // defined in SPIR spec v1.2 and also opencl-c.h
7371 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7372 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7373 if (FilterMode != 1 && FilterMode != 2)
7374 S.Diag(Kind.getLocation(),
7375 diag::warn_sampler_initializer_invalid_bits)
7376 << "Filter Mode";
7377 if (AddressingMode > 4)
7378 S.Diag(Kind.getLocation(),
7379 diag::warn_sampler_initializer_invalid_bits)
7380 << "Addressing Mode";
7381 }
7382
7383 // Cases 1a, 2a and 2b
7384 // Insert cast from integer to sampler.
7385 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7386 CK_IntToOCLSampler);
7387 break;
7388 }
7389 case SK_OCLZeroEvent: {
7390 assert(Step->Type->isEventT() &&(static_cast <bool> (Step->Type->isEventT() &&
"Event initialization on non-event type.") ? void (0) : __assert_fail
("Step->Type->isEventT() && \"Event initialization on non-event type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7391, __extension__ __PRETTY_FUNCTION__))
7391 "Event initialization on non-event type.")(static_cast <bool> (Step->Type->isEventT() &&
"Event initialization on non-event type.") ? void (0) : __assert_fail
("Step->Type->isEventT() && \"Event initialization on non-event type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7391, __extension__ __PRETTY_FUNCTION__))
;
7392
7393 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7394 CK_ZeroToOCLEvent,
7395 CurInit.get()->getValueKind());
7396 break;
7397 }
7398 case SK_OCLZeroQueue: {
7399 assert(Step->Type->isQueueT() &&(static_cast <bool> (Step->Type->isQueueT() &&
"Event initialization on non queue type.") ? void (0) : __assert_fail
("Step->Type->isQueueT() && \"Event initialization on non queue type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7400, __extension__ __PRETTY_FUNCTION__))
7400 "Event initialization on non queue type.")(static_cast <bool> (Step->Type->isQueueT() &&
"Event initialization on non queue type.") ? void (0) : __assert_fail
("Step->Type->isQueueT() && \"Event initialization on non queue type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7400, __extension__ __PRETTY_FUNCTION__))
;
7401
7402 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7403 CK_ZeroToOCLQueue,
7404 CurInit.get()->getValueKind());
7405 break;
7406 }
7407 }
7408 }
7409
7410 // Diagnose non-fatal problems with the completed initialization.
7411 if (Entity.getKind() == InitializedEntity::EK_Member &&
7412 cast<FieldDecl>(Entity.getDecl())->isBitField())
7413 S.CheckBitFieldInitialization(Kind.getLocation(),
7414 cast<FieldDecl>(Entity.getDecl()),
7415 CurInit.get());
7416
7417 // Check for std::move on construction.
7418 if (const Expr *E = CurInit.get()) {
7419 CheckMoveOnConstruction(S, E,
7420 Entity.getKind() == InitializedEntity::EK_Result);
7421 }
7422
7423 return CurInit;
7424}
7425
7426/// Somewhere within T there is an uninitialized reference subobject.
7427/// Dig it out and diagnose it.
7428static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7429 QualType T) {
7430 if (T->isReferenceType()) {
7431 S.Diag(Loc, diag::err_reference_without_init)
7432 << T.getNonReferenceType();
7433 return true;
7434 }
7435
7436 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7437 if (!RD || !RD->hasUninitializedReferenceMember())
7438 return false;
7439
7440 for (const auto *FI : RD->fields()) {
7441 if (FI->isUnnamedBitfield())
7442 continue;
7443
7444 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7445 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7446 return true;
7447 }
7448 }
7449
7450 for (const auto &BI : RD->bases()) {
7451 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
7452 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7453 return true;
7454 }
7455 }
7456
7457 return false;
7458}
7459
7460
7461//===----------------------------------------------------------------------===//
7462// Diagnose initialization failures
7463//===----------------------------------------------------------------------===//
7464
7465/// Emit notes associated with an initialization that failed due to a
7466/// "simple" conversion failure.
7467static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7468 Expr *op) {
7469 QualType destType = entity.getType();
7470 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7471 op->getType()->isObjCObjectPointerType()) {
7472
7473 // Emit a possible note about the conversion failing because the
7474 // operand is a message send with a related result type.
7475 S.EmitRelatedResultTypeNote(op);
7476
7477 // Emit a possible note about a return failing because we're
7478 // expecting a related result type.
7479 if (entity.getKind() == InitializedEntity::EK_Result)
7480 S.EmitRelatedResultTypeNoteForReturn(destType);
7481 }
7482}
7483
7484static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7485 InitListExpr *InitList) {
7486 QualType DestType = Entity.getType();
7487
7488 QualType E;
7489 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7490 QualType ArrayType = S.Context.getConstantArrayType(
7491 E.withConst(),
7492 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7493 InitList->getNumInits()),
7494 clang::ArrayType::Normal, 0);
7495 InitializedEntity HiddenArray =
7496 InitializedEntity::InitializeTemporary(ArrayType);
7497 return diagnoseListInit(S, HiddenArray, InitList);
7498 }
7499
7500 if (DestType->isReferenceType()) {
7501 // A list-initialization failure for a reference means that we tried to
7502 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7503 // inner initialization failed.
7504 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7505 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7506 SourceLocation Loc = InitList->getLocStart();
7507 if (auto *D = Entity.getDecl())
7508 Loc = D->getLocation();
7509 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7510 return;
7511 }
7512
7513 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
7514 /*VerifyOnly=*/false,
7515 /*TreatUnavailableAsInvalid=*/false);
7516 assert(DiagnoseInitList.HadError() &&(static_cast <bool> (DiagnoseInitList.HadError() &&
"Inconsistent init list check result.") ? void (0) : __assert_fail
("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7517, __extension__ __PRETTY_FUNCTION__))
7517 "Inconsistent init list check result.")(static_cast <bool> (DiagnoseInitList.HadError() &&
"Inconsistent init list check result.") ? void (0) : __assert_fail
("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7517, __extension__ __PRETTY_FUNCTION__))
;
7518}
7519
7520bool InitializationSequence::Diagnose(Sema &S,
7521 const InitializedEntity &Entity,
7522 const InitializationKind &Kind,
7523 ArrayRef<Expr *> Args) {
7524 if (!Failed())
7525 return false;
7526
7527 QualType DestType = Entity.getType();
7528 switch (Failure) {
7529 case FK_TooManyInitsForReference:
7530 // FIXME: Customize for the initialized entity?
7531 if (Args.empty()) {
7532 // Dig out the reference subobject which is uninitialized and diagnose it.
7533 // If this is value-initialization, this could be nested some way within
7534 // the target type.
7535 assert(Kind.getKind() == InitializationKind::IK_Value ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail
("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7536, __extension__ __PRETTY_FUNCTION__))
7536 DestType->isReferenceType())(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail
("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7536, __extension__ __PRETTY_FUNCTION__))
;
7537 bool Diagnosed =
7538 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7539 assert(Diagnosed && "couldn't find uninitialized reference to diagnose")(static_cast <bool> (Diagnosed && "couldn't find uninitialized reference to diagnose"
) ? void (0) : __assert_fail ("Diagnosed && \"couldn't find uninitialized reference to diagnose\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7539, __extension__ __PRETTY_FUNCTION__))
;
7540 (void)Diagnosed;
7541 } else // FIXME: diagnostic below could be better!
7542 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
7543 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
7544 break;
7545 case FK_ParenthesizedListInitForReference:
7546 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7547 << 1 << Entity.getType() << Args[0]->getSourceRange();
7548 break;
7549
7550 case FK_ArrayNeedsInitList:
7551 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
7552 break;
7553 case FK_ArrayNeedsInitListOrStringLiteral:
7554 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7555 break;
7556 case FK_ArrayNeedsInitListOrWideStringLiteral:
7557 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7558 break;
7559 case FK_NarrowStringIntoWideCharArray:
7560 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7561 break;
7562 case FK_WideStringIntoCharArray:
7563 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7564 break;
7565 case FK_IncompatWideStringIntoWideChar:
7566 S.Diag(Kind.getLocation(),
7567 diag::err_array_init_incompat_wide_string_into_wchar);
7568 break;
7569 case FK_ArrayTypeMismatch:
7570 case FK_NonConstantArrayInit:
7571 S.Diag(Kind.getLocation(),
7572 (Failure == FK_ArrayTypeMismatch
7573 ? diag::err_array_init_different_type
7574 : diag::err_array_init_non_constant_array))
7575 << DestType.getNonReferenceType()
7576 << Args[0]->getType()
7577 << Args[0]->getSourceRange();
7578 break;
7579
7580 case FK_VariableLengthArrayHasInitializer:
7581 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7582 << Args[0]->getSourceRange();
7583 break;
7584
7585 case FK_AddressOfOverloadFailed: {
7586 DeclAccessPair Found;
7587 S.ResolveAddressOfOverloadedFunction(Args[0],
7588 DestType.getNonReferenceType(),
7589 true,
7590 Found);
7591 break;
7592 }
7593
7594 case FK_AddressOfUnaddressableFunction: {
7595 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7596 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7597 Args[0]->getLocStart());
7598 break;
7599 }
7600
7601 case FK_ReferenceInitOverloadFailed:
7602 case FK_UserConversionOverloadFailed:
7603 switch (FailedOverloadResult) {
7604 case OR_Ambiguous:
7605 if (Failure == FK_UserConversionOverloadFailed)
7606 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7607 << Args[0]->getType() << DestType
7608 << Args[0]->getSourceRange();
7609 else
7610 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7611 << DestType << Args[0]->getType()
7612 << Args[0]->getSourceRange();
7613
7614 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7615 break;
7616
7617 case OR_No_Viable_Function:
7618 if (!S.RequireCompleteType(Kind.getLocation(),
7619 DestType.getNonReferenceType(),
7620 diag::err_typecheck_nonviable_condition_incomplete,
7621 Args[0]->getType(), Args[0]->getSourceRange()))
7622 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
7623 << (Entity.getKind() == InitializedEntity::EK_Result)
7624 << Args[0]->getType() << Args[0]->getSourceRange()
7625 << DestType.getNonReferenceType();
7626
7627 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7628 break;
7629
7630 case OR_Deleted: {
7631 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7632 << Args[0]->getType() << DestType.getNonReferenceType()
7633 << Args[0]->getSourceRange();
7634 OverloadCandidateSet::iterator Best;
7635 OverloadingResult Ovl
7636 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7637 if (Ovl == OR_Deleted) {
7638 S.NoteDeletedFunction(Best->Function);
7639 } else {
7640 llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7640)
;
7641 }
7642 break;
7643 }
7644
7645 case OR_Success:
7646 llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!",
"/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7646)
;
7647 }
7648 break;
7649
7650 case FK_NonConstLValueReferenceBindingToTemporary:
7651 if (isa<InitListExpr>(Args[0])) {
7652 S.Diag(Kind.getLocation(),
7653 diag::err_lvalue_reference_bind_to_initlist)
7654 << DestType.getNonReferenceType().isVolatileQualified()
7655 << DestType.getNonReferenceType()
7656 << Args[0]->getSourceRange();
7657 break;
7658 }
7659 // Intentional fallthrough
7660
7661 case FK_NonConstLValueReferenceBindingToUnrelated:
7662 S.Diag(Kind.getLocation(),
7663 Failure == FK_NonConstLValueReferenceBindingToTemporary
7664 ? diag::err_lvalue_reference_bind_to_temporary
7665 : diag::err_lvalue_reference_bind_to_unrelated)
7666 << DestType.getNonReferenceType().isVolatileQualified()
7667 << DestType.getNonReferenceType()
7668 << Args[0]->getType()
7669 << Args[0]->getSourceRange();
7670 break;
7671
7672 case FK_NonConstLValueReferenceBindingToBitfield: {
7673 // We don't necessarily have an unambiguous source bit-field.
7674 FieldDecl *BitField = Args[0]->getSourceBitField();
7675 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7676 << DestType.isVolatileQualified()
7677 << (BitField ? BitField->getDeclName() : DeclarationName())
7678 << (BitField != nullptr)
7679 << Args[0]->getSourceRange();
7680 if (BitField)
7681 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7682 break;
7683 }
7684
7685 case FK_NonConstLValueReferenceBindingToVectorElement:
7686 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7687 << DestType.isVolatileQualified()
7688 << Args[0]->getSourceRange();
7689 break;
7690
7691 case FK_RValueReferenceBindingToLValue:
7692 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
7693 << DestType.getNonReferenceType() << Args[0]->getType()
7694 << Args[0]->getSourceRange();
7695 break;
7696
7697 case FK_ReferenceInitDropsQualifiers: {
7698 QualType SourceType = Args[0]->getType();
7699 QualType NonRefType = DestType.getNonReferenceType();
7700 Qualifiers DroppedQualifiers =
7701 SourceType.getQualifiers() - NonRefType.getQualifiers();
7702
7703 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
7704 << SourceType
7705 << NonRefType
7706 << DroppedQualifiers.getCVRQualifiers()
7707 << Args[0]->getSourceRange();
7708 break;
7709 }
7710
7711 case FK_ReferenceInitFailed:
7712 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7713 << DestType.getNonReferenceType()
7714 << Args[0]->isLValue()
7715 << Args[0]->getType()
7716 << Args[0]->getSourceRange();
7717 emitBadConversionNotes(S, Entity, Args[0]);
7718 break;
7719
7720 case FK_ConversionFailed: {
7721 QualType FromType = Args[0]->getType();
7722 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
7723 << (int)Entity.getKind()
7724 << DestType
7725 << Args[0]->isLValue()
7726 << FromType
7727 << Args[0]->getSourceRange();
7728 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7729 S.Diag(Kind.getLocation(), PDiag);
7730 emitBadConversionNotes(S, Entity, Args[0]);
7731 break;
7732 }
7733
7734 case FK_ConversionFromPropertyFailed:
7735 // No-op. This error has already been reported.
7736 break;
7737
7738 case FK_TooManyInitsForScalar: {
7739 SourceRange R;
7740
7741 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
7742 if (InitList && InitList->getNumInits() >= 1) {
7743 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
7744 } else {
7745 assert(Args.size() > 1 && "Expected multiple initializers!")(static_cast <bool> (Args.size() > 1 && "Expected multiple initializers!"
) ? void (0) : __assert_fail ("Args.size() > 1 && \"Expected multiple initializers!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7745, __extension__ __PRETTY_FUNCTION__))
;
7746 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
7747 }
7748
7749 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
7750 if (Kind.isCStyleOrFunctionalCast())
7751 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7752 << R;
7753 else
7754 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7755 << /*scalar=*/2 << R;
7756 break;
7757 }
7758
7759 case FK_ParenthesizedListInitForScalar:
7760 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7761 << 0 << Entity.getType() << Args[0]->getSourceRange();
7762 break;
7763
7764 case FK_ReferenceBindingToInitList:
7765 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7766 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7767 break;
7768
7769 case FK_InitListBadDestinationType:
7770 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7771 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7772 break;
7773
7774 case FK_ListConstructorOverloadFailed:
7775 case FK_ConstructorOverloadFailed: {
7776 SourceRange ArgsRange;
7777 if (Args.size())
7778 ArgsRange = SourceRange(Args.front()->getLocStart(),
7779 Args.back()->getLocEnd());
7780
7781 if (Failure == FK_ListConstructorOverloadFailed) {
7782 assert(Args.size() == 1 &&(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7783, __extension__ __PRETTY_FUNCTION__))
7783 "List construction from other than 1 argument.")(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/Sema/SemaInit.cpp"
, 7783, __extension__ __PRETTY_FUNCTION__))
;
7784 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7785 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
7786 }
7787
7788 // FIXME: Using "DestType" for the entity we're printing is probably
7789 // bad.
7790 switch (FailedOverloadResult) {
7791 case OR_Ambiguous:
7792 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7793 << DestType << ArgsRange;
7794 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7795 break;
7796
7797 case OR_No_Viable_Function:
7798 if (Kind.getKind() == InitializationKind::IK_Default &&
7799 (Entity.getKind() == InitializedEntity::EK_Base ||
7800 Entity.getKind() == InitializedEntity::EK_Member) &&
7801 isa<CXXConstructorDecl>(S.CurContext)) {
7802 // This is implicit default initialization of a member or
7803 // base within a constructor. If no viable function was
7804 // found, notify the user that they need to explicitly
7805 // initialize this base/member.
7806 CXXConstructorDecl *Constructor
7807 = cast<CXXConstructorDecl>(S.CurContext);
7808 const CXXRecordDecl *InheritedFrom