Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaInit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337490/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-20-043646-20380-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp -faddrsig
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/// 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_UTF8StringIntoPlainChar,
53 SIF_PlainStringIntoUTF8Char,
54 SIF_Other
55};
56
57/// Check whether the array of type AT can be initialized by the Init
58/// expression by means of string initialization. Returns SIF_None if so,
59/// otherwise returns a StringInitFailureKind that describes why the
60/// initialization would not work.
61static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
62 ASTContext &Context) {
63 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
64 return SIF_Other;
65
66 // See if this is a string literal or @encode.
67 Init = Init->IgnoreParens();
68
69 // Handle @encode, which is a narrow string.
70 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
71 return SIF_None;
72
73 // Otherwise we can only handle string literals.
74 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
75 if (!SL)
76 return SIF_Other;
77
78 const QualType ElemTy =
79 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
80
81 switch (SL->getKind()) {
82 case StringLiteral::UTF8:
83 // char8_t array can be initialized with a UTF-8 string.
84 if (ElemTy->isChar8Type())
85 return SIF_None;
86 LLVM_FALLTHROUGH[[clang::fallthrough]];
87 case StringLiteral::Ascii:
88 // char array can be initialized with a narrow string.
89 // Only allow char x[] = "foo"; not char x[] = L"foo";
90 if (ElemTy->isCharType())
91 return (SL->getKind() == StringLiteral::UTF8 &&
92 Context.getLangOpts().Char8)
93 ? SIF_UTF8StringIntoPlainChar
94 : SIF_None;
95 if (ElemTy->isChar8Type())
96 return SIF_PlainStringIntoUTF8Char;
97 if (IsWideCharCompatible(ElemTy, Context))
98 return SIF_NarrowStringIntoWideChar;
99 return SIF_Other;
100 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
101 // "An array with element type compatible with a qualified or unqualified
102 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
103 // string literal with the corresponding encoding prefix (L, u, or U,
104 // respectively), optionally enclosed in braces.
105 case StringLiteral::UTF16:
106 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
107 return SIF_None;
108 if (ElemTy->isCharType() || ElemTy->isChar8Type())
109 return SIF_WideStringIntoChar;
110 if (IsWideCharCompatible(ElemTy, Context))
111 return SIF_IncompatWideStringIntoWideChar;
112 return SIF_Other;
113 case StringLiteral::UTF32:
114 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
115 return SIF_None;
116 if (ElemTy->isCharType() || ElemTy->isChar8Type())
117 return SIF_WideStringIntoChar;
118 if (IsWideCharCompatible(ElemTy, Context))
119 return SIF_IncompatWideStringIntoWideChar;
120 return SIF_Other;
121 case StringLiteral::Wide:
122 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
123 return SIF_None;
124 if (ElemTy->isCharType() || ElemTy->isChar8Type())
125 return SIF_WideStringIntoChar;
126 if (IsWideCharCompatible(ElemTy, Context))
127 return SIF_IncompatWideStringIntoWideChar;
128 return SIF_Other;
129 }
130
131 llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 131)
;
132}
133
134static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
135 ASTContext &Context) {
136 const ArrayType *arrayType = Context.getAsArrayType(declType);
137 if (!arrayType)
138 return SIF_Other;
139 return IsStringInit(init, arrayType, Context);
140}
141
142/// Update the type of a string literal, including any surrounding parentheses,
143/// to match the type of the object which it is initializing.
144static void updateStringLiteralType(Expr *E, QualType Ty) {
145 while (true) {
146 E->setType(Ty);
147 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
148 break;
149 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
150 E = PE->getSubExpr();
151 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
152 E = UO->getSubExpr();
153 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
154 E = GSE->getResultExpr();
155 else
156 llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 156)
;
157 }
158}
159
160static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
161 Sema &S) {
162 // Get the length of the string as parsed.
163 auto *ConstantArrayTy =
164 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
165 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
166
167 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
168 // C99 6.7.8p14. We have an array of character type with unknown size
169 // being initialized to a string literal.
170 llvm::APInt ConstVal(32, StrLength);
171 // Return a new array type (C99 6.7.8p22).
172 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
173 ConstVal,
174 ArrayType::Normal, 0);
175 updateStringLiteralType(Str, DeclT);
176 return;
177 }
178
179 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
180
181 // We have an array of character type with known size. However,
182 // the size may be smaller or larger than the string we are initializing.
183 // FIXME: Avoid truncation for 64-bit length strings.
184 if (S.getLangOpts().CPlusPlus) {
185 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
186 // For Pascal strings it's OK to strip off the terminating null character,
187 // so the example below is valid:
188 //
189 // unsigned char a[2] = "\pa";
190 if (SL->isPascal())
191 StrLength--;
192 }
193
194 // [dcl.init.string]p2
195 if (StrLength > CAT->getSize().getZExtValue())
196 S.Diag(Str->getLocStart(),
197 diag::err_initializer_string_for_char_array_too_long)
198 << Str->getSourceRange();
199 } else {
200 // C99 6.7.8p14.
201 if (StrLength-1 > CAT->getSize().getZExtValue())
202 S.Diag(Str->getLocStart(),
203 diag::ext_initializer_string_for_char_array_too_long)
204 << Str->getSourceRange();
205 }
206
207 // Set the type to the actual size that we are initializing. If we have
208 // something like:
209 // char x[1] = "foo";
210 // then this will set the string literal's type to char[1].
211 updateStringLiteralType(Str, DeclT);
212}
213
214//===----------------------------------------------------------------------===//
215// Semantic checking for initializer lists.
216//===----------------------------------------------------------------------===//
217
218namespace {
219
220/// Semantic checking for initializer lists.
221///
222/// The InitListChecker class contains a set of routines that each
223/// handle the initialization of a certain kind of entity, e.g.,
224/// arrays, vectors, struct/union types, scalars, etc. The
225/// InitListChecker itself performs a recursive walk of the subobject
226/// structure of the type to be initialized, while stepping through
227/// the initializer list one element at a time. The IList and Index
228/// parameters to each of the Check* routines contain the active
229/// (syntactic) initializer list and the index into that initializer
230/// list that represents the current initializer. Each routine is
231/// responsible for moving that Index forward as it consumes elements.
232///
233/// Each Check* routine also has a StructuredList/StructuredIndex
234/// arguments, which contains the current "structured" (semantic)
235/// initializer list and the index into that initializer list where we
236/// are copying initializers as we map them over to the semantic
237/// list. Once we have completed our recursive walk of the subobject
238/// structure, we will have constructed a full semantic initializer
239/// list.
240///
241/// C99 designators cause changes in the initializer list traversal,
242/// because they make the initialization "jump" into a specific
243/// subobject and then continue the initialization from that
244/// point. CheckDesignatedInitializer() recursively steps into the
245/// designated subobject and manages backing out the recursion to
246/// initialize the subobjects after the one designated.
247class InitListChecker {
248 Sema &SemaRef;
249 bool hadError;
250 bool VerifyOnly; // no diagnostics, no structure building
251 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
252 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
253 InitListExpr *FullyStructuredList;
254
255 void CheckImplicitInitList(const InitializedEntity &Entity,
256 InitListExpr *ParentIList, QualType T,
257 unsigned &Index, InitListExpr *StructuredList,
258 unsigned &StructuredIndex);
259 void CheckExplicitInitList(const InitializedEntity &Entity,
260 InitListExpr *IList, QualType &T,
261 InitListExpr *StructuredList,
262 bool TopLevelObject = false);
263 void CheckListElementTypes(const InitializedEntity &Entity,
264 InitListExpr *IList, QualType &DeclType,
265 bool SubobjectIsDesignatorContext,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex,
269 bool TopLevelObject = false);
270 void CheckSubElementType(const InitializedEntity &Entity,
271 InitListExpr *IList, QualType ElemType,
272 unsigned &Index,
273 InitListExpr *StructuredList,
274 unsigned &StructuredIndex);
275 void CheckComplexType(const InitializedEntity &Entity,
276 InitListExpr *IList, QualType DeclType,
277 unsigned &Index,
278 InitListExpr *StructuredList,
279 unsigned &StructuredIndex);
280 void CheckScalarType(const InitializedEntity &Entity,
281 InitListExpr *IList, QualType DeclType,
282 unsigned &Index,
283 InitListExpr *StructuredList,
284 unsigned &StructuredIndex);
285 void CheckReferenceType(const InitializedEntity &Entity,
286 InitListExpr *IList, QualType DeclType,
287 unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex);
290 void CheckVectorType(const InitializedEntity &Entity,
291 InitListExpr *IList, QualType DeclType, unsigned &Index,
292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
294 void CheckStructUnionTypes(const InitializedEntity &Entity,
295 InitListExpr *IList, QualType DeclType,
296 CXXRecordDecl::base_class_range Bases,
297 RecordDecl::field_iterator Field,
298 bool SubobjectIsDesignatorContext, unsigned &Index,
299 InitListExpr *StructuredList,
300 unsigned &StructuredIndex,
301 bool TopLevelObject = false);
302 void CheckArrayType(const InitializedEntity &Entity,
303 InitListExpr *IList, QualType &DeclType,
304 llvm::APSInt elementIndex,
305 bool SubobjectIsDesignatorContext, unsigned &Index,
306 InitListExpr *StructuredList,
307 unsigned &StructuredIndex);
308 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
309 InitListExpr *IList, DesignatedInitExpr *DIE,
310 unsigned DesigIdx,
311 QualType &CurrentObjectType,
312 RecordDecl::field_iterator *NextField,
313 llvm::APSInt *NextElementIndex,
314 unsigned &Index,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex,
317 bool FinishSubobjectInit,
318 bool TopLevelObject);
319 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
320 QualType CurrentObjectType,
321 InitListExpr *StructuredList,
322 unsigned StructuredIndex,
323 SourceRange InitRange,
324 bool IsFullyOverwritten = false);
325 void UpdateStructuredListElement(InitListExpr *StructuredList,
326 unsigned &StructuredIndex,
327 Expr *expr);
328 int numArrayElements(QualType DeclType);
329 int numStructUnionElements(QualType DeclType);
330
331 static ExprResult PerformEmptyInit(Sema &SemaRef,
332 SourceLocation Loc,
333 const InitializedEntity &Entity,
334 bool VerifyOnly,
335 bool TreatUnavailableAsInvalid);
336
337 // Explanation on the "FillWithNoInit" mode:
338 //
339 // Assume we have the following definitions (Case#1):
340 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
341 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
342 //
343 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
344 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
345 //
346 // But if we have (Case#2):
347 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
348 //
349 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
350 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
351 //
352 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
353 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
354 // initializers but with special "NoInitExpr" place holders, which tells the
355 // CodeGen not to generate any initializers for these parts.
356 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
357 const InitializedEntity &ParentEntity,
358 InitListExpr *ILE, bool &RequiresSecondPass,
359 bool FillWithNoInit);
360 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
361 const InitializedEntity &ParentEntity,
362 InitListExpr *ILE, bool &RequiresSecondPass,
363 bool FillWithNoInit = false);
364 void FillInEmptyInitializations(const InitializedEntity &Entity,
365 InitListExpr *ILE, bool &RequiresSecondPass,
366 InitListExpr *OuterILE, unsigned OuterIndex,
367 bool FillWithNoInit = false);
368 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
369 Expr *InitExpr, FieldDecl *Field,
370 bool TopLevelObject);
371 void CheckEmptyInitializable(const InitializedEntity &Entity,
372 SourceLocation Loc);
373
374public:
375 InitListChecker(Sema &S, const InitializedEntity &Entity,
376 InitListExpr *IL, QualType &T, bool VerifyOnly,
377 bool TreatUnavailableAsInvalid);
378 bool HadError() { return hadError; }
379
380 // Retrieves the fully-structured initializer list used for
381 // semantic analysis and code generation.
382 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
383};
384
385} // end anonymous namespace
386
387ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
388 SourceLocation Loc,
389 const InitializedEntity &Entity,
390 bool VerifyOnly,
391 bool TreatUnavailableAsInvalid) {
392 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
393 true);
394 MultiExprArg SubInit;
395 Expr *InitExpr;
396 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
397
398 // C++ [dcl.init.aggr]p7:
399 // If there are fewer initializer-clauses in the list than there are
400 // members in the aggregate, then each member not explicitly initialized
401 // ...
402 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
403 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
404 if (EmptyInitList) {
405 // C++1y / DR1070:
406 // shall be initialized [...] from an empty initializer list.
407 //
408 // We apply the resolution of this DR to C++11 but not C++98, since C++98
409 // does not have useful semantics for initialization from an init list.
410 // We treat this as copy-initialization, because aggregate initialization
411 // always performs copy-initialization on its elements.
412 //
413 // Only do this if we're initializing a class type, to avoid filling in
414 // the initializer list where possible.
415 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
416 InitListExpr(SemaRef.Context, Loc, None, Loc);
417 InitExpr->setType(SemaRef.Context.VoidTy);
418 SubInit = InitExpr;
419 Kind = InitializationKind::CreateCopy(Loc, Loc);
420 } else {
421 // C++03:
422 // shall be value-initialized.
423 }
424
425 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
426 // libstdc++4.6 marks the vector default constructor as explicit in
427 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
428 // stlport does so too. Look for std::__debug for libstdc++, and for
429 // std:: for stlport. This is effectively a compiler-side implementation of
430 // LWG2193.
431 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
432 InitializationSequence::FK_ExplicitConstructor) {
433 OverloadCandidateSet::iterator Best;
434 OverloadingResult O =
435 InitSeq.getFailedCandidateSet()
436 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
437 (void)O;
438 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 438, __extension__ __PRETTY_FUNCTION__))
;
439 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
440 CXXRecordDecl *R = CtorDecl->getParent();
441
442 if (CtorDecl->getMinRequiredArguments() == 0 &&
443 CtorDecl->isExplicit() && R->getDeclName() &&
444 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
445 bool IsInStd = false;
446 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
447 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
448 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
449 IsInStd = true;
450 }
451
452 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
453 .Cases("basic_string", "deque", "forward_list", true)
454 .Cases("list", "map", "multimap", "multiset", true)
455 .Cases("priority_queue", "queue", "set", "stack", true)
456 .Cases("unordered_map", "unordered_set", "vector", true)
457 .Default(false)) {
458 InitSeq.InitializeFrom(
459 SemaRef, Entity,
460 InitializationKind::CreateValue(Loc, Loc, Loc, true),
461 MultiExprArg(), /*TopLevelOfInitList=*/false,
462 TreatUnavailableAsInvalid);
463 // Emit a warning for this. System header warnings aren't shown
464 // by default, but people working on system headers should see it.
465 if (!VerifyOnly) {
466 SemaRef.Diag(CtorDecl->getLocation(),
467 diag::warn_invalid_initializer_from_system_header);
468 if (Entity.getKind() == InitializedEntity::EK_Member)
469 SemaRef.Diag(Entity.getDecl()->getLocation(),
470 diag::note_used_in_initialization_here);
471 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
472 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
473 }
474 }
475 }
476 }
477 if (!InitSeq) {
478 if (!VerifyOnly) {
479 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
480 if (Entity.getKind() == InitializedEntity::EK_Member)
481 SemaRef.Diag(Entity.getDecl()->getLocation(),
482 diag::note_in_omitted_aggregate_initializer)
483 << /*field*/1 << Entity.getDecl();
484 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
485 bool IsTrailingArrayNewMember =
486 Entity.getParent() &&
487 Entity.getParent()->isVariableLengthArrayNew();
488 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
489 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
490 << Entity.getElementIndex();
491 }
492 }
493 return ExprError();
494 }
495
496 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
497 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
498}
499
500void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
501 SourceLocation Loc) {
502 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 503, __extension__ __PRETTY_FUNCTION__))
503 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 503, __extension__ __PRETTY_FUNCTION__))
;
504 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
505 TreatUnavailableAsInvalid).isInvalid())
506 hadError = true;
507}
508
509void InitListChecker::FillInEmptyInitForBase(
510 unsigned Init, const CXXBaseSpecifier &Base,
511 const InitializedEntity &ParentEntity, InitListExpr *ILE,
512 bool &RequiresSecondPass, bool FillWithNoInit) {
513 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 513, __extension__ __PRETTY_FUNCTION__))
;
514
515 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
516 SemaRef.Context, &Base, false, &ParentEntity);
517
518 if (!ILE->getInit(Init)) {
519 ExprResult BaseInit =
520 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
521 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
522 /*VerifyOnly*/ false,
523 TreatUnavailableAsInvalid);
524 if (BaseInit.isInvalid()) {
525 hadError = true;
526 return;
527 }
528
529 ILE->setInit(Init, BaseInit.getAs<Expr>());
530 } else if (InitListExpr *InnerILE =
531 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
532 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
533 ILE, Init, FillWithNoInit);
534 } else if (DesignatedInitUpdateExpr *InnerDIUE =
535 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
536 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
537 RequiresSecondPass, ILE, Init,
538 /*FillWithNoInit =*/true);
539 }
540}
541
542void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
543 const InitializedEntity &ParentEntity,
544 InitListExpr *ILE,
545 bool &RequiresSecondPass,
546 bool FillWithNoInit) {
547 SourceLocation Loc = ILE->getLocEnd();
548 unsigned NumInits = ILE->getNumInits();
549 InitializedEntity MemberEntity
550 = InitializedEntity::InitializeMember(Field, &ParentEntity);
551
552 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
553 if (!RType->getDecl()->isUnion())
554 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 554, __extension__ __PRETTY_FUNCTION__))
;
555
556 if (Init >= NumInits || !ILE->getInit(Init)) {
557 if (FillWithNoInit) {
558 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
559 if (Init < NumInits)
560 ILE->setInit(Init, Filler);
561 else
562 ILE->updateInit(SemaRef.Context, Init, Filler);
563 return;
564 }
565 // C++1y [dcl.init.aggr]p7:
566 // If there are fewer initializer-clauses in the list than there are
567 // members in the aggregate, then each member not explicitly initialized
568 // shall be initialized from its brace-or-equal-initializer [...]
569 if (Field->hasInClassInitializer()) {
570 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
571 if (DIE.isInvalid()) {
572 hadError = true;
573 return;
574 }
575 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
576 if (Init < NumInits)
577 ILE->setInit(Init, DIE.get());
578 else {
579 ILE->updateInit(SemaRef.Context, Init, DIE.get());
580 RequiresSecondPass = true;
581 }
582 return;
583 }
584
585 if (Field->getType()->isReferenceType()) {
586 // C++ [dcl.init.aggr]p9:
587 // If an incomplete or empty initializer-list leaves a
588 // member of reference type uninitialized, the program is
589 // ill-formed.
590 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
591 << Field->getType()
592 << ILE->getSyntacticForm()->getSourceRange();
593 SemaRef.Diag(Field->getLocation(),
594 diag::note_uninit_reference_member);
595 hadError = true;
596 return;
597 }
598
599 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
600 /*VerifyOnly*/false,
601 TreatUnavailableAsInvalid);
602 if (MemberInit.isInvalid()) {
603 hadError = true;
604 return;
605 }
606
607 if (hadError) {
608 // Do nothing
609 } else if (Init < NumInits) {
610 ILE->setInit(Init, MemberInit.getAs<Expr>());
611 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
612 // Empty initialization requires a constructor call, so
613 // extend the initializer list to include the constructor
614 // call and make a note that we'll need to take another pass
615 // through the initializer list.
616 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
617 RequiresSecondPass = true;
618 }
619 } else if (InitListExpr *InnerILE
620 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
621 FillInEmptyInitializations(MemberEntity, InnerILE,
622 RequiresSecondPass, ILE, Init, FillWithNoInit);
623 else if (DesignatedInitUpdateExpr *InnerDIUE
624 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
625 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
626 RequiresSecondPass, ILE, Init,
627 /*FillWithNoInit =*/true);
628}
629
630/// Recursively replaces NULL values within the given initializer list
631/// with expressions that perform value-initialization of the
632/// appropriate type, and finish off the InitListExpr formation.
633void
634InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
635 InitListExpr *ILE,
636 bool &RequiresSecondPass,
637 InitListExpr *OuterILE,
638 unsigned OuterIndex,
639 bool FillWithNoInit) {
640 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 641, __extension__ __PRETTY_FUNCTION__))
641 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 641, __extension__ __PRETTY_FUNCTION__))
;
642
643 // If this is a nested initializer list, we might have changed its contents
644 // (and therefore some of its properties, such as instantiation-dependence)
645 // while filling it in. Inform the outer initializer list so that its state
646 // can be updated to match.
647 // FIXME: We should fully build the inner initializers before constructing
648 // the outer InitListExpr instead of mutating AST nodes after they have
649 // been used as subexpressions of other nodes.
650 struct UpdateOuterILEWithUpdatedInit {
651 InitListExpr *Outer;
652 unsigned OuterIndex;
653 ~UpdateOuterILEWithUpdatedInit() {
654 if (Outer)
655 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
656 }
657 } UpdateOuterRAII = {OuterILE, OuterIndex};
658
659 // A transparent ILE is not performing aggregate initialization and should
660 // not be filled in.
661 if (ILE->isTransparent())
662 return;
663
664 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
665 const RecordDecl *RDecl = RType->getDecl();
666 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
667 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
668 Entity, ILE, RequiresSecondPass, FillWithNoInit);
669 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
670 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
671 for (auto *Field : RDecl->fields()) {
672 if (Field->hasInClassInitializer()) {
673 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
674 FillWithNoInit);
675 break;
676 }
677 }
678 } else {
679 // The fields beyond ILE->getNumInits() are default initialized, so in
680 // order to leave them uninitialized, the ILE is expanded and the extra
681 // fields are then filled with NoInitExpr.
682 unsigned NumElems = numStructUnionElements(ILE->getType());
683 if (RDecl->hasFlexibleArrayMember())
684 ++NumElems;
685 if (ILE->getNumInits() < NumElems)
686 ILE->resizeInits(SemaRef.Context, NumElems);
687
688 unsigned Init = 0;
689
690 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
691 for (auto &Base : CXXRD->bases()) {
692 if (hadError)
693 return;
694
695 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
696 FillWithNoInit);
697 ++Init;
698 }
699 }
700
701 for (auto *Field : RDecl->fields()) {
702 if (Field->isUnnamedBitfield())
703 continue;
704
705 if (hadError)
706 return;
707
708 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
709 FillWithNoInit);
710 if (hadError)
711 return;
712
713 ++Init;
714
715 // Only look at the first initialization of a union.
716 if (RDecl->isUnion())
717 break;
718 }
719 }
720
721 return;
722 }
723
724 QualType ElementType;
725
726 InitializedEntity ElementEntity = Entity;
727 unsigned NumInits = ILE->getNumInits();
728 unsigned NumElements = NumInits;
729 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
730 ElementType = AType->getElementType();
731 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
732 NumElements = CAType->getSize().getZExtValue();
733 // For an array new with an unknown bound, ask for one additional element
734 // in order to populate the array filler.
735 if (Entity.isVariableLengthArrayNew())
736 ++NumElements;
737 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
738 0, Entity);
739 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
740 ElementType = VType->getElementType();
741 NumElements = VType->getNumElements();
742 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
743 0, Entity);
744 } else
745 ElementType = ILE->getType();
746
747 for (unsigned Init = 0; Init != NumElements; ++Init) {
748 if (hadError)
749 return;
750
751 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
752 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
753 ElementEntity.setElementIndex(Init);
754
755 if (Init >= NumInits && ILE->hasArrayFiller())
756 return;
757
758 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
759 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
760 ILE->setInit(Init, ILE->getArrayFiller());
761 else if (!InitExpr && !ILE->hasArrayFiller()) {
762 Expr *Filler = nullptr;
763
764 if (FillWithNoInit)
765 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
766 else {
767 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
768 ElementEntity,
769 /*VerifyOnly*/false,
770 TreatUnavailableAsInvalid);
771 if (ElementInit.isInvalid()) {
772 hadError = true;
773 return;
774 }
775
776 Filler = ElementInit.getAs<Expr>();
777 }
778
779 if (hadError) {
780 // Do nothing
781 } else if (Init < NumInits) {
782 // For arrays, just set the expression used for value-initialization
783 // of the "holes" in the array.
784 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
785 ILE->setArrayFiller(Filler);
786 else
787 ILE->setInit(Init, Filler);
788 } else {
789 // For arrays, just set the expression used for value-initialization
790 // of the rest of elements and exit.
791 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
792 ILE->setArrayFiller(Filler);
793 return;
794 }
795
796 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
797 // Empty initialization requires a constructor call, so
798 // extend the initializer list to include the constructor
799 // call and make a note that we'll need to take another pass
800 // through the initializer list.
801 ILE->updateInit(SemaRef.Context, Init, Filler);
802 RequiresSecondPass = true;
803 }
804 }
805 } else if (InitListExpr *InnerILE
806 = dyn_cast_or_null<InitListExpr>(InitExpr))
807 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
808 ILE, Init, FillWithNoInit);
809 else if (DesignatedInitUpdateExpr *InnerDIUE
810 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
811 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
812 RequiresSecondPass, ILE, Init,
813 /*FillWithNoInit =*/true);
814 }
815}
816
817InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
818 InitListExpr *IL, QualType &T,
819 bool VerifyOnly,
820 bool TreatUnavailableAsInvalid)
821 : SemaRef(S), VerifyOnly(VerifyOnly),
822 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
823 // FIXME: Check that IL isn't already the semantic form of some other
824 // InitListExpr. If it is, we'd create a broken AST.
825
826 hadError = false;
827
828 FullyStructuredList =
829 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
830 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
831 /*TopLevelObject=*/true);
832
833 if (!hadError && !VerifyOnly) {
834 bool RequiresSecondPass = false;
835 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
836 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
837 if (RequiresSecondPass && !hadError)
838 FillInEmptyInitializations(Entity, FullyStructuredList,
839 RequiresSecondPass, nullptr, 0);
840 }
841}
842
843int InitListChecker::numArrayElements(QualType DeclType) {
844 // FIXME: use a proper constant
845 int maxElements = 0x7FFFFFFF;
846 if (const ConstantArrayType *CAT =
847 SemaRef.Context.getAsConstantArrayType(DeclType)) {
848 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
849 }
850 return maxElements;
851}
852
853int InitListChecker::numStructUnionElements(QualType DeclType) {
854 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
855 int InitializableMembers = 0;
856 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
857 InitializableMembers += CXXRD->getNumBases();
858 for (const auto *Field : structDecl->fields())
859 if (!Field->isUnnamedBitfield())
860 ++InitializableMembers;
861
862 if (structDecl->isUnion())
863 return std::min(InitializableMembers, 1);
864 return InitializableMembers - structDecl->hasFlexibleArrayMember();
865}
866
867/// Determine whether Entity is an entity for which it is idiomatic to elide
868/// the braces in aggregate initialization.
869static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
870 // Recursive initialization of the one and only field within an aggregate
871 // class is considered idiomatic. This case arises in particular for
872 // initialization of std::array, where the C++ standard suggests the idiom of
873 //
874 // std::array<T, N> arr = {1, 2, 3};
875 //
876 // (where std::array is an aggregate struct containing a single array field.
877
878 // FIXME: Should aggregate initialization of a struct with a single
879 // base class and no members also suppress the warning?
880 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
881 return false;
882
883 auto *ParentRD =
884 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
885 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
886 if (CXXRD->getNumBases())
887 return false;
888
889 auto FieldIt = ParentRD->field_begin();
890 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 891, __extension__ __PRETTY_FUNCTION__))
891 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 891, __extension__ __PRETTY_FUNCTION__))
;
892 return ++FieldIt == ParentRD->field_end();
893}
894
895/// Check whether the range of the initializer \p ParentIList from element
896/// \p Index onwards can be used to initialize an object of type \p T. Update
897/// \p Index to indicate how many elements of the list were consumed.
898///
899/// This also fills in \p StructuredList, from element \p StructuredIndex
900/// onwards, with the fully-braced, desugared form of the initialization.
901void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
902 InitListExpr *ParentIList,
903 QualType T, unsigned &Index,
904 InitListExpr *StructuredList,
905 unsigned &StructuredIndex) {
906 int maxElements = 0;
907
908 if (T->isArrayType())
909 maxElements = numArrayElements(T);
910 else if (T->isRecordType())
911 maxElements = numStructUnionElements(T);
912 else if (T->isVectorType())
913 maxElements = T->getAs<VectorType>()->getNumElements();
914 else
915 llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 915)
;
916
917 if (maxElements == 0) {
918 if (!VerifyOnly)
919 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
920 diag::err_implicit_empty_initializer);
921 ++Index;
922 hadError = true;
923 return;
924 }
925
926 // Build a structured initializer list corresponding to this subobject.
927 InitListExpr *StructuredSubobjectInitList
928 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
929 StructuredIndex,
930 SourceRange(ParentIList->getInit(Index)->getLocStart(),
931 ParentIList->getSourceRange().getEnd()));
932 unsigned StructuredSubobjectInitIndex = 0;
933
934 // Check the element types and build the structural subobject.
935 unsigned StartIndex = Index;
936 CheckListElementTypes(Entity, ParentIList, T,
937 /*SubobjectIsDesignatorContext=*/false, Index,
938 StructuredSubobjectInitList,
939 StructuredSubobjectInitIndex);
940
941 if (!VerifyOnly) {
942 StructuredSubobjectInitList->setType(T);
943
944 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
945 // Update the structured sub-object initializer so that it's ending
946 // range corresponds with the end of the last initializer it used.
947 if (EndIndex < ParentIList->getNumInits() &&
948 ParentIList->getInit(EndIndex)) {
949 SourceLocation EndLoc
950 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
951 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
952 }
953
954 // Complain about missing braces.
955 if ((T->isArrayType() || T->isRecordType()) &&
956 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
957 !isIdiomaticBraceElisionEntity(Entity)) {
958 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
959 diag::warn_missing_braces)
960 << StructuredSubobjectInitList->getSourceRange()
961 << FixItHint::CreateInsertion(
962 StructuredSubobjectInitList->getLocStart(), "{")
963 << FixItHint::CreateInsertion(
964 SemaRef.getLocForEndOfToken(
965 StructuredSubobjectInitList->getLocEnd()),
966 "}");
967 }
968 }
969}
970
971/// Warn that \p Entity was of scalar type and was initialized by a
972/// single-element braced initializer list.
973static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
974 SourceRange Braces) {
975 // Don't warn during template instantiation. If the initialization was
976 // non-dependent, we warned during the initial parse; otherwise, the
977 // type might not be scalar in some uses of the template.
978 if (S.inTemplateInstantiation())
979 return;
980
981 unsigned DiagID = 0;
982
983 switch (Entity.getKind()) {
984 case InitializedEntity::EK_VectorElement:
985 case InitializedEntity::EK_ComplexElement:
986 case InitializedEntity::EK_ArrayElement:
987 case InitializedEntity::EK_Parameter:
988 case InitializedEntity::EK_Parameter_CF_Audited:
989 case InitializedEntity::EK_Result:
990 // Extra braces here are suspicious.
991 DiagID = diag::warn_braces_around_scalar_init;
992 break;
993
994 case InitializedEntity::EK_Member:
995 // Warn on aggregate initialization but not on ctor init list or
996 // default member initializer.
997 if (Entity.getParent())
998 DiagID = diag::warn_braces_around_scalar_init;
999 break;
1000
1001 case InitializedEntity::EK_Variable:
1002 case InitializedEntity::EK_LambdaCapture:
1003 // No warning, might be direct-list-initialization.
1004 // FIXME: Should we warn for copy-list-initialization in these cases?
1005 break;
1006
1007 case InitializedEntity::EK_New:
1008 case InitializedEntity::EK_Temporary:
1009 case InitializedEntity::EK_CompoundLiteralInit:
1010 // No warning, braces are part of the syntax of the underlying construct.
1011 break;
1012
1013 case InitializedEntity::EK_RelatedResult:
1014 // No warning, we already warned when initializing the result.
1015 break;
1016
1017 case InitializedEntity::EK_Exception:
1018 case InitializedEntity::EK_Base:
1019 case InitializedEntity::EK_Delegating:
1020 case InitializedEntity::EK_BlockElement:
1021 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1022 case InitializedEntity::EK_Binding:
1023 llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1023)
;
1024 }
1025
1026 if (DiagID) {
1027 S.Diag(Braces.getBegin(), DiagID)
1028 << Braces
1029 << FixItHint::CreateRemoval(Braces.getBegin())
1030 << FixItHint::CreateRemoval(Braces.getEnd());
1031 }
1032}
1033
1034/// Check whether the initializer \p IList (that was written with explicit
1035/// braces) can be used to initialize an object of type \p T.
1036///
1037/// This also fills in \p StructuredList with the fully-braced, desugared
1038/// form of the initialization.
1039void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1040 InitListExpr *IList, QualType &T,
1041 InitListExpr *StructuredList,
1042 bool TopLevelObject) {
1043 if (!VerifyOnly) {
1044 SyntacticToSemantic[IList] = StructuredList;
1045 StructuredList->setSyntacticForm(IList);
1046 }
1047
1048 unsigned Index = 0, StructuredIndex = 0;
1049 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1050 Index, StructuredList, StructuredIndex, TopLevelObject);
1051 if (!VerifyOnly) {
1052 QualType ExprTy = T;
1053 if (!ExprTy->isArrayType())
1054 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1055 IList->setType(ExprTy);
1056 StructuredList->setType(ExprTy);
1057 }
1058 if (hadError)
1059 return;
1060
1061 if (Index < IList->getNumInits()) {
1062 // We have leftover initializers
1063 if (VerifyOnly) {
1064 if (SemaRef.getLangOpts().CPlusPlus ||
1065 (SemaRef.getLangOpts().OpenCL &&
1066 IList->getType()->isVectorType())) {
1067 hadError = true;
1068 }
1069 return;
1070 }
1071
1072 if (StructuredIndex == 1 &&
1073 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1074 SIF_None) {
1075 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1076 if (SemaRef.getLangOpts().CPlusPlus) {
1077 DK = diag::err_excess_initializers_in_char_array_initializer;
1078 hadError = true;
1079 }
1080 // Special-case
1081 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1082 << IList->getInit(Index)->getSourceRange();
1083 } else if (!T->isIncompleteType()) {
1084 // Don't complain for incomplete types, since we'll get an error
1085 // elsewhere
1086 QualType CurrentObjectType = StructuredList->getType();
1087 int initKind =
1088 CurrentObjectType->isArrayType()? 0 :
1089 CurrentObjectType->isVectorType()? 1 :
1090 CurrentObjectType->isScalarType()? 2 :
1091 CurrentObjectType->isUnionType()? 3 :
1092 4;
1093
1094 unsigned DK = diag::ext_excess_initializers;
1095 if (SemaRef.getLangOpts().CPlusPlus) {
1096 DK = diag::err_excess_initializers;
1097 hadError = true;
1098 }
1099 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1100 DK = diag::err_excess_initializers;
1101 hadError = true;
1102 }
1103
1104 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1105 << initKind << IList->getInit(Index)->getSourceRange();
1106 }
1107 }
1108
1109 if (!VerifyOnly && T->isScalarType() &&
1110 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1111 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1112}
1113
1114void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1115 InitListExpr *IList,
1116 QualType &DeclType,
1117 bool SubobjectIsDesignatorContext,
1118 unsigned &Index,
1119 InitListExpr *StructuredList,
1120 unsigned &StructuredIndex,
1121 bool TopLevelObject) {
1122 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1123 // Explicitly braced initializer for complex type can be real+imaginary
1124 // parts.
1125 CheckComplexType(Entity, IList, DeclType, Index,
1126 StructuredList, StructuredIndex);
1127 } else if (DeclType->isScalarType()) {
1128 CheckScalarType(Entity, IList, DeclType, Index,
1129 StructuredList, StructuredIndex);
1130 } else if (DeclType->isVectorType()) {
1131 CheckVectorType(Entity, IList, DeclType, Index,
1132 StructuredList, StructuredIndex);
1133 } else if (DeclType->isRecordType()) {
1134 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1135, __extension__ __PRETTY_FUNCTION__))
1135 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1135, __extension__ __PRETTY_FUNCTION__))
;
1136 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1137 auto Bases =
1138 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1139 CXXRecordDecl::base_class_iterator());
1140 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1141 Bases = CXXRD->bases();
1142 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1143 SubobjectIsDesignatorContext, Index, StructuredList,
1144 StructuredIndex, TopLevelObject);
1145 } else if (DeclType->isArrayType()) {
1146 llvm::APSInt Zero(
1147 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1148 false);
1149 CheckArrayType(Entity, IList, DeclType, Zero,
1150 SubobjectIsDesignatorContext, Index,
1151 StructuredList, StructuredIndex);
1152 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1153 // This type is invalid, issue a diagnostic.
1154 ++Index;
1155 if (!VerifyOnly)
1156 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1157 << DeclType;
1158 hadError = true;
1159 } else if (DeclType->isReferenceType()) {
1160 CheckReferenceType(Entity, IList, DeclType, Index,
1161 StructuredList, StructuredIndex);
1162 } else if (DeclType->isObjCObjectType()) {
1163 if (!VerifyOnly)
1164 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1165 << DeclType;
1166 hadError = true;
1167 } else {
1168 if (!VerifyOnly)
1169 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1170 << DeclType;
1171 hadError = true;
1172 }
1173}
1174
1175void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1176 InitListExpr *IList,
1177 QualType ElemType,
1178 unsigned &Index,
1179 InitListExpr *StructuredList,
1180 unsigned &StructuredIndex) {
1181 Expr *expr = IList->getInit(Index);
1182
1183 if (ElemType->isReferenceType())
1184 return CheckReferenceType(Entity, IList, ElemType, Index,
1185 StructuredList, StructuredIndex);
1186
1187 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1188 if (SubInitList->getNumInits() == 1 &&
1189 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1190 SIF_None) {
1191 expr = SubInitList->getInit(0);
1192 } else if (!SemaRef.getLangOpts().CPlusPlus) {
1193 InitListExpr *InnerStructuredList
1194 = getStructuredSubobjectInit(IList, Index, ElemType,
1195 StructuredList, StructuredIndex,
1196 SubInitList->getSourceRange(), true);
1197 CheckExplicitInitList(Entity, SubInitList, ElemType,
1198 InnerStructuredList);
1199
1200 if (!hadError && !VerifyOnly) {
1201 bool RequiresSecondPass = false;
1202 FillInEmptyInitializations(Entity, InnerStructuredList,
1203 RequiresSecondPass, StructuredList,
1204 StructuredIndex);
1205 if (RequiresSecondPass && !hadError)
1206 FillInEmptyInitializations(Entity, InnerStructuredList,
1207 RequiresSecondPass, StructuredList,
1208 StructuredIndex);
1209 }
1210 ++StructuredIndex;
1211 ++Index;
1212 return;
1213 }
1214 // C++ initialization is handled later.
1215 } else if (isa<ImplicitValueInitExpr>(expr)) {
1216 // This happens during template instantiation when we see an InitListExpr
1217 // that we've already checked once.
1218 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1219, __extension__ __PRETTY_FUNCTION__))
1219 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1219, __extension__ __PRETTY_FUNCTION__))
;
1220 if (!VerifyOnly)
1221 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1222 ++Index;
1223 return;
1224 }
1225
1226 if (SemaRef.getLangOpts().CPlusPlus) {
1227 // C++ [dcl.init.aggr]p2:
1228 // Each member is copy-initialized from the corresponding
1229 // initializer-clause.
1230
1231 // FIXME: Better EqualLoc?
1232 InitializationKind Kind =
1233 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1234 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1235 /*TopLevelOfInitList*/ true);
1236
1237 // C++14 [dcl.init.aggr]p13:
1238 // If the assignment-expression can initialize a member, the member is
1239 // initialized. Otherwise [...] brace elision is assumed
1240 //
1241 // Brace elision is never performed if the element is not an
1242 // assignment-expression.
1243 if (Seq || isa<InitListExpr>(expr)) {
1244 if (!VerifyOnly) {
1245 ExprResult Result =
1246 Seq.Perform(SemaRef, Entity, Kind, expr);
1247 if (Result.isInvalid())
1248 hadError = true;
1249
1250 UpdateStructuredListElement(StructuredList, StructuredIndex,
1251 Result.getAs<Expr>());
1252 } else if (!Seq)
1253 hadError = true;
1254 ++Index;
1255 return;
1256 }
1257
1258 // Fall through for subaggregate initialization
1259 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1260 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1261 return CheckScalarType(Entity, IList, ElemType, Index,
1262 StructuredList, StructuredIndex);
1263 } else if (const ArrayType *arrayType =
1264 SemaRef.Context.getAsArrayType(ElemType)) {
1265 // arrayType can be incomplete if we're initializing a flexible
1266 // array member. There's nothing we can do with the completed
1267 // type here, though.
1268
1269 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1270 if (!VerifyOnly) {
1271 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1272 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1273 }
1274 ++Index;
1275 return;
1276 }
1277
1278 // Fall through for subaggregate initialization.
1279
1280 } else {
1281 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1282, __extension__ __PRETTY_FUNCTION__))
1282 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1282, __extension__ __PRETTY_FUNCTION__))
;
1283
1284 // C99 6.7.8p13:
1285 //
1286 // The initializer for a structure or union object that has
1287 // automatic storage duration shall be either an initializer
1288 // list as described below, or a single expression that has
1289 // compatible structure or union type. In the latter case, the
1290 // initial value of the object, including unnamed members, is
1291 // that of the expression.
1292 ExprResult ExprRes = expr;
1293 if (SemaRef.CheckSingleAssignmentConstraints(
1294 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1295 if (ExprRes.isInvalid())
1296 hadError = true;
1297 else {
1298 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1299 if (ExprRes.isInvalid())
1300 hadError = true;
1301 }
1302 UpdateStructuredListElement(StructuredList, StructuredIndex,
1303 ExprRes.getAs<Expr>());
1304 ++Index;
1305 return;
1306 }
1307 ExprRes.get();
1308 // Fall through for subaggregate initialization
1309 }
1310
1311 // C++ [dcl.init.aggr]p12:
1312 //
1313 // [...] Otherwise, if the member is itself a non-empty
1314 // subaggregate, brace elision is assumed and the initializer is
1315 // considered for the initialization of the first member of
1316 // the subaggregate.
1317 // OpenCL vector initializer is handled elsewhere.
1318 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1319 ElemType->isAggregateType()) {
1320 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1321 StructuredIndex);
1322 ++StructuredIndex;
1323 } else {
1324 if (!VerifyOnly) {
1325 // We cannot initialize this element, so let
1326 // PerformCopyInitialization produce the appropriate diagnostic.
1327 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1328 /*TopLevelOfInitList=*/true);
1329 }
1330 hadError = true;
1331 ++Index;
1332 ++StructuredIndex;
1333 }
1334}
1335
1336void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1337 InitListExpr *IList, QualType DeclType,
1338 unsigned &Index,
1339 InitListExpr *StructuredList,
1340 unsigned &StructuredIndex) {
1341 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1341, __extension__ __PRETTY_FUNCTION__))
;
1342
1343 // As an extension, clang supports complex initializers, which initialize
1344 // a complex number component-wise. When an explicit initializer list for
1345 // a complex number contains two two initializers, this extension kicks in:
1346 // it exepcts the initializer list to contain two elements convertible to
1347 // the element type of the complex type. The first element initializes
1348 // the real part, and the second element intitializes the imaginary part.
1349
1350 if (IList->getNumInits() != 2)
1351 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1352 StructuredIndex);
1353
1354 // This is an extension in C. (The builtin _Complex type does not exist
1355 // in the C++ standard.)
1356 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1357 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1358 << IList->getSourceRange();
1359
1360 // Initialize the complex number.
1361 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1362 InitializedEntity ElementEntity =
1363 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1364
1365 for (unsigned i = 0; i < 2; ++i) {
1366 ElementEntity.setElementIndex(Index);
1367 CheckSubElementType(ElementEntity, IList, elementType, Index,
1368 StructuredList, StructuredIndex);
1369 }
1370}
1371
1372void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1373 InitListExpr *IList, QualType DeclType,
1374 unsigned &Index,
1375 InitListExpr *StructuredList,
1376 unsigned &StructuredIndex) {
1377 if (Index >= IList->getNumInits()) {
1378 if (!VerifyOnly)
1379 SemaRef.Diag(IList->getLocStart(),
1380 SemaRef.getLangOpts().CPlusPlus11 ?
1381 diag::warn_cxx98_compat_empty_scalar_initializer :
1382 diag::err_empty_scalar_initializer)
1383 << IList->getSourceRange();
1384 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1385 ++Index;
1386 ++StructuredIndex;
1387 return;
1388 }
1389
1390 Expr *expr = IList->getInit(Index);
1391 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1392 // FIXME: This is invalid, and accepting it causes overload resolution
1393 // to pick the wrong overload in some corner cases.
1394 if (!VerifyOnly)
1395 SemaRef.Diag(SubIList->getLocStart(),
1396 diag::ext_many_braces_around_scalar_init)
1397 << SubIList->getSourceRange();
1398
1399 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1400 StructuredIndex);
1401 return;
1402 } else if (isa<DesignatedInitExpr>(expr)) {
1403 if (!VerifyOnly)
1404 SemaRef.Diag(expr->getLocStart(),
1405 diag::err_designator_for_scalar_init)
1406 << DeclType << expr->getSourceRange();
1407 hadError = true;
1408 ++Index;
1409 ++StructuredIndex;
1410 return;
1411 }
1412
1413 if (VerifyOnly) {
1414 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1415 hadError = true;
1416 ++Index;
1417 return;
1418 }
1419
1420 ExprResult Result =
1421 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1422 /*TopLevelOfInitList=*/true);
1423
1424 Expr *ResultExpr = nullptr;
1425
1426 if (Result.isInvalid())
1427 hadError = true; // types weren't compatible.
1428 else {
1429 ResultExpr = Result.getAs<Expr>();
1430
1431 if (ResultExpr != expr) {
1432 // The type was promoted, update initializer list.
1433 IList->setInit(Index, ResultExpr);
1434 }
1435 }
1436 if (hadError)
1437 ++StructuredIndex;
1438 else
1439 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1440 ++Index;
1441}
1442
1443void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1444 InitListExpr *IList, QualType DeclType,
1445 unsigned &Index,
1446 InitListExpr *StructuredList,
1447 unsigned &StructuredIndex) {
1448 if (Index >= IList->getNumInits()) {
1449 // FIXME: It would be wonderful if we could point at the actual member. In
1450 // general, it would be useful to pass location information down the stack,
1451 // so that we know the location (or decl) of the "current object" being
1452 // initialized.
1453 if (!VerifyOnly)
1454 SemaRef.Diag(IList->getLocStart(),
1455 diag::err_init_reference_member_uninitialized)
1456 << DeclType
1457 << IList->getSourceRange();
1458 hadError = true;
1459 ++Index;
1460 ++StructuredIndex;
1461 return;
1462 }
1463
1464 Expr *expr = IList->getInit(Index);
1465 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1466 if (!VerifyOnly)
1467 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1468 << DeclType << IList->getSourceRange();
1469 hadError = true;
1470 ++Index;
1471 ++StructuredIndex;
1472 return;
1473 }
1474
1475 if (VerifyOnly) {
1476 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1477 hadError = true;
1478 ++Index;
1479 return;
1480 }
1481
1482 ExprResult Result =
1483 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1484 /*TopLevelOfInitList=*/true);
1485
1486 if (Result.isInvalid())
1487 hadError = true;
1488
1489 expr = Result.getAs<Expr>();
1490 IList->setInit(Index, expr);
1491
1492 if (hadError)
1493 ++StructuredIndex;
1494 else
1495 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1496 ++Index;
1497}
1498
1499void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1500 InitListExpr *IList, QualType DeclType,
1501 unsigned &Index,
1502 InitListExpr *StructuredList,
1503 unsigned &StructuredIndex) {
1504 const VectorType *VT = DeclType->getAs<VectorType>();
1505 unsigned maxElements = VT->getNumElements();
1506 unsigned numEltsInit = 0;
1507 QualType elementType = VT->getElementType();
1508
1509 if (Index >= IList->getNumInits()) {
1510 // Make sure the element type can be value-initialized.
1511 if (VerifyOnly)
1512 CheckEmptyInitializable(
1513 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1514 IList->getLocEnd());
1515 return;
1516 }
1517
1518 if (!SemaRef.getLangOpts().OpenCL) {
1519 // If the initializing element is a vector, try to copy-initialize
1520 // instead of breaking it apart (which is doomed to failure anyway).
1521 Expr *Init = IList->getInit(Index);
1522 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1523 if (VerifyOnly) {
1524 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1525 hadError = true;
1526 ++Index;
1527 return;
1528 }
1529
1530 ExprResult Result =
1531 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1532 /*TopLevelOfInitList=*/true);
1533
1534 Expr *ResultExpr = nullptr;
1535 if (Result.isInvalid())
1536 hadError = true; // types weren't compatible.
1537 else {
1538 ResultExpr = Result.getAs<Expr>();
1539
1540 if (ResultExpr != Init) {
1541 // The type was promoted, update initializer list.
1542 IList->setInit(Index, ResultExpr);
1543 }
1544 }
1545 if (hadError)
1546 ++StructuredIndex;
1547 else
1548 UpdateStructuredListElement(StructuredList, StructuredIndex,
1549 ResultExpr);
1550 ++Index;
1551 return;
1552 }
1553
1554 InitializedEntity ElementEntity =
1555 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1556
1557 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1558 // Don't attempt to go past the end of the init list
1559 if (Index >= IList->getNumInits()) {
1560 if (VerifyOnly)
1561 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1562 break;
1563 }
1564
1565 ElementEntity.setElementIndex(Index);
1566 CheckSubElementType(ElementEntity, IList, elementType, Index,
1567 StructuredList, StructuredIndex);
1568 }
1569
1570 if (VerifyOnly)
1571 return;
1572
1573 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1574 const VectorType *T = Entity.getType()->getAs<VectorType>();
1575 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1576 T->getVectorKind() == VectorType::NeonPolyVector)) {
1577 // The ability to use vector initializer lists is a GNU vector extension
1578 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1579 // endian machines it works fine, however on big endian machines it
1580 // exhibits surprising behaviour:
1581 //
1582 // uint32x2_t x = {42, 64};
1583 // return vget_lane_u32(x, 0); // Will return 64.
1584 //
1585 // Because of this, explicitly call out that it is non-portable.
1586 //
1587 SemaRef.Diag(IList->getLocStart(),
1588 diag::warn_neon_vector_initializer_non_portable);
1589
1590 const char *typeCode;
1591 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1592
1593 if (elementType->isFloatingType())
1594 typeCode = "f";
1595 else if (elementType->isSignedIntegerType())
1596 typeCode = "s";
1597 else if (elementType->isUnsignedIntegerType())
1598 typeCode = "u";
1599 else
1600 llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 1600)
;
1601
1602 SemaRef.Diag(IList->getLocStart(),
1603 SemaRef.Context.getTypeSize(VT) > 64 ?
1604 diag::note_neon_vector_initializer_non_portable_q :
1605 diag::note_neon_vector_initializer_non_portable)
1606 << typeCode << typeSize;
1607 }
1608
1609 return;
1610 }
1611
1612 InitializedEntity ElementEntity =
1613 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1614
1615 // OpenCL initializers allows vectors to be constructed from vectors.
1616 for (unsigned i = 0; i < maxElements; ++i) {
1617 // Don't attempt to go past the end of the init list
1618 if (Index >= IList->getNumInits())
1619 break;
1620
1621 ElementEntity.setElementIndex(Index);
1622
1623 QualType IType = IList->getInit(Index)->getType();
1624 if (!IType->isVectorType()) {
1625 CheckSubElementType(ElementEntity, IList, elementType, Index,
1626 StructuredList, StructuredIndex);
1627 ++numEltsInit;
1628 } else {
1629 QualType VecType;
1630 const VectorType *IVT = IType->getAs<VectorType>();
1631 unsigned numIElts = IVT->getNumElements();
1632
1633 if (IType->isExtVectorType())
1634 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1635 else
1636 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1637 IVT->getVectorKind());
1638 CheckSubElementType(ElementEntity, IList, VecType, Index,
1639 StructuredList, StructuredIndex);
1640 numEltsInit += numIElts;
1641 }
1642 }
1643
1644 // OpenCL requires all elements to be initialized.
1645 if (numEltsInit != maxElements) {
1646 if (!VerifyOnly)
1647 SemaRef.Diag(IList->getLocStart(),
1648 diag::err_vector_incorrect_num_initializers)
1649 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1650 hadError = true;
1651 }
1652}
1653
1654void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1655 InitListExpr *IList, QualType &DeclType,
1656 llvm::APSInt elementIndex,
1657 bool SubobjectIsDesignatorContext,
1658 unsigned &Index,
1659 InitListExpr *StructuredList,
1660 unsigned &StructuredIndex) {
1661 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1662
1663 // Check for the special-case of initializing an array with a string.
1664 if (Index < IList->getNumInits()) {
1665 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1666 SIF_None) {
1667 // We place the string literal directly into the resulting
1668 // initializer list. This is the only place where the structure
1669 // of the structured initializer list doesn't match exactly,
1670 // because doing so would involve allocating one character
1671 // constant for each string.
1672 if (!VerifyOnly) {
1673 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1674 UpdateStructuredListElement(StructuredList, StructuredIndex,
1675 IList->getInit(Index));
1676 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1677 }
1678 ++Index;
1679 return;
1680 }
1681 }
1682 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1683 // Check for VLAs; in standard C it would be possible to check this
1684 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1685 // them in all sorts of strange places).
1686 if (!VerifyOnly)
1687 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1688 diag::err_variable_object_no_init)
1689 << VAT->getSizeExpr()->getSourceRange();
1690 hadError = true;
1691 ++Index;
1692 ++StructuredIndex;
1693 return;
1694 }
1695
1696 // We might know the maximum number of elements in advance.
1697 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1698 elementIndex.isUnsigned());
1699 bool maxElementsKnown = false;
1700 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1701 maxElements = CAT->getSize();
1702 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1703 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1704 maxElementsKnown = true;
1705 }
1706
1707 QualType elementType = arrayType->getElementType();
1708 while (Index < IList->getNumInits()) {
1709 Expr *Init = IList->getInit(Index);
1710 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1711 // If we're not the subobject that matches up with the '{' for
1712 // the designator, we shouldn't be handling the
1713 // designator. Return immediately.
1714 if (!SubobjectIsDesignatorContext)
1715 return;
1716
1717 // Handle this designated initializer. elementIndex will be
1718 // updated to be the next array element we'll initialize.
1719 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1720 DeclType, nullptr, &elementIndex, Index,
1721 StructuredList, StructuredIndex, true,
1722 false)) {
1723 hadError = true;
1724 continue;
1725 }
1726
1727 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1728 maxElements = maxElements.extend(elementIndex.getBitWidth());
1729 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1730 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1731 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1732
1733 // If the array is of incomplete type, keep track of the number of
1734 // elements in the initializer.
1735 if (!maxElementsKnown && elementIndex > maxElements)
1736 maxElements = elementIndex;
1737
1738 continue;
1739 }
1740
1741 // If we know the maximum number of elements, and we've already
1742 // hit it, stop consuming elements in the initializer list.
1743 if (maxElementsKnown && elementIndex == maxElements)
1744 break;
1745
1746 InitializedEntity ElementEntity =
1747 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1748 Entity);
1749 // Check this element.
1750 CheckSubElementType(ElementEntity, IList, elementType, Index,
1751 StructuredList, StructuredIndex);
1752 ++elementIndex;
1753
1754 // If the array is of incomplete type, keep track of the number of
1755 // elements in the initializer.
1756 if (!maxElementsKnown && elementIndex > maxElements)
1757 maxElements = elementIndex;
1758 }
1759 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1760 // If this is an incomplete array type, the actual type needs to
1761 // be calculated here.
1762 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1763 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1764 // Sizing an array implicitly to zero is not allowed by ISO C,
1765 // but is supported by GNU.
1766 SemaRef.Diag(IList->getLocStart(),
1767 diag::ext_typecheck_zero_array_size);
1768 }
1769
1770 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1771 ArrayType::Normal, 0);
1772 }
1773 if (!hadError && VerifyOnly) {
1774 // If there are any members of the array that get value-initialized, check
1775 // that is possible. That happens if we know the bound and don't have
1776 // enough elements, or if we're performing an array new with an unknown
1777 // bound.
1778 // FIXME: This needs to detect holes left by designated initializers too.
1779 if ((maxElementsKnown && elementIndex < maxElements) ||
1780 Entity.isVariableLengthArrayNew())
1781 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1782 SemaRef.Context, 0, Entity),
1783 IList->getLocEnd());
1784 }
1785}
1786
1787bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1788 Expr *InitExpr,
1789 FieldDecl *Field,
1790 bool TopLevelObject) {
1791 // Handle GNU flexible array initializers.
1792 unsigned FlexArrayDiag;
1793 if (isa<InitListExpr>(InitExpr) &&
1794 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1795 // Empty flexible array init always allowed as an extension
1796 FlexArrayDiag = diag::ext_flexible_array_init;
1797 } else if (SemaRef.getLangOpts().CPlusPlus) {
1798 // Disallow flexible array init in C++; it is not required for gcc
1799 // compatibility, and it needs work to IRGen correctly in general.
1800 FlexArrayDiag = diag::err_flexible_array_init;
1801 } else if (!TopLevelObject) {
1802 // Disallow flexible array init on non-top-level object
1803 FlexArrayDiag = diag::err_flexible_array_init;
1804 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1805 // Disallow flexible array init on anything which is not a variable.
1806 FlexArrayDiag = diag::err_flexible_array_init;
1807 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1808 // Disallow flexible array init on local variables.
1809 FlexArrayDiag = diag::err_flexible_array_init;
1810 } else {
1811 // Allow other cases.
1812 FlexArrayDiag = diag::ext_flexible_array_init;
1813 }
1814
1815 if (!VerifyOnly) {
1816 SemaRef.Diag(InitExpr->getLocStart(),
1817 FlexArrayDiag)
1818 << InitExpr->getLocStart();
1819 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1820 << Field;
1821 }
1822
1823 return FlexArrayDiag != diag::ext_flexible_array_init;
1824}
1825
1826void InitListChecker::CheckStructUnionTypes(
1827 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1828 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1829 bool SubobjectIsDesignatorContext, unsigned &Index,
1830 InitListExpr *StructuredList, unsigned &StructuredIndex,
1831 bool TopLevelObject) {
1832 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1833
1834 // If the record is invalid, some of it's members are invalid. To avoid
1835 // confusion, we forgo checking the intializer for the entire record.
1836 if (structDecl->isInvalidDecl()) {
1837 // Assume it was supposed to consume a single initializer.
1838 ++Index;
1839 hadError = true;
1840 return;
1841 }
1842
1843 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1844 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1845
1846 // If there's a default initializer, use it.
1847 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1848 if (VerifyOnly)
1849 return;
1850 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1851 Field != FieldEnd; ++Field) {
1852 if (Field->hasInClassInitializer()) {
1853 StructuredList->setInitializedFieldInUnion(*Field);
1854 // FIXME: Actually build a CXXDefaultInitExpr?
1855 return;
1856 }
1857 }
1858 }
1859
1860 // Value-initialize the first member of the union that isn't an unnamed
1861 // bitfield.
1862 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1863 Field != FieldEnd; ++Field) {
1864 if (!Field->isUnnamedBitfield()) {
1865 if (VerifyOnly)
1866 CheckEmptyInitializable(
1867 InitializedEntity::InitializeMember(*Field, &Entity),
1868 IList->getLocEnd());
1869 else
1870 StructuredList->setInitializedFieldInUnion(*Field);
1871 break;
1872 }
1873 }
1874 return;
1875 }
1876
1877 bool InitializedSomething = false;
1878
1879 // If we have any base classes, they are initialized prior to the fields.
1880 for (auto &Base : Bases) {
1881 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1882 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1883
1884 // Designated inits always initialize fields, so if we see one, all
1885 // remaining base classes have no explicit initializer.
1886 if (Init && isa<DesignatedInitExpr>(Init))
1887 Init = nullptr;
1888
1889 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1890 SemaRef.Context, &Base, false, &Entity);
1891 if (Init) {
1892 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1893 StructuredList, StructuredIndex);
1894 InitializedSomething = true;
1895 } else if (VerifyOnly) {
1896 CheckEmptyInitializable(BaseEntity, InitLoc);
1897 }
1898 }
1899
1900 // If structDecl is a forward declaration, this loop won't do
1901 // anything except look at designated initializers; That's okay,
1902 // because an error should get printed out elsewhere. It might be
1903 // worthwhile to skip over the rest of the initializer, though.
1904 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1905 RecordDecl::field_iterator FieldEnd = RD->field_end();
1906 bool CheckForMissingFields =
1907 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1908
1909 while (Index < IList->getNumInits()) {
1910 Expr *Init = IList->getInit(Index);
1911
1912 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1913 // If we're not the subobject that matches up with the '{' for
1914 // the designator, we shouldn't be handling the
1915 // designator. Return immediately.
1916 if (!SubobjectIsDesignatorContext)
1917 return;
1918
1919 // Handle this designated initializer. Field will be updated to
1920 // the next field that we'll be initializing.
1921 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1922 DeclType, &Field, nullptr, Index,
1923 StructuredList, StructuredIndex,
1924 true, TopLevelObject))
1925 hadError = true;
1926
1927 InitializedSomething = true;
1928
1929 // Disable check for missing fields when designators are used.
1930 // This matches gcc behaviour.
1931 CheckForMissingFields = false;
1932 continue;
1933 }
1934
1935 if (Field == FieldEnd) {
1936 // We've run out of fields. We're done.
1937 break;
1938 }
1939
1940 // We've already initialized a member of a union. We're done.
1941 if (InitializedSomething && DeclType->isUnionType())
1942 break;
1943
1944 // If we've hit the flexible array member at the end, we're done.
1945 if (Field->getType()->isIncompleteArrayType())
1946 break;
1947
1948 if (Field->isUnnamedBitfield()) {
1949 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1950 ++Field;
1951 continue;
1952 }
1953
1954 // Make sure we can use this declaration.
1955 bool InvalidUse;
1956 if (VerifyOnly)
1957 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
1958 else
1959 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1960 IList->getInit(Index)->getLocStart());
1961 if (InvalidUse) {
1962 ++Index;
1963 ++Field;
1964 hadError = true;
1965 continue;
1966 }
1967
1968 InitializedEntity MemberEntity =
1969 InitializedEntity::InitializeMember(*Field, &Entity);
1970 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1971 StructuredList, StructuredIndex);
1972 InitializedSomething = true;
1973
1974 if (DeclType->isUnionType() && !VerifyOnly) {
1975 // Initialize the first field within the union.
1976 StructuredList->setInitializedFieldInUnion(*Field);
1977 }
1978
1979 ++Field;
1980 }
1981
1982 // Emit warnings for missing struct field initializers.
1983 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1984 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1985 !DeclType->isUnionType()) {
1986 // It is possible we have one or more unnamed bitfields remaining.
1987 // Find first (if any) named field and emit warning.
1988 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1989 it != end; ++it) {
1990 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1991 SemaRef.Diag(IList->getSourceRange().getEnd(),
1992 diag::warn_missing_field_initializers) << *it;
1993 break;
1994 }
1995 }
1996 }
1997
1998 // Check that any remaining fields can be value-initialized.
1999 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2000 !Field->getType()->isIncompleteArrayType()) {
2001 // FIXME: Should check for holes left by designated initializers too.
2002 for (; Field != FieldEnd && !hadError; ++Field) {
2003 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2004 CheckEmptyInitializable(
2005 InitializedEntity::InitializeMember(*Field, &Entity),
2006 IList->getLocEnd());
2007 }
2008 }
2009
2010 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2011 Index >= IList->getNumInits())
2012 return;
2013
2014 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2015 TopLevelObject)) {
2016 hadError = true;
2017 ++Index;
2018 return;
2019 }
2020
2021 InitializedEntity MemberEntity =
2022 InitializedEntity::InitializeMember(*Field, &Entity);
2023
2024 if (isa<InitListExpr>(IList->getInit(Index)))
2025 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2026 StructuredList, StructuredIndex);
2027 else
2028 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2029 StructuredList, StructuredIndex);
2030}
2031
2032/// Expand a field designator that refers to a member of an
2033/// anonymous struct or union into a series of field designators that
2034/// refers to the field within the appropriate subobject.
2035///
2036static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2037 DesignatedInitExpr *DIE,
2038 unsigned DesigIdx,
2039 IndirectFieldDecl *IndirectField) {
2040 typedef DesignatedInitExpr::Designator Designator;
2041
2042 // Build the replacement designators.
2043 SmallVector<Designator, 4> Replacements;
2044 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2045 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2046 if (PI + 1 == PE)
2047 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2048 DIE->getDesignator(DesigIdx)->getDotLoc(),
2049 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2050 else
2051 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2052 SourceLocation(), SourceLocation()));
2053 assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(*PI)", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2053, __extension__ __PRETTY_FUNCTION__))
;
2054 Replacements.back().setField(cast<FieldDecl>(*PI));
2055 }
2056
2057 // Expand the current designator into the set of replacement
2058 // designators, so we have a full subobject path down to where the
2059 // member of the anonymous struct/union is actually stored.
2060 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2061 &Replacements[0] + Replacements.size());
2062}
2063
2064static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2065 DesignatedInitExpr *DIE) {
2066 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2067 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2068 for (unsigned I = 0; I < NumIndexExprs; ++I)
2069 IndexExprs[I] = DIE->getSubExpr(I + 1);
2070 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2071 IndexExprs,
2072 DIE->getEqualOrColonLoc(),
2073 DIE->usesGNUSyntax(), DIE->getInit());
2074}
2075
2076namespace {
2077
2078// Callback to only accept typo corrections that are for field members of
2079// the given struct or union.
2080class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2081 public:
2082 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2083 : Record(RD) {}
2084
2085 bool ValidateCandidate(const TypoCorrection &candidate) override {
2086 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2087 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2088 }
2089
2090 private:
2091 RecordDecl *Record;
2092};
2093
2094} // end anonymous namespace
2095
2096/// Check the well-formedness of a C99 designated initializer.
2097///
2098/// Determines whether the designated initializer @p DIE, which
2099/// resides at the given @p Index within the initializer list @p
2100/// IList, is well-formed for a current object of type @p DeclType
2101/// (C99 6.7.8). The actual subobject that this designator refers to
2102/// within the current subobject is returned in either
2103/// @p NextField or @p NextElementIndex (whichever is appropriate).
2104///
2105/// @param IList The initializer list in which this designated
2106/// initializer occurs.
2107///
2108/// @param DIE The designated initializer expression.
2109///
2110/// @param DesigIdx The index of the current designator.
2111///
2112/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2113/// into which the designation in @p DIE should refer.
2114///
2115/// @param NextField If non-NULL and the first designator in @p DIE is
2116/// a field, this will be set to the field declaration corresponding
2117/// to the field named by the designator.
2118///
2119/// @param NextElementIndex If non-NULL and the first designator in @p
2120/// DIE is an array designator or GNU array-range designator, this
2121/// will be set to the last index initialized by this designator.
2122///
2123/// @param Index Index into @p IList where the designated initializer
2124/// @p DIE occurs.
2125///
2126/// @param StructuredList The initializer list expression that
2127/// describes all of the subobject initializers in the order they'll
2128/// actually be initialized.
2129///
2130/// @returns true if there was an error, false otherwise.
2131bool
2132InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2133 InitListExpr *IList,
2134 DesignatedInitExpr *DIE,
2135 unsigned DesigIdx,
2136 QualType &CurrentObjectType,
2137 RecordDecl::field_iterator *NextField,
2138 llvm::APSInt *NextElementIndex,
2139 unsigned &Index,
2140 InitListExpr *StructuredList,
2141 unsigned &StructuredIndex,
2142 bool FinishSubobjectInit,
2143 bool TopLevelObject) {
2144 if (DesigIdx == DIE->size()) {
2145 // Check the actual initialization for the designated object type.
2146 bool prevHadError = hadError;
2147
2148 // Temporarily remove the designator expression from the
2149 // initializer list that the child calls see, so that we don't try
2150 // to re-process the designator.
2151 unsigned OldIndex = Index;
2152 IList->setInit(OldIndex, DIE->getInit());
2153
2154 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2155 StructuredList, StructuredIndex);
2156
2157 // Restore the designated initializer expression in the syntactic
2158 // form of the initializer list.
2159 if (IList->getInit(OldIndex) != DIE->getInit())
2160 DIE->setInit(IList->getInit(OldIndex));
2161 IList->setInit(OldIndex, DIE);
2162
2163 return hadError && !prevHadError;
2164 }
2165
2166 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2167 bool IsFirstDesignator = (DesigIdx == 0);
2168 if (!VerifyOnly) {
2169 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2170, __extension__ __PRETTY_FUNCTION__))
2170 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2170, __extension__ __PRETTY_FUNCTION__))
;
2171
2172 // Determine the structural initializer list that corresponds to the
2173 // current subobject.
2174 if (IsFirstDesignator)
2175 StructuredList = SyntacticToSemantic.lookup(IList);
2176 else {
2177 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2178 StructuredList->getInit(StructuredIndex) : nullptr;
2179 if (!ExistingInit && StructuredList->hasArrayFiller())
2180 ExistingInit = StructuredList->getArrayFiller();
2181
2182 if (!ExistingInit)
2183 StructuredList =
2184 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2185 StructuredList, StructuredIndex,
2186 SourceRange(D->getLocStart(),
2187 DIE->getLocEnd()));
2188 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2189 StructuredList = Result;
2190 else {
2191 if (DesignatedInitUpdateExpr *E =
2192 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2193 StructuredList = E->getUpdater();
2194 else {
2195 DesignatedInitUpdateExpr *DIUE =
2196 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2197 D->getLocStart(), ExistingInit,
2198 DIE->getLocEnd());
2199 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2200 StructuredList = DIUE->getUpdater();
2201 }
2202
2203 // We need to check on source range validity because the previous
2204 // initializer does not have to be an explicit initializer. e.g.,
2205 //
2206 // struct P { int a, b; };
2207 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2208 //
2209 // There is an overwrite taking place because the first braced initializer
2210 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2211 if (ExistingInit->getSourceRange().isValid()) {
2212 // We are creating an initializer list that initializes the
2213 // subobjects of the current object, but there was already an
2214 // initialization that completely initialized the current
2215 // subobject, e.g., by a compound literal:
2216 //
2217 // struct X { int a, b; };
2218 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2219 //
2220 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2221 // designated initializer re-initializes the whole
2222 // subobject [0], overwriting previous initializers.
2223 SemaRef.Diag(D->getLocStart(),
2224 diag::warn_subobject_initializer_overrides)
2225 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2226
2227 SemaRef.Diag(ExistingInit->getLocStart(),
2228 diag::note_previous_initializer)
2229 << /*FIXME:has side effects=*/0
2230 << ExistingInit->getSourceRange();
2231 }
2232 }
2233 }
2234 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2234, __extension__ __PRETTY_FUNCTION__))
;
2235 }
2236
2237 if (D->isFieldDesignator()) {
2238 // C99 6.7.8p7:
2239 //
2240 // If a designator has the form
2241 //
2242 // . identifier
2243 //
2244 // then the current object (defined below) shall have
2245 // structure or union type and the identifier shall be the
2246 // name of a member of that type.
2247 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2248 if (!RT) {
2249 SourceLocation Loc = D->getDotLoc();
2250 if (Loc.isInvalid())
2251 Loc = D->getFieldLoc();
2252 if (!VerifyOnly)
2253 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2254 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2255 ++Index;
2256 return true;
2257 }
2258
2259 FieldDecl *KnownField = D->getField();
2260 if (!KnownField) {
2261 IdentifierInfo *FieldName = D->getFieldName();
2262 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2263 for (NamedDecl *ND : Lookup) {
2264 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2265 KnownField = FD;
2266 break;
2267 }
2268 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2269 // In verify mode, don't modify the original.
2270 if (VerifyOnly)
2271 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2272 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2273 D = DIE->getDesignator(DesigIdx);
2274 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2275 break;
2276 }
2277 }
2278 if (!KnownField) {
2279 if (VerifyOnly) {
2280 ++Index;
2281 return true; // No typo correction when just trying this out.
2282 }
2283
2284 // Name lookup found something, but it wasn't a field.
2285 if (!Lookup.empty()) {
2286 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2287 << FieldName;
2288 SemaRef.Diag(Lookup.front()->getLocation(),
2289 diag::note_field_designator_found);
2290 ++Index;
2291 return true;
2292 }
2293
2294 // Name lookup didn't find anything.
2295 // Determine whether this was a typo for another field name.
2296 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2297 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2298 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2299 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2300 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2301 SemaRef.diagnoseTypo(
2302 Corrected,
2303 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2304 << FieldName << CurrentObjectType);
2305 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2306 hadError = true;
2307 } else {
2308 // Typo correction didn't find anything.
2309 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2310 << FieldName << CurrentObjectType;
2311 ++Index;
2312 return true;
2313 }
2314 }
2315 }
2316
2317 unsigned FieldIndex = 0;
2318
2319 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2320 FieldIndex = CXXRD->getNumBases();
2321
2322 for (auto *FI : RT->getDecl()->fields()) {
2323 if (FI->isUnnamedBitfield())
2324 continue;
2325 if (declaresSameEntity(KnownField, FI)) {
2326 KnownField = FI;
2327 break;
2328 }
2329 ++FieldIndex;
2330 }
2331
2332 RecordDecl::field_iterator Field =
2333 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2334
2335 // All of the fields of a union are located at the same place in
2336 // the initializer list.
2337 if (RT->getDecl()->isUnion()) {
2338 FieldIndex = 0;
2339 if (!VerifyOnly) {
2340 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2341 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2342 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2343, __extension__ __PRETTY_FUNCTION__))
2343 && "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2343, __extension__ __PRETTY_FUNCTION__))
;
2344
2345 Expr *ExistingInit = StructuredList->getInit(0);
2346 if (ExistingInit) {
2347 // We're about to throw away an initializer, emit warning.
2348 SemaRef.Diag(D->getFieldLoc(),
2349 diag::warn_initializer_overrides)
2350 << D->getSourceRange();
2351 SemaRef.Diag(ExistingInit->getLocStart(),
2352 diag::note_previous_initializer)
2353 << /*FIXME:has side effects=*/0
2354 << ExistingInit->getSourceRange();
2355 }
2356
2357 // remove existing initializer
2358 StructuredList->resizeInits(SemaRef.Context, 0);
2359 StructuredList->setInitializedFieldInUnion(nullptr);
2360 }
2361
2362 StructuredList->setInitializedFieldInUnion(*Field);
2363 }
2364 }
2365
2366 // Make sure we can use this declaration.
2367 bool InvalidUse;
2368 if (VerifyOnly)
2369 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2370 else
2371 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2372 if (InvalidUse) {
2373 ++Index;
2374 return true;
2375 }
2376
2377 if (!VerifyOnly) {
2378 // Update the designator with the field declaration.
2379 D->setField(*Field);
2380
2381 // Make sure that our non-designated initializer list has space
2382 // for a subobject corresponding to this field.
2383 if (FieldIndex >= StructuredList->getNumInits())
2384 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2385 }
2386
2387 // This designator names a flexible array member.
2388 if (Field->getType()->isIncompleteArrayType()) {
2389 bool Invalid = false;
2390 if ((DesigIdx + 1) != DIE->size()) {
2391 // We can't designate an object within the flexible array
2392 // member (because GCC doesn't allow it).
2393 if (!VerifyOnly) {
2394 DesignatedInitExpr::Designator *NextD
2395 = DIE->getDesignator(DesigIdx + 1);
2396 SemaRef.Diag(NextD->getLocStart(),
2397 diag::err_designator_into_flexible_array_member)
2398 << SourceRange(NextD->getLocStart(),
2399 DIE->getLocEnd());
2400 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2401 << *Field;
2402 }
2403 Invalid = true;
2404 }
2405
2406 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2407 !isa<StringLiteral>(DIE->getInit())) {
2408 // The initializer is not an initializer list.
2409 if (!VerifyOnly) {
2410 SemaRef.Diag(DIE->getInit()->getLocStart(),
2411 diag::err_flexible_array_init_needs_braces)
2412 << DIE->getInit()->getSourceRange();
2413 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2414 << *Field;
2415 }
2416 Invalid = true;
2417 }
2418
2419 // Check GNU flexible array initializer.
2420 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2421 TopLevelObject))
2422 Invalid = true;
2423
2424 if (Invalid) {
2425 ++Index;
2426 return true;
2427 }
2428
2429 // Initialize the array.
2430 bool prevHadError = hadError;
2431 unsigned newStructuredIndex = FieldIndex;
2432 unsigned OldIndex = Index;
2433 IList->setInit(Index, DIE->getInit());
2434
2435 InitializedEntity MemberEntity =
2436 InitializedEntity::InitializeMember(*Field, &Entity);
2437 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2438 StructuredList, newStructuredIndex);
2439
2440 IList->setInit(OldIndex, DIE);
2441 if (hadError && !prevHadError) {
2442 ++Field;
2443 ++FieldIndex;
2444 if (NextField)
2445 *NextField = Field;
2446 StructuredIndex = FieldIndex;
2447 return true;
2448 }
2449 } else {
2450 // Recurse to check later designated subobjects.
2451 QualType FieldType = Field->getType();
2452 unsigned newStructuredIndex = FieldIndex;
2453
2454 InitializedEntity MemberEntity =
2455 InitializedEntity::InitializeMember(*Field, &Entity);
2456 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2457 FieldType, nullptr, nullptr, Index,
2458 StructuredList, newStructuredIndex,
2459 FinishSubobjectInit, false))
2460 return true;
2461 }
2462
2463 // Find the position of the next field to be initialized in this
2464 // subobject.
2465 ++Field;
2466 ++FieldIndex;
2467
2468 // If this the first designator, our caller will continue checking
2469 // the rest of this struct/class/union subobject.
2470 if (IsFirstDesignator) {
2471 if (NextField)
2472 *NextField = Field;
2473 StructuredIndex = FieldIndex;
2474 return false;
2475 }
2476
2477 if (!FinishSubobjectInit)
2478 return false;
2479
2480 // We've already initialized something in the union; we're done.
2481 if (RT->getDecl()->isUnion())
2482 return hadError;
2483
2484 // Check the remaining fields within this class/struct/union subobject.
2485 bool prevHadError = hadError;
2486
2487 auto NoBases =
2488 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2489 CXXRecordDecl::base_class_iterator());
2490 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2491 false, Index, StructuredList, FieldIndex);
2492 return hadError && !prevHadError;
2493 }
2494
2495 // C99 6.7.8p6:
2496 //
2497 // If a designator has the form
2498 //
2499 // [ constant-expression ]
2500 //
2501 // then the current object (defined below) shall have array
2502 // type and the expression shall be an integer constant
2503 // expression. If the array is of unknown size, any
2504 // nonnegative value is valid.
2505 //
2506 // Additionally, cope with the GNU extension that permits
2507 // designators of the form
2508 //
2509 // [ constant-expression ... constant-expression ]
2510 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2511 if (!AT) {
2512 if (!VerifyOnly)
2513 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2514 << CurrentObjectType;
2515 ++Index;
2516 return true;
2517 }
2518
2519 Expr *IndexExpr = nullptr;
2520 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2521 if (D->isArrayDesignator()) {
2522 IndexExpr = DIE->getArrayIndex(*D);
2523 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2524 DesignatedEndIndex = DesignatedStartIndex;
2525 } else {
2526 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2526, __extension__ __PRETTY_FUNCTION__))
;
2527
2528 DesignatedStartIndex =
2529 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2530 DesignatedEndIndex =
2531 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2532 IndexExpr = DIE->getArrayRangeEnd(*D);
2533
2534 // Codegen can't handle evaluating array range designators that have side
2535 // effects, because we replicate the AST value for each initialized element.
2536 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2537 // elements with something that has a side effect, so codegen can emit an
2538 // "error unsupported" error instead of miscompiling the app.
2539 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2540 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2541 FullyStructuredList->sawArrayRangeDesignator();
2542 }
2543
2544 if (isa<ConstantArrayType>(AT)) {
2545 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2546 DesignatedStartIndex
2547 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2548 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2549 DesignatedEndIndex
2550 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2551 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2552 if (DesignatedEndIndex >= MaxElements) {
2553 if (!VerifyOnly)
2554 SemaRef.Diag(IndexExpr->getLocStart(),
2555 diag::err_array_designator_too_large)
2556 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2557 << IndexExpr->getSourceRange();
2558 ++Index;
2559 return true;
2560 }
2561 } else {
2562 unsigned DesignatedIndexBitWidth =
2563 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2564 DesignatedStartIndex =
2565 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2566 DesignatedEndIndex =
2567 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2568 DesignatedStartIndex.setIsUnsigned(true);
2569 DesignatedEndIndex.setIsUnsigned(true);
2570 }
2571
2572 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2573 // We're modifying a string literal init; we have to decompose the string
2574 // so we can modify the individual characters.
2575 ASTContext &Context = SemaRef.Context;
2576 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2577
2578 // Compute the character type
2579 QualType CharTy = AT->getElementType();
2580
2581 // Compute the type of the integer literals.
2582 QualType PromotedCharTy = CharTy;
2583 if (CharTy->isPromotableIntegerType())
2584 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2585 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2586
2587 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2588 // Get the length of the string.
2589 uint64_t StrLen = SL->getLength();
2590 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2591 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2592 StructuredList->resizeInits(Context, StrLen);
2593
2594 // Build a literal for each character in the string, and put them into
2595 // the init list.
2596 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2597 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2598 Expr *Init = new (Context) IntegerLiteral(
2599 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2600 if (CharTy != PromotedCharTy)
2601 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2602 Init, nullptr, VK_RValue);
2603 StructuredList->updateInit(Context, i, Init);
2604 }
2605 } else {
2606 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2607 std::string Str;
2608 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2609
2610 // Get the length of the string.
2611 uint64_t StrLen = Str.size();
2612 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2613 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2614 StructuredList->resizeInits(Context, StrLen);
2615
2616 // Build a literal for each character in the string, and put them into
2617 // the init list.
2618 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2619 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2620 Expr *Init = new (Context) IntegerLiteral(
2621 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2622 if (CharTy != PromotedCharTy)
2623 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2624 Init, nullptr, VK_RValue);
2625 StructuredList->updateInit(Context, i, Init);
2626 }
2627 }
2628 }
2629
2630 // Make sure that our non-designated initializer list has space
2631 // for a subobject corresponding to this array element.
2632 if (!VerifyOnly &&
2633 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2634 StructuredList->resizeInits(SemaRef.Context,
2635 DesignatedEndIndex.getZExtValue() + 1);
2636
2637 // Repeatedly perform subobject initializations in the range
2638 // [DesignatedStartIndex, DesignatedEndIndex].
2639
2640 // Move to the next designator
2641 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2642 unsigned OldIndex = Index;
2643
2644 InitializedEntity ElementEntity =
2645 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2646
2647 while (DesignatedStartIndex <= DesignatedEndIndex) {
2648 // Recurse to check later designated subobjects.
2649 QualType ElementType = AT->getElementType();
2650 Index = OldIndex;
2651
2652 ElementEntity.setElementIndex(ElementIndex);
2653 if (CheckDesignatedInitializer(
2654 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2655 nullptr, Index, StructuredList, ElementIndex,
2656 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2657 false))
2658 return true;
2659
2660 // Move to the next index in the array that we'll be initializing.
2661 ++DesignatedStartIndex;
2662 ElementIndex = DesignatedStartIndex.getZExtValue();
2663 }
2664
2665 // If this the first designator, our caller will continue checking
2666 // the rest of this array subobject.
2667 if (IsFirstDesignator) {
2668 if (NextElementIndex)
2669 *NextElementIndex = DesignatedStartIndex;
2670 StructuredIndex = ElementIndex;
2671 return false;
2672 }
2673
2674 if (!FinishSubobjectInit)
2675 return false;
2676
2677 // Check the remaining elements within this array subobject.
2678 bool prevHadError = hadError;
2679 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2680 /*SubobjectIsDesignatorContext=*/false, Index,
2681 StructuredList, ElementIndex);
2682 return hadError && !prevHadError;
2683}
2684
2685// Get the structured initializer list for a subobject of type
2686// @p CurrentObjectType.
2687InitListExpr *
2688InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2689 QualType CurrentObjectType,
2690 InitListExpr *StructuredList,
2691 unsigned StructuredIndex,
2692 SourceRange InitRange,
2693 bool IsFullyOverwritten) {
2694 if (VerifyOnly)
2695 return nullptr; // No structured list in verification-only mode.
2696 Expr *ExistingInit = nullptr;
2697 if (!StructuredList)
2698 ExistingInit = SyntacticToSemantic.lookup(IList);
2699 else if (StructuredIndex < StructuredList->getNumInits())
2700 ExistingInit = StructuredList->getInit(StructuredIndex);
2701
2702 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2703 // There might have already been initializers for subobjects of the current
2704 // object, but a subsequent initializer list will overwrite the entirety
2705 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2706 //
2707 // struct P { char x[6]; };
2708 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2709 //
2710 // The first designated initializer is ignored, and l.x is just "f".
2711 if (!IsFullyOverwritten)
2712 return Result;
2713
2714 if (ExistingInit) {
2715 // We are creating an initializer list that initializes the
2716 // subobjects of the current object, but there was already an
2717 // initialization that completely initialized the current
2718 // subobject, e.g., by a compound literal:
2719 //
2720 // struct X { int a, b; };
2721 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2722 //
2723 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2724 // designated initializer re-initializes the whole
2725 // subobject [0], overwriting previous initializers.
2726 SemaRef.Diag(InitRange.getBegin(),
2727 diag::warn_subobject_initializer_overrides)
2728 << InitRange;
2729 SemaRef.Diag(ExistingInit->getLocStart(),
2730 diag::note_previous_initializer)
2731 << /*FIXME:has side effects=*/0
2732 << ExistingInit->getSourceRange();
2733 }
2734
2735 InitListExpr *Result
2736 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2737 InitRange.getBegin(), None,
2738 InitRange.getEnd());
2739
2740 QualType ResultType = CurrentObjectType;
2741 if (!ResultType->isArrayType())
2742 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2743 Result->setType(ResultType);
2744
2745 // Pre-allocate storage for the structured initializer list.
2746 unsigned NumElements = 0;
2747 unsigned NumInits = 0;
2748 bool GotNumInits = false;
2749 if (!StructuredList) {
2750 NumInits = IList->getNumInits();
2751 GotNumInits = true;
2752 } else if (Index < IList->getNumInits()) {
2753 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2754 NumInits = SubList->getNumInits();
2755 GotNumInits = true;
2756 }
2757 }
2758
2759 if (const ArrayType *AType
2760 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2761 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2762 NumElements = CAType->getSize().getZExtValue();
2763 // Simple heuristic so that we don't allocate a very large
2764 // initializer with many empty entries at the end.
2765 if (GotNumInits && NumElements > NumInits)
2766 NumElements = 0;
2767 }
2768 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2769 NumElements = VType->getNumElements();
2770 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2771 RecordDecl *RDecl = RType->getDecl();
2772 if (RDecl->isUnion())
2773 NumElements = 1;
2774 else
2775 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2776 }
2777
2778 Result->reserveInits(SemaRef.Context, NumElements);
2779
2780 // Link this new initializer list into the structured initializer
2781 // lists.
2782 if (StructuredList)
2783 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2784 else {
2785 Result->setSyntacticForm(IList);
2786 SyntacticToSemantic[IList] = Result;
2787 }
2788
2789 return Result;
2790}
2791
2792/// Update the initializer at index @p StructuredIndex within the
2793/// structured initializer list to the value @p expr.
2794void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2795 unsigned &StructuredIndex,
2796 Expr *expr) {
2797 // No structured initializer list to update
2798 if (!StructuredList)
2799 return;
2800
2801 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2802 StructuredIndex, expr)) {
2803 // This initializer overwrites a previous initializer. Warn.
2804 // We need to check on source range validity because the previous
2805 // initializer does not have to be an explicit initializer.
2806 // struct P { int a, b; };
2807 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2808 // There is an overwrite taking place because the first braced initializer
2809 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2810 if (PrevInit->getSourceRange().isValid()) {
2811 SemaRef.Diag(expr->getLocStart(),
2812 diag::warn_initializer_overrides)
2813 << expr->getSourceRange();
2814
2815 SemaRef.Diag(PrevInit->getLocStart(),
2816 diag::note_previous_initializer)
2817 << /*FIXME:has side effects=*/0
2818 << PrevInit->getSourceRange();
2819 }
2820 }
2821
2822 ++StructuredIndex;
2823}
2824
2825/// Check that the given Index expression is a valid array designator
2826/// value. This is essentially just a wrapper around
2827/// VerifyIntegerConstantExpression that also checks for negative values
2828/// and produces a reasonable diagnostic if there is a
2829/// failure. Returns the index expression, possibly with an implicit cast
2830/// added, on success. If everything went okay, Value will receive the
2831/// value of the constant expression.
2832static ExprResult
2833CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2834 SourceLocation Loc = Index->getLocStart();
2835
2836 // Make sure this is an integer constant expression.
2837 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2838 if (Result.isInvalid())
2839 return Result;
2840
2841 if (Value.isSigned() && Value.isNegative())
2842 return S.Diag(Loc, diag::err_array_designator_negative)
2843 << Value.toString(10) << Index->getSourceRange();
2844
2845 Value.setIsUnsigned(true);
2846 return Result;
2847}
2848
2849ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2850 SourceLocation Loc,
2851 bool GNUSyntax,
2852 ExprResult Init) {
2853 typedef DesignatedInitExpr::Designator ASTDesignator;
2854
2855 bool Invalid = false;
2856 SmallVector<ASTDesignator, 32> Designators;
2857 SmallVector<Expr *, 32> InitExpressions;
2858
2859 // Build designators and check array designator expressions.
2860 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2861 const Designator &D = Desig.getDesignator(Idx);
2862 switch (D.getKind()) {
2863 case Designator::FieldDesignator:
2864 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2865 D.getFieldLoc()));
2866 break;
2867
2868 case Designator::ArrayDesignator: {
2869 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2870 llvm::APSInt IndexValue;
2871 if (!Index->isTypeDependent() && !Index->isValueDependent())
2872 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2873 if (!Index)
2874 Invalid = true;
2875 else {
2876 Designators.push_back(ASTDesignator(InitExpressions.size(),
2877 D.getLBracketLoc(),
2878 D.getRBracketLoc()));
2879 InitExpressions.push_back(Index);
2880 }
2881 break;
2882 }
2883
2884 case Designator::ArrayRangeDesignator: {
2885 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2886 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2887 llvm::APSInt StartValue;
2888 llvm::APSInt EndValue;
2889 bool StartDependent = StartIndex->isTypeDependent() ||
2890 StartIndex->isValueDependent();
2891 bool EndDependent = EndIndex->isTypeDependent() ||
2892 EndIndex->isValueDependent();
2893 if (!StartDependent)
2894 StartIndex =
2895 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2896 if (!EndDependent)
2897 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2898
2899 if (!StartIndex || !EndIndex)
2900 Invalid = true;
2901 else {
2902 // Make sure we're comparing values with the same bit width.
2903 if (StartDependent || EndDependent) {
2904 // Nothing to compute.
2905 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2906 EndValue = EndValue.extend(StartValue.getBitWidth());
2907 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2908 StartValue = StartValue.extend(EndValue.getBitWidth());
2909
2910 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2911 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2912 << StartValue.toString(10) << EndValue.toString(10)
2913 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2914 Invalid = true;
2915 } else {
2916 Designators.push_back(ASTDesignator(InitExpressions.size(),
2917 D.getLBracketLoc(),
2918 D.getEllipsisLoc(),
2919 D.getRBracketLoc()));
2920 InitExpressions.push_back(StartIndex);
2921 InitExpressions.push_back(EndIndex);
2922 }
2923 }
2924 break;
2925 }
2926 }
2927 }
2928
2929 if (Invalid || Init.isInvalid())
2930 return ExprError();
2931
2932 // Clear out the expressions within the designation.
2933 Desig.ClearExprs(*this);
2934
2935 DesignatedInitExpr *DIE
2936 = DesignatedInitExpr::Create(Context,
2937 Designators,
2938 InitExpressions, Loc, GNUSyntax,
2939 Init.getAs<Expr>());
2940
2941 if (!getLangOpts().C99)
2942 Diag(DIE->getLocStart(), diag::ext_designated_init)
2943 << DIE->getSourceRange();
2944
2945 return DIE;
2946}
2947
2948//===----------------------------------------------------------------------===//
2949// Initialization entity
2950//===----------------------------------------------------------------------===//
2951
2952InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2953 const InitializedEntity &Parent)
2954 : Parent(&Parent), Index(Index)
2955{
2956 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2957 Kind = EK_ArrayElement;
2958 Type = AT->getElementType();
2959 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2960 Kind = EK_VectorElement;
2961 Type = VT->getElementType();
2962 } else {
2963 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2964 assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ?
void (0) : __assert_fail ("CT && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 2964, __extension__ __PRETTY_FUNCTION__))
;
2965 Kind = EK_ComplexElement;
2966 Type = CT->getElementType();
2967 }
2968}
2969
2970InitializedEntity
2971InitializedEntity::InitializeBase(ASTContext &Context,
2972 const CXXBaseSpecifier *Base,
2973 bool IsInheritedVirtualBase,
2974 const InitializedEntity *Parent) {
2975 InitializedEntity Result;
2976 Result.Kind = EK_Base;
2977 Result.Parent = Parent;
2978 Result.Base = reinterpret_cast<uintptr_t>(Base);
2979 if (IsInheritedVirtualBase)
2980 Result.Base |= 0x01;
2981
2982 Result.Type = Base->getType();
2983 return Result;
2984}
2985
2986DeclarationName InitializedEntity::getName() const {
2987 switch (getKind()) {
2988 case EK_Parameter:
2989 case EK_Parameter_CF_Audited: {
2990 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2991 return (D ? D->getDeclName() : DeclarationName());
2992 }
2993
2994 case EK_Variable:
2995 case EK_Member:
2996 case EK_Binding:
2997 return Variable.VariableOrMember->getDeclName();
2998
2999 case EK_LambdaCapture:
3000 return DeclarationName(Capture.VarID);
3001
3002 case EK_Result:
3003 case EK_Exception:
3004 case EK_New:
3005 case EK_Temporary:
3006 case EK_Base:
3007 case EK_Delegating:
3008 case EK_ArrayElement:
3009 case EK_VectorElement:
3010 case EK_ComplexElement:
3011 case EK_BlockElement:
3012 case EK_LambdaToBlockConversionBlockElement:
3013 case EK_CompoundLiteralInit:
3014 case EK_RelatedResult:
3015 return DeclarationName();
3016 }
3017
3018 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3018)
;
3019}
3020
3021ValueDecl *InitializedEntity::getDecl() const {
3022 switch (getKind()) {
3023 case EK_Variable:
3024 case EK_Member:
3025 case EK_Binding:
3026 return Variable.VariableOrMember;
3027
3028 case EK_Parameter:
3029 case EK_Parameter_CF_Audited:
3030 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3031
3032 case EK_Result:
3033 case EK_Exception:
3034 case EK_New:
3035 case EK_Temporary:
3036 case EK_Base:
3037 case EK_Delegating:
3038 case EK_ArrayElement:
3039 case EK_VectorElement:
3040 case EK_ComplexElement:
3041 case EK_BlockElement:
3042 case EK_LambdaToBlockConversionBlockElement:
3043 case EK_LambdaCapture:
3044 case EK_CompoundLiteralInit:
3045 case EK_RelatedResult:
3046 return nullptr;
3047 }
3048
3049 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3049)
;
3050}
3051
3052bool InitializedEntity::allowsNRVO() const {
3053 switch (getKind()) {
3054 case EK_Result:
3055 case EK_Exception:
3056 return LocAndNRVO.NRVO;
3057
3058 case EK_Variable:
3059 case EK_Parameter:
3060 case EK_Parameter_CF_Audited:
3061 case EK_Member:
3062 case EK_Binding:
3063 case EK_New:
3064 case EK_Temporary:
3065 case EK_CompoundLiteralInit:
3066 case EK_Base:
3067 case EK_Delegating:
3068 case EK_ArrayElement:
3069 case EK_VectorElement:
3070 case EK_ComplexElement:
3071 case EK_BlockElement:
3072 case EK_LambdaToBlockConversionBlockElement:
3073 case EK_LambdaCapture:
3074 case EK_RelatedResult:
3075 break;
3076 }
3077
3078 return false;
3079}
3080
3081unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3082 assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail
("getParent() != this", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3082, __extension__ __PRETTY_FUNCTION__))
;
3083 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3084 for (unsigned I = 0; I != Depth; ++I)
3085 OS << "`-";
3086
3087 switch (getKind()) {
3088 case EK_Variable: OS << "Variable"; break;
3089 case EK_Parameter: OS << "Parameter"; break;
3090 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3091 break;
3092 case EK_Result: OS << "Result"; break;
3093 case EK_Exception: OS << "Exception"; break;
3094 case EK_Member: OS << "Member"; break;
3095 case EK_Binding: OS << "Binding"; break;
3096 case EK_New: OS << "New"; break;
3097 case EK_Temporary: OS << "Temporary"; break;
3098 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3099 case EK_RelatedResult: OS << "RelatedResult"; break;
3100 case EK_Base: OS << "Base"; break;
3101 case EK_Delegating: OS << "Delegating"; break;
3102 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3103 case EK_VectorElement: OS << "VectorElement " << Index; break;
3104 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3105 case EK_BlockElement: OS << "Block"; break;
3106 case EK_LambdaToBlockConversionBlockElement:
3107 OS << "Block (lambda)";
3108 break;
3109 case EK_LambdaCapture:
3110 OS << "LambdaCapture ";
3111 OS << DeclarationName(Capture.VarID);
3112 break;
3113 }
3114
3115 if (auto *D = getDecl()) {
3116 OS << " ";
3117 D->printQualifiedName(OS);
3118 }
3119
3120 OS << " '" << getType().getAsString() << "'\n";
3121
3122 return Depth + 1;
3123}
3124
3125LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const {
3126 dumpImpl(llvm::errs());
3127}
3128
3129//===----------------------------------------------------------------------===//
3130// Initialization sequence
3131//===----------------------------------------------------------------------===//
3132
3133void InitializationSequence::Step::Destroy() {
3134 switch (Kind) {
3135 case SK_ResolveAddressOfOverloadedFunction:
3136 case SK_CastDerivedToBaseRValue:
3137 case SK_CastDerivedToBaseXValue:
3138 case SK_CastDerivedToBaseLValue:
3139 case SK_BindReference:
3140 case SK_BindReferenceToTemporary:
3141 case SK_FinalCopy:
3142 case SK_ExtraneousCopyToTemporary:
3143 case SK_UserConversion:
3144 case SK_QualificationConversionRValue:
3145 case SK_QualificationConversionXValue:
3146 case SK_QualificationConversionLValue:
3147 case SK_AtomicConversion:
3148 case SK_LValueToRValue:
3149 case SK_ListInitialization:
3150 case SK_UnwrapInitList:
3151 case SK_RewrapInitList:
3152 case SK_ConstructorInitialization:
3153 case SK_ConstructorInitializationFromList:
3154 case SK_ZeroInitialization:
3155 case SK_CAssignment:
3156 case SK_StringInit:
3157 case SK_ObjCObjectConversion:
3158 case SK_ArrayLoopIndex:
3159 case SK_ArrayLoopInit:
3160 case SK_ArrayInit:
3161 case SK_GNUArrayInit:
3162 case SK_ParenthesizedArrayInit:
3163 case SK_PassByIndirectCopyRestore:
3164 case SK_PassByIndirectRestore:
3165 case SK_ProduceObjCObject:
3166 case SK_StdInitializerList:
3167 case SK_StdInitializerListConstructorCall:
3168 case SK_OCLSamplerInit:
3169 case SK_OCLZeroEvent:
3170 case SK_OCLZeroQueue:
3171 break;
3172
3173 case SK_ConversionSequence:
3174 case SK_ConversionSequenceNoNarrowing:
3175 delete ICS;
3176 }
3177}
3178
3179bool InitializationSequence::isDirectReferenceBinding() const {
3180 // There can be some lvalue adjustments after the SK_BindReference step.
3181 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3182 if (I->Kind == SK_BindReference)
3183 return true;
3184 if (I->Kind == SK_BindReferenceToTemporary)
3185 return false;
3186 }
3187 return false;
3188}
3189
3190bool InitializationSequence::isAmbiguous() const {
3191 if (!Failed())
3192 return false;
3193
3194 switch (getFailureKind()) {
3195 case FK_TooManyInitsForReference:
3196 case FK_ParenthesizedListInitForReference:
3197 case FK_ArrayNeedsInitList:
3198 case FK_ArrayNeedsInitListOrStringLiteral:
3199 case FK_ArrayNeedsInitListOrWideStringLiteral:
3200 case FK_NarrowStringIntoWideCharArray:
3201 case FK_WideStringIntoCharArray:
3202 case FK_IncompatWideStringIntoWideChar:
3203 case FK_PlainStringIntoUTF8Char:
3204 case FK_UTF8StringIntoPlainChar:
3205 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3206 case FK_NonConstLValueReferenceBindingToTemporary:
3207 case FK_NonConstLValueReferenceBindingToBitfield:
3208 case FK_NonConstLValueReferenceBindingToVectorElement:
3209 case FK_NonConstLValueReferenceBindingToUnrelated:
3210 case FK_RValueReferenceBindingToLValue:
3211 case FK_ReferenceInitDropsQualifiers:
3212 case FK_ReferenceInitFailed:
3213 case FK_ConversionFailed:
3214 case FK_ConversionFromPropertyFailed:
3215 case FK_TooManyInitsForScalar:
3216 case FK_ParenthesizedListInitForScalar:
3217 case FK_ReferenceBindingToInitList:
3218 case FK_InitListBadDestinationType:
3219 case FK_DefaultInitOfConst:
3220 case FK_Incomplete:
3221 case FK_ArrayTypeMismatch:
3222 case FK_NonConstantArrayInit:
3223 case FK_ListInitializationFailed:
3224 case FK_VariableLengthArrayHasInitializer:
3225 case FK_PlaceholderType:
3226 case FK_ExplicitConstructor:
3227 case FK_AddressOfUnaddressableFunction:
3228 return false;
3229
3230 case FK_ReferenceInitOverloadFailed:
3231 case FK_UserConversionOverloadFailed:
3232 case FK_ConstructorOverloadFailed:
3233 case FK_ListConstructorOverloadFailed:
3234 return FailedOverloadResult == OR_Ambiguous;
3235 }
3236
3237 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3237)
;
3238}
3239
3240bool InitializationSequence::isConstructorInitialization() const {
3241 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3242}
3243
3244void
3245InitializationSequence
3246::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3247 DeclAccessPair Found,
3248 bool HadMultipleCandidates) {
3249 Step S;
3250 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3251 S.Type = Function->getType();
3252 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3253 S.Function.Function = Function;
3254 S.Function.FoundDecl = Found;
3255 Steps.push_back(S);
3256}
3257
3258void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3259 ExprValueKind VK) {
3260 Step S;
3261 switch (VK) {
3262 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3263 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3264 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3265 }
3266 S.Type = BaseType;
3267 Steps.push_back(S);
3268}
3269
3270void InitializationSequence::AddReferenceBindingStep(QualType T,
3271 bool BindingTemporary) {
3272 Step S;
3273 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3274 S.Type = T;
3275 Steps.push_back(S);
3276}
3277
3278void InitializationSequence::AddFinalCopy(QualType T) {
3279 Step S;
3280 S.Kind = SK_FinalCopy;
3281 S.Type = T;
3282 Steps.push_back(S);
3283}
3284
3285void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3286 Step S;
3287 S.Kind = SK_ExtraneousCopyToTemporary;
3288 S.Type = T;
3289 Steps.push_back(S);
3290}
3291
3292void
3293InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3294 DeclAccessPair FoundDecl,
3295 QualType T,
3296 bool HadMultipleCandidates) {
3297 Step S;
3298 S.Kind = SK_UserConversion;
3299 S.Type = T;
3300 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3301 S.Function.Function = Function;
3302 S.Function.FoundDecl = FoundDecl;
3303 Steps.push_back(S);
3304}
3305
3306void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3307 ExprValueKind VK) {
3308 Step S;
3309 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3310 switch (VK) {
3311 case VK_RValue:
3312 S.Kind = SK_QualificationConversionRValue;
3313 break;
3314 case VK_XValue:
3315 S.Kind = SK_QualificationConversionXValue;
3316 break;
3317 case VK_LValue:
3318 S.Kind = SK_QualificationConversionLValue;
3319 break;
3320 }
3321 S.Type = Ty;
3322 Steps.push_back(S);
3323}
3324
3325void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3326 Step S;
3327 S.Kind = SK_AtomicConversion;
3328 S.Type = Ty;
3329 Steps.push_back(S);
3330}
3331
3332void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3333 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3333, __extension__ __PRETTY_FUNCTION__))
;
3334
3335 Step S;
3336 S.Kind = SK_LValueToRValue;
3337 S.Type = Ty;
3338 Steps.push_back(S);
3339}
3340
3341void InitializationSequence::AddConversionSequenceStep(
3342 const ImplicitConversionSequence &ICS, QualType T,
3343 bool TopLevelOfInitList) {
3344 Step S;
3345 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3346 : SK_ConversionSequence;
3347 S.Type = T;
3348 S.ICS = new ImplicitConversionSequence(ICS);
3349 Steps.push_back(S);
3350}
3351
3352void InitializationSequence::AddListInitializationStep(QualType T) {
3353 Step S;
3354 S.Kind = SK_ListInitialization;
3355 S.Type = T;
3356 Steps.push_back(S);
3357}
3358
3359void InitializationSequence::AddConstructorInitializationStep(
3360 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3361 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3362 Step S;
3363 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3364 : SK_ConstructorInitializationFromList
3365 : SK_ConstructorInitialization;
3366 S.Type = T;
3367 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3368 S.Function.Function = Constructor;
3369 S.Function.FoundDecl = FoundDecl;
3370 Steps.push_back(S);
3371}
3372
3373void InitializationSequence::AddZeroInitializationStep(QualType T) {
3374 Step S;
3375 S.Kind = SK_ZeroInitialization;
3376 S.Type = T;
3377 Steps.push_back(S);
3378}
3379
3380void InitializationSequence::AddCAssignmentStep(QualType T) {
3381 Step S;
3382 S.Kind = SK_CAssignment;
3383 S.Type = T;
3384 Steps.push_back(S);
3385}
3386
3387void InitializationSequence::AddStringInitStep(QualType T) {
3388 Step S;
3389 S.Kind = SK_StringInit;
3390 S.Type = T;
3391 Steps.push_back(S);
3392}
3393
3394void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3395 Step S;
3396 S.Kind = SK_ObjCObjectConversion;
3397 S.Type = T;
3398 Steps.push_back(S);
3399}
3400
3401void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3402 Step S;
3403 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3404 S.Type = T;
3405 Steps.push_back(S);
3406}
3407
3408void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3409 Step S;
3410 S.Kind = SK_ArrayLoopIndex;
3411 S.Type = EltT;
3412 Steps.insert(Steps.begin(), S);
3413
3414 S.Kind = SK_ArrayLoopInit;
3415 S.Type = T;
3416 Steps.push_back(S);
3417}
3418
3419void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3420 Step S;
3421 S.Kind = SK_ParenthesizedArrayInit;
3422 S.Type = T;
3423 Steps.push_back(S);
3424}
3425
3426void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3427 bool shouldCopy) {
3428 Step s;
3429 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3430 : SK_PassByIndirectRestore);
3431 s.Type = type;
3432 Steps.push_back(s);
3433}
3434
3435void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3436 Step S;
3437 S.Kind = SK_ProduceObjCObject;
3438 S.Type = T;
3439 Steps.push_back(S);
3440}
3441
3442void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3443 Step S;
3444 S.Kind = SK_StdInitializerList;
3445 S.Type = T;
3446 Steps.push_back(S);
3447}
3448
3449void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3450 Step S;
3451 S.Kind = SK_OCLSamplerInit;
3452 S.Type = T;
3453 Steps.push_back(S);
3454}
3455
3456void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3457 Step S;
3458 S.Kind = SK_OCLZeroEvent;
3459 S.Type = T;
3460 Steps.push_back(S);
3461}
3462
3463void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3464 Step S;
3465 S.Kind = SK_OCLZeroQueue;
3466 S.Type = T;
3467 Steps.push_back(S);
3468}
3469
3470void InitializationSequence::RewrapReferenceInitList(QualType T,
3471 InitListExpr *Syntactic) {
3472 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3473, __extension__ __PRETTY_FUNCTION__))
3473 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3473, __extension__ __PRETTY_FUNCTION__))
;
3474 Step S;
3475 S.Kind = SK_UnwrapInitList;
3476 S.Type = Syntactic->getInit(0)->getType();
3477 Steps.insert(Steps.begin(), S);
3478
3479 S.Kind = SK_RewrapInitList;
3480 S.Type = T;
3481 S.WrappingSyntacticList = Syntactic;
3482 Steps.push_back(S);
3483}
3484
3485void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3486 OverloadingResult Result) {
3487 setSequenceKind(FailedSequence);
3488 this->Failure = Failure;
3489 this->FailedOverloadResult = Result;
3490}
3491
3492//===----------------------------------------------------------------------===//
3493// Attempt initialization
3494//===----------------------------------------------------------------------===//
3495
3496/// Tries to add a zero initializer. Returns true if that worked.
3497static bool
3498maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3499 const InitializedEntity &Entity) {
3500 if (Entity.getKind() != InitializedEntity::EK_Variable)
3501 return false;
3502
3503 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3504 if (VD->getInit() || VD->getLocEnd().isMacroID())
3505 return false;
3506
3507 QualType VariableTy = VD->getType().getCanonicalType();
3508 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3509 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3510 if (!Init.empty()) {
3511 Sequence.AddZeroInitializationStep(Entity.getType());
3512 Sequence.SetZeroInitializationFixit(Init, Loc);
3513 return true;
3514 }
3515 return false;
3516}
3517
3518static void MaybeProduceObjCObject(Sema &S,
3519 InitializationSequence &Sequence,
3520 const InitializedEntity &Entity) {
3521 if (!S.getLangOpts().ObjCAutoRefCount) return;
3522
3523 /// When initializing a parameter, produce the value if it's marked
3524 /// __attribute__((ns_consumed)).
3525 if (Entity.isParameterKind()) {
3526 if (!Entity.isParameterConsumed())
3527 return;
3528
3529 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3530, __extension__ __PRETTY_FUNCTION__))
3530 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3530, __extension__ __PRETTY_FUNCTION__))
;
3531 Sequence.AddProduceObjCObjectStep(Entity.getType());
3532
3533 /// When initializing a return value, if the return type is a
3534 /// retainable type, then returns need to immediately retain the
3535 /// object. If an autorelease is required, it will be done at the
3536 /// last instant.
3537 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3538 if (!Entity.getType()->isObjCRetainableType())
3539 return;
3540
3541 Sequence.AddProduceObjCObjectStep(Entity.getType());
3542 }
3543}
3544
3545static void TryListInitialization(Sema &S,
3546 const InitializedEntity &Entity,
3547 const InitializationKind &Kind,
3548 InitListExpr *InitList,
3549 InitializationSequence &Sequence,
3550 bool TreatUnavailableAsInvalid);
3551
3552/// When initializing from init list via constructor, handle
3553/// initialization of an object of type std::initializer_list<T>.
3554///
3555/// \return true if we have handled initialization of an object of type
3556/// std::initializer_list<T>, false otherwise.
3557static bool TryInitializerListConstruction(Sema &S,
3558 InitListExpr *List,
3559 QualType DestType,
3560 InitializationSequence &Sequence,
3561 bool TreatUnavailableAsInvalid) {
3562 QualType E;
3563 if (!S.isStdInitializerList(DestType, &E))
3564 return false;
3565
3566 if (!S.isCompleteType(List->getExprLoc(), E)) {
3567 Sequence.setIncompleteTypeFailure(E);
3568 return true;
3569 }
3570
3571 // Try initializing a temporary array from the init list.
3572 QualType ArrayType = S.Context.getConstantArrayType(
3573 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3574 List->getNumInits()),
3575 clang::ArrayType::Normal, 0);
3576 InitializedEntity HiddenArray =
3577 InitializedEntity::InitializeTemporary(ArrayType);
3578 InitializationKind Kind = InitializationKind::CreateDirectList(
3579 List->getExprLoc(), List->getLocStart(), List->getLocEnd());
3580 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3581 TreatUnavailableAsInvalid);
3582 if (Sequence)
3583 Sequence.AddStdInitializerListConstructionStep(DestType);
3584 return true;
3585}
3586
3587/// Determine if the constructor has the signature of a copy or move
3588/// constructor for the type T of the class in which it was found. That is,
3589/// determine if its first parameter is of type T or reference to (possibly
3590/// cv-qualified) T.
3591static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3592 const ConstructorInfo &Info) {
3593 if (Info.Constructor->getNumParams() == 0)
3594 return false;
3595
3596 QualType ParmT =
3597 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3598 QualType ClassT =
3599 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3600
3601 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3602}
3603
3604static OverloadingResult
3605ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3606 MultiExprArg Args,
3607 OverloadCandidateSet &CandidateSet,
3608 QualType DestType,
3609 DeclContext::lookup_result Ctors,
3610 OverloadCandidateSet::iterator &Best,
3611 bool CopyInitializing, bool AllowExplicit,
3612 bool OnlyListConstructors, bool IsListInit,
3613 bool SecondStepOfCopyInit = false) {
3614 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3615
3616 for (NamedDecl *D : Ctors) {
3617 auto Info = getConstructorInfo(D);
3618 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3619 continue;
3620
3621 if (!AllowExplicit && Info.Constructor->isExplicit())
3622 continue;
3623
3624 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3625 continue;
3626
3627 // C++11 [over.best.ics]p4:
3628 // ... and the constructor or user-defined conversion function is a
3629 // candidate by
3630 // - 13.3.1.3, when the argument is the temporary in the second step
3631 // of a class copy-initialization, or
3632 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3633 // - the second phase of 13.3.1.7 when the initializer list has exactly
3634 // one element that is itself an initializer list, and the target is
3635 // the first parameter of a constructor of class X, and the conversion
3636 // is to X or reference to (possibly cv-qualified X),
3637 // user-defined conversion sequences are not considered.
3638 bool SuppressUserConversions =
3639 SecondStepOfCopyInit ||
3640 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3641 hasCopyOrMoveCtorParam(S.Context, Info));
3642
3643 if (Info.ConstructorTmpl)
3644 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3645 /*ExplicitArgs*/ nullptr, Args,
3646 CandidateSet, SuppressUserConversions);
3647 else {
3648 // C++ [over.match.copy]p1:
3649 // - When initializing a temporary to be bound to the first parameter
3650 // of a constructor [for type T] that takes a reference to possibly
3651 // cv-qualified T as its first argument, called with a single
3652 // argument in the context of direct-initialization, explicit
3653 // conversion functions are also considered.
3654 // FIXME: What if a constructor template instantiates to such a signature?
3655 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3656 Args.size() == 1 &&
3657 hasCopyOrMoveCtorParam(S.Context, Info);
3658 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3659 CandidateSet, SuppressUserConversions,
3660 /*PartialOverloading=*/false,
3661 /*AllowExplicit=*/AllowExplicitConv);
3662 }
3663 }
3664
3665 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3666 //
3667 // When initializing an object of class type T by constructor
3668 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3669 // from a single expression of class type U, conversion functions of
3670 // U that convert to the non-reference type cv T are candidates.
3671 // Explicit conversion functions are only candidates during
3672 // direct-initialization.
3673 //
3674 // Note: SecondStepOfCopyInit is only ever true in this case when
3675 // evaluating whether to produce a C++98 compatibility warning.
3676 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
3677 !SecondStepOfCopyInit) {
3678 Expr *Initializer = Args[0];
3679 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3680 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3681 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3682 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3683 NamedDecl *D = *I;
3684 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3685 D = D->getUnderlyingDecl();
3686
3687 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3688 CXXConversionDecl *Conv;
3689 if (ConvTemplate)
3690 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3691 else
3692 Conv = cast<CXXConversionDecl>(D);
3693
3694 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3695 if (ConvTemplate)
3696 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3697 ActingDC, Initializer, DestType,
3698 CandidateSet, AllowExplicit,
3699 /*AllowResultConversion*/false);
3700 else
3701 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3702 DestType, CandidateSet, AllowExplicit,
3703 /*AllowResultConversion*/false);
3704 }
3705 }
3706 }
3707 }
3708
3709 // Perform overload resolution and return the result.
3710 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3711}
3712
3713/// Attempt initialization by constructor (C++ [dcl.init]), which
3714/// enumerates the constructors of the initialized entity and performs overload
3715/// resolution to select the best.
3716/// \param DestType The destination class type.
3717/// \param DestArrayType The destination type, which is either DestType or
3718/// a (possibly multidimensional) array of DestType.
3719/// \param IsListInit Is this list-initialization?
3720/// \param IsInitListCopy Is this non-list-initialization resulting from a
3721/// list-initialization from {x} where x is the same
3722/// type as the entity?
3723static void TryConstructorInitialization(Sema &S,
3724 const InitializedEntity &Entity,
3725 const InitializationKind &Kind,
3726 MultiExprArg Args, QualType DestType,
3727 QualType DestArrayType,
3728 InitializationSequence &Sequence,
3729 bool IsListInit = false,
3730 bool IsInitListCopy = false) {
3731 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3734, __extension__ __PRETTY_FUNCTION__))
3732 (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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3734, __extension__ __PRETTY_FUNCTION__))
3733 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3734, __extension__ __PRETTY_FUNCTION__))
3734 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3734, __extension__ __PRETTY_FUNCTION__))
;
3735 InitListExpr *ILE =
3736 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3737 MultiExprArg UnwrappedArgs =
3738 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3739
3740 // The type we're constructing needs to be complete.
3741 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3742 Sequence.setIncompleteTypeFailure(DestType);
3743 return;
3744 }
3745
3746 // C++17 [dcl.init]p17:
3747 // - If the initializer expression is a prvalue and the cv-unqualified
3748 // version of the source type is the same class as the class of the
3749 // destination, the initializer expression is used to initialize the
3750 // destination object.
3751 // Per DR (no number yet), this does not apply when initializing a base
3752 // class or delegating to another constructor from a mem-initializer.
3753 // ObjC++: Lambda captured by the block in the lambda to block conversion
3754 // should avoid copy elision.
3755 if (S.getLangOpts().CPlusPlus17 &&
3756 Entity.getKind() != InitializedEntity::EK_Base &&
3757 Entity.getKind() != InitializedEntity::EK_Delegating &&
3758 Entity.getKind() !=
3759 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3760 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3761 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3762 // Convert qualifications if necessary.
3763 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3764 if (ILE)
3765 Sequence.RewrapReferenceInitList(DestType, ILE);
3766 return;
3767 }
3768
3769 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3770 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3770, __extension__ __PRETTY_FUNCTION__))
;
3771 CXXRecordDecl *DestRecordDecl
3772 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3773
3774 // Build the candidate set directly in the initialization sequence
3775 // structure, so that it will persist if we fail.
3776 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3777
3778 // Determine whether we are allowed to call explicit constructors or
3779 // explicit conversion operators.
3780 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3781 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3782
3783 // - Otherwise, if T is a class type, constructors are considered. The
3784 // applicable constructors are enumerated, and the best one is chosen
3785 // through overload resolution.
3786 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3787
3788 OverloadingResult Result = OR_No_Viable_Function;
3789 OverloadCandidateSet::iterator Best;
3790 bool AsInitializerList = false;
3791
3792 // C++11 [over.match.list]p1, per DR1467:
3793 // When objects of non-aggregate type T are list-initialized, such that
3794 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3795 // according to the rules in this section, overload resolution selects
3796 // the constructor in two phases:
3797 //
3798 // - Initially, the candidate functions are the initializer-list
3799 // constructors of the class T and the argument list consists of the
3800 // initializer list as a single argument.
3801 if (IsListInit) {
3802 AsInitializerList = true;
3803
3804 // If the initializer list has no elements and T has a default constructor,
3805 // the first phase is omitted.
3806 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3807 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3808 CandidateSet, DestType, Ctors, Best,
3809 CopyInitialization, AllowExplicit,
3810 /*OnlyListConstructor=*/true,
3811 IsListInit);
3812 }
3813
3814 // C++11 [over.match.list]p1:
3815 // - If no viable initializer-list constructor is found, overload resolution
3816 // is performed again, where the candidate functions are all the
3817 // constructors of the class T and the argument list consists of the
3818 // elements of the initializer list.
3819 if (Result == OR_No_Viable_Function) {
3820 AsInitializerList = false;
3821 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3822 CandidateSet, DestType, Ctors, Best,
3823 CopyInitialization, AllowExplicit,
3824 /*OnlyListConstructors=*/false,
3825 IsListInit);
3826 }
3827 if (Result) {
3828 Sequence.SetOverloadFailure(IsListInit ?
3829 InitializationSequence::FK_ListConstructorOverloadFailed :
3830 InitializationSequence::FK_ConstructorOverloadFailed,
3831 Result);
3832 return;
3833 }
3834
3835 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3836
3837 // In C++17, ResolveConstructorOverload can select a conversion function
3838 // instead of a constructor.
3839 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3840 // Add the user-defined conversion step that calls the conversion function.
3841 QualType ConvType = CD->getConversionType();
3842 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3843, __extension__ __PRETTY_FUNCTION__))
3843 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 3843, __extension__ __PRETTY_FUNCTION__))
;
3844 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3845 HadMultipleCandidates);
3846 if (!S.Context.hasSameType(ConvType, DestType))
3847 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3848 if (IsListInit)
3849 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3850 return;
3851 }
3852
3853 // C++11 [dcl.init]p6:
3854 // If a program calls for the default initialization of an object
3855 // of a const-qualified type T, T shall be a class type with a
3856 // user-provided default constructor.
3857 // C++ core issue 253 proposal:
3858 // If the implicit default constructor initializes all subobjects, no
3859 // initializer should be required.
3860 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3861 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3862 if (Kind.getKind() == InitializationKind::IK_Default &&
3863 Entity.getType().isConstQualified()) {
3864 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3865 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3866 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3867 return;
3868 }
3869 }
3870
3871 // C++11 [over.match.list]p1:
3872 // In copy-list-initialization, if an explicit constructor is chosen, the
3873 // initializer is ill-formed.
3874 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3875 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3876 return;
3877 }
3878
3879 // Add the constructor initialization step. Any cv-qualification conversion is
3880 // subsumed by the initialization.
3881 Sequence.AddConstructorInitializationStep(
3882 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
3883 IsListInit | IsInitListCopy, AsInitializerList);
3884}
3885
3886static bool
3887ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3888 Expr *Initializer,
3889 QualType &SourceType,
3890 QualType &UnqualifiedSourceType,
3891 QualType UnqualifiedTargetType,
3892 InitializationSequence &Sequence) {
3893 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3894 S.Context.OverloadTy) {
3895 DeclAccessPair Found;
3896 bool HadMultipleCandidates = false;
3897 if (FunctionDecl *Fn
3898 = S.ResolveAddressOfOverloadedFunction(Initializer,
3899 UnqualifiedTargetType,
3900 false, Found,
3901 &HadMultipleCandidates)) {
3902 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3903 HadMultipleCandidates);
3904 SourceType = Fn->getType();
3905 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3906 } else if (!UnqualifiedTargetType->isRecordType()) {
3907 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3908 return true;
3909 }
3910 }
3911 return false;
3912}
3913
3914static void TryReferenceInitializationCore(Sema &S,
3915 const InitializedEntity &Entity,
3916 const InitializationKind &Kind,
3917 Expr *Initializer,
3918 QualType cv1T1, QualType T1,
3919 Qualifiers T1Quals,
3920 QualType cv2T2, QualType T2,
3921 Qualifiers T2Quals,
3922 InitializationSequence &Sequence);
3923
3924static void TryValueInitialization(Sema &S,
3925 const InitializedEntity &Entity,
3926 const InitializationKind &Kind,
3927 InitializationSequence &Sequence,
3928 InitListExpr *InitList = nullptr);
3929
3930/// Attempt list initialization of a reference.
3931static void TryReferenceListInitialization(Sema &S,
3932 const InitializedEntity &Entity,
3933 const InitializationKind &Kind,
3934 InitListExpr *InitList,
3935 InitializationSequence &Sequence,
3936 bool TreatUnavailableAsInvalid) {
3937 // First, catch C++03 where this isn't possible.
3938 if (!S.getLangOpts().CPlusPlus11) {
3939 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3940 return;
3941 }
3942 // Can't reference initialize a compound literal.
3943 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3944 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3945 return;
3946 }
3947
3948 QualType DestType = Entity.getType();
3949 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3950 Qualifiers T1Quals;
3951 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3952
3953 // Reference initialization via an initializer list works thus:
3954 // If the initializer list consists of a single element that is
3955 // reference-related to the referenced type, bind directly to that element
3956 // (possibly creating temporaries).
3957 // Otherwise, initialize a temporary with the initializer list and
3958 // bind to that.
3959 if (InitList->getNumInits() == 1) {
3960 Expr *Initializer = InitList->getInit(0);
3961 QualType cv2T2 = Initializer->getType();
3962 Qualifiers T2Quals;
3963 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3964
3965 // If this fails, creating a temporary wouldn't work either.
3966 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3967 T1, Sequence))
3968 return;
3969
3970 SourceLocation DeclLoc = Initializer->getLocStart();
3971 bool dummy1, dummy2, dummy3;
3972 Sema::ReferenceCompareResult RefRelationship
3973 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3974 dummy2, dummy3);
3975 if (RefRelationship >= Sema::Ref_Related) {
3976 // Try to bind the reference here.
3977 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3978 T1Quals, cv2T2, T2, T2Quals, Sequence);
3979 if (Sequence)
3980 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3981 return;
3982 }
3983
3984 // Update the initializer if we've resolved an overloaded function.
3985 if (Sequence.step_begin() != Sequence.step_end())
3986 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3987 }
3988
3989 // Not reference-related. Create a temporary and bind to that.
3990 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3991
3992 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3993 TreatUnavailableAsInvalid);
3994 if (Sequence) {
3995 if (DestType->isRValueReferenceType() ||
3996 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3997 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3998 else
3999 Sequence.SetFailed(
4000 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4001 }
4002}
4003
4004/// Attempt list initialization (C++0x [dcl.init.list])
4005static void TryListInitialization(Sema &S,
4006 const InitializedEntity &Entity,
4007 const InitializationKind &Kind,
4008 InitListExpr *InitList,
4009 InitializationSequence &Sequence,
4010 bool TreatUnavailableAsInvalid) {
4011 QualType DestType = Entity.getType();
4012
4013 // C++ doesn't allow scalar initialization with more than one argument.
4014 // But C99 complex numbers are scalars and it makes sense there.
4015 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4016 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4017 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4018 return;
4019 }
4020 if (DestType->isReferenceType()) {
4021 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4022 TreatUnavailableAsInvalid);
4023 return;
4024 }
4025
4026 if (DestType->isRecordType() &&
4027 !S.isCompleteType(InitList->getLocStart(), DestType)) {
4028 Sequence.setIncompleteTypeFailure(DestType);
4029 return;
4030 }
4031
4032 // C++11 [dcl.init.list]p3, per DR1467:
4033 // - If T is a class type and the initializer list has a single element of
4034 // type cv U, where U is T or a class derived from T, the object is
4035 // initialized from that element (by copy-initialization for
4036 // copy-list-initialization, or by direct-initialization for
4037 // direct-list-initialization).
4038 // - Otherwise, if T is a character array and the initializer list has a
4039 // single element that is an appropriately-typed string literal
4040 // (8.5.2 [dcl.init.string]), initialization is performed as described
4041 // in that section.
4042 // - Otherwise, if T is an aggregate, [...] (continue below).
4043 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4044 if (DestType->isRecordType()) {
4045 QualType InitType = InitList->getInit(0)->getType();
4046 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4047 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
4048 Expr *InitListAsExpr = InitList;
4049 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4050 DestType, Sequence,
4051 /*InitListSyntax*/false,
4052 /*IsInitListCopy*/true);
4053 return;
4054 }
4055 }
4056 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4057 Expr *SubInit[1] = {InitList->getInit(0)};
4058 if (!isa<VariableArrayType>(DestAT) &&
4059 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4060 InitializationKind SubKind =
4061 Kind.getKind() == InitializationKind::IK_DirectList
4062 ? InitializationKind::CreateDirect(Kind.getLocation(),
4063 InitList->getLBraceLoc(),
4064 InitList->getRBraceLoc())
4065 : Kind;
4066 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4067 /*TopLevelOfInitList*/ true,
4068 TreatUnavailableAsInvalid);
4069
4070 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4071 // the element is not an appropriately-typed string literal, in which
4072 // case we should proceed as in C++11 (below).
4073 if (Sequence) {
4074 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4075 return;
4076 }
4077 }
4078 }
4079 }
4080
4081 // C++11 [dcl.init.list]p3:
4082 // - If T is an aggregate, aggregate initialization is performed.
4083 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4084 (S.getLangOpts().CPlusPlus11 &&
4085 S.isStdInitializerList(DestType, nullptr))) {
4086 if (S.getLangOpts().CPlusPlus11) {
4087 // - Otherwise, if the initializer list has no elements and T is a
4088 // class type with a default constructor, the object is
4089 // value-initialized.
4090 if (InitList->getNumInits() == 0) {
4091 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4092 if (RD->hasDefaultConstructor()) {
4093 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4094 return;
4095 }
4096 }
4097
4098 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4099 // an initializer_list object constructed [...]
4100 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4101 TreatUnavailableAsInvalid))
4102 return;
4103
4104 // - Otherwise, if T is a class type, constructors are considered.
4105 Expr *InitListAsExpr = InitList;
4106 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4107 DestType, Sequence, /*InitListSyntax*/true);
4108 } else
4109 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4110 return;
4111 }
4112
4113 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4114 InitList->getNumInits() == 1) {
4115 Expr *E = InitList->getInit(0);
4116
4117 // - Otherwise, if T is an enumeration with a fixed underlying type,
4118 // the initializer-list has a single element v, and the initialization
4119 // is direct-list-initialization, the object is initialized with the
4120 // value T(v); if a narrowing conversion is required to convert v to
4121 // the underlying type of T, the program is ill-formed.
4122 auto *ET = DestType->getAs<EnumType>();
4123 if (S.getLangOpts().CPlusPlus17 &&
4124 Kind.getKind() == InitializationKind::IK_DirectList &&
4125 ET && ET->getDecl()->isFixed() &&
4126 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4127 (E->getType()->isIntegralOrEnumerationType() ||
4128 E->getType()->isFloatingType())) {
4129 // There are two ways that T(v) can work when T is an enumeration type.
4130 // If there is either an implicit conversion sequence from v to T or
4131 // a conversion function that can convert from v to T, then we use that.
4132 // Otherwise, if v is of integral, enumeration, or floating-point type,
4133 // it is converted to the enumeration type via its underlying type.
4134 // There is no overlap possible between these two cases (except when the
4135 // source value is already of the destination type), and the first
4136 // case is handled by the general case for single-element lists below.
4137 ImplicitConversionSequence ICS;
4138 ICS.setStandard();
4139 ICS.Standard.setAsIdentityConversion();
4140 if (!E->isRValue())
4141 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4142 // If E is of a floating-point type, then the conversion is ill-formed
4143 // due to narrowing, but go through the motions in order to produce the
4144 // right diagnostic.
4145 ICS.Standard.Second = E->getType()->isFloatingType()
4146 ? ICK_Floating_Integral
4147 : ICK_Integral_Conversion;
4148 ICS.Standard.setFromType(E->getType());
4149 ICS.Standard.setToType(0, E->getType());
4150 ICS.Standard.setToType(1, DestType);
4151 ICS.Standard.setToType(2, DestType);
4152 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4153 /*TopLevelOfInitList*/true);
4154 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4155 return;
4156 }
4157
4158 // - Otherwise, if the initializer list has a single element of type E
4159 // [...references are handled above...], the object or reference is
4160 // initialized from that element (by copy-initialization for
4161 // copy-list-initialization, or by direct-initialization for
4162 // direct-list-initialization); if a narrowing conversion is required
4163 // to convert the element to T, the program is ill-formed.
4164 //
4165 // Per core-24034, this is direct-initialization if we were performing
4166 // direct-list-initialization and copy-initialization otherwise.
4167 // We can't use InitListChecker for this, because it always performs
4168 // copy-initialization. This only matters if we might use an 'explicit'
4169 // conversion operator, so we only need to handle the cases where the source
4170 // is of record type.
4171 if (InitList->getInit(0)->getType()->isRecordType()) {
4172 InitializationKind SubKind =
4173 Kind.getKind() == InitializationKind::IK_DirectList
4174 ? InitializationKind::CreateDirect(Kind.getLocation(),
4175 InitList->getLBraceLoc(),
4176 InitList->getRBraceLoc())
4177 : Kind;
4178 Expr *SubInit[1] = { InitList->getInit(0) };
4179 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4180 /*TopLevelOfInitList*/true,
4181 TreatUnavailableAsInvalid);
4182 if (Sequence)
4183 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4184 return;
4185 }
4186 }
4187
4188 InitListChecker CheckInitList(S, Entity, InitList,
4189 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4190 if (CheckInitList.HadError()) {
4191 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4192 return;
4193 }
4194
4195 // Add the list initialization step with the built init list.
4196 Sequence.AddListInitializationStep(DestType);
4197}
4198
4199/// Try a reference initialization that involves calling a conversion
4200/// function.
4201static OverloadingResult TryRefInitWithConversionFunction(
4202 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4203 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4204 InitializationSequence &Sequence) {
4205 QualType DestType = Entity.getType();
4206 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4207 QualType T1 = cv1T1.getUnqualifiedType();
4208 QualType cv2T2 = Initializer->getType();
4209 QualType T2 = cv2T2.getUnqualifiedType();
4210
4211 bool DerivedToBase;
4212 bool ObjCConversion;
4213 bool ObjCLifetimeConversion;
4214 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
4215 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
4216 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
4217 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
4218 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
;
4219 (void)DerivedToBase;
4220 (void)ObjCConversion;
4221 (void)ObjCLifetimeConversion;
4222
4223 // Build the candidate set directly in the initialization sequence
4224 // structure, so that it will persist if we fail.
4225 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4226 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4227
4228 // Determine whether we are allowed to call explicit conversion operators.
4229 // Note that none of [over.match.copy], [over.match.conv], nor
4230 // [over.match.ref] permit an explicit constructor to be chosen when
4231 // initializing a reference, not even for direct-initialization.
4232 bool AllowExplicitCtors = false;
4233 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4234
4235 const RecordType *T1RecordType = nullptr;
4236 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4237 S.isCompleteType(Kind.getLocation(), T1)) {
4238 // The type we're converting to is a class type. Enumerate its constructors
4239 // to see if there is a suitable conversion.
4240 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4241
4242 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4243 auto Info = getConstructorInfo(D);
4244 if (!Info.Constructor)
4245 continue;
4246
4247 if (!Info.Constructor->isInvalidDecl() &&
4248 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
4249 if (Info.ConstructorTmpl)
4250 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4251 /*ExplicitArgs*/ nullptr,
4252 Initializer, CandidateSet,
4253 /*SuppressUserConversions=*/true);
4254 else
4255 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4256 Initializer, CandidateSet,
4257 /*SuppressUserConversions=*/true);
4258 }
4259 }
4260 }
4261 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4262 return OR_No_Viable_Function;
4263
4264 const RecordType *T2RecordType = nullptr;
4265 if ((T2RecordType = T2->getAs<RecordType>()) &&
4266 S.isCompleteType(Kind.getLocation(), T2)) {
4267 // The type we're converting from is a class type, enumerate its conversion
4268 // functions.
4269 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4270
4271 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4272 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4273 NamedDecl *D = *I;
4274 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4275 if (isa<UsingShadowDecl>(D))
4276 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4277
4278 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4279 CXXConversionDecl *Conv;
4280 if (ConvTemplate)
4281 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4282 else
4283 Conv = cast<CXXConversionDecl>(D);
4284
4285 // If the conversion function doesn't return a reference type,
4286 // it can't be considered for this conversion unless we're allowed to
4287 // consider rvalues.
4288 // FIXME: Do we need to make sure that we only consider conversion
4289 // candidates with reference-compatible results? That might be needed to
4290 // break recursion.
4291 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4292 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4293 if (ConvTemplate)
4294 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4295 ActingDC, Initializer,
4296 DestType, CandidateSet,
4297 /*AllowObjCConversionOnExplicit=*/
4298 false);
4299 else
4300 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4301 Initializer, DestType, CandidateSet,
4302 /*AllowObjCConversionOnExplicit=*/false);
4303 }
4304 }
4305 }
4306 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4307 return OR_No_Viable_Function;
4308
4309 SourceLocation DeclLoc = Initializer->getLocStart();
4310
4311 // Perform overload resolution. If it fails, return the failed result.
4312 OverloadCandidateSet::iterator Best;
4313 if (OverloadingResult Result
4314 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4315 return Result;
4316
4317 FunctionDecl *Function = Best->Function;
4318 // This is the overload that will be used for this initialization step if we
4319 // use this initialization. Mark it as referenced.
4320 Function->setReferenced();
4321
4322 // Compute the returned type and value kind of the conversion.
4323 QualType cv3T3;
4324 if (isa<CXXConversionDecl>(Function))
4325 cv3T3 = Function->getReturnType();
4326 else
4327 cv3T3 = T1;
4328
4329 ExprValueKind VK = VK_RValue;
4330 if (cv3T3->isLValueReferenceType())
4331 VK = VK_LValue;
4332 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4333 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4334 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4335
4336 // Add the user-defined conversion step.
4337 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4338 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4339 HadMultipleCandidates);
4340
4341 // Determine whether we'll need to perform derived-to-base adjustments or
4342 // other conversions.
4343 bool NewDerivedToBase = false;
4344 bool NewObjCConversion = false;
4345 bool NewObjCLifetimeConversion = false;
4346 Sema::ReferenceCompareResult NewRefRelationship
4347 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4348 NewDerivedToBase, NewObjCConversion,
4349 NewObjCLifetimeConversion);
4350
4351 // Add the final conversion sequence, if necessary.
4352 if (NewRefRelationship == Sema::Ref_Incompatible) {
4353 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4354, __extension__ __PRETTY_FUNCTION__))
4354 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4354, __extension__ __PRETTY_FUNCTION__))
;
4355
4356 ImplicitConversionSequence ICS;
4357 ICS.setStandard();
4358 ICS.Standard = Best->FinalConversion;
4359 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4360
4361 // Every implicit conversion results in a prvalue, except for a glvalue
4362 // derived-to-base conversion, which we handle below.
4363 cv3T3 = ICS.Standard.getToType(2);
4364 VK = VK_RValue;
4365 }
4366
4367 // If the converted initializer is a prvalue, its type T4 is adjusted to
4368 // type "cv1 T4" and the temporary materialization conversion is applied.
4369 //
4370 // We adjust the cv-qualifications to match the reference regardless of
4371 // whether we have a prvalue so that the AST records the change. In this
4372 // case, T4 is "cv3 T3".
4373 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4374 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4375 Sequence.AddQualificationConversionStep(cv1T4, VK);
4376 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4377 VK = IsLValueRef ? VK_LValue : VK_XValue;
4378
4379 if (NewDerivedToBase)
4380 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4381 else if (NewObjCConversion)
4382 Sequence.AddObjCObjectConversionStep(cv1T1);
4383
4384 return OR_Success;
4385}
4386
4387static void CheckCXX98CompatAccessibleCopy(Sema &S,
4388 const InitializedEntity &Entity,
4389 Expr *CurInitExpr);
4390
4391/// Attempt reference initialization (C++0x [dcl.init.ref])
4392static void TryReferenceInitialization(Sema &S,
4393 const InitializedEntity &Entity,
4394 const InitializationKind &Kind,
4395 Expr *Initializer,
4396 InitializationSequence &Sequence) {
4397 QualType DestType = Entity.getType();
4398 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4399 Qualifiers T1Quals;
4400 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4401 QualType cv2T2 = Initializer->getType();
4402 Qualifiers T2Quals;
4403 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4404
4405 // If the initializer is the address of an overloaded function, try
4406 // to resolve the overloaded function. If all goes well, T2 is the
4407 // type of the resulting function.
4408 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4409 T1, Sequence))
4410 return;
4411
4412 // Delegate everything else to a subfunction.
4413 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4414 T1Quals, cv2T2, T2, T2Quals, Sequence);
4415}
4416
4417/// Determine whether an expression is a non-referenceable glvalue (one to
4418/// which a reference can never bind). Attempting to bind a reference to
4419/// such a glvalue will always create a temporary.
4420static bool isNonReferenceableGLValue(Expr *E) {
4421 return E->refersToBitField() || E->refersToVectorElement();
4422}
4423
4424/// Reference initialization without resolving overloaded functions.
4425static void TryReferenceInitializationCore(Sema &S,
4426 const InitializedEntity &Entity,
4427 const InitializationKind &Kind,
4428 Expr *Initializer,
4429 QualType cv1T1, QualType T1,
4430 Qualifiers T1Quals,
4431 QualType cv2T2, QualType T2,
4432 Qualifiers T2Quals,
4433 InitializationSequence &Sequence) {
4434 QualType DestType = Entity.getType();
4435 SourceLocation DeclLoc = Initializer->getLocStart();
4436 // Compute some basic properties of the types and the initializer.
4437 bool isLValueRef = DestType->isLValueReferenceType();
4438 bool isRValueRef = !isLValueRef;
4439 bool DerivedToBase = false;
4440 bool ObjCConversion = false;
4441 bool ObjCLifetimeConversion = false;
4442 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4443 Sema::ReferenceCompareResult RefRelationship
4444 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4445 ObjCConversion, ObjCLifetimeConversion);
4446
4447 // C++0x [dcl.init.ref]p5:
4448 // A reference to type "cv1 T1" is initialized by an expression of type
4449 // "cv2 T2" as follows:
4450 //
4451 // - If the reference is an lvalue reference and the initializer
4452 // expression
4453 // Note the analogous bullet points for rvalue refs to functions. Because
4454 // there are no function rvalues in C++, rvalue refs to functions are treated
4455 // like lvalue refs.
4456 OverloadingResult ConvOvlResult = OR_Success;
4457 bool T1Function = T1->isFunctionType();
4458 if (isLValueRef || T1Function) {
4459 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4460 (RefRelationship == Sema::Ref_Compatible ||
4461 (Kind.isCStyleOrFunctionalCast() &&
4462 RefRelationship == Sema::Ref_Related))) {
4463 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4464 // reference-compatible with "cv2 T2," or
4465 if (T1Quals != T2Quals)
4466 // Convert to cv1 T2. This should only add qualifiers unless this is a
4467 // c-style cast. The removal of qualifiers in that case notionally
4468 // happens after the reference binding, but that doesn't matter.
4469 Sequence.AddQualificationConversionStep(
4470 S.Context.getQualifiedType(T2, T1Quals),
4471 Initializer->getValueKind());
4472 if (DerivedToBase)
4473 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4474 else if (ObjCConversion)
4475 Sequence.AddObjCObjectConversionStep(cv1T1);
4476
4477 // We only create a temporary here when binding a reference to a
4478 // bit-field or vector element. Those cases are't supposed to be
4479 // handled by this bullet, but the outcome is the same either way.
4480 Sequence.AddReferenceBindingStep(cv1T1, false);
4481 return;
4482 }
4483
4484 // - has a class type (i.e., T2 is a class type), where T1 is not
4485 // reference-related to T2, and can be implicitly converted to an
4486 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4487 // with "cv3 T3" (this conversion is selected by enumerating the
4488 // applicable conversion functions (13.3.1.6) and choosing the best
4489 // one through overload resolution (13.3)),
4490 // If we have an rvalue ref to function type here, the rhs must be
4491 // an rvalue. DR1287 removed the "implicitly" here.
4492 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4493 (isLValueRef || InitCategory.isRValue())) {
4494 ConvOvlResult = TryRefInitWithConversionFunction(
4495 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4496 /*IsLValueRef*/ isLValueRef, Sequence);
4497 if (ConvOvlResult == OR_Success)
4498 return;
4499 if (ConvOvlResult != OR_No_Viable_Function)
4500 Sequence.SetOverloadFailure(
4501 InitializationSequence::FK_ReferenceInitOverloadFailed,
4502 ConvOvlResult);
4503 }
4504 }
4505
4506 // - Otherwise, the reference shall be an lvalue reference to a
4507 // non-volatile const type (i.e., cv1 shall be const), or the reference
4508 // shall be an rvalue reference.
4509 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4510 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4511 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4512 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4513 Sequence.SetOverloadFailure(
4514 InitializationSequence::FK_ReferenceInitOverloadFailed,
4515 ConvOvlResult);
4516 else if (!InitCategory.isLValue())
4517 Sequence.SetFailed(
4518 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4519 else {
4520 InitializationSequence::FailureKind FK;
4521 switch (RefRelationship) {
4522 case Sema::Ref_Compatible:
4523 if (Initializer->refersToBitField())
4524 FK = InitializationSequence::
4525 FK_NonConstLValueReferenceBindingToBitfield;
4526 else if (Initializer->refersToVectorElement())
4527 FK = InitializationSequence::
4528 FK_NonConstLValueReferenceBindingToVectorElement;
4529 else
4530 llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4530)
;
4531 break;
4532 case Sema::Ref_Related:
4533 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4534 break;
4535 case Sema::Ref_Incompatible:
4536 FK = InitializationSequence::
4537 FK_NonConstLValueReferenceBindingToUnrelated;
4538 break;
4539 }
4540 Sequence.SetFailed(FK);
4541 }
4542 return;
4543 }
4544
4545 // - If the initializer expression
4546 // - is an
4547 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4548 // [1z] rvalue (but not a bit-field) or
4549 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4550 //
4551 // Note: functions are handled above and below rather than here...
4552 if (!T1Function &&
4553 (RefRelationship == Sema::Ref_Compatible ||
4554 (Kind.isCStyleOrFunctionalCast() &&
4555 RefRelationship == Sema::Ref_Related)) &&
4556 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4557 (InitCategory.isPRValue() &&
4558 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4559 T2->isArrayType())))) {
4560 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4561 if (InitCategory.isPRValue() && T2->isRecordType()) {
4562 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4563 // compiler the freedom to perform a copy here or bind to the
4564 // object, while C++0x requires that we bind directly to the
4565 // object. Hence, we always bind to the object without making an
4566 // extra copy. However, in C++03 requires that we check for the
4567 // presence of a suitable copy constructor:
4568 //
4569 // The constructor that would be used to make the copy shall
4570 // be callable whether or not the copy is actually done.
4571 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4572 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4573 else if (S.getLangOpts().CPlusPlus11)
4574 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4575 }
4576
4577 // C++1z [dcl.init.ref]/5.2.1.2:
4578 // If the converted initializer is a prvalue, its type T4 is adjusted
4579 // to type "cv1 T4" and the temporary materialization conversion is
4580 // applied.
4581 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4582 if (T1Quals != T2Quals)
4583 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4584 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4585 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4586
4587 // In any case, the reference is bound to the resulting glvalue (or to
4588 // an appropriate base class subobject).
4589 if (DerivedToBase)
4590 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4591 else if (ObjCConversion)
4592 Sequence.AddObjCObjectConversionStep(cv1T1);
4593 return;
4594 }
4595
4596 // - has a class type (i.e., T2 is a class type), where T1 is not
4597 // reference-related to T2, and can be implicitly converted to an
4598 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4599 // where "cv1 T1" is reference-compatible with "cv3 T3",
4600 //
4601 // DR1287 removes the "implicitly" here.
4602 if (T2->isRecordType()) {
4603 if (RefRelationship == Sema::Ref_Incompatible) {
4604 ConvOvlResult = TryRefInitWithConversionFunction(
4605 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4606 /*IsLValueRef*/ isLValueRef, Sequence);
4607 if (ConvOvlResult)
4608 Sequence.SetOverloadFailure(
4609 InitializationSequence::FK_ReferenceInitOverloadFailed,
4610 ConvOvlResult);
4611
4612 return;
4613 }
4614
4615 if (RefRelationship == Sema::Ref_Compatible &&
4616 isRValueRef && InitCategory.isLValue()) {
4617 Sequence.SetFailed(
4618 InitializationSequence::FK_RValueReferenceBindingToLValue);
4619 return;
4620 }
4621
4622 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4623 return;
4624 }
4625
4626 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4627 // from the initializer expression using the rules for a non-reference
4628 // copy-initialization (8.5). The reference is then bound to the
4629 // temporary. [...]
4630
4631 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4632
4633 // FIXME: Why do we use an implicit conversion here rather than trying
4634 // copy-initialization?
4635 ImplicitConversionSequence ICS
4636 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4637 /*SuppressUserConversions=*/false,
4638 /*AllowExplicit=*/false,
4639 /*FIXME:InOverloadResolution=*/false,
4640 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4641 /*AllowObjCWritebackConversion=*/false);
4642
4643 if (ICS.isBad()) {
4644 // FIXME: Use the conversion function set stored in ICS to turn
4645 // this into an overloading ambiguity diagnostic. However, we need
4646 // to keep that set as an OverloadCandidateSet rather than as some
4647 // other kind of set.
4648 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4649 Sequence.SetOverloadFailure(
4650 InitializationSequence::FK_ReferenceInitOverloadFailed,
4651 ConvOvlResult);
4652 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4653 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4654 else
4655 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4656 return;
4657 } else {
4658 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4659 }
4660
4661 // [...] If T1 is reference-related to T2, cv1 must be the
4662 // same cv-qualification as, or greater cv-qualification
4663 // than, cv2; otherwise, the program is ill-formed.
4664 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4665 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4666 if (RefRelationship == Sema::Ref_Related &&
4667 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4668 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4669 return;
4670 }
4671
4672 // [...] If T1 is reference-related to T2 and the reference is an rvalue
4673 // reference, the initializer expression shall not be an lvalue.
4674 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4675 InitCategory.isLValue()) {
4676 Sequence.SetFailed(
4677 InitializationSequence::FK_RValueReferenceBindingToLValue);
4678 return;
4679 }
4680
4681 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4682}
4683
4684/// Attempt character array initialization from a string literal
4685/// (C++ [dcl.init.string], C99 6.7.8).
4686static void TryStringLiteralInitialization(Sema &S,
4687 const InitializedEntity &Entity,
4688 const InitializationKind &Kind,
4689 Expr *Initializer,
4690 InitializationSequence &Sequence) {
4691 Sequence.AddStringInitStep(Entity.getType());
4692}
4693
4694/// Attempt value initialization (C++ [dcl.init]p7).
4695static void TryValueInitialization(Sema &S,
4696 const InitializedEntity &Entity,
4697 const InitializationKind &Kind,
4698 InitializationSequence &Sequence,
4699 InitListExpr *InitList) {
4700 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4701, __extension__ __PRETTY_FUNCTION__))
4701 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4701, __extension__ __PRETTY_FUNCTION__))
;
4702
4703 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4704 //
4705 // To value-initialize an object of type T means:
4706 QualType T = Entity.getType();
4707
4708 // -- if T is an array type, then each element is value-initialized;
4709 T = S.Context.getBaseElementType(T);
4710
4711 if (const RecordType *RT = T->getAs<RecordType>()) {
4712 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4713 bool NeedZeroInitialization = true;
4714 // C++98:
4715 // -- if T is a class type (clause 9) with a user-declared constructor
4716 // (12.1), then the default constructor for T is called (and the
4717 // initialization is ill-formed if T has no accessible default
4718 // constructor);
4719 // C++11:
4720 // -- if T is a class type (clause 9) with either no default constructor
4721 // (12.1 [class.ctor]) or a default constructor that is user-provided
4722 // or deleted, then the object is default-initialized;
4723 //
4724 // Note that the C++11 rule is the same as the C++98 rule if there are no
4725 // defaulted or deleted constructors, so we just use it unconditionally.
4726 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4727 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4728 NeedZeroInitialization = false;
4729
4730 // -- if T is a (possibly cv-qualified) non-union class type without a
4731 // user-provided or deleted default constructor, then the object is
4732 // zero-initialized and, if T has a non-trivial default constructor,
4733 // default-initialized;
4734 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4735 // constructor' part was removed by DR1507.
4736 if (NeedZeroInitialization)
4737 Sequence.AddZeroInitializationStep(Entity.getType());
4738
4739 // C++03:
4740 // -- if T is a non-union class type without a user-declared constructor,
4741 // then every non-static data member and base class component of T is
4742 // value-initialized;
4743 // [...] A program that calls for [...] value-initialization of an
4744 // entity of reference type is ill-formed.
4745 //
4746 // C++11 doesn't need this handling, because value-initialization does not
4747 // occur recursively there, and the implicit default constructor is
4748 // defined as deleted in the problematic cases.
4749 if (!S.getLangOpts().CPlusPlus11 &&
4750 ClassDecl->hasUninitializedReferenceMember()) {
4751 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4752 return;
4753 }
4754
4755 // If this is list-value-initialization, pass the empty init list on when
4756 // building the constructor call. This affects the semantics of a few
4757 // things (such as whether an explicit default constructor can be called).
4758 Expr *InitListAsExpr = InitList;
4759 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4760 bool InitListSyntax = InitList;
4761
4762 // FIXME: Instead of creating a CXXConstructExpr of array type here,
4763 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4764 return TryConstructorInitialization(
4765 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4766 }
4767 }
4768
4769 Sequence.AddZeroInitializationStep(Entity.getType());
4770}
4771
4772/// Attempt default initialization (C++ [dcl.init]p6).
4773static void TryDefaultInitialization(Sema &S,
4774 const InitializedEntity &Entity,
4775 const InitializationKind &Kind,
4776 InitializationSequence &Sequence) {
4777 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4777, __extension__ __PRETTY_FUNCTION__))
;
4778
4779 // C++ [dcl.init]p6:
4780 // To default-initialize an object of type T means:
4781 // - if T is an array type, each element is default-initialized;
4782 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4783
4784 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4785 // constructor for T is called (and the initialization is ill-formed if
4786 // T has no accessible default constructor);
4787 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4788 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4789 Entity.getType(), Sequence);
4790 return;
4791 }
4792
4793 // - otherwise, no initialization is performed.
4794
4795 // If a program calls for the default initialization of an object of
4796 // a const-qualified type T, T shall be a class type with a user-provided
4797 // default constructor.
4798 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4799 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4800 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4801 return;
4802 }
4803
4804 // If the destination type has a lifetime property, zero-initialize it.
4805 if (DestType.getQualifiers().hasObjCLifetime()) {
4806 Sequence.AddZeroInitializationStep(Entity.getType());
4807 return;
4808 }
4809}
4810
4811/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
4812/// which enumerates all conversion functions and performs overload resolution
4813/// to select the best.
4814static void TryUserDefinedConversion(Sema &S,
4815 QualType DestType,
4816 const InitializationKind &Kind,
4817 Expr *Initializer,
4818 InitializationSequence &Sequence,
4819 bool TopLevelOfInitList) {
4820 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4820, __extension__ __PRETTY_FUNCTION__))
;
4821 QualType SourceType = Initializer->getType();
4822 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4823, __extension__ __PRETTY_FUNCTION__))
4823 "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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 4823, __extension__ __PRETTY_FUNCTION__))
;
4824
4825 // Build the candidate set directly in the initialization sequence
4826 // structure, so that it will persist if we fail.
4827 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4828 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4829
4830 // Determine whether we are allowed to call explicit constructors or
4831 // explicit conversion operators.
4832 bool AllowExplicit = Kind.AllowExplicit();
4833
4834 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4835 // The type we're converting to is a class type. Enumerate its constructors
4836 // to see if there is a suitable conversion.
4837 CXXRecordDecl *DestRecordDecl
4838 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4839
4840 // Try to complete the type we're converting to.
4841 if (S.isCompleteType(Kind.getLocation(), DestType)) {
4842 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
4843 auto Info = getConstructorInfo(D);
4844 if (!Info.Constructor)
4845 continue;
4846
4847 if (!Info.Constructor->isInvalidDecl() &&
4848 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4849 if (Info.ConstructorTmpl)
4850 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4851 /*ExplicitArgs*/ nullptr,
4852 Initializer, CandidateSet,
4853 /*SuppressUserConversions=*/true);
4854 else
4855 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4856 Initializer, CandidateSet,
4857 /*SuppressUserConversions=*/true);
4858 }
4859 }
4860 }
4861 }
4862
4863 SourceLocation DeclLoc = Initializer->getLocStart();
4864
4865 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4866 // The type we're converting from is a class type, enumerate its conversion
4867 // functions.
4868
4869 // We can only enumerate the conversion functions for a complete type; if
4870 // the type isn't complete, simply skip this step.
4871 if (S.isCompleteType(DeclLoc, SourceType)) {
4872 CXXRecordDecl *SourceRecordDecl
4873 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4874
4875 const auto &Conversions =
4876 SourceRecordDecl->getVisibleConversionFunctions();
4877 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4878 NamedDecl *D = *I;
4879 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4880 if (isa<UsingShadowDecl>(D))
4881 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4882
4883 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4884 CXXConversionDecl *Conv;
4885 if (ConvTemplate)
4886 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4887 else
4888 Conv = cast<CXXConversionDecl>(D);
4889
4890 if (AllowExplicit || !Conv->isExplicit()) {
4891 if (ConvTemplate)
4892 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4893 ActingDC, Initializer, DestType,
4894 CandidateSet, AllowExplicit);
4895 else
4896 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4897 Initializer, DestType, CandidateSet,
4898 AllowExplicit);
4899 }
4900 }
4901 }
4902 }
4903
4904 // Perform overload resolution. If it fails, return the failed result.
4905 OverloadCandidateSet::iterator Best;
4906 if (OverloadingResult Result
4907 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4908 Sequence.SetOverloadFailure(
4909 InitializationSequence::FK_UserConversionOverloadFailed,
4910 Result);
4911 return;
4912 }
4913
4914 FunctionDecl *Function = Best->Function;
4915 Function->setReferenced();
4916 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4917
4918 if (isa<CXXConstructorDecl>(Function)) {
4919 // Add the user-defined conversion step. Any cv-qualification conversion is
4920 // subsumed by the initialization. Per DR5, the created temporary is of the
4921 // cv-unqualified type of the destination.
4922 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4923 DestType.getUnqualifiedType(),
4924 HadMultipleCandidates);
4925
4926 // C++14 and before:
4927 // - if the function is a constructor, the call initializes a temporary
4928 // of the cv-unqualified version of the destination type. The [...]
4929 // temporary [...] is then used to direct-initialize, according to the
4930 // rules above, the object that is the destination of the
4931 // copy-initialization.
4932 // Note that this just performs a simple object copy from the temporary.
4933 //
4934 // C++17:
4935 // - if the function is a constructor, the call is a prvalue of the
4936 // cv-unqualified version of the destination type whose return object
4937 // is initialized by the constructor. The call is used to
4938 // direct-initialize, according to the rules above, the object that
4939 // is the destination of the copy-initialization.
4940 // Therefore we need to do nothing further.
4941 //
4942 // FIXME: Mark this copy as extraneous.
4943 if (!S.getLangOpts().CPlusPlus17)
4944 Sequence.AddFinalCopy(DestType);
4945 else if (DestType.hasQualifiers())
4946 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4947 return;
4948 }
4949
4950 // Add the user-defined conversion step that calls the conversion function.
4951 QualType ConvType = Function->getCallResultType();
4952 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4953 HadMultipleCandidates);
4954
4955 if (ConvType->getAs<RecordType>()) {
4956 // The call is used to direct-initialize [...] the object that is the
4957 // destination of the copy-initialization.
4958 //
4959 // In C++17, this does not call a constructor if we enter /17.6.1:
4960 // - If the initializer expression is a prvalue and the cv-unqualified
4961 // version of the source type is the same as the class of the
4962 // destination [... do not make an extra copy]
4963 //
4964 // FIXME: Mark this copy as extraneous.
4965 if (!S.getLangOpts().CPlusPlus17 ||
4966 Function->getReturnType()->isReferenceType() ||
4967 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4968 Sequence.AddFinalCopy(DestType);
4969 else if (!S.Context.hasSameType(ConvType, DestType))
4970 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4971 return;
4972 }
4973
4974 // If the conversion following the call to the conversion function
4975 // is interesting, add it as a separate step.
4976 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4977 Best->FinalConversion.Third) {
4978 ImplicitConversionSequence ICS;
4979 ICS.setStandard();
4980 ICS.Standard = Best->FinalConversion;
4981 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4982 }
4983}
4984
4985/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4986/// a function with a pointer return type contains a 'return false;' statement.
4987/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4988/// code using that header.
4989///
4990/// Work around this by treating 'return false;' as zero-initializing the result
4991/// if it's used in a pointer-returning function in a system header.
4992static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4993 const InitializedEntity &Entity,
4994 const Expr *Init) {
4995 return S.getLangOpts().CPlusPlus11 &&
4996 Entity.getKind() == InitializedEntity::EK_Result &&
4997 Entity.getType()->isPointerType() &&
4998 isa<CXXBoolLiteralExpr>(Init) &&
4999 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5000 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5001}
5002
5003/// The non-zero enum values here are indexes into diagnostic alternatives.
5004enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5005
5006/// Determines whether this expression is an acceptable ICR source.
5007static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5008 bool isAddressOf, bool &isWeakAccess) {
5009 // Skip parens.
5010 e = e->IgnoreParens();
5011
5012 // Skip address-of nodes.
5013 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5014 if (op->getOpcode() == UO_AddrOf)
5015 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5016 isWeakAccess);
5017
5018 // Skip certain casts.
5019 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5020 switch (ce->getCastKind()) {
5021 case CK_Dependent:
5022 case CK_BitCast:
5023 case CK_LValueBitCast:
5024 case CK_NoOp:
5025 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5026
5027 case CK_ArrayToPointerDecay:
5028 return IIK_nonscalar;
5029
5030 case CK_NullToPointer:
5031 return IIK_okay;
5032
5033 default:
5034 break;
5035 }
5036
5037 // If we have a declaration reference, it had better be a local variable.
5038 } else if (isa<DeclRefExpr>(e)) {
5039 // set isWeakAccess to true, to mean that there will be an implicit
5040 // load which requires a cleanup.
5041 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5042 isWeakAccess = true;
5043
5044 if (!isAddressOf) return IIK_nonlocal;
5045
5046 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5047 if (!var) return IIK_nonlocal;
5048
5049 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5050
5051 // If we have a conditional operator, check both sides.
5052 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5053 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5054 isWeakAccess))
5055 return iik;
5056
5057 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5058
5059 // These are never scalar.
5060 } else if (isa<ArraySubscriptExpr>(e)) {
5061 return IIK_nonscalar;
5062
5063 // Otherwise, it needs to be a null pointer constant.
5064 } else {
5065 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5066 ? IIK_okay : IIK_nonlocal);
5067 }
5068
5069 return IIK_nonlocal;
5070}
5071
5072/// Check whether the given expression is a valid operand for an
5073/// indirect copy/restore.
5074static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5075 assert(src->isRValue())(static_cast <bool> (src->isRValue()) ? void (0) : __assert_fail
("src->isRValue()", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5075, __extension__ __PRETTY_FUNCTION__))
;
5076 bool isWeakAccess = false;
5077 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5078 // If isWeakAccess to true, there will be an implicit
5079 // load which requires a cleanup.
5080 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5081 S.Cleanup.setExprNeedsCleanups(true);
5082
5083 if (iik == IIK_okay) return;
5084
5085 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5086 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5087 << src->getSourceRange();
5088}
5089
5090/// Determine whether we have compatible array types for the
5091/// purposes of GNU by-copy array initialization.
5092static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5093 const ArrayType *Source) {
5094 // If the source and destination array types are equivalent, we're
5095 // done.
5096 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5097 return true;
5098
5099 // Make sure that the element types are the same.
5100 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5101 return false;
5102
5103 // The only mismatch we allow is when the destination is an
5104 // incomplete array type and the source is a constant array type.
5105 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5106}
5107
5108static bool tryObjCWritebackConversion(Sema &S,
5109 InitializationSequence &Sequence,
5110 const InitializedEntity &Entity,
5111 Expr *Initializer) {
5112 bool ArrayDecay = false;
5113 QualType ArgType = Initializer->getType();
5114 QualType ArgPointee;
5115 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5116 ArrayDecay = true;
5117 ArgPointee = ArgArrayType->getElementType();
5118 ArgType = S.Context.getPointerType(ArgPointee);
5119 }
5120
5121 // Handle write-back conversion.
5122 QualType ConvertedArgType;
5123 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5124 ConvertedArgType))
5125 return false;
5126
5127 // We should copy unless we're passing to an argument explicitly
5128 // marked 'out'.
5129 bool ShouldCopy = true;
5130 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5131 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5132
5133 // Do we need an lvalue conversion?
5134 if (ArrayDecay || Initializer->isGLValue()) {
5135 ImplicitConversionSequence ICS;
5136 ICS.setStandard();
5137 ICS.Standard.setAsIdentityConversion();
5138
5139 QualType ResultType;
5140 if (ArrayDecay) {
5141 ICS.Standard.First = ICK_Array_To_Pointer;
5142 ResultType = S.Context.getPointerType(ArgPointee);
5143 } else {
5144 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5145 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5146 }
5147
5148 Sequence.AddConversionSequenceStep(ICS, ResultType);
5149 }
5150
5151 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5152 return true;
5153}
5154
5155static bool TryOCLSamplerInitialization(Sema &S,
5156 InitializationSequence &Sequence,
5157 QualType DestType,
5158 Expr *Initializer) {
5159 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
22
Assuming the condition is false
5160 (!Initializer->isIntegerConstantExpr(S.Context) &&
23
Called C++ object pointer is null
5161 !Initializer->getType()->isSamplerT()))
5162 return false;
5163
5164 Sequence.AddOCLSamplerInitStep(DestType);
5165 return true;
5166}
5167
5168//
5169// OpenCL 1.2 spec, s6.12.10
5170//
5171// The event argument can also be used to associate the
5172// async_work_group_copy with a previous async copy allowing
5173// an event to be shared by multiple async copies; otherwise
5174// event should be zero.
5175//
5176static bool TryOCLZeroEventInitialization(Sema &S,
5177 InitializationSequence &Sequence,
5178 QualType DestType,
5179 Expr *Initializer) {
5180 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5181 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5182 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5183 return false;
5184
5185 Sequence.AddOCLZeroEventStep(DestType);
5186 return true;
5187}
5188
5189static bool TryOCLZeroQueueInitialization(Sema &S,
5190 InitializationSequence &Sequence,
5191 QualType DestType,
5192 Expr *Initializer) {
5193 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5194 !DestType->isQueueT() ||
5195 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5196 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5197 return false;
5198
5199 Sequence.AddOCLZeroQueueStep(DestType);
5200 return true;
5201}
5202
5203InitializationSequence::InitializationSequence(Sema &S,
5204 const InitializedEntity &Entity,
5205 const InitializationKind &Kind,
5206 MultiExprArg Args,
5207 bool TopLevelOfInitList,
5208 bool TreatUnavailableAsInvalid)
5209 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5210 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5211 TreatUnavailableAsInvalid);
5212}
5213
5214/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5215/// address of that function, this returns true. Otherwise, it returns false.
5216static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5217 auto *DRE = dyn_cast<DeclRefExpr>(E);
5218 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5219 return false;
5220
5221 return !S.checkAddressOfFunctionIsAvailable(
5222 cast<FunctionDecl>(DRE->getDecl()));
5223}
5224
5225/// Determine whether we can perform an elementwise array copy for this kind
5226/// of entity.
5227static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5228 switch (Entity.getKind()) {
5229 case InitializedEntity::EK_LambdaCapture:
5230 // C++ [expr.prim.lambda]p24:
5231 // For array members, the array elements are direct-initialized in
5232 // increasing subscript order.
5233 return true;
5234
5235 case InitializedEntity::EK_Variable:
5236 // C++ [dcl.decomp]p1:
5237 // [...] each element is copy-initialized or direct-initialized from the
5238 // corresponding element of the assignment-expression [...]
5239 return isa<DecompositionDecl>(Entity.getDecl());
5240
5241 case InitializedEntity::EK_Member:
5242 // C++ [class.copy.ctor]p14:
5243 // - if the member is an array, each element is direct-initialized with
5244 // the corresponding subobject of x
5245 return Entity.isImplicitMemberInitializer();
5246
5247 case InitializedEntity::EK_ArrayElement:
5248 // All the above cases are intended to apply recursively, even though none
5249 // of them actually say that.
5250 if (auto *E = Entity.getParent())
5251 return canPerformArrayCopy(*E);
5252 break;
5253
5254 default:
5255 break;
5256 }
5257
5258 return false;
5259}
5260
5261void InitializationSequence::InitializeFrom(Sema &S,
5262 const InitializedEntity &Entity,
5263 const InitializationKind &Kind,
5264 MultiExprArg Args,
5265 bool TopLevelOfInitList,
5266 bool TreatUnavailableAsInvalid) {
5267 ASTContext &Context = S.Context;
5268
5269 // Eliminate non-overload placeholder types in the arguments. We
5270 // need to do this before checking whether types are dependent
5271 // because lowering a pseudo-object expression might well give us
5272 // something of dependent type.
5273 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 5290
5274 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5275 // FIXME: should we be doing this here?
5276 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5277 if (result.isInvalid()) {
5278 SetFailed(FK_PlaceholderType);
5279 return;
5280 }
5281 Args[I] = result.get();
5282 }
5283
5284 // C++0x [dcl.init]p16:
5285 // The semantics of initializers are as follows. The destination type is
5286 // the type of the object or reference being initialized and the source
5287 // type is the type of the initializer expression. The source type is not
5288 // defined when the initializer is a braced-init-list or when it is a
5289 // parenthesized list of expressions.
5290 QualType DestType = Entity.getType();
5291
5292 if (DestType->isDependentType() ||
3
Assuming the condition is false
5
Taking false branch
5293 Expr::hasAnyTypeDependentArguments(Args)) {
4
Assuming the condition is false
5294 SequenceKind = DependentSequence;
5295 return;
5296 }
5297
5298 // Almost everything is a normal sequence.
5299 setSequenceKind(NormalSequence);
5300
5301 QualType SourceType;
5302 Expr *Initializer = nullptr;
6
'Initializer' initialized to a null pointer value
5303 if (Args.size() == 1) {
7
Assuming the condition is false
8
Taking false branch
5304 Initializer = Args[0];
5305 if (S.getLangOpts().ObjC1) {
5306 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5307 DestType, Initializer->getType(),
5308 Initializer) ||
5309 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5310 Args[0] = Initializer;
5311 }
5312 if (!isa<InitListExpr>(Initializer))
5313 SourceType = Initializer->getType();
5314 }
5315
5316 // - If the initializer is a (non-parenthesized) braced-init-list, the
5317 // object is list-initialized (8.5.4).
5318 if (Kind.getKind() != InitializationKind::IK_Direct) {
9
Assuming the condition is false
10
Taking false branch
5319 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5320 TryListInitialization(S, Entity, Kind, InitList, *this,
5321 TreatUnavailableAsInvalid);
5322 return;
5323 }
5324 }
5325
5326 // - If the destination type is a reference type, see 8.5.3.
5327 if (DestType->isReferenceType()) {
11
Taking false branch
5328 // C++0x [dcl.init.ref]p1:
5329 // A variable declared to be a T& or T&&, that is, "reference to type T"
5330 // (8.3.2), shall be initialized by an object, or function, of type T or
5331 // by an object that can be converted into a T.
5332 // (Therefore, multiple arguments are not permitted.)
5333 if (Args.size() != 1)
5334 SetFailed(FK_TooManyInitsForReference);
5335 // C++17 [dcl.init.ref]p5:
5336 // A reference [...] is initialized by an expression [...] as follows:
5337 // If the initializer is not an expression, presumably we should reject,
5338 // but the standard fails to actually say so.
5339 else if (isa<InitListExpr>(Args[0]))
5340 SetFailed(FK_ParenthesizedListInitForReference);
5341 else
5342 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5343 return;
5344 }
5345
5346 // - If the initializer is (), the object is value-initialized.
5347 if (Kind.getKind() == InitializationKind::IK_Value ||
13
Taking false branch
5348 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
12
Assuming the condition is false
5349 TryValueInitialization(S, Entity, Kind, *this);
5350 return;
5351 }
5352
5353 // Handle default initialization.
5354 if (Kind.getKind() == InitializationKind::IK_Default) {
14
Taking false branch
5355 TryDefaultInitialization(S, Entity, Kind, *this);
5356 return;
5357 }
5358
5359 // - If the destination type is an array of characters, an array of
5360 // char16_t, an array of char32_t, or an array of wchar_t, and the
5361 // initializer is a string literal, see 8.5.2.
5362 // - Otherwise, if the destination type is an array, the program is
5363 // ill-formed.
5364 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
15
Assuming 'DestAT' is null
16
Taking false branch
5365 if (Initializer && isa<VariableArrayType>(DestAT)) {
5366 SetFailed(FK_VariableLengthArrayHasInitializer);
5367 return;
5368 }
5369
5370 if (Initializer) {
5371 switch (IsStringInit(Initializer, DestAT, Context)) {
5372 case SIF_None:
5373 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5374 return;
5375 case SIF_NarrowStringIntoWideChar:
5376 SetFailed(FK_NarrowStringIntoWideCharArray);
5377 return;
5378 case SIF_WideStringIntoChar:
5379 SetFailed(FK_WideStringIntoCharArray);
5380 return;
5381 case SIF_IncompatWideStringIntoWideChar:
5382 SetFailed(FK_IncompatWideStringIntoWideChar);
5383 return;
5384 case SIF_PlainStringIntoUTF8Char:
5385 SetFailed(FK_PlainStringIntoUTF8Char);
5386 return;
5387 case SIF_UTF8StringIntoPlainChar:
5388 SetFailed(FK_UTF8StringIntoPlainChar);
5389 return;
5390 case SIF_Other:
5391 break;
5392 }
5393 }
5394
5395 // Some kinds of initialization permit an array to be initialized from
5396 // another array of the same type, and perform elementwise initialization.
5397 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5398 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5399 Entity.getType()) &&
5400 canPerformArrayCopy(Entity)) {
5401 // If source is a prvalue, use it directly.
5402 if (Initializer->getValueKind() == VK_RValue) {
5403 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5404 return;
5405 }
5406
5407 // Emit element-at-a-time copy loop.
5408 InitializedEntity Element =
5409 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5410 QualType InitEltT =
5411 Context.getAsArrayType(Initializer->getType())->getElementType();
5412 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5413 Initializer->getValueKind(),
5414 Initializer->getObjectKind());
5415 Expr *OVEAsExpr = &OVE;
5416 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5417 TreatUnavailableAsInvalid);
5418 if (!Failed())
5419 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5420 return;
5421 }
5422
5423 // Note: as an GNU C extension, we allow initialization of an
5424 // array from a compound literal that creates an array of the same
5425 // type, so long as the initializer has no side effects.
5426 if (!S.getLangOpts().CPlusPlus && Initializer &&
5427 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5428 Initializer->getType()->isArrayType()) {
5429 const ArrayType *SourceAT
5430 = Context.getAsArrayType(Initializer->getType());
5431 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5432 SetFailed(FK_ArrayTypeMismatch);
5433 else if (Initializer->HasSideEffects(S.Context))
5434 SetFailed(FK_NonConstantArrayInit);
5435 else {
5436 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5437 }
5438 }
5439 // Note: as a GNU C++ extension, we allow list-initialization of a
5440 // class member of array type from a parenthesized initializer list.
5441 else if (S.getLangOpts().CPlusPlus &&
5442 Entity.getKind() == InitializedEntity::EK_Member &&
5443 Initializer && isa<InitListExpr>(Initializer)) {
5444 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5445 *this, TreatUnavailableAsInvalid);
5446 AddParenthesizedArrayInitStep(DestType);
5447 } else if (DestAT->getElementType()->isCharType())
5448 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5449 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5450 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5451 else
5452 SetFailed(FK_ArrayNeedsInitList);
5453
5454 return;
5455 }
5456
5457 // Determine whether we should consider writeback conversions for
5458 // Objective-C ARC.
5459 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
17
Assuming the condition is false
5460 Entity.isParameterKind();
5461
5462 // We're at the end of the line for C: it's either a write-back conversion
5463 // or it's a C assignment. There's no need to check anything else.
5464 if (!S.getLangOpts().CPlusPlus) {
18
Assuming the condition is true
19
Taking true branch
5465 // If allowed, check whether this is an Objective-C writeback conversion.
5466 if (allowObjCWritebackConversion &&
5467 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5468 return;
5469 }
5470
5471 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
20
Passing null pointer value via 4th parameter 'Initializer'
21
Calling 'TryOCLSamplerInitialization'
5472 return;
5473
5474 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5475 return;
5476
5477 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5478 return;
5479
5480 // Handle initialization in C
5481 AddCAssignmentStep(DestType);
5482 MaybeProduceObjCObject(S, *this, Entity);
5483 return;
5484 }
5485
5486 assert(S.getLangOpts().CPlusPlus)(static_cast <bool> (S.getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("S.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
;
5487
5488 // - If the destination type is a (possibly cv-qualified) class type:
5489 if (DestType->isRecordType()) {
5490 // - If the initialization is direct-initialization, or if it is
5491 // copy-initialization where the cv-unqualified version of the
5492 // source type is the same class as, or a derived class of, the
5493 // class of the destination, constructors are considered. [...]
5494 if (Kind.getKind() == InitializationKind::IK_Direct ||
5495 (Kind.getKind() == InitializationKind::IK_Copy &&
5496 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5497 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
5498 TryConstructorInitialization(S, Entity, Kind, Args,
5499 DestType, DestType, *this);
5500 // - Otherwise (i.e., for the remaining copy-initialization cases),
5501 // user-defined conversion sequences that can convert from the source
5502 // type to the destination type or (when a conversion function is
5503 // used) to a derived class thereof are enumerated as described in
5504 // 13.3.1.4, and the best one is chosen through overload resolution
5505 // (13.3).
5506 else
5507 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5508 TopLevelOfInitList);
5509 return;
5510 }
5511
5512 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-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5512, __extension__ __PRETTY_FUNCTION__))
;
5513
5514 // The remaining cases all need a source type.
5515 if (Args.size() > 1) {
5516 SetFailed(FK_TooManyInitsForScalar);
5517 return;
5518 } else if (isa<InitListExpr>(Args[0])) {
5519 SetFailed(FK_ParenthesizedListInitForScalar);
5520 return;
5521 }
5522
5523 // - Otherwise, if the source type is a (possibly cv-qualified) class
5524 // type, conversion functions are considered.
5525 if (!SourceType.isNull() && SourceType->isRecordType()) {
5526 // For a conversion to _Atomic(T) from either T or a class type derived
5527 // from T, initialize the T object then convert to _Atomic type.
5528 bool NeedAtomicConversion = false;
5529 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5530 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5531 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5532 Atomic->getValueType())) {
5533 DestType = Atomic->getValueType();
5534 NeedAtomicConversion = true;
5535 }
5536 }
5537
5538 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5539 TopLevelOfInitList);
5540 MaybeProduceObjCObject(S, *this, Entity);
5541 if (!Failed() && NeedAtomicConversion)
5542 AddAtomicConversionStep(Entity.getType());
5543 return;
5544 }
5545
5546 // - Otherwise, the initial value of the object being initialized is the
5547 // (possibly converted) value of the initializer expression. Standard
5548 // conversions (Clause 4) will be used, if necessary, to convert the
5549 // initializer expression to the cv-unqualified version of the
5550 // destination type; no user-defined conversions are considered.
5551
5552 ImplicitConversionSequence ICS
5553 = S.TryImplicitConversion(Initializer, DestType,
5554 /*SuppressUserConversions*/true,
5555 /*AllowExplicitConversions*/ false,
5556 /*InOverloadResolution*/ false,
5557 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5558 allowObjCWritebackConversion);
5559
5560 if (ICS.isStandard() &&
5561 ICS.Standard.Second == ICK_Writeback_Conversion) {
5562 // Objective-C ARC writeback conversion.
5563
5564 // We should copy unless we're passing to an argument explicitly
5565 // marked 'out'.
5566 bool ShouldCopy = true;
5567 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5568 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5569
5570 // If there was an lvalue adjustment, add it as a separate conversion.
5571 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5572 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5573 ImplicitConversionSequence LvalueICS;
5574 LvalueICS.setStandard();
5575 LvalueICS.Standard.setAsIdentityConversion();
5576 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5577 LvalueICS.Standard.First = ICS.Standard.First;
5578 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5579 }
5580
5581 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5582 } else if (ICS.isBad()) {
5583 DeclAccessPair dap;
5584 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5585 AddZeroInitializationStep(Entity.getType());
5586 } else if (Initializer->getType() == Context.OverloadTy &&
5587 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5588 false, dap))
5589 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5590 else if (Initializer->getType()->isFunctionType() &&
5591 isExprAnUnaddressableFunction(S, Initializer))
5592 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
5593 else
5594 SetFailed(InitializationSequence::FK_ConversionFailed);
5595 } else {
5596 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5597
5598 MaybeProduceObjCObject(S, *this, Entity);
5599 }
5600}
5601
5602InitializationSequence::~InitializationSequence() {
5603 for (auto &S : Steps)
5604 S.Destroy();
5605}
5606
5607//===----------------------------------------------------------------------===//
5608// Perform initialization
5609//===----------------------------------------------------------------------===//
5610static Sema::AssignmentAction
5611getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5612 switch(Entity.getKind()) {
5613 case InitializedEntity::EK_Variable:
5614 case InitializedEntity::EK_New:
5615 case InitializedEntity::EK_Exception:
5616 case InitializedEntity::EK_Base:
5617 case InitializedEntity::EK_Delegating:
5618 return Sema::AA_Initializing;
5619
5620 case InitializedEntity::EK_Parameter:
5621 if (Entity.getDecl() &&
5622 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5623 return Sema::AA_Sending;
5624
5625 return Sema::AA_Passing;
5626
5627 case InitializedEntity::EK_Parameter_CF_Audited:
5628 if (Entity.getDecl() &&
5629 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5630 return Sema::AA_Sending;
5631
5632 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5633
5634 case InitializedEntity::EK_Result:
5635 return Sema::AA_Returning;
5636
5637 case InitializedEntity::EK_Temporary:
5638 case InitializedEntity::EK_RelatedResult:
5639 // FIXME: Can we tell apart casting vs. converting?
5640 return Sema::AA_Casting;
5641
5642 case InitializedEntity::EK_Member:
5643 case InitializedEntity::EK_Binding:
5644 case InitializedEntity::EK_ArrayElement:
5645 case InitializedEntity::EK_VectorElement:
5646 case InitializedEntity::EK_ComplexElement:
5647 case InitializedEntity::EK_BlockElement:
5648 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5649 case InitializedEntity::EK_LambdaCapture:
5650 case InitializedEntity::EK_CompoundLiteralInit:
5651 return Sema::AA_Initializing;
5652 }
5653
5654 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5654)
;
5655}
5656
5657/// Whether we should bind a created object as a temporary when
5658/// initializing the given entity.
5659static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5660 switch (Entity.getKind()) {
5661 case InitializedEntity::EK_ArrayElement:
5662 case InitializedEntity::EK_Member:
5663 case InitializedEntity::EK_Result:
5664 case InitializedEntity::EK_New:
5665 case InitializedEntity::EK_Variable:
5666 case InitializedEntity::EK_Base:
5667 case InitializedEntity::EK_Delegating:
5668 case InitializedEntity::EK_VectorElement:
5669 case InitializedEntity::EK_ComplexElement:
5670 case InitializedEntity::EK_Exception:
5671 case InitializedEntity::EK_BlockElement:
5672 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5673 case InitializedEntity::EK_LambdaCapture:
5674 case InitializedEntity::EK_CompoundLiteralInit:
5675 return false;
5676
5677 case InitializedEntity::EK_Parameter:
5678 case InitializedEntity::EK_Parameter_CF_Audited:
5679 case InitializedEntity::EK_Temporary:
5680 case InitializedEntity::EK_RelatedResult:
5681 case InitializedEntity::EK_Binding:
5682 return true;
5683 }
5684
5685 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5685)
;
5686}
5687
5688/// Whether the given entity, when initialized with an object
5689/// created for that initialization, requires destruction.
5690static bool shouldDestroyEntity(const InitializedEntity &Entity) {
5691 switch (Entity.getKind()) {
5692 case InitializedEntity::EK_Result:
5693 case InitializedEntity::EK_New:
5694 case InitializedEntity::EK_Base:
5695 case InitializedEntity::EK_Delegating:
5696 case InitializedEntity::EK_VectorElement:
5697 case InitializedEntity::EK_ComplexElement:
5698 case InitializedEntity::EK_BlockElement:
5699 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5700 case InitializedEntity::EK_LambdaCapture:
5701 return false;
5702
5703 case InitializedEntity::EK_Member:
5704 case InitializedEntity::EK_Binding:
5705 case InitializedEntity::EK_Variable:
5706 case InitializedEntity::EK_Parameter:
5707 case InitializedEntity::EK_Parameter_CF_Audited:
5708 case InitializedEntity::EK_Temporary:
5709 case InitializedEntity::EK_ArrayElement:
5710 case InitializedEntity::EK_Exception:
5711 case InitializedEntity::EK_CompoundLiteralInit:
5712 case InitializedEntity::EK_RelatedResult:
5713 return true;
5714 }
5715
5716 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5716)
;
5717}
5718
5719/// Get the location at which initialization diagnostics should appear.
5720static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5721 Expr *Initializer) {
5722 switch (Entity.getKind()) {
5723 case InitializedEntity::EK_Result:
5724 return Entity.getReturnLoc();
5725
5726 case InitializedEntity::EK_Exception:
5727 return Entity.getThrowLoc();
5728
5729 case InitializedEntity::EK_Variable:
5730 case InitializedEntity::EK_Binding:
5731 return Entity.getDecl()->getLocation();
5732
5733 case InitializedEntity::EK_LambdaCapture:
5734 return Entity.getCaptureLoc();
5735
5736 case InitializedEntity::EK_ArrayElement:
5737 case InitializedEntity::EK_Member:
5738 case InitializedEntity::EK_Parameter:
5739 case InitializedEntity::EK_Parameter_CF_Audited:
5740 case InitializedEntity::EK_Temporary:
5741 case InitializedEntity::EK_New:
5742 case InitializedEntity::EK_Base:
5743 case InitializedEntity::EK_Delegating:
5744 case InitializedEntity::EK_VectorElement:
5745 case InitializedEntity::EK_ComplexElement:
5746 case InitializedEntity::EK_BlockElement:
5747 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5748 case InitializedEntity::EK_CompoundLiteralInit:
5749 case InitializedEntity::EK_RelatedResult:
5750 return Initializer->getLocStart();
5751 }
5752 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5752)
;
5753}
5754
5755/// Make a (potentially elidable) temporary copy of the object
5756/// provided by the given initializer by calling the appropriate copy
5757/// constructor.
5758///
5759/// \param S The Sema object used for type-checking.
5760///
5761/// \param T The type of the temporary object, which must either be
5762/// the type of the initializer expression or a superclass thereof.
5763///
5764/// \param Entity The entity being initialized.
5765///
5766/// \param CurInit The initializer expression.
5767///
5768/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5769/// is permitted in C++03 (but not C++0x) when binding a reference to
5770/// an rvalue.
5771///
5772/// \returns An expression that copies the initializer expression into
5773/// a temporary object, or an error expression if a copy could not be
5774/// created.
5775static ExprResult CopyObject(Sema &S,
5776 QualType T,
5777 const InitializedEntity &Entity,
5778 ExprResult CurInit,
5779 bool IsExtraneousCopy) {
5780 if (CurInit.isInvalid())
5781 return CurInit;
5782 // Determine which class type we're copying to.
5783 Expr *CurInitExpr = (Expr *)CurInit.get();
5784 CXXRecordDecl *Class = nullptr;
5785 if (const RecordType *Record = T->getAs<RecordType>())
5786 Class = cast<CXXRecordDecl>(Record->getDecl());
5787 if (!Class)
5788 return CurInit;
5789
5790 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5791
5792 // Make sure that the type we are copying is complete.
5793 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5794 return CurInit;
5795
5796 // Perform overload resolution using the class's constructors. Per
5797 // C++11 [dcl.init]p16, second bullet for class types, this initialization
5798 // is direct-initialization.
5799 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5800 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
5801
5802 OverloadCandidateSet::iterator Best;
5803 switch (ResolveConstructorOverload(
5804 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
5805 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5806 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5807 /*SecondStepOfCopyInit=*/true)) {
5808 case OR_Success:
5809 break;
5810
5811 case OR_No_Viable_Function:
5812 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5813 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5814 : diag::err_temp_copy_no_viable)
5815 << (int)Entity.getKind() << CurInitExpr->getType()
5816 << CurInitExpr->getSourceRange();
5817 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5818 if (!IsExtraneousCopy || S.isSFINAEContext())
5819 return ExprError();
5820 return CurInit;
5821
5822 case OR_Ambiguous:
5823 S.Diag(Loc, diag::err_temp_copy_ambiguous)
5824 << (int)Entity.getKind() << CurInitExpr->getType()
5825 << CurInitExpr->getSourceRange();
5826 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5827 return ExprError();
5828
5829 case OR_Deleted:
5830 S.Diag(Loc, diag::err_temp_copy_deleted)
5831 << (int)Entity.getKind() << CurInitExpr->getType()
5832 << CurInitExpr->getSourceRange();
5833 S.NoteDeletedFunction(Best->Function);
5834 return ExprError();
5835 }
5836
5837 bool HadMultipleCandidates = CandidateSet.size() > 1;
5838
5839 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5840 SmallVector<Expr*, 8> ConstructorArgs;
5841 CurInit.get(); // Ownership transferred into MultiExprArg, below.
5842
5843 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5844 IsExtraneousCopy);
5845
5846 if (IsExtraneousCopy) {
5847 // If this is a totally extraneous copy for C++03 reference
5848 // binding purposes, just return the original initialization
5849 // expression. We don't generate an (elided) copy operation here
5850 // because doing so would require us to pass down a flag to avoid
5851 // infinite recursion, where each step adds another extraneous,
5852 // elidable copy.
5853
5854 // Instantiate the default arguments of any extra parameters in
5855 // the selected copy constructor, as if we were going to create a
5856 // proper call to the copy constructor.
5857 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5858 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5859 if (S.RequireCompleteType(Loc, Parm->getType(),
5860 diag::err_call_incomplete_argument))
5861 break;
5862
5863 // Build the default argument expression; we don't actually care
5864 // if this succeeds or not, because this routine will complain
5865 // if there was a problem.
5866 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5867 }
5868
5869 return CurInitExpr;
5870 }
5871
5872 // Determine the arguments required to actually perform the
5873 // constructor call (we might have derived-to-base conversions, or
5874 // the copy constructor may have default arguments).
5875 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5876 return ExprError();
5877
5878 // C++0x [class.copy]p32:
5879 // When certain criteria are met, an implementation is allowed to
5880 // omit the copy/move construction of a class object, even if the
5881 // copy/move constructor and/or destructor for the object have
5882 // side effects. [...]
5883 // - when a temporary class object that has not been bound to a
5884 // reference (12.2) would be copied/moved to a class object
5885 // with the same cv-unqualified type, the copy/move operation
5886 // can be omitted by constructing the temporary object
5887 // directly into the target of the omitted copy/move
5888 //
5889 // Note that the other three bullets are handled elsewhere. Copy
5890 // elision for return statements and throw expressions are handled as part
5891 // of constructor initialization, while copy elision for exception handlers
5892 // is handled by the run-time.
5893 //
5894 // FIXME: If the function parameter is not the same type as the temporary, we
5895 // should still be able to elide the copy, but we don't have a way to
5896 // represent in the AST how much should be elided in this case.
5897 bool Elidable =
5898 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5899 S.Context.hasSameUnqualifiedType(
5900 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5901 CurInitExpr->getType());
5902
5903 // Actually perform the constructor call.
5904 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5905 Elidable,
5906 ConstructorArgs,
5907 HadMultipleCandidates,
5908 /*ListInit*/ false,
5909 /*StdInitListInit*/ false,
5910 /*ZeroInit*/ false,
5911 CXXConstructExpr::CK_Complete,
5912 SourceRange());
5913
5914 // If we're supposed to bind temporaries, do so.
5915 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5916 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5917 return CurInit;
5918}
5919
5920/// Check whether elidable copy construction for binding a reference to
5921/// a temporary would have succeeded if we were building in C++98 mode, for
5922/// -Wc++98-compat.
5923static void CheckCXX98CompatAccessibleCopy(Sema &S,
5924 const InitializedEntity &Entity,
5925 Expr *CurInitExpr) {
5926 assert(S.getLangOpts().CPlusPlus11)(static_cast <bool> (S.getLangOpts().CPlusPlus11) ? void
(0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaInit.cpp"
, 5926, __extension__ __PRETTY_FUNCTION__))
;
5927
5928 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5929 if (!Record)
5930 return;
5931
5932 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5933 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5934 return;
5935
5936 // Find constructors which would have been considered.
5937 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5938 DeclContext::lookup_result Ctors =
5939 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
5940
5941 // Perform overload resolution.
5942 OverloadCandidateSet::iterator Best;
5943 OverloadingResult OR = ResolveConstructorOverload(
5944 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
5945 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5946 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5947 /*SecondStepOfCopyInit=*/true);
5948
5949 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5950 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5951 << CurInitExpr->getSourceRange();
5952