blob: 25d091f1d8c8227fecbb9d6cadd944c9b0c5cdd7 [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- 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//
Sebastian Redl26bcc942011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattner0cb78032009-02-24 22:27:37 +000011//
Steve Narofff8ecff22008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
James Molloy9eef2652014-06-20 14:35:13 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
Sebastian Redlc1839b12012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000035/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38 if (Context.typesAreCompatible(Context.getWideCharType(), T))
39 return true;
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
43 }
44 return false;
45}
46
47enum StringInitFailureKind {
48 SIF_None,
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
52 SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman893abe42009-05-29 18:22:49 +000063
Chris Lattnera9196812009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000066
Chris Lattnera9196812009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattnera9196812009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Craig Topperc3ec1492014-05-26 06:22:03 +000073 if (!SL)
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000074 return SIF_Other;
Eli Friedman42a84652009-05-31 10:54:53 +000075
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregorfb65e592011-07-27 05:40:30 +000078
79 switch (SL->getKind()) {
80 case StringLiteral::Ascii:
81 case StringLiteral::UTF8:
82 // char array can be initialized with a narrow string.
83 // Only allow char x[] = "foo"; not char x[] = L"foo";
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000084 if (ElemTy->isCharType())
85 return SIF_None;
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
88 return SIF_Other;
89 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90 // "An array with element type compatible with a qualified or unqualified
91 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92 // string literal with the corresponding encoding prefix (L, u, or U,
93 // respectively), optionally enclosed in braces.
Douglas Gregorfb65e592011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000095 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96 return SIF_None;
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
101 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104 return SIF_None;
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
109 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112 return SIF_None;
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
117 return SIF_Other;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregorfb65e592011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +0000121}
122
Hans Wennborg950f3182013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCall66884dd2011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborg950f3182013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCall66884dd2011-02-21 07:22:22 +0000129}
130
Richard Smith430c23b2013-05-05 16:40:13 +0000131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
Richard Smithd74b16062013-05-06 00:35:47 +0000134 while (true) {
Richard Smith430c23b2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smithd74b16062013-05-06 00:35:47 +0000136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137 break;
138 else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139 E = PE->getSubExpr();
140 else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141 E = UO->getSubExpr();
142 else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143 E = GSE->getResultExpr();
144 else
145 llvm_unreachable("unexpected expr in string literal init");
Richard Smith430c23b2013-05-05 16:40:13 +0000146 }
Richard Smith430c23b2013-05-05 16:40:13 +0000147}
148
John McCall5decec92011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000151 // Get the length of the string as parsed.
Ben Langmuir577b3932015-01-26 19:04:10 +0000152 auto *ConstantArrayTy =
Ben Langmuir7b30f532015-01-26 20:01:17 +0000153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
Ben Langmuir577b3932015-01-26 19:04:10 +0000154 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner0cb78032009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramere0731772012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattner0cb78032009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith430c23b2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000165 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000166 }
Mike Stump11289f42009-09-09 15:08:12 +0000167
Eli Friedman893abe42009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Eli Friedman554eba92011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000171 // the size may be smaller or larger than the string we are initializing.
172 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith430c23b2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000175 // For Pascal strings it's OK to strip off the terminating null character,
176 // so the example below is valid:
177 //
178 // unsigned char a[2] = "\pa";
179 if (SL->isPascal())
180 StrLength--;
181 }
182
Eli Friedman554eba92011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedman554eba92011-04-11 00:23:45 +0000186 diag::err_initializer_string_for_char_array_too_long)
187 << Str->getSourceRange();
188 } else {
189 // C99 6.7.8p14.
190 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Richard Smith1b98ccc2014-07-19 01:39:17 +0000192 diag::ext_initializer_string_for_char_array_too_long)
Eli Friedman554eba92011-04-11 00:23:45 +0000193 << Str->getSourceRange();
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Eli Friedman893abe42009-05-29 18:22:49 +0000196 // Set the type to the actual size that we are initializing. If we have
197 // something like:
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
Richard Smith430c23b2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000201}
202
Chris Lattner0cb78032009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000234namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramer6b441d62012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Anders Carlsson6cabf312010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smith4e0d2e42013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
264 unsigned &Index,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000305 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306 QualType CurrentObjectType,
307 InitListExpr *StructuredList,
308 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000309 SourceRange InitRange,
310 bool IsFullyOverwritten = false);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000311 void UpdateStructuredListElement(InitListExpr *StructuredList,
312 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000313 Expr *expr);
314 int numArrayElements(QualType DeclType);
315 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000316
Richard Smith454a7cd2014-06-03 08:26:00 +0000317 static ExprResult PerformEmptyInit(Sema &SemaRef,
318 SourceLocation Loc,
319 const InitializedEntity &Entity,
320 bool VerifyOnly);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000321
322 // Explanation on the "FillWithNoInit" mode:
323 //
324 // Assume we have the following definitions (Case#1):
325 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
326 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
327 //
328 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
329 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
330 //
331 // But if we have (Case#2):
332 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
333 //
334 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
335 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
336 //
337 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
338 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
339 // initializers but with special "NoInitExpr" place holders, which tells the
340 // CodeGen not to generate any initializers for these parts.
Richard Smith454a7cd2014-06-03 08:26:00 +0000341 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000342 const InitializedEntity &ParentEntity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000343 InitListExpr *ILE, bool &RequiresSecondPass,
344 bool FillWithNoInit = false);
Richard Smith454a7cd2014-06-03 08:26:00 +0000345 void FillInEmptyInitializations(const InitializedEntity &Entity,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000346 InitListExpr *ILE, bool &RequiresSecondPass,
347 bool FillWithNoInit = false);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000348 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
349 Expr *InitExpr, FieldDecl *Field,
350 bool TopLevelObject);
Richard Smith454a7cd2014-06-03 08:26:00 +0000351 void CheckEmptyInitializable(const InitializedEntity &Entity,
352 SourceLocation Loc);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000353
Douglas Gregor85df8d82009-01-29 00:45:39 +0000354public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000355 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000356 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000357 bool HadError() { return hadError; }
358
359 // @brief Retrieves the fully-structured initializer list used for
360 // semantic analysis and code generation.
361 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
362};
Chris Lattner9ececce2009-02-24 22:48:58 +0000363} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000364
Richard Smith454a7cd2014-06-03 08:26:00 +0000365ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
366 SourceLocation Loc,
367 const InitializedEntity &Entity,
368 bool VerifyOnly) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000369 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
370 true);
Richard Smith454a7cd2014-06-03 08:26:00 +0000371 MultiExprArg SubInit;
372 Expr *InitExpr;
373 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
374
375 // C++ [dcl.init.aggr]p7:
376 // If there are fewer initializer-clauses in the list than there are
377 // members in the aggregate, then each member not explicitly initialized
378 // ...
Nico Weberbcb70ee2014-07-02 23:51:09 +0000379 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
380 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
381 if (EmptyInitList) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000382 // C++1y / DR1070:
383 // shall be initialized [...] from an empty initializer list.
384 //
385 // We apply the resolution of this DR to C++11 but not C++98, since C++98
386 // does not have useful semantics for initialization from an init list.
387 // We treat this as copy-initialization, because aggregate initialization
388 // always performs copy-initialization on its elements.
389 //
390 // Only do this if we're initializing a class type, to avoid filling in
391 // the initializer list where possible.
392 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
393 InitListExpr(SemaRef.Context, Loc, None, Loc);
394 InitExpr->setType(SemaRef.Context.VoidTy);
395 SubInit = InitExpr;
396 Kind = InitializationKind::CreateCopy(Loc, Loc);
397 } else {
398 // C++03:
399 // shall be value-initialized.
400 }
401
402 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
Nico Weberbcb70ee2014-07-02 23:51:09 +0000403 // libstdc++4.6 marks the vector default constructor as explicit in
404 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
405 // stlport does so too. Look for std::__debug for libstdc++, and for
406 // std:: for stlport. This is effectively a compiler-side implementation of
407 // LWG2193.
408 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
409 InitializationSequence::FK_ExplicitConstructor) {
410 OverloadCandidateSet::iterator Best;
411 OverloadingResult O =
412 InitSeq.getFailedCandidateSet()
413 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
414 (void)O;
415 assert(O == OR_Success && "Inconsistent overload resolution");
416 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
417 CXXRecordDecl *R = CtorDecl->getParent();
418
419 if (CtorDecl->getMinRequiredArguments() == 0 &&
420 CtorDecl->isExplicit() && R->getDeclName() &&
421 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
422
423
424 bool IsInStd = false;
425 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
Nico Weber5752ad02014-07-03 00:38:25 +0000426 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
Nico Weberbcb70ee2014-07-02 23:51:09 +0000427 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
428 IsInStd = true;
429 }
430
431 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
432 .Cases("basic_string", "deque", "forward_list", true)
433 .Cases("list", "map", "multimap", "multiset", true)
434 .Cases("priority_queue", "queue", "set", "stack", true)
435 .Cases("unordered_map", "unordered_set", "vector", true)
436 .Default(false)) {
437 InitSeq.InitializeFrom(
438 SemaRef, Entity,
439 InitializationKind::CreateValue(Loc, Loc, Loc, true),
440 MultiExprArg(), /*TopLevelOfInitList=*/false);
441 // Emit a warning for this. System header warnings aren't shown
442 // by default, but people working on system headers should see it.
443 if (!VerifyOnly) {
444 SemaRef.Diag(CtorDecl->getLocation(),
445 diag::warn_invalid_initializer_from_system_header);
446 SemaRef.Diag(Entity.getDecl()->getLocation(),
447 diag::note_used_in_initialization_here);
448 }
449 }
450 }
451 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000452 if (!InitSeq) {
453 if (!VerifyOnly) {
454 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
455 if (Entity.getKind() == InitializedEntity::EK_Member)
456 SemaRef.Diag(Entity.getDecl()->getLocation(),
457 diag::note_in_omitted_aggregate_initializer)
458 << /*field*/1 << Entity.getDecl();
459 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
460 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
461 << /*array element*/0 << Entity.getElementIndex();
462 }
463 return ExprError();
464 }
465
466 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
467 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
468}
469
470void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
471 SourceLocation Loc) {
472 assert(VerifyOnly &&
473 "CheckEmptyInitializable is only inteded for verification mode.");
474 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000475 hadError = true;
476}
477
Richard Smith454a7cd2014-06-03 08:26:00 +0000478void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000479 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000480 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000481 bool &RequiresSecondPass,
482 bool FillWithNoInit) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000483 SourceLocation Loc = ILE->getLocEnd();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000484 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000486 = InitializedEntity::InitializeMember(Field, &ParentEntity);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000487
488 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
489 if (!RType->getDecl()->isUnion())
490 assert(Init < NumInits && "This ILE should have been expanded");
491
Douglas Gregor2bb07652009-12-22 00:05:34 +0000492 if (Init >= NumInits || !ILE->getInit(Init)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000493 if (FillWithNoInit) {
494 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
495 if (Init < NumInits)
496 ILE->setInit(Init, Filler);
497 else
498 ILE->updateInit(SemaRef.Context, Init, Filler);
499 return;
500 }
Richard Smith454a7cd2014-06-03 08:26:00 +0000501 // C++1y [dcl.init.aggr]p7:
502 // If there are fewer initializer-clauses in the list than there are
503 // members in the aggregate, then each member not explicitly initialized
504 // shall be initialized from its brace-or-equal-initializer [...]
Richard Smith852c9db2013-04-20 22:23:05 +0000505 if (Field->hasInClassInitializer()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000506 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
507 if (DIE.isInvalid()) {
508 hadError = true;
509 return;
510 }
Richard Smith852c9db2013-04-20 22:23:05 +0000511 if (Init < NumInits)
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000512 ILE->setInit(Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000513 else {
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000514 ILE->updateInit(SemaRef.Context, Init, DIE.get());
Richard Smith852c9db2013-04-20 22:23:05 +0000515 RequiresSecondPass = true;
516 }
517 return;
518 }
519
Douglas Gregor2bb07652009-12-22 00:05:34 +0000520 if (Field->getType()->isReferenceType()) {
521 // C++ [dcl.init.aggr]p9:
522 // If an incomplete or empty initializer-list leaves a
523 // member of reference type uninitialized, the program is
524 // ill-formed.
525 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
526 << Field->getType()
527 << ILE->getSyntacticForm()->getSourceRange();
528 SemaRef.Diag(Field->getLocation(),
529 diag::note_uninit_reference_member);
530 hadError = true;
531 return;
532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Richard Smith454a7cd2014-06-03 08:26:00 +0000534 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
535 /*VerifyOnly*/false);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000536 if (MemberInit.isInvalid()) {
537 hadError = true;
538 return;
539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor2bb07652009-12-22 00:05:34 +0000541 if (hadError) {
542 // Do nothing
543 } else if (Init < NumInits) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000544 ILE->setInit(Init, MemberInit.getAs<Expr>());
Richard Smith454a7cd2014-06-03 08:26:00 +0000545 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
546 // Empty initialization requires a constructor call, so
Douglas Gregor2bb07652009-12-22 00:05:34 +0000547 // extend the initializer list to include the constructor
548 // call and make a note that we'll need to take another pass
549 // through the initializer list.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000550 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000551 RequiresSecondPass = true;
552 }
553 } else if (InitListExpr *InnerILE
554 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Richard Smith454a7cd2014-06-03 08:26:00 +0000555 FillInEmptyInitializations(MemberEntity, InnerILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000556 RequiresSecondPass, FillWithNoInit);
557 else if (DesignatedInitUpdateExpr *InnerDIUE
558 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
559 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
560 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000561}
562
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000563/// Recursively replaces NULL values within the given initializer list
564/// with expressions that perform value-initialization of the
565/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566void
Richard Smith454a7cd2014-06-03 08:26:00 +0000567InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
Douglas Gregor723796a2009-12-16 06:35:08 +0000568 InitListExpr *ILE,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000569 bool &RequiresSecondPass,
570 bool FillWithNoInit) {
Mike Stump11289f42009-09-09 15:08:12 +0000571 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000572 "Should not have void type");
Mike Stump11289f42009-09-09 15:08:12 +0000573
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000574 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000575 const RecordDecl *RDecl = RType->getDecl();
576 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Richard Smith454a7cd2014-06-03 08:26:00 +0000577 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
Yunzhong Gaocb779302015-06-10 00:27:52 +0000578 Entity, ILE, RequiresSecondPass, FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000579 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
580 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000581 for (auto *Field : RDecl->fields()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000582 if (Field->hasInClassInitializer()) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000583 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
584 FillWithNoInit);
Richard Smith852c9db2013-04-20 22:23:05 +0000585 break;
586 }
587 }
588 } else {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000589 // The fields beyond ILE->getNumInits() are default initialized, so in
590 // order to leave them uninitialized, the ILE is expanded and the extra
591 // fields are then filled with NoInitExpr.
592 unsigned NumFields = 0;
593 for (auto *Field : RDecl->fields())
594 if (!Field->isUnnamedBitfield())
595 ++NumFields;
596 if (ILE->getNumInits() < NumFields)
597 ILE->resizeInits(SemaRef.Context, NumFields);
598
Douglas Gregor2bb07652009-12-22 00:05:34 +0000599 unsigned Init = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000600 for (auto *Field : RDecl->fields()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000601 if (Field->isUnnamedBitfield())
602 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000603
Douglas Gregor2bb07652009-12-22 00:05:34 +0000604 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000605 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000606
Yunzhong Gaocb779302015-06-10 00:27:52 +0000607 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
608 FillWithNoInit);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000609 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000610 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000611
Douglas Gregor2bb07652009-12-22 00:05:34 +0000612 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000613
Douglas Gregor2bb07652009-12-22 00:05:34 +0000614 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000615 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000616 break;
617 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000618 }
619
620 return;
Mike Stump11289f42009-09-09 15:08:12 +0000621 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000622
623 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000624
Douglas Gregor723796a2009-12-16 06:35:08 +0000625 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000626 unsigned NumInits = ILE->getNumInits();
627 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000628 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000629 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000630 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
631 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000633 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000634 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000635 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000636 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000638 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000639 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000640 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000641
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000642 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000643 if (hadError)
644 return;
645
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000646 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
647 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000648 ElementEntity.setElementIndex(Init);
649
Craig Topperc3ec1492014-05-26 06:22:03 +0000650 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000651 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
652 ILE->setInit(Init, ILE->getArrayFiller());
653 else if (!InitExpr && !ILE->hasArrayFiller()) {
654 Expr *Filler = nullptr;
655
656 if (FillWithNoInit)
657 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
658 else {
659 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
660 ElementEntity,
661 /*VerifyOnly*/false);
662 if (ElementInit.isInvalid()) {
663 hadError = true;
664 return;
665 }
666
667 Filler = ElementInit.getAs<Expr>();
Douglas Gregor723796a2009-12-16 06:35:08 +0000668 }
669
670 if (hadError) {
671 // Do nothing
672 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000673 // For arrays, just set the expression used for value-initialization
674 // of the "holes" in the array.
675 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
Yunzhong Gaocb779302015-06-10 00:27:52 +0000676 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000677 else
Yunzhong Gaocb779302015-06-10 00:27:52 +0000678 ILE->setInit(Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000679 } else {
680 // For arrays, just set the expression used for value-initialization
681 // of the rest of elements and exit.
682 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
Yunzhong Gaocb779302015-06-10 00:27:52 +0000683 ILE->setArrayFiller(Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000684 return;
685 }
686
Yunzhong Gaocb779302015-06-10 00:27:52 +0000687 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
Richard Smith454a7cd2014-06-03 08:26:00 +0000688 // Empty initialization requires a constructor call, so
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000689 // extend the initializer list to include the constructor
690 // call and make a note that we'll need to take another pass
691 // through the initializer list.
Yunzhong Gaocb779302015-06-10 00:27:52 +0000692 ILE->updateInit(SemaRef.Context, Init, Filler);
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000693 RequiresSecondPass = true;
694 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000695 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000696 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000697 = dyn_cast_or_null<InitListExpr>(InitExpr))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000698 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
699 FillWithNoInit);
700 else if (DesignatedInitUpdateExpr *InnerDIUE
701 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
702 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
703 RequiresSecondPass, /*FillWithNoInit =*/ true);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000704 }
705}
706
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000707
Douglas Gregor723796a2009-12-16 06:35:08 +0000708InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000709 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000710 bool VerifyOnly)
711 : SemaRef(S), VerifyOnly(VerifyOnly) {
Richard Smith520449d2015-02-05 06:15:50 +0000712 // FIXME: Check that IL isn't already the semantic form of some other
713 // InitListExpr. If it is, we'd create a broken AST.
714
Steve Narofff8ecff22008-05-01 22:18:59 +0000715 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000716
Richard Smith4e0d2e42013-09-20 20:10:22 +0000717 FullyStructuredList =
Craig Topperc3ec1492014-05-26 06:22:03 +0000718 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000719 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000720 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000721
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000722 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000723 bool RequiresSecondPass = false;
Richard Smith454a7cd2014-06-03 08:26:00 +0000724 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000725 if (RequiresSecondPass && !hadError)
Richard Smith454a7cd2014-06-03 08:26:00 +0000726 FillInEmptyInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000727 RequiresSecondPass);
728 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000729}
730
731int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000732 // FIXME: use a proper constant
733 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000734 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000735 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000736 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
737 }
738 return maxElements;
739}
740
741int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000742 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 int InitializableMembers = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000744 for (const auto *Field : structDecl->fields())
Douglas Gregor556e5862011-10-10 17:22:13 +0000745 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000746 ++InitializableMembers;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000747
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000748 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000749 return std::min(InitializableMembers, 1);
750 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000751}
752
Richard Smith4e0d2e42013-09-20 20:10:22 +0000753/// Check whether the range of the initializer \p ParentIList from element
754/// \p Index onwards can be used to initialize an object of type \p T. Update
755/// \p Index to indicate how many elements of the list were consumed.
756///
757/// This also fills in \p StructuredList, from element \p StructuredIndex
758/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000759void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000760 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000761 QualType T, unsigned &Index,
762 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000763 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000764 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000765
Steve Narofff8ecff22008-05-01 22:18:59 +0000766 if (T->isArrayType())
767 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000768 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000769 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000770 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000771 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000772 else
David Blaikie83d382b2011-09-23 05:06:16 +0000773 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000774
Eli Friedmane0f832b2008-05-25 13:49:22 +0000775 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000776 if (!VerifyOnly)
777 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
778 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000779 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000780 hadError = true;
781 return;
782 }
783
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000784 // Build a structured initializer list corresponding to this subobject.
785 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000786 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
787 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000788 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000789 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000790 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000791
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000792 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000793 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000795 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000796 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000797 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000798
Richard Smithde229232013-06-06 11:41:05 +0000799 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000800 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000801
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000802 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000803 // Update the structured sub-object initializer so that it's ending
804 // range corresponds with the end of the last initializer it used.
805 if (EndIndex < ParentIList->getNumInits()) {
806 SourceLocation EndLoc
807 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
808 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000811 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000812 if (T->isArrayType() || T->isRecordType()) {
813 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000814 diag::warn_missing_braces)
Alp Tokerb6cc5922014-05-03 03:45:55 +0000815 << StructuredSubobjectInitList->getSourceRange()
816 << FixItHint::CreateInsertion(
817 StructuredSubobjectInitList->getLocStart(), "{")
818 << FixItHint::CreateInsertion(
819 SemaRef.getLocForEndOfToken(
820 StructuredSubobjectInitList->getLocEnd()),
821 "}");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000822 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000823 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000824}
825
Richard Smith420fa122015-02-12 01:50:05 +0000826/// Warn that \p Entity was of scalar type and was initialized by a
827/// single-element braced initializer list.
828static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
829 SourceRange Braces) {
830 // Don't warn during template instantiation. If the initialization was
831 // non-dependent, we warned during the initial parse; otherwise, the
832 // type might not be scalar in some uses of the template.
833 if (!S.ActiveTemplateInstantiations.empty())
834 return;
835
836 unsigned DiagID = 0;
837
838 switch (Entity.getKind()) {
839 case InitializedEntity::EK_VectorElement:
840 case InitializedEntity::EK_ComplexElement:
841 case InitializedEntity::EK_ArrayElement:
842 case InitializedEntity::EK_Parameter:
843 case InitializedEntity::EK_Parameter_CF_Audited:
844 case InitializedEntity::EK_Result:
845 // Extra braces here are suspicious.
846 DiagID = diag::warn_braces_around_scalar_init;
847 break;
848
849 case InitializedEntity::EK_Member:
850 // Warn on aggregate initialization but not on ctor init list or
851 // default member initializer.
852 if (Entity.getParent())
853 DiagID = diag::warn_braces_around_scalar_init;
854 break;
855
856 case InitializedEntity::EK_Variable:
857 case InitializedEntity::EK_LambdaCapture:
858 // No warning, might be direct-list-initialization.
859 // FIXME: Should we warn for copy-list-initialization in these cases?
860 break;
861
862 case InitializedEntity::EK_New:
863 case InitializedEntity::EK_Temporary:
864 case InitializedEntity::EK_CompoundLiteralInit:
865 // No warning, braces are part of the syntax of the underlying construct.
866 break;
867
868 case InitializedEntity::EK_RelatedResult:
869 // No warning, we already warned when initializing the result.
870 break;
871
872 case InitializedEntity::EK_Exception:
873 case InitializedEntity::EK_Base:
874 case InitializedEntity::EK_Delegating:
875 case InitializedEntity::EK_BlockElement:
876 llvm_unreachable("unexpected braced scalar init");
877 }
878
879 if (DiagID) {
880 S.Diag(Braces.getBegin(), DiagID)
881 << Braces
882 << FixItHint::CreateRemoval(Braces.getBegin())
883 << FixItHint::CreateRemoval(Braces.getEnd());
884 }
885}
886
887
Richard Smith4e0d2e42013-09-20 20:10:22 +0000888/// Check whether the initializer \p IList (that was written with explicit
889/// braces) can be used to initialize an object of type \p T.
890///
891/// This also fills in \p StructuredList with the fully-braced, desugared
892/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000893void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000894 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000895 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000896 bool TopLevelObject) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000897 if (!VerifyOnly) {
898 SyntacticToSemantic[IList] = StructuredList;
899 StructuredList->setSyntacticForm(IList);
900 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000901
902 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000904 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000905 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000906 QualType ExprTy = T;
907 if (!ExprTy->isArrayType())
908 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000909 IList->setType(ExprTy);
910 StructuredList->setType(ExprTy);
911 }
Eli Friedman85f54972008-05-25 13:22:35 +0000912 if (hadError)
913 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000914
Eli Friedman85f54972008-05-25 13:22:35 +0000915 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000916 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000917 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000918 if (SemaRef.getLangOpts().CPlusPlus ||
919 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000920 IList->getType()->isVectorType())) {
921 hadError = true;
922 }
923 return;
924 }
925
Eli Friedmanbd327452009-05-29 20:20:05 +0000926 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000927 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
928 SIF_None) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000929 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000930 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000931 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000932 hadError = true;
933 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000934 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000935 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000936 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000937 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000938 // Don't complain for incomplete types, since we'll get an error
939 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000940 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000941 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000942 CurrentObjectType->isArrayType()? 0 :
943 CurrentObjectType->isVectorType()? 1 :
944 CurrentObjectType->isScalarType()? 2 :
945 CurrentObjectType->isUnionType()? 3 :
946 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000947
Richard Smith1b98ccc2014-07-19 01:39:17 +0000948 unsigned DK = diag::ext_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000949 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000950 DK = diag::err_excess_initializers;
951 hadError = true;
952 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000953 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000954 DK = diag::err_excess_initializers;
955 hadError = true;
956 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000957
Chris Lattnerb0912a52009-02-24 22:50:46 +0000958 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000959 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000960 }
961 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000962
Richard Smith420fa122015-02-12 01:50:05 +0000963 if (!VerifyOnly && T->isScalarType() &&
964 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
965 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
Steve Narofff8ecff22008-05-01 22:18:59 +0000966}
967
Anders Carlsson6cabf312010-01-23 23:23:01 +0000968void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000969 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000970 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000971 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000972 unsigned &Index,
973 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000974 unsigned &StructuredIndex,
975 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000976 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
977 // Explicitly braced initializer for complex type can be real+imaginary
978 // parts.
979 CheckComplexType(Entity, IList, DeclType, Index,
980 StructuredList, StructuredIndex);
981 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000982 CheckScalarType(Entity, IList, DeclType, Index,
983 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000984 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000986 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000987 } else if (DeclType->isRecordType()) {
988 assert(DeclType->isAggregateType() &&
989 "non-aggregate records should be handed in CheckSubElementType");
990 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
991 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
992 SubobjectIsDesignatorContext, Index,
993 StructuredList, StructuredIndex,
994 TopLevelObject);
995 } else if (DeclType->isArrayType()) {
996 llvm::APSInt Zero(
997 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
998 false);
999 CheckArrayType(Entity, IList, DeclType, Zero,
1000 SubobjectIsDesignatorContext, Index,
1001 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +00001002 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1003 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001004 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001005 if (!VerifyOnly)
1006 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1007 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +00001008 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +00001009 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +00001010 CheckReferenceType(Entity, IList, DeclType, Index,
1011 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +00001012 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001013 if (!VerifyOnly)
1014 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1015 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001016 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001017 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001018 if (!VerifyOnly)
1019 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1020 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +00001021 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +00001022 }
1023}
1024
Anders Carlsson6cabf312010-01-23 23:23:01 +00001025void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001026 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001027 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001028 unsigned &Index,
1029 InitListExpr *StructuredList,
1030 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +00001031 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +00001032
1033 if (ElemType->isReferenceType())
1034 return CheckReferenceType(Entity, IList, ElemType, Index,
1035 StructuredList, StructuredIndex);
1036
Eli Friedman5a36d3f2008-05-19 20:00:43 +00001037 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Yunzhong Gaocb779302015-06-10 00:27:52 +00001038 if (SubInitList->getNumInits() == 1 &&
1039 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1040 SIF_None) {
1041 expr = SubInitList->getInit(0);
1042 } else if (!SemaRef.getLangOpts().CPlusPlus) {
Richard Smith4e0d2e42013-09-20 20:10:22 +00001043 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +00001044 = getStructuredSubobjectInit(IList, Index, ElemType,
1045 StructuredList, StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001046 SubInitList->getSourceRange(), true);
Richard Smith4e0d2e42013-09-20 20:10:22 +00001047 CheckExplicitInitList(Entity, SubInitList, ElemType,
1048 InnerStructuredList);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001049
1050 if (!hadError && !VerifyOnly) {
1051 bool RequiresSecondPass = false;
1052 FillInEmptyInitializations(Entity, InnerStructuredList,
1053 RequiresSecondPass);
1054 if (RequiresSecondPass && !hadError)
1055 FillInEmptyInitializations(Entity, InnerStructuredList,
1056 RequiresSecondPass);
1057 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001058 ++StructuredIndex;
1059 ++Index;
1060 return;
1061 }
Richard Smithe20c83d2012-07-07 08:35:56 +00001062 // C++ initialization is handled later.
Richard Smithc4158e862014-07-18 04:47:25 +00001063 } else if (isa<ImplicitValueInitExpr>(expr)) {
Richard Smith8aa561b2014-07-17 23:12:06 +00001064 // This happens during template instantiation when we see an InitListExpr
1065 // that we've already checked once.
Richard Smithc4158e862014-07-18 04:47:25 +00001066 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
Richard Smith8aa561b2014-07-17 23:12:06 +00001067 "found implicit initialization for the wrong type");
1068 if (!VerifyOnly)
1069 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1070 ++Index;
1071 return;
Richard Smithe20c83d2012-07-07 08:35:56 +00001072 }
1073
Richard Smith3c567fc2015-02-12 01:55:09 +00001074 if (SemaRef.getLangOpts().CPlusPlus) {
1075 // C++ [dcl.init.aggr]p2:
1076 // Each member is copy-initialized from the corresponding
1077 // initializer-clause.
1078
1079 // FIXME: Better EqualLoc?
1080 InitializationKind Kind =
1081 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1082 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1083 /*TopLevelOfInitList*/ true);
1084
1085 // C++14 [dcl.init.aggr]p13:
1086 // If the assignment-expression can initialize a member, the member is
1087 // initialized. Otherwise [...] brace elision is assumed
1088 //
1089 // Brace elision is never performed if the element is not an
1090 // assignment-expression.
1091 if (Seq || isa<InitListExpr>(expr)) {
1092 if (!VerifyOnly) {
1093 ExprResult Result =
1094 Seq.Perform(SemaRef, Entity, Kind, expr);
1095 if (Result.isInvalid())
1096 hadError = true;
1097
1098 UpdateStructuredListElement(StructuredList, StructuredIndex,
1099 Result.getAs<Expr>());
Richard Smith40574cc2015-02-16 04:42:59 +00001100 } else if (!Seq)
1101 hadError = true;
Richard Smith3c567fc2015-02-12 01:55:09 +00001102 ++Index;
1103 return;
1104 }
1105
1106 // Fall through for subaggregate initialization
1107 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1108 // FIXME: Need to handle atomic aggregate types with implicit init lists.
John McCall5decec92011-02-21 07:57:55 +00001109 return CheckScalarType(Entity, IList, ElemType, Index,
1110 StructuredList, StructuredIndex);
Richard Smith3c567fc2015-02-12 01:55:09 +00001111 } else if (const ArrayType *arrayType =
1112 SemaRef.Context.getAsArrayType(ElemType)) {
John McCall5decec92011-02-21 07:57:55 +00001113 // arrayType can be incomplete if we're initializing a flexible
1114 // array member. There's nothing we can do with the completed
1115 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001117 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +00001118 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001119 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1120 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +00001121 }
Douglas Gregord14247a2009-01-30 22:09:00 +00001122 ++Index;
John McCall5decec92011-02-21 07:57:55 +00001123 return;
Douglas Gregord14247a2009-01-30 22:09:00 +00001124 }
John McCall5decec92011-02-21 07:57:55 +00001125
1126 // Fall through for subaggregate initialization.
1127
John McCall5decec92011-02-21 07:57:55 +00001128 } else {
Richard Smith3c567fc2015-02-12 01:55:09 +00001129 assert((ElemType->isRecordType() || ElemType->isVectorType()) &&
1130 "Unexpected type");
1131
John McCall5decec92011-02-21 07:57:55 +00001132 // C99 6.7.8p13:
1133 //
1134 // The initializer for a structure or union object that has
1135 // automatic storage duration shall be either an initializer
1136 // list as described below, or a single expression that has
1137 // compatible structure or union type. In the latter case, the
1138 // initial value of the object, including unnamed members, is
1139 // that of the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001140 ExprResult ExprRes = expr;
Richard Smith3c567fc2015-02-12 01:55:09 +00001141 if (SemaRef.CheckSingleAssignmentConstraints(
1142 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +00001143 if (ExprRes.isInvalid())
1144 hadError = true;
1145 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001146 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001147 if (ExprRes.isInvalid())
1148 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +00001149 }
1150 UpdateStructuredListElement(StructuredList, StructuredIndex,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001151 ExprRes.getAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +00001152 ++Index;
1153 return;
1154 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001155 ExprRes.get();
John McCall5decec92011-02-21 07:57:55 +00001156 // Fall through for subaggregate initialization
1157 }
1158
1159 // C++ [dcl.init.aggr]p12:
1160 //
1161 // [...] Otherwise, if the member is itself a non-empty
1162 // subaggregate, brace elision is assumed and the initializer is
1163 // considered for the initialization of the first member of
1164 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001165 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00001166 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +00001167 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1168 StructuredIndex);
1169 ++StructuredIndex;
1170 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001171 if (!VerifyOnly) {
1172 // We cannot initialize this element, so let
1173 // PerformCopyInitialization produce the appropriate diagnostic.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001174 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001175 /*TopLevelOfInitList=*/true);
1176 }
John McCall5decec92011-02-21 07:57:55 +00001177 hadError = true;
1178 ++Index;
1179 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +00001180 }
Eli Friedman23a9e312008-05-19 19:16:24 +00001181}
1182
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001183void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1184 InitListExpr *IList, QualType DeclType,
1185 unsigned &Index,
1186 InitListExpr *StructuredList,
1187 unsigned &StructuredIndex) {
1188 assert(Index == 0 && "Index in explicit init list must be zero");
1189
1190 // As an extension, clang supports complex initializers, which initialize
1191 // a complex number component-wise. When an explicit initializer list for
1192 // a complex number contains two two initializers, this extension kicks in:
1193 // it exepcts the initializer list to contain two elements convertible to
1194 // the element type of the complex type. The first element initializes
1195 // the real part, and the second element intitializes the imaginary part.
1196
1197 if (IList->getNumInits() != 2)
1198 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1199 StructuredIndex);
1200
1201 // This is an extension in C. (The builtin _Complex type does not exist
1202 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +00001204 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1205 << IList->getSourceRange();
1206
1207 // Initialize the complex number.
1208 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1209 InitializedEntity ElementEntity =
1210 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1211
1212 for (unsigned i = 0; i < 2; ++i) {
1213 ElementEntity.setElementIndex(Index);
1214 CheckSubElementType(ElementEntity, IList, elementType, Index,
1215 StructuredList, StructuredIndex);
1216 }
1217}
1218
1219
Anders Carlsson6cabf312010-01-23 23:23:01 +00001220void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001221 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +00001222 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001223 InitListExpr *StructuredList,
1224 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +00001225 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +00001226 if (!VerifyOnly)
1227 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001228 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +00001229 diag::warn_cxx98_compat_empty_scalar_initializer :
1230 diag::err_empty_scalar_initializer)
1231 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001232 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001233 ++Index;
1234 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001235 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001236 }
John McCall643169b2010-11-11 00:46:36 +00001237
1238 Expr *expr = IList->getInit(Index);
1239 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001240 // FIXME: This is invalid, and accepting it causes overload resolution
1241 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001242 if (!VerifyOnly)
1243 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001244 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001245 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001246
1247 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1248 StructuredIndex);
1249 return;
1250 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001251 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001252 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001253 diag::err_designator_for_scalar_init)
1254 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001255 hadError = true;
1256 ++Index;
1257 ++StructuredIndex;
1258 return;
1259 }
1260
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001261 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001262 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001263 hadError = true;
1264 ++Index;
1265 return;
1266 }
1267
John McCall643169b2010-11-11 00:46:36 +00001268 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001269 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001270 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001271
Craig Topperc3ec1492014-05-26 06:22:03 +00001272 Expr *ResultExpr = nullptr;
John McCall643169b2010-11-11 00:46:36 +00001273
1274 if (Result.isInvalid())
1275 hadError = true; // types weren't compatible.
1276 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001277 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
John McCall643169b2010-11-11 00:46:36 +00001279 if (ResultExpr != expr) {
1280 // The type was promoted, update initializer list.
1281 IList->setInit(Index, ResultExpr);
1282 }
1283 }
1284 if (hadError)
1285 ++StructuredIndex;
1286 else
1287 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1288 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001289}
1290
Anders Carlsson6cabf312010-01-23 23:23:01 +00001291void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1292 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001293 unsigned &Index,
1294 InitListExpr *StructuredList,
1295 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001296 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001297 // FIXME: It would be wonderful if we could point at the actual member. In
1298 // general, it would be useful to pass location information down the stack,
1299 // so that we know the location (or decl) of the "current object" being
1300 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001301 if (!VerifyOnly)
1302 SemaRef.Diag(IList->getLocStart(),
1303 diag::err_init_reference_member_uninitialized)
1304 << DeclType
1305 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001306 hadError = true;
1307 ++Index;
1308 ++StructuredIndex;
1309 return;
1310 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001311
1312 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001313 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001314 if (!VerifyOnly)
1315 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1316 << DeclType << IList->getSourceRange();
1317 hadError = true;
1318 ++Index;
1319 ++StructuredIndex;
1320 return;
1321 }
1322
1323 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001324 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001325 hadError = true;
1326 ++Index;
1327 return;
1328 }
1329
1330 ExprResult Result =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001331 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1332 /*TopLevelOfInitList=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001333
1334 if (Result.isInvalid())
1335 hadError = true;
1336
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001337 expr = Result.getAs<Expr>();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001338 IList->setInit(Index, expr);
1339
1340 if (hadError)
1341 ++StructuredIndex;
1342 else
1343 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1344 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001345}
1346
Anders Carlsson6cabf312010-01-23 23:23:01 +00001347void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001348 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001349 unsigned &Index,
1350 InitListExpr *StructuredList,
1351 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001352 const VectorType *VT = DeclType->getAs<VectorType>();
1353 unsigned maxElements = VT->getNumElements();
1354 unsigned numEltsInit = 0;
1355 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001356
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001357 if (Index >= IList->getNumInits()) {
1358 // Make sure the element type can be value-initialized.
1359 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001360 CheckEmptyInitializable(
1361 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1362 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001363 return;
1364 }
1365
David Blaikiebbafb8a2012-03-11 07:00:24 +00001366 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001367 // If the initializing element is a vector, try to copy-initialize
1368 // instead of breaking it apart (which is doomed to failure anyway).
1369 Expr *Init = IList->getInit(Index);
1370 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001371 if (VerifyOnly) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001372 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001373 hadError = true;
1374 ++Index;
1375 return;
1376 }
1377
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001378 ExprResult Result =
1379 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1380 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001381
Craig Topperc3ec1492014-05-26 06:22:03 +00001382 Expr *ResultExpr = nullptr;
John McCall6a16b2f2010-10-30 00:11:39 +00001383 if (Result.isInvalid())
1384 hadError = true; // types weren't compatible.
1385 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001386 ResultExpr = Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
John McCall6a16b2f2010-10-30 00:11:39 +00001388 if (ResultExpr != Init) {
1389 // The type was promoted, update initializer list.
1390 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001391 }
1392 }
John McCall6a16b2f2010-10-30 00:11:39 +00001393 if (hadError)
1394 ++StructuredIndex;
1395 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001396 UpdateStructuredListElement(StructuredList, StructuredIndex,
1397 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001398 ++Index;
1399 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCall6a16b2f2010-10-30 00:11:39 +00001402 InitializedEntity ElementEntity =
1403 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001404
John McCall6a16b2f2010-10-30 00:11:39 +00001405 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1406 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001407 if (Index >= IList->getNumInits()) {
1408 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001409 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
John McCall6a16b2f2010-10-30 00:11:39 +00001410 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412
John McCall6a16b2f2010-10-30 00:11:39 +00001413 ElementEntity.setElementIndex(Index);
1414 CheckSubElementType(ElementEntity, IList, elementType, Index,
1415 StructuredList, StructuredIndex);
1416 }
James Molloy9eef2652014-06-20 14:35:13 +00001417
1418 if (VerifyOnly)
1419 return;
1420
1421 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1422 const VectorType *T = Entity.getType()->getAs<VectorType>();
1423 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1424 T->getVectorKind() == VectorType::NeonPolyVector)) {
1425 // The ability to use vector initializer lists is a GNU vector extension
1426 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1427 // endian machines it works fine, however on big endian machines it
1428 // exhibits surprising behaviour:
1429 //
1430 // uint32x2_t x = {42, 64};
1431 // return vget_lane_u32(x, 0); // Will return 64.
1432 //
1433 // Because of this, explicitly call out that it is non-portable.
1434 //
1435 SemaRef.Diag(IList->getLocStart(),
1436 diag::warn_neon_vector_initializer_non_portable);
1437
1438 const char *typeCode;
1439 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1440
1441 if (elementType->isFloatingType())
1442 typeCode = "f";
1443 else if (elementType->isSignedIntegerType())
1444 typeCode = "s";
1445 else if (elementType->isUnsignedIntegerType())
1446 typeCode = "u";
1447 else
1448 llvm_unreachable("Invalid element type!");
1449
1450 SemaRef.Diag(IList->getLocStart(),
1451 SemaRef.Context.getTypeSize(VT) > 64 ?
1452 diag::note_neon_vector_initializer_non_portable_q :
1453 diag::note_neon_vector_initializer_non_portable)
1454 << typeCode << typeSize;
1455 }
1456
John McCall6a16b2f2010-10-30 00:11:39 +00001457 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001458 }
John McCall6a16b2f2010-10-30 00:11:39 +00001459
1460 InitializedEntity ElementEntity =
1461 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462
John McCall6a16b2f2010-10-30 00:11:39 +00001463 // OpenCL initializers allows vectors to be constructed from vectors.
1464 for (unsigned i = 0; i < maxElements; ++i) {
1465 // Don't attempt to go past the end of the init list
1466 if (Index >= IList->getNumInits())
1467 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
John McCall6a16b2f2010-10-30 00:11:39 +00001469 ElementEntity.setElementIndex(Index);
1470
1471 QualType IType = IList->getInit(Index)->getType();
1472 if (!IType->isVectorType()) {
1473 CheckSubElementType(ElementEntity, IList, elementType, Index,
1474 StructuredList, StructuredIndex);
1475 ++numEltsInit;
1476 } else {
1477 QualType VecType;
1478 const VectorType *IVT = IType->getAs<VectorType>();
1479 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
John McCall6a16b2f2010-10-30 00:11:39 +00001481 if (IType->isExtVectorType())
1482 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1483 else
1484 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001485 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001486 CheckSubElementType(ElementEntity, IList, VecType, Index,
1487 StructuredList, StructuredIndex);
1488 numEltsInit += numIElts;
1489 }
1490 }
1491
1492 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001493 if (numEltsInit != maxElements) {
1494 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001495 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001496 diag::err_vector_incorrect_num_initializers)
1497 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1498 hadError = true;
1499 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001500}
1501
Anders Carlsson6cabf312010-01-23 23:23:01 +00001502void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001503 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001504 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001505 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001506 unsigned &Index,
1507 InitListExpr *StructuredList,
1508 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001509 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1510
Steve Narofff8ecff22008-05-01 22:18:59 +00001511 // Check for the special-case of initializing an array with a string.
1512 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001513 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1514 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001515 // We place the string literal directly into the resulting
1516 // initializer list. This is the only place where the structure
1517 // of the structured initializer list doesn't match exactly,
1518 // because doing so would involve allocating one character
1519 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001520 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001521 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1522 UpdateStructuredListElement(StructuredList, StructuredIndex,
1523 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001524 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1525 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001526 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001527 return;
1528 }
1529 }
John McCall66884dd2011-02-21 07:22:22 +00001530 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001531 // Check for VLAs; in standard C it would be possible to check this
1532 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1533 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001534 if (!VerifyOnly)
1535 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1536 diag::err_variable_object_no_init)
1537 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001538 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001539 ++Index;
1540 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001541 return;
1542 }
1543
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001544 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001545 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1546 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001547 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001548 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001549 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001550 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001551 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001552 maxElementsKnown = true;
1553 }
1554
John McCall66884dd2011-02-21 07:22:22 +00001555 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001556 while (Index < IList->getNumInits()) {
1557 Expr *Init = IList->getInit(Index);
1558 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001559 // If we're not the subobject that matches up with the '{' for
1560 // the designator, we shouldn't be handling the
1561 // designator. Return immediately.
1562 if (!SubobjectIsDesignatorContext)
1563 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001564
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001565 // Handle this designated initializer. elementIndex will be
1566 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001567 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001568 DeclType, nullptr, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001569 StructuredList, StructuredIndex, true,
1570 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001571 hadError = true;
1572 continue;
1573 }
1574
Douglas Gregor033d1252009-01-23 16:54:12 +00001575 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001576 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001577 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001578 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001579 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001580
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001581 // If the array is of incomplete type, keep track of the number of
1582 // elements in the initializer.
1583 if (!maxElementsKnown && elementIndex > maxElements)
1584 maxElements = elementIndex;
1585
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001586 continue;
1587 }
1588
1589 // If we know the maximum number of elements, and we've already
1590 // hit it, stop consuming elements in the initializer list.
1591 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001592 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001593
Anders Carlsson6cabf312010-01-23 23:23:01 +00001594 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001595 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001596 Entity);
1597 // Check this element.
1598 CheckSubElementType(ElementEntity, IList, elementType, Index,
1599 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001600 ++elementIndex;
1601
1602 // If the array is of incomplete type, keep track of the number of
1603 // elements in the initializer.
1604 if (!maxElementsKnown && elementIndex > maxElements)
1605 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001606 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001607 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001608 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001609 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001610 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001611 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001612 // Sizing an array implicitly to zero is not allowed by ISO C,
1613 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001614 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001615 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001616 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001617
Mike Stump11289f42009-09-09 15:08:12 +00001618 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001619 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001620 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001621 if (!hadError && VerifyOnly) {
1622 // Check if there are any members of the array that get value-initialized.
1623 // If so, check if doing that is possible.
1624 // FIXME: This needs to detect holes left by designated initializers too.
1625 if (maxElementsKnown && elementIndex < maxElements)
Richard Smith454a7cd2014-06-03 08:26:00 +00001626 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1627 SemaRef.Context, 0, Entity),
1628 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001629 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001630}
1631
Eli Friedman3fa64df2011-08-23 22:24:57 +00001632bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1633 Expr *InitExpr,
1634 FieldDecl *Field,
1635 bool TopLevelObject) {
1636 // Handle GNU flexible array initializers.
1637 unsigned FlexArrayDiag;
1638 if (isa<InitListExpr>(InitExpr) &&
1639 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1640 // Empty flexible array init always allowed as an extension
1641 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001642 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001643 // Disallow flexible array init in C++; it is not required for gcc
1644 // compatibility, and it needs work to IRGen correctly in general.
1645 FlexArrayDiag = diag::err_flexible_array_init;
1646 } else if (!TopLevelObject) {
1647 // Disallow flexible array init on non-top-level object
1648 FlexArrayDiag = diag::err_flexible_array_init;
1649 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1650 // Disallow flexible array init on anything which is not a variable.
1651 FlexArrayDiag = diag::err_flexible_array_init;
1652 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1653 // Disallow flexible array init on local variables.
1654 FlexArrayDiag = diag::err_flexible_array_init;
1655 } else {
1656 // Allow other cases.
1657 FlexArrayDiag = diag::ext_flexible_array_init;
1658 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001659
1660 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001661 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001662 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001663 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001664 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1665 << Field;
1666 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001667
1668 return FlexArrayDiag != diag::ext_flexible_array_init;
1669}
1670
Anders Carlsson6cabf312010-01-23 23:23:01 +00001671void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001672 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001673 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001674 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001675 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001676 unsigned &Index,
1677 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001678 unsigned &StructuredIndex,
1679 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001680 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001681
Eli Friedman23a9e312008-05-19 19:16:24 +00001682 // If the record is invalid, some of it's members are invalid. To avoid
1683 // confusion, we forgo checking the intializer for the entire record.
1684 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001685 // Assume it was supposed to consume a single initializer.
1686 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001687 hadError = true;
1688 return;
Mike Stump11289f42009-09-09 15:08:12 +00001689 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001690
1691 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001692 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001693
1694 // If there's a default initializer, use it.
1695 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1696 if (VerifyOnly)
1697 return;
1698 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1699 Field != FieldEnd; ++Field) {
1700 if (Field->hasInClassInitializer()) {
1701 StructuredList->setInitializedFieldInUnion(*Field);
1702 // FIXME: Actually build a CXXDefaultInitExpr?
1703 return;
1704 }
1705 }
1706 }
1707
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001708 // Value-initialize the first member of the union that isn't an unnamed
1709 // bitfield.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001710 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1711 Field != FieldEnd; ++Field) {
Reid Kleckner6d829bd2014-11-12 21:30:23 +00001712 if (!Field->isUnnamedBitfield()) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001713 if (VerifyOnly)
Richard Smith454a7cd2014-06-03 08:26:00 +00001714 CheckEmptyInitializable(
1715 InitializedEntity::InitializeMember(*Field, &Entity),
1716 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001717 else
David Blaikie40ed2972012-06-06 20:45:41 +00001718 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001719 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001720 }
1721 }
1722 return;
1723 }
1724
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001725 // If structDecl is a forward declaration, this loop won't do
1726 // anything except look at designated initializers; That's okay,
1727 // because an error should get printed out elsewhere. It might be
1728 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001729 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001730 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001731 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001732 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001733 while (Index < IList->getNumInits()) {
1734 Expr *Init = IList->getInit(Index);
1735
1736 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001737 // If we're not the subobject that matches up with the '{' for
1738 // the designator, we shouldn't be handling the
1739 // designator. Return immediately.
1740 if (!SubobjectIsDesignatorContext)
1741 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001742
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001743 // Handle this designated initializer. Field will be updated to
1744 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001745 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Craig Topperc3ec1492014-05-26 06:22:03 +00001746 DeclType, &Field, nullptr, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001747 StructuredList, StructuredIndex,
1748 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001749 hadError = true;
1750
Douglas Gregora9add4e2009-02-12 19:00:39 +00001751 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001752
1753 // Disable check for missing fields when designators are used.
1754 // This matches gcc behaviour.
1755 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001756 continue;
1757 }
1758
1759 if (Field == FieldEnd) {
1760 // We've run out of fields. We're done.
1761 break;
1762 }
1763
Douglas Gregora9add4e2009-02-12 19:00:39 +00001764 // We've already initialized a member of a union. We're done.
1765 if (InitializedSomething && DeclType->isUnionType())
1766 break;
1767
Douglas Gregor91f84212008-12-11 16:49:14 +00001768 // If we've hit the flexible array member at the end, we're done.
1769 if (Field->getType()->isIncompleteArrayType())
1770 break;
1771
Douglas Gregor51695702009-01-29 16:53:55 +00001772 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001773 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001774 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001775 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001776 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001777
Douglas Gregora82064c2011-06-29 21:51:31 +00001778 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001779 bool InvalidUse;
1780 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001781 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001782 else
David Blaikie40ed2972012-06-06 20:45:41 +00001783 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001784 IList->getInit(Index)->getLocStart());
1785 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001786 ++Index;
1787 ++Field;
1788 hadError = true;
1789 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001790 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001791
Anders Carlsson6cabf312010-01-23 23:23:01 +00001792 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001793 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001794 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1795 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001796 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001797
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001798 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001799 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001800 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001801 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001802
1803 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001804 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001805
John McCalle40b58e2010-03-11 19:32:38 +00001806 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001807 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1808 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1809 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001810 // It is possible we have one or more unnamed bitfields remaining.
1811 // Find first (if any) named field and emit warning.
1812 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1813 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001814 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001815 SemaRef.Diag(IList->getSourceRange().getEnd(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001816 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001817 break;
1818 }
1819 }
1820 }
1821
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001822 // Check that any remaining fields can be value-initialized.
1823 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1824 !Field->getType()->isIncompleteArrayType()) {
1825 // FIXME: Should check for holes left by designated initializers too.
1826 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001827 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Richard Smith454a7cd2014-06-03 08:26:00 +00001828 CheckEmptyInitializable(
1829 InitializedEntity::InitializeMember(*Field, &Entity),
1830 IList->getLocEnd());
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001831 }
1832 }
1833
Mike Stump11289f42009-09-09 15:08:12 +00001834 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001835 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001836 return;
1837
David Blaikie40ed2972012-06-06 20:45:41 +00001838 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001839 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001840 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001841 ++Index;
1842 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001843 }
1844
Anders Carlsson6cabf312010-01-23 23:23:01 +00001845 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001846 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001847
Anders Carlsson6cabf312010-01-23 23:23:01 +00001848 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001850 StructuredList, StructuredIndex);
1851 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001852 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001853 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001854}
Steve Narofff8ecff22008-05-01 22:18:59 +00001855
Douglas Gregord5846a12009-04-15 06:41:24 +00001856/// \brief Expand a field designator that refers to a member of an
1857/// anonymous struct or union into a series of field designators that
1858/// refers to the field within the appropriate subobject.
1859///
Douglas Gregord5846a12009-04-15 06:41:24 +00001860static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001861 DesignatedInitExpr *DIE,
1862 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001863 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001864 typedef DesignatedInitExpr::Designator Designator;
1865
Douglas Gregord5846a12009-04-15 06:41:24 +00001866 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001867 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001868 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1869 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1870 if (PI + 1 == PE)
Craig Topperc3ec1492014-05-26 06:22:03 +00001871 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
Douglas Gregord5846a12009-04-15 06:41:24 +00001872 DIE->getDesignator(DesigIdx)->getDotLoc(),
1873 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1874 else
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1876 SourceLocation(), SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001877 assert(isa<FieldDecl>(*PI));
1878 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001879 }
1880
1881 // Expand the current designator into the set of replacement
1882 // designators, so we have a full subobject path down to where the
1883 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001884 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001885 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001886}
Mike Stump11289f42009-09-09 15:08:12 +00001887
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001888static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1889 DesignatedInitExpr *DIE) {
1890 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1891 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1892 for (unsigned I = 0; I < NumIndexExprs; ++I)
1893 IndexExprs[I] = DIE->getSubExpr(I + 1);
1894 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001895 DIE->size(), IndexExprs,
1896 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001897 DIE->usesGNUSyntax(), DIE->getInit());
1898}
1899
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001900namespace {
1901
1902// Callback to only accept typo corrections that are for field members of
1903// the given struct or union.
1904class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1905 public:
1906 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1907 : Record(RD) {}
1908
Craig Toppere14c0f82014-03-12 04:55:44 +00001909 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001910 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1911 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1912 }
1913
1914 private:
1915 RecordDecl *Record;
1916};
1917
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001918}
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001919
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001920/// @brief Check the well-formedness of a C99 designated initializer.
1921///
1922/// Determines whether the designated initializer @p DIE, which
1923/// resides at the given @p Index within the initializer list @p
1924/// IList, is well-formed for a current object of type @p DeclType
1925/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001926/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001927/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001928///
1929/// @param IList The initializer list in which this designated
1930/// initializer occurs.
1931///
Douglas Gregora5324162009-04-15 04:56:10 +00001932/// @param DIE The designated initializer expression.
1933///
1934/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001935///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001936/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001937/// into which the designation in @p DIE should refer.
1938///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001939/// @param NextField If non-NULL and the first designator in @p DIE is
1940/// a field, this will be set to the field declaration corresponding
1941/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001942///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001943/// @param NextElementIndex If non-NULL and the first designator in @p
1944/// DIE is an array designator or GNU array-range designator, this
1945/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001946///
1947/// @param Index Index into @p IList where the designated initializer
1948/// @p DIE occurs.
1949///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001950/// @param StructuredList The initializer list expression that
1951/// describes all of the subobject initializers in the order they'll
1952/// actually be initialized.
1953///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001954/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001955bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001956InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001957 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001958 DesignatedInitExpr *DIE,
1959 unsigned DesigIdx,
1960 QualType &CurrentObjectType,
1961 RecordDecl::field_iterator *NextField,
1962 llvm::APSInt *NextElementIndex,
1963 unsigned &Index,
1964 InitListExpr *StructuredList,
1965 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001966 bool FinishSubobjectInit,
1967 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001968 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001969 // Check the actual initialization for the designated object type.
1970 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001971
1972 // Temporarily remove the designator expression from the
1973 // initializer list that the child calls see, so that we don't try
1974 // to re-process the designator.
1975 unsigned OldIndex = Index;
1976 IList->setInit(OldIndex, DIE->getInit());
1977
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001978 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001979 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001980
1981 // Restore the designated initializer expression in the syntactic
1982 // form of the initializer list.
1983 if (IList->getInit(OldIndex) != DIE->getInit())
1984 DIE->setInit(IList->getInit(OldIndex));
1985 IList->setInit(OldIndex, DIE);
1986
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001987 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001988 }
1989
Douglas Gregora5324162009-04-15 04:56:10 +00001990 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001991 bool IsFirstDesignator = (DesigIdx == 0);
1992 if (!VerifyOnly) {
1993 assert((IsFirstDesignator || StructuredList) &&
1994 "Need a non-designated initializer list to start from");
1995
1996 // Determine the structural initializer list that corresponds to the
1997 // current subobject.
Yunzhong Gaocb779302015-06-10 00:27:52 +00001998 if (IsFirstDesignator)
1999 StructuredList = SyntacticToSemantic.lookup(IList);
2000 else {
2001 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2002 StructuredList->getInit(StructuredIndex) : nullptr;
2003 if (!ExistingInit && StructuredList->hasArrayFiller())
2004 ExistingInit = StructuredList->getArrayFiller();
2005
2006 if (!ExistingInit)
2007 StructuredList =
2008 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2009 StructuredList, StructuredIndex,
2010 SourceRange(D->getLocStart(),
2011 DIE->getLocEnd()));
2012 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2013 StructuredList = Result;
2014 else {
2015 if (DesignatedInitUpdateExpr *E =
2016 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2017 StructuredList = E->getUpdater();
2018 else {
2019 DesignatedInitUpdateExpr *DIUE =
2020 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2021 D->getLocStart(), ExistingInit,
2022 DIE->getLocEnd());
2023 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2024 StructuredList = DIUE->getUpdater();
2025 }
2026
2027 // We need to check on source range validity because the previous
2028 // initializer does not have to be an explicit initializer. e.g.,
2029 //
2030 // struct P { int a, b; };
2031 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2032 //
2033 // There is an overwrite taking place because the first braced initializer
2034 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2035 if (ExistingInit->getSourceRange().isValid()) {
2036 // We are creating an initializer list that initializes the
2037 // subobjects of the current object, but there was already an
2038 // initialization that completely initialized the current
2039 // subobject, e.g., by a compound literal:
2040 //
2041 // struct X { int a, b; };
2042 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2043 //
2044 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2045 // designated initializer re-initializes the whole
2046 // subobject [0], overwriting previous initializers.
2047 SemaRef.Diag(D->getLocStart(),
2048 diag::warn_subobject_initializer_overrides)
2049 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2050
2051 SemaRef.Diag(ExistingInit->getLocStart(),
2052 diag::note_previous_initializer)
2053 << /*FIXME:has side effects=*/0
2054 << ExistingInit->getSourceRange();
2055 }
2056 }
2057 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002058 assert(StructuredList && "Expected a structured initializer list");
2059 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002060
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002061 if (D->isFieldDesignator()) {
2062 // C99 6.7.8p7:
2063 //
2064 // If a designator has the form
2065 //
2066 // . identifier
2067 //
2068 // then the current object (defined below) shall have
2069 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00002070 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002071 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002072 if (!RT) {
2073 SourceLocation Loc = D->getDotLoc();
2074 if (Loc.isInvalid())
2075 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002076 if (!VerifyOnly)
2077 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002078 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002079 ++Index;
2080 return true;
2081 }
2082
Douglas Gregord5846a12009-04-15 06:41:24 +00002083 FieldDecl *KnownField = D->getField();
David Majnemer36ef8982014-08-11 18:33:59 +00002084 if (!KnownField) {
2085 IdentifierInfo *FieldName = D->getFieldName();
2086 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2087 for (NamedDecl *ND : Lookup) {
2088 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2089 KnownField = FD;
2090 break;
2091 }
2092 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002093 // In verify mode, don't modify the original.
2094 if (VerifyOnly)
2095 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
David Majnemer36ef8982014-08-11 18:33:59 +00002096 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002097 D = DIE->getDesignator(DesigIdx);
David Majnemer36ef8982014-08-11 18:33:59 +00002098 KnownField = cast<FieldDecl>(*IFD->chain_begin());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00002099 break;
2100 }
2101 }
David Majnemer36ef8982014-08-11 18:33:59 +00002102 if (!KnownField) {
2103 if (VerifyOnly) {
2104 ++Index;
2105 return true; // No typo correction when just trying this out.
2106 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002107
David Majnemer36ef8982014-08-11 18:33:59 +00002108 // Name lookup found something, but it wasn't a field.
2109 if (!Lookup.empty()) {
2110 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2111 << FieldName;
2112 SemaRef.Diag(Lookup.front()->getLocation(),
2113 diag::note_field_designator_found);
2114 ++Index;
2115 return true;
2116 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002117
David Majnemer36ef8982014-08-11 18:33:59 +00002118 // Name lookup didn't find anything.
2119 // Determine whether this was a typo for another field name.
Richard Smithf9b15102013-08-17 00:46:16 +00002120 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2121 DeclarationNameInfo(FieldName, D->getFieldLoc()),
David Majnemer36ef8982014-08-11 18:33:59 +00002122 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002123 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2124 Sema::CTK_ErrorRecovery, RT->getDecl())) {
Richard Smithf9b15102013-08-17 00:46:16 +00002125 SemaRef.diagnoseTypo(
2126 Corrected,
2127 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
David Majnemer36ef8982014-08-11 18:33:59 +00002128 << FieldName << CurrentObjectType);
2129 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00002130 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002131 } else {
David Majnemer36ef8982014-08-11 18:33:59 +00002132 // Typo correction didn't find anything.
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002133 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2134 << FieldName << CurrentObjectType;
2135 ++Index;
2136 return true;
2137 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00002138 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002139 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002140
David Majnemer58e4ea92014-08-23 01:48:50 +00002141 unsigned FieldIndex = 0;
2142 for (auto *FI : RT->getDecl()->fields()) {
2143 if (FI->isUnnamedBitfield())
2144 continue;
2145 if (KnownField == FI)
2146 break;
2147 ++FieldIndex;
2148 }
2149
David Majnemer36ef8982014-08-11 18:33:59 +00002150 RecordDecl::field_iterator Field =
2151 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2152
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002153 // All of the fields of a union are located at the same place in
2154 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00002155 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002156 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002157 if (!VerifyOnly) {
2158 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2159 if (CurrentField && CurrentField != *Field) {
2160 assert(StructuredList->getNumInits() == 1
2161 && "A union should never have more than one initializer!");
2162
2163 // we're about to throw away an initializer, emit warning
2164 SemaRef.Diag(D->getFieldLoc(),
2165 diag::warn_initializer_overrides)
2166 << D->getSourceRange();
2167 Expr *ExistingInit = StructuredList->getInit(0);
2168 SemaRef.Diag(ExistingInit->getLocStart(),
2169 diag::note_previous_initializer)
2170 << /*FIXME:has side effects=*/0
2171 << ExistingInit->getSourceRange();
2172
2173 // remove existing initializer
2174 StructuredList->resizeInits(SemaRef.Context, 0);
Craig Topperc3ec1492014-05-26 06:22:03 +00002175 StructuredList->setInitializedFieldInUnion(nullptr);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002176 }
2177
David Blaikie40ed2972012-06-06 20:45:41 +00002178 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00002179 }
Douglas Gregor51695702009-01-29 16:53:55 +00002180 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002181
Douglas Gregora82064c2011-06-29 21:51:31 +00002182 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002183 bool InvalidUse;
2184 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00002185 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002186 else
David Blaikie40ed2972012-06-06 20:45:41 +00002187 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002188 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00002189 ++Index;
2190 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002191 }
Douglas Gregora82064c2011-06-29 21:51:31 +00002192
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002193 if (!VerifyOnly) {
2194 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00002195 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002197 // Make sure that our non-designated initializer list has space
2198 // for a subobject corresponding to this field.
2199 if (FieldIndex >= StructuredList->getNumInits())
2200 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2201 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002202
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002203 // This designator names a flexible array member.
2204 if (Field->getType()->isIncompleteArrayType()) {
2205 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00002206 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002207 // We can't designate an object within the flexible array
2208 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002209 if (!VerifyOnly) {
2210 DesignatedInitExpr::Designator *NextD
2211 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002212 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002213 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002214 << SourceRange(NextD->getLocStart(),
2215 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002216 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002217 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002218 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002219 Invalid = true;
2220 }
2221
Chris Lattner001b29c2010-10-10 17:49:49 +00002222 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2223 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002224 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002225 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002226 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002227 diag::err_flexible_array_init_needs_braces)
2228 << DIE->getInit()->getSourceRange();
2229 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00002230 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002231 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002232 Invalid = true;
2233 }
2234
Eli Friedman3fa64df2011-08-23 22:24:57 +00002235 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00002236 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00002237 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002238 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002239
2240 if (Invalid) {
2241 ++Index;
2242 return true;
2243 }
2244
2245 // Initialize the array.
2246 bool prevHadError = hadError;
2247 unsigned newStructuredIndex = FieldIndex;
2248 unsigned OldIndex = Index;
2249 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00002250
2251 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002252 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002253 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002254 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00002255
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002256 IList->setInit(OldIndex, DIE);
2257 if (hadError && !prevHadError) {
2258 ++Field;
2259 ++FieldIndex;
2260 if (NextField)
2261 *NextField = Field;
2262 StructuredIndex = FieldIndex;
2263 return true;
2264 }
2265 } else {
2266 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00002267 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002268 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002270 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00002271 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002272 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002273 FieldType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002274 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002275 true, false))
2276 return true;
2277 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002278
2279 // Find the position of the next field to be initialized in this
2280 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002281 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002282 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002283
2284 // If this the first designator, our caller will continue checking
2285 // the rest of this struct/class/union subobject.
2286 if (IsFirstDesignator) {
2287 if (NextField)
2288 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002289 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002290 return false;
2291 }
2292
Douglas Gregor17bd0942009-01-28 23:36:17 +00002293 if (!FinishSubobjectInit)
2294 return false;
2295
Douglas Gregord5846a12009-04-15 06:41:24 +00002296 // We've already initialized something in the union; we're done.
2297 if (RT->getDecl()->isUnion())
2298 return hadError;
2299
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002300 // Check the remaining fields within this class/struct/union subobject.
2301 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302
Anders Carlsson6cabf312010-01-23 23:23:01 +00002303 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002304 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002305 return hadError && !prevHadError;
2306 }
2307
2308 // C99 6.7.8p6:
2309 //
2310 // If a designator has the form
2311 //
2312 // [ constant-expression ]
2313 //
2314 // then the current object (defined below) shall have array
2315 // type and the expression shall be an integer constant
2316 // expression. If the array is of unknown size, any
2317 // nonnegative value is valid.
2318 //
2319 // Additionally, cope with the GNU extension that permits
2320 // designators of the form
2321 //
2322 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002323 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002324 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002325 if (!VerifyOnly)
2326 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2327 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002328 ++Index;
2329 return true;
2330 }
2331
Craig Topperc3ec1492014-05-26 06:22:03 +00002332 Expr *IndexExpr = nullptr;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002333 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2334 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002335 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002336 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002337 DesignatedEndIndex = DesignatedStartIndex;
2338 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002339 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002340
Mike Stump11289f42009-09-09 15:08:12 +00002341 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002342 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002343 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002344 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002345 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002346
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002347 // Codegen can't handle evaluating array range designators that have side
2348 // effects, because we replicate the AST value for each initialized element.
2349 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2350 // elements with something that has a side effect, so codegen can emit an
2351 // "error unsupported" error instead of miscompiling the app.
2352 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002353 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002354 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002355 }
2356
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002357 if (isa<ConstantArrayType>(AT)) {
2358 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002359 DesignatedStartIndex
2360 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002361 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002362 DesignatedEndIndex
2363 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002364 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2365 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002366 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002367 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002368 diag::err_array_designator_too_large)
2369 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2370 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002371 ++Index;
2372 return true;
2373 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002374 } else {
2375 // Make sure the bit-widths and signedness match.
2376 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002377 DesignatedEndIndex
2378 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002379 else if (DesignatedStartIndex.getBitWidth() <
2380 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002381 DesignatedStartIndex
2382 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002383 DesignatedStartIndex.setIsUnsigned(true);
2384 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002385 }
Mike Stump11289f42009-09-09 15:08:12 +00002386
Eli Friedman1f16b742013-06-11 21:48:11 +00002387 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2388 // We're modifying a string literal init; we have to decompose the string
2389 // so we can modify the individual characters.
2390 ASTContext &Context = SemaRef.Context;
2391 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2392
2393 // Compute the character type
2394 QualType CharTy = AT->getElementType();
2395
2396 // Compute the type of the integer literals.
2397 QualType PromotedCharTy = CharTy;
2398 if (CharTy->isPromotableIntegerType())
2399 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2400 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2401
2402 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2403 // Get the length of the string.
2404 uint64_t StrLen = SL->getLength();
2405 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2406 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2407 StructuredList->resizeInits(Context, StrLen);
2408
2409 // Build a literal for each character in the string, and put them into
2410 // the init list.
2411 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2412 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2413 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002414 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002415 if (CharTy != PromotedCharTy)
2416 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002417 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002418 StructuredList->updateInit(Context, i, Init);
2419 }
2420 } else {
2421 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2422 std::string Str;
2423 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2424
2425 // Get the length of the string.
2426 uint64_t StrLen = Str.size();
2427 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2428 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2429 StructuredList->resizeInits(Context, StrLen);
2430
2431 // Build a literal for each character in the string, and put them into
2432 // the init list.
2433 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2434 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2435 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002436 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002437 if (CharTy != PromotedCharTy)
2438 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
Craig Topperc3ec1492014-05-26 06:22:03 +00002439 Init, nullptr, VK_RValue);
Eli Friedman1f16b742013-06-11 21:48:11 +00002440 StructuredList->updateInit(Context, i, Init);
2441 }
2442 }
2443 }
2444
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002445 // Make sure that our non-designated initializer list has space
2446 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002447 if (!VerifyOnly &&
2448 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002449 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002450 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002451
Douglas Gregor17bd0942009-01-28 23:36:17 +00002452 // Repeatedly perform subobject initializations in the range
2453 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002454
Douglas Gregor17bd0942009-01-28 23:36:17 +00002455 // Move to the next designator
2456 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2457 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002459 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002460 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002461
Douglas Gregor17bd0942009-01-28 23:36:17 +00002462 while (DesignatedStartIndex <= DesignatedEndIndex) {
2463 // Recurse to check later designated subobjects.
2464 QualType ElementType = AT->getElementType();
2465 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002466
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002467 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002468 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Craig Topperc3ec1492014-05-26 06:22:03 +00002469 ElementType, nullptr, nullptr, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002470 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002471 (DesignatedStartIndex == DesignatedEndIndex),
2472 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002473 return true;
2474
2475 // Move to the next index in the array that we'll be initializing.
2476 ++DesignatedStartIndex;
2477 ElementIndex = DesignatedStartIndex.getZExtValue();
2478 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002479
2480 // If this the first designator, our caller will continue checking
2481 // the rest of this array subobject.
2482 if (IsFirstDesignator) {
2483 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002484 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002485 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002486 return false;
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregor17bd0942009-01-28 23:36:17 +00002489 if (!FinishSubobjectInit)
2490 return false;
2491
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002492 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002493 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002494 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002495 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002496 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002497 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002498}
2499
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002500// Get the structured initializer list for a subobject of type
2501// @p CurrentObjectType.
2502InitListExpr *
2503InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2504 QualType CurrentObjectType,
2505 InitListExpr *StructuredList,
2506 unsigned StructuredIndex,
Yunzhong Gaocb779302015-06-10 00:27:52 +00002507 SourceRange InitRange,
2508 bool IsFullyOverwritten) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002509 if (VerifyOnly)
Craig Topperc3ec1492014-05-26 06:22:03 +00002510 return nullptr; // No structured list in verification-only mode.
2511 Expr *ExistingInit = nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002512 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002513 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002514 else if (StructuredIndex < StructuredList->getNumInits())
2515 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002516
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002517 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
Yunzhong Gaocb779302015-06-10 00:27:52 +00002518 // There might have already been initializers for subobjects of the current
2519 // object, but a subsequent initializer list will overwrite the entirety
2520 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2521 //
2522 // struct P { char x[6]; };
2523 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2524 //
2525 // The first designated initializer is ignored, and l.x is just "f".
2526 if (!IsFullyOverwritten)
2527 return Result;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002528
2529 if (ExistingInit) {
2530 // We are creating an initializer list that initializes the
2531 // subobjects of the current object, but there was already an
2532 // initialization that completely initialized the current
2533 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002534 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002535 // struct X { int a, b; };
2536 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002537 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002538 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2539 // designated initializer re-initializes the whole
2540 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002541 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002542 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002543 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002544 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002545 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002546 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002547 << ExistingInit->getSourceRange();
2548 }
2549
Mike Stump11289f42009-09-09 15:08:12 +00002550 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002551 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002552 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002553 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002554
Eli Friedman91f5ae52012-02-23 02:25:10 +00002555 QualType ResultType = CurrentObjectType;
2556 if (!ResultType->isArrayType())
2557 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2558 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002559
Douglas Gregor6d00c992009-03-20 23:58:33 +00002560 // Pre-allocate storage for the structured initializer list.
2561 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002562 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002563 bool GotNumInits = false;
2564 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002565 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002566 GotNumInits = true;
2567 } else if (Index < IList->getNumInits()) {
2568 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002569 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002570 GotNumInits = true;
2571 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002572 }
2573
Mike Stump11289f42009-09-09 15:08:12 +00002574 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002575 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2576 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2577 NumElements = CAType->getSize().getZExtValue();
2578 // Simple heuristic so that we don't allocate a very large
2579 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002580 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002581 NumElements = 0;
2582 }
John McCall9dd450b2009-09-21 23:43:11 +00002583 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002584 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002585 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002586 RecordDecl *RDecl = RType->getDecl();
2587 if (RDecl->isUnion())
2588 NumElements = 1;
2589 else
Aaron Ballman62e47c42014-03-10 13:43:55 +00002590 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002591 }
2592
Ted Kremenekac034612010-04-13 23:39:13 +00002593 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002594
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002595 // Link this new initializer list into the structured initializer
2596 // lists.
2597 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002598 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002599 else {
2600 Result->setSyntacticForm(IList);
2601 SyntacticToSemantic[IList] = Result;
2602 }
2603
2604 return Result;
2605}
2606
2607/// Update the initializer at index @p StructuredIndex within the
2608/// structured initializer list to the value @p expr.
2609void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2610 unsigned &StructuredIndex,
2611 Expr *expr) {
2612 // No structured initializer list to update
2613 if (!StructuredList)
2614 return;
2615
Ted Kremenekac034612010-04-13 23:39:13 +00002616 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2617 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002618 // This initializer overwrites a previous initializer. Warn.
Yunzhong Gaocb779302015-06-10 00:27:52 +00002619 // We need to check on source range validity because the previous
2620 // initializer does not have to be an explicit initializer.
2621 // struct P { int a, b; };
2622 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2623 // There is an overwrite taking place because the first braced initializer
2624 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2625 if (PrevInit->getSourceRange().isValid()) {
2626 SemaRef.Diag(expr->getLocStart(),
2627 diag::warn_initializer_overrides)
2628 << expr->getSourceRange();
2629
2630 SemaRef.Diag(PrevInit->getLocStart(),
2631 diag::note_previous_initializer)
2632 << /*FIXME:has side effects=*/0
2633 << PrevInit->getSourceRange();
2634 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002635 }
Mike Stump11289f42009-09-09 15:08:12 +00002636
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002637 ++StructuredIndex;
2638}
2639
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002640/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002641/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002642/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002643/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002644/// failure. Returns the index expression, possibly with an implicit cast
2645/// added, on success. If everything went okay, Value will receive the
2646/// value of the constant expression.
2647static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002648CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002649 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002650
2651 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002652 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2653 if (Result.isInvalid())
2654 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002655
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002656 if (Value.isSigned() && Value.isNegative())
2657 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002658 << Value.toString(10) << Index->getSourceRange();
2659
Douglas Gregor51650d32009-01-23 21:04:18 +00002660 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002661 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002662}
2663
John McCalldadc5752010-08-24 06:29:42 +00002664ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002665 SourceLocation Loc,
2666 bool GNUSyntax,
2667 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002668 typedef DesignatedInitExpr::Designator ASTDesignator;
2669
2670 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002671 SmallVector<ASTDesignator, 32> Designators;
2672 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002673
2674 // Build designators and check array designator expressions.
2675 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2676 const Designator &D = Desig.getDesignator(Idx);
2677 switch (D.getKind()) {
2678 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002679 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002680 D.getFieldLoc()));
2681 break;
2682
2683 case Designator::ArrayDesignator: {
2684 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2685 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002686 if (!Index->isTypeDependent() && !Index->isValueDependent())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002687 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002688 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002689 Invalid = true;
2690 else {
2691 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002692 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002693 D.getRBracketLoc()));
2694 InitExpressions.push_back(Index);
2695 }
2696 break;
2697 }
2698
2699 case Designator::ArrayRangeDesignator: {
2700 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2701 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2702 llvm::APSInt StartValue;
2703 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002704 bool StartDependent = StartIndex->isTypeDependent() ||
2705 StartIndex->isValueDependent();
2706 bool EndDependent = EndIndex->isTypeDependent() ||
2707 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002708 if (!StartDependent)
2709 StartIndex =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002710 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002711 if (!EndDependent)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002712 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00002713
2714 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002715 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002716 else {
2717 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002718 if (StartDependent || EndDependent) {
2719 // Nothing to compute.
2720 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002721 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002722 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002723 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002724
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002725 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002726 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002727 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002728 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2729 Invalid = true;
2730 } else {
2731 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002732 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002733 D.getEllipsisLoc(),
2734 D.getRBracketLoc()));
2735 InitExpressions.push_back(StartIndex);
2736 InitExpressions.push_back(EndIndex);
2737 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002738 }
2739 break;
2740 }
2741 }
2742 }
2743
2744 if (Invalid || Init.isInvalid())
2745 return ExprError();
2746
2747 // Clear out the expressions within the designation.
2748 Desig.ClearExprs(*this);
2749
2750 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002751 = DesignatedInitExpr::Create(Context,
2752 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002753 InitExpressions, Loc, GNUSyntax,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002754 Init.getAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002755
David Blaikiebbafb8a2012-03-11 07:00:24 +00002756 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002757 Diag(DIE->getLocStart(), diag::ext_designated_init)
2758 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002759
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002760 return DIE;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002761}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002762
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002763//===----------------------------------------------------------------------===//
2764// Initialization entity
2765//===----------------------------------------------------------------------===//
2766
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002768 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002769 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002770{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002771 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2772 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002773 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002774 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002775 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002776 Type = VT->getElementType();
2777 } else {
2778 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2779 assert(CT && "Unexpected type");
2780 Kind = EK_ComplexElement;
2781 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002782 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002783}
2784
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002785InitializedEntity
2786InitializedEntity::InitializeBase(ASTContext &Context,
2787 const CXXBaseSpecifier *Base,
2788 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002789 InitializedEntity Result;
2790 Result.Kind = EK_Base;
Craig Topperc3ec1492014-05-26 06:22:03 +00002791 Result.Parent = nullptr;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002792 Result.Base = reinterpret_cast<uintptr_t>(Base);
2793 if (IsInheritedVirtualBase)
2794 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795
Douglas Gregor1b303932009-12-22 15:35:07 +00002796 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002797 return Result;
2798}
2799
Douglas Gregor85dabae2009-12-16 01:38:02 +00002800DeclarationName InitializedEntity::getName() const {
2801 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002802 case EK_Parameter:
2803 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002804 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2805 return (D ? D->getDeclName() : DeclarationName());
2806 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002807
2808 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002809 case EK_Member:
2810 return VariableOrMember->getDeclName();
2811
Douglas Gregor19666fb2012-02-15 16:57:26 +00002812 case EK_LambdaCapture:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002813 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002814
Douglas Gregor85dabae2009-12-16 01:38:02 +00002815 case EK_Result:
2816 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002817 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002818 case EK_Temporary:
2819 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002820 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002821 case EK_ArrayElement:
2822 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002823 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002824 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002825 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002826 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002827 return DeclarationName();
2828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829
David Blaikie8a40f702012-01-17 06:56:22 +00002830 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002831}
2832
Douglas Gregora4b592a2009-12-19 03:01:41 +00002833DeclaratorDecl *InitializedEntity::getDecl() const {
2834 switch (getKind()) {
2835 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002836 case EK_Member:
2837 return VariableOrMember;
2838
John McCall31168b02011-06-15 23:02:42 +00002839 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002840 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002841 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2842
Douglas Gregora4b592a2009-12-19 03:01:41 +00002843 case EK_Result:
2844 case EK_Exception:
2845 case EK_New:
2846 case EK_Temporary:
2847 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002848 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002849 case EK_ArrayElement:
2850 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002851 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002852 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002853 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002854 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002855 case EK_RelatedResult:
Craig Topperc3ec1492014-05-26 06:22:03 +00002856 return nullptr;
Douglas Gregora4b592a2009-12-19 03:01:41 +00002857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002858
David Blaikie8a40f702012-01-17 06:56:22 +00002859 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002860}
2861
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002862bool InitializedEntity::allowsNRVO() const {
2863 switch (getKind()) {
2864 case EK_Result:
2865 case EK_Exception:
2866 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002868 case EK_Variable:
2869 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002870 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002871 case EK_Member:
2872 case EK_New:
2873 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002874 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002875 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002876 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002877 case EK_ArrayElement:
2878 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002879 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002880 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002881 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002882 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002883 break;
2884 }
2885
2886 return false;
2887}
2888
Richard Smithe6c01442013-06-05 00:46:14 +00002889unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002890 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002891 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2892 for (unsigned I = 0; I != Depth; ++I)
2893 OS << "`-";
2894
2895 switch (getKind()) {
2896 case EK_Variable: OS << "Variable"; break;
2897 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002898 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2899 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002900 case EK_Result: OS << "Result"; break;
2901 case EK_Exception: OS << "Exception"; break;
2902 case EK_Member: OS << "Member"; break;
2903 case EK_New: OS << "New"; break;
2904 case EK_Temporary: OS << "Temporary"; break;
2905 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002906 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002907 case EK_Base: OS << "Base"; break;
2908 case EK_Delegating: OS << "Delegating"; break;
2909 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2910 case EK_VectorElement: OS << "VectorElement " << Index; break;
2911 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2912 case EK_BlockElement: OS << "Block"; break;
2913 case EK_LambdaCapture:
2914 OS << "LambdaCapture ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002915 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002916 break;
2917 }
2918
2919 if (Decl *D = getDecl()) {
2920 OS << " ";
2921 cast<NamedDecl>(D)->printQualifiedName(OS);
2922 }
2923
2924 OS << " '" << getType().getAsString() << "'\n";
2925
2926 return Depth + 1;
2927}
2928
2929void InitializedEntity::dump() const {
2930 dumpImpl(llvm::errs());
2931}
2932
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002933//===----------------------------------------------------------------------===//
2934// Initialization sequence
2935//===----------------------------------------------------------------------===//
2936
2937void InitializationSequence::Step::Destroy() {
2938 switch (Kind) {
2939 case SK_ResolveAddressOfOverloadedFunction:
2940 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002941 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002942 case SK_CastDerivedToBaseLValue:
2943 case SK_BindReference:
2944 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002945 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002946 case SK_UserConversion:
2947 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002948 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002949 case SK_QualificationConversionLValue:
Richard Smith77be48a2014-07-31 06:31:19 +00002950 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00002951 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002952 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00002953 case SK_UnwrapInitList:
2954 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002955 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00002956 case SK_ConstructorInitializationFromList:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002957 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002958 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002959 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002960 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002961 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002962 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002963 case SK_PassByIndirectCopyRestore:
2964 case SK_PassByIndirectRestore:
2965 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002966 case SK_StdInitializerList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00002967 case SK_StdInitializerListConstructorCall:
Guy Benyei61054192013-02-07 10:55:47 +00002968 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002969 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002970 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002972 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002973 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002974 delete ICS;
2975 }
2976}
2977
Douglas Gregor838fcc32010-03-26 20:14:36 +00002978bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002979 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002980}
2981
2982bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002983 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002984 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985
Douglas Gregor838fcc32010-03-26 20:14:36 +00002986 switch (getFailureKind()) {
2987 case FK_TooManyInitsForReference:
2988 case FK_ArrayNeedsInitList:
2989 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002990 case FK_ArrayNeedsInitListOrWideStringLiteral:
2991 case FK_NarrowStringIntoWideCharArray:
2992 case FK_WideStringIntoCharArray:
2993 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002994 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2995 case FK_NonConstLValueReferenceBindingToTemporary:
2996 case FK_NonConstLValueReferenceBindingToUnrelated:
2997 case FK_RValueReferenceBindingToLValue:
2998 case FK_ReferenceInitDropsQualifiers:
2999 case FK_ReferenceInitFailed:
3000 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00003001 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003002 case FK_TooManyInitsForScalar:
3003 case FK_ReferenceBindingToInitList:
3004 case FK_InitListBadDestinationType:
3005 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003006 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00003007 case FK_ArrayTypeMismatch:
3008 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00003009 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00003010 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00003011 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00003012 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003013 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014
Douglas Gregor838fcc32010-03-26 20:14:36 +00003015 case FK_ReferenceInitOverloadFailed:
3016 case FK_UserConversionOverloadFailed:
3017 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003018 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00003019 return FailedOverloadResult == OR_Ambiguous;
3020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
David Blaikie8a40f702012-01-17 06:56:22 +00003022 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00003023}
3024
Douglas Gregorb33eed02010-04-16 22:09:46 +00003025bool InitializationSequence::isConstructorInitialization() const {
3026 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3027}
3028
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003029void
3030InitializationSequence
3031::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3032 DeclAccessPair Found,
3033 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003034 Step S;
3035 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3036 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003037 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003038 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00003039 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003040 Steps.push_back(S);
3041}
3042
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00003044 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003045 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00003046 switch (VK) {
3047 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3048 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3049 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003050 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003051 S.Type = BaseType;
3052 Steps.push_back(S);
3053}
3054
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003055void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003056 bool BindingTemporary) {
3057 Step S;
3058 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3059 S.Type = T;
3060 Steps.push_back(S);
3061}
3062
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003063void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3064 Step S;
3065 S.Kind = SK_ExtraneousCopyToTemporary;
3066 S.Type = T;
3067 Steps.push_back(S);
3068}
3069
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003070void
3071InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3072 DeclAccessPair FoundDecl,
3073 QualType T,
3074 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003075 Step S;
3076 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003077 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003078 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003079 S.Function.Function = Function;
3080 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003081 Steps.push_back(S);
3082}
3083
3084void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00003085 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003086 Step S;
John McCall7a1da892010-08-26 16:36:35 +00003087 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00003088 switch (VK) {
3089 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003090 S.Kind = SK_QualificationConversionRValue;
3091 break;
John McCall2536c6d2010-08-25 10:28:54 +00003092 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003093 S.Kind = SK_QualificationConversionXValue;
3094 break;
John McCall2536c6d2010-08-25 10:28:54 +00003095 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003096 S.Kind = SK_QualificationConversionLValue;
3097 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003098 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003099 S.Type = Ty;
3100 Steps.push_back(S);
3101}
3102
Richard Smith77be48a2014-07-31 06:31:19 +00003103void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3104 Step S;
3105 S.Kind = SK_AtomicConversion;
3106 S.Type = Ty;
3107 Steps.push_back(S);
3108}
3109
Jordan Roseb1312a52013-04-11 00:58:58 +00003110void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3111 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3112
3113 Step S;
3114 S.Kind = SK_LValueToRValue;
3115 S.Type = Ty;
3116 Steps.push_back(S);
3117}
3118
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003119void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00003120 const ImplicitConversionSequence &ICS, QualType T,
3121 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003122 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00003123 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3124 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003125 S.Type = T;
3126 S.ICS = new ImplicitConversionSequence(ICS);
3127 Steps.push_back(S);
3128}
3129
Douglas Gregor51e77d52009-12-10 17:56:55 +00003130void InitializationSequence::AddListInitializationStep(QualType T) {
3131 Step S;
3132 S.Kind = SK_ListInitialization;
3133 S.Type = T;
3134 Steps.push_back(S);
3135}
3136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003137void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003138InitializationSequence
3139::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
3140 AccessSpecifier Access,
3141 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00003142 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003143 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003144 Step S;
Richard Smithf8adcdc2014-07-17 05:12:35 +00003145 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
Richard Smith53324112014-07-16 21:33:43 +00003146 : SK_ConstructorInitializationFromList
3147 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003148 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003149 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00003150 S.Function.Function = Constructor;
3151 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003152 Steps.push_back(S);
3153}
3154
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003155void InitializationSequence::AddZeroInitializationStep(QualType T) {
3156 Step S;
3157 S.Kind = SK_ZeroInitialization;
3158 S.Type = T;
3159 Steps.push_back(S);
3160}
3161
Douglas Gregore1314a62009-12-18 05:02:21 +00003162void InitializationSequence::AddCAssignmentStep(QualType T) {
3163 Step S;
3164 S.Kind = SK_CAssignment;
3165 S.Type = T;
3166 Steps.push_back(S);
3167}
3168
Eli Friedman78275202009-12-19 08:11:05 +00003169void InitializationSequence::AddStringInitStep(QualType T) {
3170 Step S;
3171 S.Kind = SK_StringInit;
3172 S.Type = T;
3173 Steps.push_back(S);
3174}
3175
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003176void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3177 Step S;
3178 S.Kind = SK_ObjCObjectConversion;
3179 S.Type = T;
3180 Steps.push_back(S);
3181}
3182
Douglas Gregore2f943b2011-02-22 18:29:51 +00003183void InitializationSequence::AddArrayInitStep(QualType T) {
3184 Step S;
3185 S.Kind = SK_ArrayInit;
3186 S.Type = T;
3187 Steps.push_back(S);
3188}
3189
Richard Smithebeed412012-02-15 22:38:09 +00003190void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3191 Step S;
3192 S.Kind = SK_ParenthesizedArrayInit;
3193 S.Type = T;
3194 Steps.push_back(S);
3195}
3196
John McCall31168b02011-06-15 23:02:42 +00003197void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3198 bool shouldCopy) {
3199 Step s;
3200 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3201 : SK_PassByIndirectRestore);
3202 s.Type = type;
3203 Steps.push_back(s);
3204}
3205
3206void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3207 Step S;
3208 S.Kind = SK_ProduceObjCObject;
3209 S.Type = T;
3210 Steps.push_back(S);
3211}
3212
Sebastian Redlc1839b12012-01-17 22:49:42 +00003213void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3214 Step S;
3215 S.Kind = SK_StdInitializerList;
3216 S.Type = T;
3217 Steps.push_back(S);
3218}
3219
Guy Benyei61054192013-02-07 10:55:47 +00003220void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3221 Step S;
3222 S.Kind = SK_OCLSamplerInit;
3223 S.Type = T;
3224 Steps.push_back(S);
3225}
3226
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003227void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3228 Step S;
3229 S.Kind = SK_OCLZeroEvent;
3230 S.Type = T;
3231 Steps.push_back(S);
3232}
3233
Sebastian Redl29526f02011-11-27 16:50:07 +00003234void InitializationSequence::RewrapReferenceInitList(QualType T,
3235 InitListExpr *Syntactic) {
3236 assert(Syntactic->getNumInits() == 1 &&
3237 "Can only rewrap trivial init lists.");
3238 Step S;
3239 S.Kind = SK_UnwrapInitList;
3240 S.Type = Syntactic->getInit(0)->getType();
3241 Steps.insert(Steps.begin(), S);
3242
3243 S.Kind = SK_RewrapInitList;
3244 S.Type = T;
3245 S.WrappingSyntacticList = Syntactic;
3246 Steps.push_back(S);
3247}
3248
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003249void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003250 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00003251 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003252 this->Failure = Failure;
3253 this->FailedOverloadResult = Result;
3254}
3255
3256//===----------------------------------------------------------------------===//
3257// Attempt initialization
3258//===----------------------------------------------------------------------===//
3259
Nico Weber337d5aa2015-04-17 08:32:38 +00003260/// Tries to add a zero initializer. Returns true if that worked.
3261static bool
3262maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3263 const InitializedEntity &Entity) {
3264 if (Entity.getKind() != InitializedEntity::EK_Variable)
3265 return false;
3266
3267 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3268 if (VD->getInit() || VD->getLocEnd().isMacroID())
3269 return false;
3270
3271 QualType VariableTy = VD->getType().getCanonicalType();
3272 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3273 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3274 if (!Init.empty()) {
3275 Sequence.AddZeroInitializationStep(Entity.getType());
3276 Sequence.SetZeroInitializationFixit(Init, Loc);
3277 return true;
3278 }
3279 return false;
3280}
3281
John McCall31168b02011-06-15 23:02:42 +00003282static void MaybeProduceObjCObject(Sema &S,
3283 InitializationSequence &Sequence,
3284 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003285 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00003286
3287 /// When initializing a parameter, produce the value if it's marked
3288 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00003289 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00003290 if (!Entity.isParameterConsumed())
3291 return;
3292
3293 assert(Entity.getType()->isObjCRetainableType() &&
3294 "consuming an object of unretainable type?");
3295 Sequence.AddProduceObjCObjectStep(Entity.getType());
3296
3297 /// When initializing a return value, if the return type is a
3298 /// retainable type, then returns need to immediately retain the
3299 /// object. If an autorelease is required, it will be done at the
3300 /// last instant.
3301 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3302 if (!Entity.getType()->isObjCRetainableType())
3303 return;
3304
3305 Sequence.AddProduceObjCObjectStep(Entity.getType());
3306 }
3307}
3308
Richard Smithcc1b96d2013-06-12 22:31:48 +00003309static void TryListInitialization(Sema &S,
3310 const InitializedEntity &Entity,
3311 const InitializationKind &Kind,
3312 InitListExpr *InitList,
3313 InitializationSequence &Sequence);
3314
Richard Smithd86812d2012-07-05 08:39:21 +00003315/// \brief When initializing from init list via constructor, handle
3316/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00003317///
Richard Smithd86812d2012-07-05 08:39:21 +00003318/// \return true if we have handled initialization of an object of type
3319/// std::initializer_list<T>, false otherwise.
3320static bool TryInitializerListConstruction(Sema &S,
3321 InitListExpr *List,
3322 QualType DestType,
3323 InitializationSequence &Sequence) {
3324 QualType E;
3325 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00003326 return false;
3327
Richard Smithcc1b96d2013-06-12 22:31:48 +00003328 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3329 Sequence.setIncompleteTypeFailure(E);
3330 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003331 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00003332
3333 // Try initializing a temporary array from the init list.
3334 QualType ArrayType = S.Context.getConstantArrayType(
3335 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3336 List->getNumInits()),
3337 clang::ArrayType::Normal, 0);
3338 InitializedEntity HiddenArray =
3339 InitializedEntity::InitializeTemporary(ArrayType);
3340 InitializationKind Kind =
3341 InitializationKind::CreateDirectList(List->getExprLoc());
3342 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3343 if (Sequence)
3344 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003345 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003346}
3347
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003348static OverloadingResult
3349ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003350 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003351 OverloadCandidateSet &CandidateSet,
Richard Smith40c78062015-02-21 02:31:57 +00003352 DeclContext::lookup_result Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003353 OverloadCandidateSet::iterator &Best,
3354 bool CopyInitializing, bool AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003355 bool OnlyListConstructors, bool IsListInit) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003356 CandidateSet.clear();
3357
Richard Smith40c78062015-02-21 02:31:57 +00003358 for (NamedDecl *D : Ctors) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003359 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3360 bool SuppressUserConversions = false;
3361
3362 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003363 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003364 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3365 if (ConstructorTmpl)
3366 Constructor = cast<CXXConstructorDecl>(
3367 ConstructorTmpl->getTemplatedDecl());
3368 else {
3369 Constructor = cast<CXXConstructorDecl>(D);
3370
Richard Smith6c6ddab2013-09-21 21:23:47 +00003371 // C++11 [over.best.ics]p4:
Larisse Voufo19d08672015-01-27 18:47:05 +00003372 // ... and the constructor or user-defined conversion function is a
3373 // candidate by
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003374 // - 13.3.1.3, when the argument is the temporary in the second step
Larisse Voufo19d08672015-01-27 18:47:05 +00003375 // of a class copy-initialization, or
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003376 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases),
Larisse Voufo19d08672015-01-27 18:47:05 +00003377 // user-defined conversion sequences are not considered.
Larisse Voufobcf327a2015-02-10 02:20:14 +00003378 // FIXME: This breaks backward compatibility, e.g. PR12117. As a
3379 // temporary fix, let's re-instate the third bullet above until
3380 // there is a resolution in the standard, i.e.,
3381 // - 13.3.1.7 when the initializer list has exactly one element that is
3382 // itself an initializer list and a conversion to some class X or
3383 // reference to (possibly cv-qualified) X is considered for the first
3384 // parameter of a constructor of X.
3385 if ((CopyInitializing ||
3386 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3387 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003388 SuppressUserConversions = true;
3389 }
3390
3391 if (!Constructor->isInvalidDecl() &&
3392 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003393 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003394 if (ConstructorTmpl)
3395 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003396 /*ExplicitArgs*/ nullptr, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003397 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003398 else {
3399 // C++ [over.match.copy]p1:
3400 // - When initializing a temporary to be bound to the first parameter
3401 // of a constructor that takes a reference to possibly cv-qualified
3402 // T as its first argument, called with a single argument in the
3403 // context of direct-initialization, explicit conversion functions
3404 // are also considered.
3405 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003406 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003407 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003408 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003409 SuppressUserConversions,
3410 /*PartialOverloading=*/false,
3411 /*AllowExplicit=*/AllowExplicitConv);
3412 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003413 }
3414 }
3415
3416 // Perform overload resolution and return the result.
3417 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3418}
3419
Sebastian Redled2e5322011-12-22 14:44:04 +00003420/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3421/// enumerates the constructors of the initialized entity and performs overload
3422/// resolution to select the best.
NAKAMURA Takumiffcc98a2015-02-05 23:12:13 +00003423/// \param IsListInit Is this list-initialization?
Richard Smithed83ebd2015-02-05 07:02:11 +00003424/// \param IsInitListCopy Is this non-list-initialization resulting from a
3425/// list-initialization from {x} where x is the same
3426/// type as the entity?
Sebastian Redled2e5322011-12-22 14:44:04 +00003427static void TryConstructorInitialization(Sema &S,
3428 const InitializedEntity &Entity,
3429 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003430 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003431 InitializationSequence &Sequence,
Richard Smithed83ebd2015-02-05 07:02:11 +00003432 bool IsListInit = false,
3433 bool IsInitListCopy = false) {
3434 assert((!IsListInit || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3435 "IsListInit must come with a single initializer list argument.");
Sebastian Redl88e4d492012-02-04 21:27:33 +00003436
Sebastian Redled2e5322011-12-22 14:44:04 +00003437 // The type we're constructing needs to be complete.
3438 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003439 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003440 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003441 }
3442
3443 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3444 assert(DestRecordType && "Constructor initialization requires record type");
3445 CXXRecordDecl *DestRecordDecl
3446 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3447
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003448 // Build the candidate set directly in the initialization sequence
3449 // structure, so that it will persist if we fail.
3450 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3451
3452 // Determine whether we are allowed to call explicit constructors or
3453 // explicit conversion operators.
Richard Smithed83ebd2015-02-05 07:02:11 +00003454 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003455 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003456
Sebastian Redled2e5322011-12-22 14:44:04 +00003457 // - Otherwise, if T is a class type, constructors are considered. The
3458 // applicable constructors are enumerated, and the best one is chosen
3459 // through overload resolution.
Richard Smith40c78062015-02-21 02:31:57 +00003460 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
Sebastian Redled2e5322011-12-22 14:44:04 +00003461
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003462 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003463 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003464 bool AsInitializerList = false;
3465
Larisse Voufo19d08672015-01-27 18:47:05 +00003466 // C++11 [over.match.list]p1, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003467 // When objects of non-aggregate type T are list-initialized, such that
3468 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3469 // according to the rules in this section, overload resolution selects
3470 // the constructor in two phases:
3471 //
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003472 // - Initially, the candidate functions are the initializer-list
3473 // constructors of the class T and the argument list consists of the
3474 // initializer list as a single argument.
Richard Smithed83ebd2015-02-05 07:02:11 +00003475 if (IsListInit) {
Richard Smithd86812d2012-07-05 08:39:21 +00003476 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003477 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003478
3479 // If the initializer list has no elements and T has a default constructor,
3480 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003481 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003482 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003483 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003484 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003485 /*OnlyListConstructor=*/true,
3486 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003487
3488 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003489 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003490 }
3491
3492 // C++11 [over.match.list]p1:
3493 // - If no viable initializer-list constructor is found, overload resolution
3494 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003495 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003496 // elements of the initializer list.
3497 if (Result == OR_No_Viable_Function) {
3498 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003499 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003500 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003501 CopyInitialization, AllowExplicit,
Larisse Voufobcf327a2015-02-10 02:20:14 +00003502 /*OnlyListConstructors=*/false,
3503 IsListInit);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003504 }
3505 if (Result) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003506 Sequence.SetOverloadFailure(IsListInit ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003507 InitializationSequence::FK_ListConstructorOverloadFailed :
3508 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003509 Result);
3510 return;
3511 }
3512
Richard Smithd86812d2012-07-05 08:39:21 +00003513 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003514 // If a program calls for the default initialization of an object
3515 // of a const-qualified type T, T shall be a class type with a
3516 // user-provided default constructor.
3517 if (Kind.getKind() == InitializationKind::IK_Default &&
3518 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003519 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Nico Weber337d5aa2015-04-17 08:32:38 +00003520 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3521 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
Sebastian Redled2e5322011-12-22 14:44:04 +00003522 return;
3523 }
3524
Sebastian Redl048a6d72012-04-01 19:54:59 +00003525 // C++11 [over.match.list]p1:
3526 // In copy-list-initialization, if an explicit constructor is chosen, the
3527 // initializer is ill-formed.
3528 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
Richard Smithed83ebd2015-02-05 07:02:11 +00003529 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
Sebastian Redl048a6d72012-04-01 19:54:59 +00003530 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3531 return;
3532 }
3533
Sebastian Redled2e5322011-12-22 14:44:04 +00003534 // Add the constructor initialization step. Any cv-qualification conversion is
3535 // subsumed by the initialization.
3536 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Richard Smithed83ebd2015-02-05 07:02:11 +00003537 Sequence.AddConstructorInitializationStep(
3538 CtorDecl, Best->FoundDecl.getAccess(), DestType, HadMultipleCandidates,
3539 IsListInit | IsInitListCopy, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003540}
3541
Sebastian Redl29526f02011-11-27 16:50:07 +00003542static bool
3543ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3544 Expr *Initializer,
3545 QualType &SourceType,
3546 QualType &UnqualifiedSourceType,
3547 QualType UnqualifiedTargetType,
3548 InitializationSequence &Sequence) {
3549 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3550 S.Context.OverloadTy) {
3551 DeclAccessPair Found;
3552 bool HadMultipleCandidates = false;
3553 if (FunctionDecl *Fn
3554 = S.ResolveAddressOfOverloadedFunction(Initializer,
3555 UnqualifiedTargetType,
3556 false, Found,
3557 &HadMultipleCandidates)) {
3558 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3559 HadMultipleCandidates);
3560 SourceType = Fn->getType();
3561 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3562 } else if (!UnqualifiedTargetType->isRecordType()) {
3563 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3564 return true;
3565 }
3566 }
3567 return false;
3568}
3569
3570static void TryReferenceInitializationCore(Sema &S,
3571 const InitializedEntity &Entity,
3572 const InitializationKind &Kind,
3573 Expr *Initializer,
3574 QualType cv1T1, QualType T1,
3575 Qualifiers T1Quals,
3576 QualType cv2T2, QualType T2,
3577 Qualifiers T2Quals,
3578 InitializationSequence &Sequence);
3579
Richard Smithd86812d2012-07-05 08:39:21 +00003580static void TryValueInitialization(Sema &S,
3581 const InitializedEntity &Entity,
3582 const InitializationKind &Kind,
3583 InitializationSequence &Sequence,
Craig Topperc3ec1492014-05-26 06:22:03 +00003584 InitListExpr *InitList = nullptr);
Richard Smithd86812d2012-07-05 08:39:21 +00003585
Sebastian Redl29526f02011-11-27 16:50:07 +00003586/// \brief Attempt list initialization of a reference.
3587static void TryReferenceListInitialization(Sema &S,
3588 const InitializedEntity &Entity,
3589 const InitializationKind &Kind,
3590 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003591 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003592 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003593 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003594 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3595 return;
3596 }
David Majnemer9370dc22015-04-26 07:35:03 +00003597 // Can't reference initialize a compound literal.
3598 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3599 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3600 return;
3601 }
Sebastian Redl29526f02011-11-27 16:50:07 +00003602
3603 QualType DestType = Entity.getType();
3604 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3605 Qualifiers T1Quals;
3606 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3607
3608 // Reference initialization via an initializer list works thus:
3609 // If the initializer list consists of a single element that is
3610 // reference-related to the referenced type, bind directly to that element
3611 // (possibly creating temporaries).
3612 // Otherwise, initialize a temporary with the initializer list and
3613 // bind to that.
3614 if (InitList->getNumInits() == 1) {
3615 Expr *Initializer = InitList->getInit(0);
3616 QualType cv2T2 = Initializer->getType();
3617 Qualifiers T2Quals;
3618 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3619
3620 // If this fails, creating a temporary wouldn't work either.
3621 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3622 T1, Sequence))
3623 return;
3624
3625 SourceLocation DeclLoc = Initializer->getLocStart();
3626 bool dummy1, dummy2, dummy3;
3627 Sema::ReferenceCompareResult RefRelationship
3628 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3629 dummy2, dummy3);
3630 if (RefRelationship >= Sema::Ref_Related) {
3631 // Try to bind the reference here.
3632 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3633 T1Quals, cv2T2, T2, T2Quals, Sequence);
3634 if (Sequence)
3635 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3636 return;
3637 }
Richard Smith03d93932013-01-15 07:58:29 +00003638
3639 // Update the initializer if we've resolved an overloaded function.
3640 if (Sequence.step_begin() != Sequence.step_end())
3641 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003642 }
3643
3644 // Not reference-related. Create a temporary and bind to that.
3645 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3646
3647 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3648 if (Sequence) {
3649 if (DestType->isRValueReferenceType() ||
3650 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3651 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3652 else
3653 Sequence.SetFailed(
3654 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3655 }
3656}
3657
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003658/// \brief Attempt list initialization (C++0x [dcl.init.list])
3659static void TryListInitialization(Sema &S,
3660 const InitializedEntity &Entity,
3661 const InitializationKind &Kind,
3662 InitListExpr *InitList,
3663 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003664 QualType DestType = Entity.getType();
3665
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003666 // C++ doesn't allow scalar initialization with more than one argument.
3667 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003668 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003669 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3670 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3671 return;
3672 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003673 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003674 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003675 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003676 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003677
Larisse Voufod2010992015-01-24 23:09:54 +00003678 if (DestType->isRecordType() &&
3679 S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3680 Sequence.setIncompleteTypeFailure(DestType);
3681 return;
3682 }
Richard Smithd86812d2012-07-05 08:39:21 +00003683
Larisse Voufo19d08672015-01-27 18:47:05 +00003684 // C++11 [dcl.init.list]p3, per DR1467:
Larisse Voufod2010992015-01-24 23:09:54 +00003685 // - If T is a class type and the initializer list has a single element of
3686 // type cv U, where U is T or a class derived from T, the object is
3687 // initialized from that element (by copy-initialization for
3688 // copy-list-initialization, or by direct-initialization for
3689 // direct-list-initialization).
3690 // - Otherwise, if T is a character array and the initializer list has a
3691 // single element that is an appropriately-typed string literal
3692 // (8.5.2 [dcl.init.string]), initialization is performed as described
3693 // in that section.
Larisse Voufo19d08672015-01-27 18:47:05 +00003694 // - Otherwise, if T is an aggregate, [...] (continue below).
3695 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
Larisse Voufod2010992015-01-24 23:09:54 +00003696 if (DestType->isRecordType()) {
3697 QualType InitType = InitList->getInit(0)->getType();
3698 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
3699 S.IsDerivedFrom(InitType, DestType)) {
Richard Smithed83ebd2015-02-05 07:02:11 +00003700 Expr *InitAsExpr = InitList->getInit(0);
3701 TryConstructorInitialization(S, Entity, Kind, InitAsExpr, DestType,
3702 Sequence, /*InitListSyntax*/ false,
3703 /*IsInitListCopy*/ true);
Larisse Voufod2010992015-01-24 23:09:54 +00003704 return;
3705 }
3706 }
3707 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
3708 Expr *SubInit[1] = {InitList->getInit(0)};
3709 if (!isa<VariableArrayType>(DestAT) &&
3710 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
3711 InitializationKind SubKind =
3712 Kind.getKind() == InitializationKind::IK_DirectList
3713 ? InitializationKind::CreateDirect(Kind.getLocation(),
3714 InitList->getLBraceLoc(),
3715 InitList->getRBraceLoc())
3716 : Kind;
3717 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3718 /*TopLevelOfInitList*/ true);
3719
3720 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
3721 // the element is not an appropriately-typed string literal, in which
3722 // case we should proceed as in C++11 (below).
3723 if (Sequence) {
3724 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3725 return;
3726 }
3727 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003728 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003729 }
Larisse Voufod2010992015-01-24 23:09:54 +00003730
3731 // C++11 [dcl.init.list]p3:
3732 // - If T is an aggregate, aggregate initialization is performed.
3733 if (DestType->isRecordType() && !DestType->isAggregateType()) {
3734 if (S.getLangOpts().CPlusPlus11) {
3735 // - Otherwise, if the initializer list has no elements and T is a
3736 // class type with a default constructor, the object is
3737 // value-initialized.
3738 if (InitList->getNumInits() == 0) {
3739 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3740 if (RD->hasDefaultConstructor()) {
3741 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3742 return;
3743 }
3744 }
3745
3746 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3747 // an initializer_list object constructed [...]
3748 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3749 return;
3750
3751 // - Otherwise, if T is a class type, constructors are considered.
3752 Expr *InitListAsExpr = InitList;
3753 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3754 Sequence, /*InitListSyntax*/ true);
3755 } else
3756 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
3757 return;
3758 }
3759
Richard Smith089c3162013-09-21 21:55:46 +00003760 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3761 InitList->getNumInits() == 1 &&
3762 InitList->getInit(0)->getType()->isRecordType()) {
3763 // - Otherwise, if the initializer list has a single element of type E
3764 // [...references are handled above...], the object or reference is
Larisse Voufod2010992015-01-24 23:09:54 +00003765 // initialized from that element (by copy-initialization for
3766 // copy-list-initialization, or by direct-initialization for
3767 // direct-list-initialization); if a narrowing conversion is required
3768 // to convert the element to T, the program is ill-formed.
3769 //
Richard Smith089c3162013-09-21 21:55:46 +00003770 // Per core-24034, this is direct-initialization if we were performing
3771 // direct-list-initialization and copy-initialization otherwise.
3772 // We can't use InitListChecker for this, because it always performs
3773 // copy-initialization. This only matters if we might use an 'explicit'
3774 // conversion operator, so we only need to handle the cases where the source
3775 // is of record type.
3776 InitializationKind SubKind =
3777 Kind.getKind() == InitializationKind::IK_DirectList
3778 ? InitializationKind::CreateDirect(Kind.getLocation(),
3779 InitList->getLBraceLoc(),
3780 InitList->getRBraceLoc())
3781 : Kind;
3782 Expr *SubInit[1] = { InitList->getInit(0) };
3783 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3784 /*TopLevelOfInitList*/true);
3785 if (Sequence)
3786 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3787 return;
3788 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003789
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003790 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003791 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003792 if (CheckInitList.HadError()) {
3793 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3794 return;
3795 }
3796
3797 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003798 Sequence.AddListInitializationStep(DestType);
3799}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003800
3801/// \brief Try a reference initialization that involves calling a conversion
3802/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003803static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3804 const InitializedEntity &Entity,
3805 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003806 Expr *Initializer,
3807 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003808 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003809 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003810 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3811 QualType T1 = cv1T1.getUnqualifiedType();
3812 QualType cv2T2 = Initializer->getType();
3813 QualType T2 = cv2T2.getUnqualifiedType();
3814
3815 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003816 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003817 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003819 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003820 ObjCConversion,
3821 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003822 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003823 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003824 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003825 (void)ObjCLifetimeConversion;
3826
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003827 // Build the candidate set directly in the initialization sequence
3828 // structure, so that it will persist if we fail.
3829 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3830 CandidateSet.clear();
3831
3832 // Determine whether we are allowed to call explicit constructors or
3833 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003834 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003835 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3836
Craig Topperc3ec1492014-05-26 06:22:03 +00003837 const RecordType *T1RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003838 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3839 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003840 // The type we're converting to is a class type. Enumerate its constructors
3841 // to see if there is a suitable conversion.
3842 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003843
Richard Smith40c78062015-02-21 02:31:57 +00003844 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00003845 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003847 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003848 CXXConstructorDecl *Constructor = nullptr;
John McCalla0296f72010-03-19 07:35:19 +00003849 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003850 if (ConstructorTmpl)
3851 Constructor = cast<CXXConstructorDecl>(
3852 ConstructorTmpl->getTemplatedDecl());
3853 else
John McCalla0296f72010-03-19 07:35:19 +00003854 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003856 if (!Constructor->isInvalidDecl() &&
3857 Constructor->isConvertingConstructor(AllowExplicit)) {
3858 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003859 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003860 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003861 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003862 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003863 else
John McCalla0296f72010-03-19 07:35:19 +00003864 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003865 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003866 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003869 }
John McCall3696dcb2010-08-17 07:23:57 +00003870 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3871 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003872
Craig Topperc3ec1492014-05-26 06:22:03 +00003873 const RecordType *T2RecordType = nullptr;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003874 if ((T2RecordType = T2->getAs<RecordType>()) &&
3875 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003876 // The type we're converting from is a class type, enumerate its conversion
3877 // functions.
3878 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3879
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003880 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
3881 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003882 NamedDecl *D = *I;
3883 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3884 if (isa<UsingShadowDecl>(D))
3885 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003887 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3888 CXXConversionDecl *Conv;
3889 if (ConvTemplate)
3890 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3891 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003892 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003894 // If the conversion function doesn't return a reference type,
3895 // it can't be considered for this conversion unless we're allowed to
3896 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 // FIXME: Do we need to make sure that we only consider conversion
3898 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003899 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003900 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003901 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3902 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003903 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003904 ActingDC, Initializer,
Douglas Gregor68782142013-12-18 21:46:16 +00003905 DestType, CandidateSet,
3906 /*AllowObjCConversionOnExplicit=*/
3907 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003908 else
John McCalla0296f72010-03-19 07:35:19 +00003909 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003910 Initializer, DestType, CandidateSet,
3911 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003912 }
3913 }
3914 }
John McCall3696dcb2010-08-17 07:23:57 +00003915 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3916 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003918 SourceLocation DeclLoc = Initializer->getLocStart();
3919
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003920 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003921 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003923 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003924 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003925
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003926 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003927 // This is the overload that will be used for this initialization step if we
3928 // use this initialization. Mark it as referenced.
3929 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003930
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003931 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003932 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003933 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003934 else
3935 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003936
3937 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003938 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003939 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003940 T2.getNonLValueExprType(S.Context),
3941 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003942
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003944 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003945 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003946 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003947 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003948 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003949 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003950
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003951 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003952 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003953 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003954 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003955 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003956 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003957 NewDerivedToBase, NewObjCConversion,
3958 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003959 if (NewRefRelationship == Sema::Ref_Incompatible) {
3960 // If the type we've converted to is not reference-related to the
3961 // type we're looking for, then there is another conversion step
3962 // we need to perform to produce a temporary of the right type
3963 // that we'll be binding to.
3964 ImplicitConversionSequence ICS;
3965 ICS.setStandard();
3966 ICS.Standard = Best->FinalConversion;
3967 T2 = ICS.Standard.getToType(2);
3968 Sequence.AddConversionSequenceStep(ICS, T2);
3969 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003970 Sequence.AddDerivedToBaseCastStep(
3971 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003972 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003973 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003974 else if (NewObjCConversion)
3975 Sequence.AddObjCObjectConversionStep(
3976 S.Context.getQualifiedType(T1,
3977 T2.getNonReferenceType().getQualifiers()));
3978
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003979 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003980 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003982 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3983 return OR_Success;
3984}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Richard Smithc620f552011-10-19 16:55:56 +00003986static void CheckCXX98CompatAccessibleCopy(Sema &S,
3987 const InitializedEntity &Entity,
3988 Expr *CurInitExpr);
3989
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003990/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3991static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003992 const InitializedEntity &Entity,
3993 const InitializationKind &Kind,
3994 Expr *Initializer,
3995 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003996 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003997 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003998 Qualifiers T1Quals;
3999 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004000 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00004001 Qualifiers T2Quals;
4002 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00004003
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004004 // If the initializer is the address of an overloaded function, try
4005 // to resolve the overloaded function. If all goes well, T2 is the
4006 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00004007 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4008 T1, Sequence))
4009 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00004010
Sebastian Redl29526f02011-11-27 16:50:07 +00004011 // Delegate everything else to a subfunction.
4012 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4013 T1Quals, cv2T2, T2, T2Quals, Sequence);
4014}
4015
Jordan Roseb1312a52013-04-11 00:58:58 +00004016/// Converts the target of reference initialization so that it has the
4017/// appropriate qualifiers and value kind.
4018///
4019/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
4020/// \code
4021/// int x;
4022/// const int &r = x;
4023/// \endcode
4024///
4025/// In this case the reference is binding to a bitfield lvalue, which isn't
4026/// valid. Perform a load to create a lifetime-extended temporary instead.
4027/// \code
4028/// const int &r = someStruct.bitfield;
4029/// \endcode
4030static ExprValueKind
4031convertQualifiersAndValueKindIfNecessary(Sema &S,
4032 InitializationSequence &Sequence,
4033 Expr *Initializer,
4034 QualType cv1T1,
4035 Qualifiers T1Quals,
4036 Qualifiers T2Quals,
4037 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00004038 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00004039 Initializer->refersToVectorElement();
4040
4041 if (IsNonAddressableType) {
4042 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
4043 // lvalue reference to a non-volatile const type, or the reference shall be
4044 // an rvalue reference.
4045 //
4046 // If not, we can't make a temporary and bind to that. Give up and allow the
4047 // error to be diagnosed later.
4048 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
4049 assert(Initializer->isGLValue());
4050 return Initializer->getValueKind();
4051 }
4052
4053 // Force a load so we can materialize a temporary.
4054 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
4055 return VK_RValue;
4056 }
4057
4058 if (T1Quals != T2Quals) {
4059 Sequence.AddQualificationConversionStep(cv1T1,
4060 Initializer->getValueKind());
4061 }
4062
4063 return Initializer->getValueKind();
4064}
4065
4066
Sebastian Redl29526f02011-11-27 16:50:07 +00004067/// \brief Reference initialization without resolving overloaded functions.
4068static void TryReferenceInitializationCore(Sema &S,
4069 const InitializedEntity &Entity,
4070 const InitializationKind &Kind,
4071 Expr *Initializer,
4072 QualType cv1T1, QualType T1,
4073 Qualifiers T1Quals,
4074 QualType cv2T2, QualType T2,
4075 Qualifiers T2Quals,
4076 InitializationSequence &Sequence) {
4077 QualType DestType = Entity.getType();
4078 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004079 // Compute some basic properties of the types and the initializer.
4080 bool isLValueRef = DestType->isLValueReferenceType();
4081 bool isRValueRef = !isLValueRef;
4082 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004083 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004084 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004085 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004086 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004087 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004088 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00004089
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004090 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004092 // "cv2 T2" as follows:
4093 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004094 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004095 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00004096 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00004097 // there are no function rvalues in C++, rvalue refs to functions are treated
4098 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004099 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00004100 bool T1Function = T1->isFunctionType();
4101 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004103 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004104 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004105 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004107 // reference-compatible with "cv2 T2," or
4108 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004109 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004110 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00004111 // can occur. However, we do pay attention to whether it is a bit-field
4112 // to decide whether we're actually binding to a temporary created from
4113 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004114 if (DerivedToBase)
4115 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00004117 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004118 else if (ObjCConversion)
4119 Sequence.AddObjCObjectConversionStep(
4120 S.Context.getQualifiedType(T1, T2Quals));
4121
Jordan Roseb1312a52013-04-11 00:58:58 +00004122 ExprValueKind ValueKind =
4123 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
4124 cv1T1, T1Quals, T2Quals,
4125 isLValueRef);
4126 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004127 return;
4128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004129
4130 // - has a class type (i.e., T2 is a class type), where T1 is not
4131 // reference-related to T2, and can be implicitly converted to an
4132 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4133 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004134 // applicable conversion functions (13.3.1.6) and choosing the best
4135 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00004136 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00004137 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00004138 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4139 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004140 ConvOvlResult = TryRefInitWithConversionFunction(
4141 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004142 if (ConvOvlResult == OR_Success)
4143 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00004144 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00004145 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004146 InitializationSequence::FK_ReferenceInitOverloadFailed,
4147 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004148 }
4149 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004150
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004151 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004152 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00004153 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004154 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00004155 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4156 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4157 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004158 Sequence.SetOverloadFailure(
4159 InitializationSequence::FK_ReferenceInitOverloadFailed,
4160 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004161 else
Sebastian Redld92badf2010-06-30 18:13:39 +00004162 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004163 ? (RefRelationship == Sema::Ref_Related
4164 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
4165 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
4166 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00004167
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004168 return;
4169 }
Sebastian Redld92badf2010-06-30 18:13:39 +00004170
Douglas Gregor92e460e2011-01-20 16:44:54 +00004171 // - If the initializer expression
4172 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
4173 // "cv1 T1" is reference-compatible with "cv2 T2"
4174 // Note: functions are handled below.
4175 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00004176 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00004178 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00004179 (InitCategory.isXValue() ||
4180 (InitCategory.isPRValue() && T2->isRecordType()) ||
4181 (InitCategory.isPRValue() && T2->isArrayType()))) {
4182 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
4183 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004184 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4185 // compiler the freedom to perform a copy here or bind to the
4186 // object, while C++0x requires that we bind directly to the
4187 // object. Hence, we always bind to the object without making an
4188 // extra copy. However, in C++03 requires that we check for the
4189 // presence of a suitable copy constructor:
4190 //
4191 // The constructor that would be used to make the copy shall
4192 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004193 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004194 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004195 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00004196 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198
Douglas Gregor92e460e2011-01-20 16:44:54 +00004199 if (DerivedToBase)
4200 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
4201 ValueKind);
4202 else if (ObjCConversion)
4203 Sequence.AddObjCObjectConversionStep(
4204 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Jordan Roseb1312a52013-04-11 00:58:58 +00004206 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
4207 Initializer, cv1T1,
4208 T1Quals, T2Quals,
4209 isLValueRef);
4210
4211 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00004213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
4215 // - has a class type (i.e., T2 is a class type), where T1 is not
4216 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00004217 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4218 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00004219 //
4220 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00004221 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004222 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00004223 ConvOvlResult = TryRefInitWithConversionFunction(
4224 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004225 if (ConvOvlResult)
4226 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00004227 InitializationSequence::FK_ReferenceInitOverloadFailed,
4228 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004230 return;
4231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00004233 if ((RefRelationship == Sema::Ref_Compatible ||
4234 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
4235 isRValueRef && InitCategory.isLValue()) {
4236 Sequence.SetFailed(
4237 InitializationSequence::FK_RValueReferenceBindingToLValue);
4238 return;
4239 }
4240
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004241 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4242 return;
4243 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004244
4245 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004246 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00004247 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004248 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00004249
John McCallec6f4e92010-06-04 02:29:22 +00004250 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4251
Richard Smith2eabf782013-06-13 00:57:57 +00004252 // FIXME: Why do we use an implicit conversion here rather than trying
4253 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00004254 ImplicitConversionSequence ICS
4255 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00004256 /*SuppressUserConversions=*/false,
4257 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004258 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004259 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4260 /*AllowObjCWritebackConversion=*/false);
4261
4262 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004263 // FIXME: Use the conversion function set stored in ICS to turn
4264 // this into an overloading ambiguity diagnostic. However, we need
4265 // to keep that set as an OverloadCandidateSet rather than as some
4266 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00004267 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4268 Sequence.SetOverloadFailure(
4269 InitializationSequence::FK_ReferenceInitOverloadFailed,
4270 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00004271 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4272 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00004273 else
4274 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004275 return;
John McCall31168b02011-06-15 23:02:42 +00004276 } else {
4277 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004278 }
4279
4280 // [...] If T1 is reference-related to T2, cv1 must be the
4281 // same cv-qualification as, or greater cv-qualification
4282 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00004283 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4284 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00004286 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004287 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4288 return;
4289 }
4290
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004292 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00004294 InitCategory.isLValue()) {
4295 Sequence.SetFailed(
4296 InitializationSequence::FK_RValueReferenceBindingToLValue);
4297 return;
4298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004300 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4301 return;
4302}
4303
4304/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305/// (C++ [dcl.init.string], C99 6.7.8).
4306static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004307 const InitializedEntity &Entity,
4308 const InitializationKind &Kind,
4309 Expr *Initializer,
4310 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004311 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004312}
4313
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004314/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004316 const InitializedEntity &Entity,
4317 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00004318 InitializationSequence &Sequence,
4319 InitListExpr *InitList) {
4320 assert((!InitList || InitList->getNumInits() == 0) &&
4321 "Shouldn't use value-init for non-empty init lists");
4322
Richard Smith1bfe0682012-02-14 21:14:13 +00004323 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004324 //
4325 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00004326 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004328 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00004329 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004331 if (const RecordType *RT = T->getAs<RecordType>()) {
4332 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00004333 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004334 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00004335 // C++98:
4336 // -- if T is a class type (clause 9) with a user-declared constructor
4337 // (12.1), then the default constructor for T is called (and the
4338 // initialization is ill-formed if T has no accessible default
4339 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00004340 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00004341 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004342 } else {
4343 // C++11:
4344 // -- if T is a class type (clause 9) with either no default constructor
4345 // (12.1 [class.ctor]) or a default constructor that is user-provided
4346 // or deleted, then the object is default-initialized;
4347 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4348 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00004349 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00004350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Richard Smith1bfe0682012-02-14 21:14:13 +00004352 // -- if T is a (possibly cv-qualified) non-union class type without a
4353 // user-provided or deleted default constructor, then the object is
4354 // zero-initialized and, if T has a non-trivial default constructor,
4355 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00004356 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4357 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00004358 if (NeedZeroInitialization)
4359 Sequence.AddZeroInitializationStep(Entity.getType());
4360
Richard Smith593f9932012-12-08 02:01:17 +00004361 // C++03:
4362 // -- if T is a non-union class type without a user-declared constructor,
4363 // then every non-static data member and base class component of T is
4364 // value-initialized;
4365 // [...] A program that calls for [...] value-initialization of an
4366 // entity of reference type is ill-formed.
4367 //
4368 // C++11 doesn't need this handling, because value-initialization does not
4369 // occur recursively there, and the implicit default constructor is
4370 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004371 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00004372 ClassDecl->hasUninitializedReferenceMember()) {
4373 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4374 return;
4375 }
4376
Richard Smithd86812d2012-07-05 08:39:21 +00004377 // If this is list-value-initialization, pass the empty init list on when
4378 // building the constructor call. This affects the semantics of a few
4379 // things (such as whether an explicit default constructor can be called).
4380 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004381 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004382 bool InitListSyntax = InitList;
4383
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004384 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4385 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004386 }
4387 }
4388
Douglas Gregor1b303932009-12-22 15:35:07 +00004389 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004390}
4391
Douglas Gregor85dabae2009-12-16 01:38:02 +00004392/// \brief Attempt default initialization (C++ [dcl.init]p6).
4393static void TryDefaultInitialization(Sema &S,
4394 const InitializedEntity &Entity,
4395 const InitializationKind &Kind,
4396 InitializationSequence &Sequence) {
4397 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregor85dabae2009-12-16 01:38:02 +00004399 // C++ [dcl.init]p6:
4400 // To default-initialize an object of type T means:
4401 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004402 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4403
Douglas Gregor85dabae2009-12-16 01:38:02 +00004404 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4405 // constructor for T is called (and the initialization is ill-formed if
4406 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004407 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004408 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004409 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregor85dabae2009-12-16 01:38:02 +00004412 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregor85dabae2009-12-16 01:38:02 +00004414 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004416 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004417 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Nico Weber337d5aa2015-04-17 08:32:38 +00004418 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4419 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004420 return;
4421 }
4422
4423 // If the destination type has a lifetime property, zero-initialize it.
4424 if (DestType.getQualifiers().hasObjCLifetime()) {
4425 Sequence.AddZeroInitializationStep(Entity.getType());
4426 return;
4427 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004428}
4429
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004430/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4431/// which enumerates all conversion functions and performs overload resolution
4432/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433static void TryUserDefinedConversion(Sema &S,
Richard Smith77be48a2014-07-31 06:31:19 +00004434 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004435 const InitializationKind &Kind,
4436 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004437 InitializationSequence &Sequence,
4438 bool TopLevelOfInitList) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004439 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4440 QualType SourceType = Initializer->getType();
4441 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4442 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Douglas Gregor540c3b02009-12-14 17:27:33 +00004444 // Build the candidate set directly in the initialization sequence
4445 // structure, so that it will persist if we fail.
4446 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4447 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448
Douglas Gregor540c3b02009-12-14 17:27:33 +00004449 // Determine whether we are allowed to call explicit constructors or
4450 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004451 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Douglas Gregor540c3b02009-12-14 17:27:33 +00004453 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4454 // The type we're converting to is a class type. Enumerate its constructors
4455 // to see if there is a suitable conversion.
4456 CXXRecordDecl *DestRecordDecl
4457 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458
Douglas Gregord9848152010-04-26 14:36:57 +00004459 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004461 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004462 // The container holding the constructors can under certain conditions
4463 // be changed while iterating. To be safe we copy the lookup results
4464 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004465 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004466 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004467 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004468 Con != ConEnd; ++Con) {
4469 NamedDecl *D = *Con;
4470 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
Douglas Gregord9848152010-04-26 14:36:57 +00004472 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00004473 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregord9848152010-04-26 14:36:57 +00004474 FunctionTemplateDecl *ConstructorTmpl
4475 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004476 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004477 Constructor = cast<CXXConstructorDecl>(
4478 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004479 else
Douglas Gregord9848152010-04-26 14:36:57 +00004480 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Douglas Gregord9848152010-04-26 14:36:57 +00004482 if (!Constructor->isInvalidDecl() &&
4483 Constructor->isConvertingConstructor(AllowExplicit)) {
4484 if (ConstructorTmpl)
4485 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00004486 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004487 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004488 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004489 else
4490 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004491 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004492 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004493 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004494 }
Douglas Gregord9848152010-04-26 14:36:57 +00004495 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004496 }
Eli Friedman78275202009-12-19 08:11:05 +00004497
4498 SourceLocation DeclLoc = Initializer->getLocStart();
4499
Douglas Gregor540c3b02009-12-14 17:27:33 +00004500 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4501 // The type we're converting from is a class type, enumerate its conversion
4502 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004503
Eli Friedman4afe9a32009-12-20 22:12:03 +00004504 // We can only enumerate the conversion functions for a complete type; if
4505 // the type isn't complete, simply skip this step.
4506 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4507 CXXRecordDecl *SourceRecordDecl
4508 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004510 const auto &Conversions =
4511 SourceRecordDecl->getVisibleConversionFunctions();
4512 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004513 NamedDecl *D = *I;
4514 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4515 if (isa<UsingShadowDecl>(D))
4516 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Eli Friedman4afe9a32009-12-20 22:12:03 +00004518 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4519 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004520 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004521 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004522 else
John McCallda4458e2010-03-31 01:36:47 +00004523 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
Eli Friedman4afe9a32009-12-20 22:12:03 +00004525 if (AllowExplicit || !Conv->isExplicit()) {
4526 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004527 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004528 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004529 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004530 else
John McCalla0296f72010-03-19 07:35:19 +00004531 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004532 Initializer, DestType, CandidateSet,
4533 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004534 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004535 }
4536 }
4537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538
4539 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004540 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004541 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004542 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004543 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004545 Result);
4546 return;
4547 }
John McCall0d1da222010-01-12 00:44:57 +00004548
Douglas Gregor540c3b02009-12-14 17:27:33 +00004549 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004550 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004551 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
Douglas Gregor540c3b02009-12-14 17:27:33 +00004553 if (isa<CXXConstructorDecl>(Function)) {
4554 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004555 // subsumed by the initialization. Per DR5, the created temporary is of the
4556 // cv-unqualified type of the destination.
4557 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4558 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004559 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004560 return;
4561 }
4562
4563 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004564 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004565 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004566 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004567 // the resulting temporary object (possible to create an object of
4568 // a base class type). That copy is not a separate conversion, so
4569 // we just make a note of the actual destination type (possibly a
4570 // base class of the type returned by the conversion function) and
4571 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004572 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4573 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004574 return;
4575 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004576
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004577 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4578 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004579
Douglas Gregor5ab11652010-04-17 22:01:05 +00004580 // If the conversion following the call to the conversion function
4581 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004582 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4583 Best->FinalConversion.Third) {
4584 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004585 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004586 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004587 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004588 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004589}
4590
Richard Smithf032001b2013-06-20 02:18:31 +00004591/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4592/// a function with a pointer return type contains a 'return false;' statement.
4593/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4594/// code using that header.
4595///
4596/// Work around this by treating 'return false;' as zero-initializing the result
4597/// if it's used in a pointer-returning function in a system header.
4598static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4599 const InitializedEntity &Entity,
4600 const Expr *Init) {
4601 return S.getLangOpts().CPlusPlus11 &&
4602 Entity.getKind() == InitializedEntity::EK_Result &&
4603 Entity.getType()->isPointerType() &&
4604 isa<CXXBoolLiteralExpr>(Init) &&
4605 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4606 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4607}
4608
John McCall31168b02011-06-15 23:02:42 +00004609/// The non-zero enum values here are indexes into diagnostic alternatives.
4610enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4611
4612/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004613static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004614 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004615 // Skip parens.
4616 e = e->IgnoreParens();
4617
4618 // Skip address-of nodes.
4619 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4620 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004621 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4622 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004623
4624 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004625 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4626 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004627 case CK_Dependent:
4628 case CK_BitCast:
4629 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004630 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004631 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004632
4633 case CK_ArrayToPointerDecay:
4634 return IIK_nonscalar;
4635
4636 case CK_NullToPointer:
4637 return IIK_okay;
4638
4639 default:
4640 break;
4641 }
4642
4643 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004644 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004645 // set isWeakAccess to true, to mean that there will be an implicit
4646 // load which requires a cleanup.
4647 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4648 isWeakAccess = true;
4649
John McCall63f84442011-06-27 23:59:58 +00004650 if (!isAddressOf) return IIK_nonlocal;
4651
John McCall113bee02012-03-10 09:33:50 +00004652 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4653 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004654
4655 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004656
4657 // If we have a conditional operator, check both sides.
4658 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004659 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4660 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004661 return iik;
4662
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004663 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004664
4665 // These are never scalar.
4666 } else if (isa<ArraySubscriptExpr>(e)) {
4667 return IIK_nonscalar;
4668
4669 // Otherwise, it needs to be a null pointer constant.
4670 } else {
4671 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4672 ? IIK_okay : IIK_nonlocal);
4673 }
4674
4675 return IIK_nonlocal;
4676}
4677
4678/// Check whether the given expression is a valid operand for an
4679/// indirect copy/restore.
4680static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4681 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004682 bool isWeakAccess = false;
4683 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4684 // If isWeakAccess to true, there will be an implicit
4685 // load which requires a cleanup.
4686 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4687 S.ExprNeedsCleanups = true;
4688
John McCall31168b02011-06-15 23:02:42 +00004689 if (iik == IIK_okay) return;
4690
4691 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4692 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4693 << src->getSourceRange();
4694}
4695
Douglas Gregore2f943b2011-02-22 18:29:51 +00004696/// \brief Determine whether we have compatible array types for the
4697/// purposes of GNU by-copy array initialization.
Larisse Voufod2010992015-01-24 23:09:54 +00004698static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
Douglas Gregore2f943b2011-02-22 18:29:51 +00004699 const ArrayType *Source) {
4700 // If the source and destination array types are equivalent, we're
4701 // done.
4702 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4703 return true;
4704
4705 // Make sure that the element types are the same.
4706 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4707 return false;
4708
4709 // The only mismatch we allow is when the destination is an
4710 // incomplete array type and the source is a constant array type.
4711 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4712}
4713
John McCall31168b02011-06-15 23:02:42 +00004714static bool tryObjCWritebackConversion(Sema &S,
4715 InitializationSequence &Sequence,
4716 const InitializedEntity &Entity,
4717 Expr *Initializer) {
4718 bool ArrayDecay = false;
4719 QualType ArgType = Initializer->getType();
4720 QualType ArgPointee;
4721 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4722 ArrayDecay = true;
4723 ArgPointee = ArgArrayType->getElementType();
4724 ArgType = S.Context.getPointerType(ArgPointee);
4725 }
4726
4727 // Handle write-back conversion.
4728 QualType ConvertedArgType;
4729 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4730 ConvertedArgType))
4731 return false;
4732
4733 // We should copy unless we're passing to an argument explicitly
4734 // marked 'out'.
4735 bool ShouldCopy = true;
4736 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4737 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4738
4739 // Do we need an lvalue conversion?
4740 if (ArrayDecay || Initializer->isGLValue()) {
4741 ImplicitConversionSequence ICS;
4742 ICS.setStandard();
4743 ICS.Standard.setAsIdentityConversion();
4744
4745 QualType ResultType;
4746 if (ArrayDecay) {
4747 ICS.Standard.First = ICK_Array_To_Pointer;
4748 ResultType = S.Context.getPointerType(ArgPointee);
4749 } else {
4750 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4751 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4752 }
4753
4754 Sequence.AddConversionSequenceStep(ICS, ResultType);
4755 }
4756
4757 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4758 return true;
4759}
4760
Guy Benyei61054192013-02-07 10:55:47 +00004761static bool TryOCLSamplerInitialization(Sema &S,
4762 InitializationSequence &Sequence,
4763 QualType DestType,
4764 Expr *Initializer) {
4765 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4766 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4767 return false;
4768
4769 Sequence.AddOCLSamplerInitStep(DestType);
4770 return true;
4771}
4772
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004773//
4774// OpenCL 1.2 spec, s6.12.10
4775//
4776// The event argument can also be used to associate the
4777// async_work_group_copy with a previous async copy allowing
4778// an event to be shared by multiple async copies; otherwise
4779// event should be zero.
4780//
4781static bool TryOCLZeroEventInitialization(Sema &S,
4782 InitializationSequence &Sequence,
4783 QualType DestType,
4784 Expr *Initializer) {
4785 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4786 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4787 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4788 return false;
4789
4790 Sequence.AddOCLZeroEventStep(DestType);
4791 return true;
4792}
4793
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004794InitializationSequence::InitializationSequence(Sema &S,
4795 const InitializedEntity &Entity,
4796 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004797 MultiExprArg Args,
4798 bool TopLevelOfInitList)
Richard Smith100b24a2014-04-17 01:52:14 +00004799 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
Richard Smith089c3162013-09-21 21:55:46 +00004800 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4801}
4802
4803void InitializationSequence::InitializeFrom(Sema &S,
4804 const InitializedEntity &Entity,
4805 const InitializationKind &Kind,
4806 MultiExprArg Args,
4807 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004808 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809
John McCall5e77d762013-04-16 07:28:30 +00004810 // Eliminate non-overload placeholder types in the arguments. We
4811 // need to do this before checking whether types are dependent
4812 // because lowering a pseudo-object expression might well give us
4813 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004814 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004815 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4816 // FIXME: should we be doing this here?
4817 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4818 if (result.isInvalid()) {
4819 SetFailed(FK_PlaceholderType);
4820 return;
4821 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004822 Args[I] = result.get();
John McCall5e77d762013-04-16 07:28:30 +00004823 }
4824
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004825 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 // The semantics of initializers are as follows. The destination type is
4827 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004828 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004830 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004831 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004832
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004833 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004834 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004835 SequenceKind = DependentSequence;
4836 return;
4837 }
4838
Sebastian Redld201edf2011-06-05 13:59:11 +00004839 // Almost everything is a normal sequence.
4840 setSequenceKind(NormalSequence);
4841
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004842 QualType SourceType;
Craig Topperc3ec1492014-05-26 06:22:03 +00004843 Expr *Initializer = nullptr;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004844 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004845 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004846 if (S.getLangOpts().ObjC1) {
4847 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4848 DestType, Initializer->getType(),
4849 Initializer) ||
4850 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4851 Args[0] = Initializer;
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004852 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004853 if (!isa<InitListExpr>(Initializer))
4854 SourceType = Initializer->getType();
4855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856
Sebastian Redl0501c632012-02-12 16:37:36 +00004857 // - If the initializer is a (non-parenthesized) braced-init-list, the
4858 // object is list-initialized (8.5.4).
4859 if (Kind.getKind() != InitializationKind::IK_Direct) {
4860 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4861 TryListInitialization(S, Entity, Kind, InitList, *this);
4862 return;
4863 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004865
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866 // - If the destination type is a reference type, see 8.5.3.
4867 if (DestType->isReferenceType()) {
4868 // C++0x [dcl.init.ref]p1:
4869 // A variable declared to be a T& or T&&, that is, "reference to type T"
4870 // (8.3.2), shall be initialized by an object, or function, of type T or
4871 // by an object that can be converted into a T.
4872 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004873 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004874 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004875 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004876 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004877 return;
4878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004880 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004881 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004882 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004883 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004884 return;
4885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Douglas Gregor85dabae2009-12-16 01:38:02 +00004887 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004888 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004889 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004890 return;
4891 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004892
John McCall66884dd2011-02-21 07:22:22 +00004893 // - If the destination type is an array of characters, an array of
4894 // char16_t, an array of char32_t, or an array of wchar_t, and the
4895 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004897 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004898 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004899 if (Initializer && isa<VariableArrayType>(DestAT)) {
4900 SetFailed(FK_VariableLengthArrayHasInitializer);
4901 return;
4902 }
4903
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004904 if (Initializer) {
4905 switch (IsStringInit(Initializer, DestAT, Context)) {
4906 case SIF_None:
4907 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4908 return;
4909 case SIF_NarrowStringIntoWideChar:
4910 SetFailed(FK_NarrowStringIntoWideCharArray);
4911 return;
4912 case SIF_WideStringIntoChar:
4913 SetFailed(FK_WideStringIntoCharArray);
4914 return;
4915 case SIF_IncompatWideStringIntoWideChar:
4916 SetFailed(FK_IncompatWideStringIntoWideChar);
4917 return;
4918 case SIF_Other:
4919 break;
4920 }
John McCall66884dd2011-02-21 07:22:22 +00004921 }
4922
Douglas Gregore2f943b2011-02-22 18:29:51 +00004923 // Note: as an GNU C extension, we allow initialization of an
4924 // array from a compound literal that creates an array of the same
4925 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004926 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004927 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4928 Initializer->getType()->isArrayType()) {
4929 const ArrayType *SourceAT
4930 = Context.getAsArrayType(Initializer->getType());
4931 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004932 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004933 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004934 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004935 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004936 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004937 }
Richard Smithebeed412012-02-15 22:38:09 +00004938 }
Richard Smithd86812d2012-07-05 08:39:21 +00004939 // Note: as a GNU C++ extension, we allow list-initialization of a
4940 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004941 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004942 Entity.getKind() == InitializedEntity::EK_Member &&
4943 Initializer && isa<InitListExpr>(Initializer)) {
4944 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4945 *this);
4946 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004947 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004948 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004949 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4950 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004951 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004952 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004954 return;
4955 }
Eli Friedman78275202009-12-19 08:11:05 +00004956
Larisse Voufod2010992015-01-24 23:09:54 +00004957 // Determine whether we should consider writeback conversions for
John McCall31168b02011-06-15 23:02:42 +00004958 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004959 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004960 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004961
4962 // We're at the end of the line for C: it's either a write-back conversion
4963 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004964 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004965 // If allowed, check whether this is an Objective-C writeback conversion.
4966 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004967 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004968 return;
4969 }
Guy Benyei61054192013-02-07 10:55:47 +00004970
4971 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4972 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004973
4974 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4975 return;
4976
John McCall31168b02011-06-15 23:02:42 +00004977 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004978 AddCAssignmentStep(DestType);
4979 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004980 return;
4981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982
David Blaikiebbafb8a2012-03-11 07:00:24 +00004983 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004984
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004985 // - If the destination type is a (possibly cv-qualified) class type:
4986 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987 // - If the initialization is direct-initialization, or if it is
4988 // copy-initialization where the cv-unqualified version of the
4989 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004990 // class of the destination, constructors are considered. [...]
4991 if (Kind.getKind() == InitializationKind::IK_Direct ||
4992 (Kind.getKind() == InitializationKind::IK_Copy &&
4993 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4994 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004995 TryConstructorInitialization(S, Entity, Kind, Args,
Richard Smith77be48a2014-07-31 06:31:19 +00004996 DestType, *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004998 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005000 // used) to a derived class thereof are enumerated as described in
5001 // 13.3.1.4, and the best one is chosen through overload resolution
5002 // (13.3).
5003 else
Richard Smith77be48a2014-07-31 06:31:19 +00005004 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005005 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005006 return;
5007 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005009 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005010 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005011 return;
5012 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005013 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014
5015 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005016 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00005017 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smith77be48a2014-07-31 06:31:19 +00005018 // For a conversion to _Atomic(T) from either T or a class type derived
5019 // from T, initialize the T object then convert to _Atomic type.
5020 bool NeedAtomicConversion = false;
5021 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5022 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5023 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
5024 DestType = Atomic->getValueType();
5025 NeedAtomicConversion = true;
5026 }
5027 }
5028
5029 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
Richard Smithaaa0ec42013-09-21 21:19:19 +00005030 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005031 MaybeProduceObjCObject(S, *this, Entity);
Richard Smith77be48a2014-07-31 06:31:19 +00005032 if (!Failed() && NeedAtomicConversion)
5033 AddAtomicConversionStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005034 return;
5035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005037 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00005038 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005039 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005041 // destination type; no user-defined conversions are considered.
Richard Smith77be48a2014-07-31 06:31:19 +00005042
John McCall31168b02011-06-15 23:02:42 +00005043 ImplicitConversionSequence ICS
Richard Smith77be48a2014-07-31 06:31:19 +00005044 = S.TryImplicitConversion(Initializer, DestType,
John McCall31168b02011-06-15 23:02:42 +00005045 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00005046 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00005047 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00005048 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5049 allowObjCWritebackConversion);
Richard Smith77be48a2014-07-31 06:31:19 +00005050
5051 if (ICS.isStandard() &&
John McCall31168b02011-06-15 23:02:42 +00005052 ICS.Standard.Second == ICK_Writeback_Conversion) {
5053 // Objective-C ARC writeback conversion.
5054
5055 // We should copy unless we're passing to an argument explicitly
5056 // marked 'out'.
5057 bool ShouldCopy = true;
5058 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5059 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5060
5061 // If there was an lvalue adjustment, add it as a separate conversion.
5062 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5063 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5064 ImplicitConversionSequence LvalueICS;
5065 LvalueICS.setStandard();
5066 LvalueICS.Standard.setAsIdentityConversion();
5067 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5068 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005069 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00005070 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005071
Richard Smith77be48a2014-07-31 06:31:19 +00005072 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00005073 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00005074 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00005075 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5076 AddZeroInitializationStep(Entity.getType());
5077 } else if (Initializer->getType() == Context.OverloadTy &&
5078 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5079 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005080 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005081 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005082 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00005083 } else {
Richard Smith77be48a2014-07-31 06:31:19 +00005084 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00005085
Rafael Espindola699fc4d2011-07-14 22:58:04 +00005086 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00005087 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005088}
5089
5090InitializationSequence::~InitializationSequence() {
Davide Italiano67bb9f72015-07-01 21:51:58 +00005091 for (auto &S : Steps)
5092 S.Destroy();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005093}
5094
5095//===----------------------------------------------------------------------===//
5096// Perform initialization
5097//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005099getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005100 switch(Entity.getKind()) {
5101 case InitializedEntity::EK_Variable:
5102 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00005103 case InitializedEntity::EK_Exception:
5104 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005105 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00005106 return Sema::AA_Initializing;
5107
5108 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00005110 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5111 return Sema::AA_Sending;
5112
Douglas Gregore1314a62009-12-18 05:02:21 +00005113 return Sema::AA_Passing;
5114
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00005115 case InitializedEntity::EK_Parameter_CF_Audited:
5116 if (Entity.getDecl() &&
5117 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5118 return Sema::AA_Sending;
5119
5120 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5121
Douglas Gregore1314a62009-12-18 05:02:21 +00005122 case InitializedEntity::EK_Result:
5123 return Sema::AA_Returning;
5124
Douglas Gregore1314a62009-12-18 05:02:21 +00005125 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00005126 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005127 // FIXME: Can we tell apart casting vs. converting?
5128 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005129
Douglas Gregore1314a62009-12-18 05:02:21 +00005130 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005131 case InitializedEntity::EK_ArrayElement:
5132 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005133 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005134 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005135 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005136 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005137 return Sema::AA_Initializing;
5138 }
5139
David Blaikie8a40f702012-01-17 06:56:22 +00005140 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00005141}
5142
Richard Smith27874d62013-01-08 00:08:23 +00005143/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00005144/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005145static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005146 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00005147 case InitializedEntity::EK_ArrayElement:
5148 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005149 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00005150 case InitializedEntity::EK_New:
5151 case InitializedEntity::EK_Variable:
5152 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005153 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00005154 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005155 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00005156 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005157 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005158 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005159 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00005160 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005161
Douglas Gregore1314a62009-12-18 05:02:21 +00005162 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005163 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00005164 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005165 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00005166 return true;
5167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Douglas Gregore1314a62009-12-18 05:02:21 +00005169 llvm_unreachable("missed an InitializedEntity kind?");
5170}
5171
Douglas Gregor95562572010-04-24 23:45:46 +00005172/// \brief Whether the given entity, when initialized with an object
5173/// created for that initialization, requires destruction.
5174static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
5175 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00005176 case InitializedEntity::EK_Result:
5177 case InitializedEntity::EK_New:
5178 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00005179 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00005180 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00005181 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00005182 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00005183 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00005184 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
Richard Smith27874d62013-01-08 00:08:23 +00005186 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00005187 case InitializedEntity::EK_Variable:
5188 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005189 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00005190 case InitializedEntity::EK_Temporary:
5191 case InitializedEntity::EK_ArrayElement:
5192 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005193 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005194 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00005195 return true;
5196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197
5198 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00005199}
5200
Richard Smithc620f552011-10-19 16:55:56 +00005201/// \brief Look for copy and move constructors and constructor templates, for
5202/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
5203static void LookupCopyAndMoveConstructors(Sema &S,
5204 OverloadCandidateSet &CandidateSet,
5205 CXXRecordDecl *Class,
5206 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00005207 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005208 // The container holding the constructors can under certain conditions
5209 // be changed while iterating (e.g. because of deserialization).
5210 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00005211 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00005212 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005213 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
5214 NamedDecl *D = *CI;
Craig Topperc3ec1492014-05-26 06:22:03 +00005215 CXXConstructorDecl *Constructor = nullptr;
Richard Smithc620f552011-10-19 16:55:56 +00005216
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005217 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00005218 // Handle copy/moveconstructors, only.
5219 if (!Constructor || Constructor->isInvalidDecl() ||
5220 !Constructor->isCopyOrMoveConstructor() ||
5221 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5222 continue;
5223
5224 DeclAccessPair FoundDecl
5225 = DeclAccessPair::make(Constructor, Constructor->getAccess());
5226 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005227 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00005228 continue;
5229 }
5230
5231 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00005232 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00005233 if (ConstructorTmpl->isInvalidDecl())
5234 continue;
5235
5236 Constructor = cast<CXXConstructorDecl>(
5237 ConstructorTmpl->getTemplatedDecl());
5238 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
5239 continue;
5240
5241 // FIXME: Do we need to limit this to copy-constructor-like
5242 // candidates?
5243 DeclAccessPair FoundDecl
5244 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
Craig Topperc3ec1492014-05-26 06:22:03 +00005245 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005246 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00005247 }
5248}
5249
5250/// \brief Get the location at which initialization diagnostics should appear.
5251static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5252 Expr *Initializer) {
5253 switch (Entity.getKind()) {
5254 case InitializedEntity::EK_Result:
5255 return Entity.getReturnLoc();
5256
5257 case InitializedEntity::EK_Exception:
5258 return Entity.getThrowLoc();
5259
5260 case InitializedEntity::EK_Variable:
5261 return Entity.getDecl()->getLocation();
5262
Douglas Gregor19666fb2012-02-15 16:57:26 +00005263 case InitializedEntity::EK_LambdaCapture:
5264 return Entity.getCaptureLoc();
5265
Richard Smithc620f552011-10-19 16:55:56 +00005266 case InitializedEntity::EK_ArrayElement:
5267 case InitializedEntity::EK_Member:
5268 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005269 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00005270 case InitializedEntity::EK_Temporary:
5271 case InitializedEntity::EK_New:
5272 case InitializedEntity::EK_Base:
5273 case InitializedEntity::EK_Delegating:
5274 case InitializedEntity::EK_VectorElement:
5275 case InitializedEntity::EK_ComplexElement:
5276 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005277 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005278 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00005279 return Initializer->getLocStart();
5280 }
5281 llvm_unreachable("missed an InitializedEntity kind?");
5282}
5283
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005284/// \brief Make a (potentially elidable) temporary copy of the object
5285/// provided by the given initializer by calling the appropriate copy
5286/// constructor.
5287///
5288/// \param S The Sema object used for type-checking.
5289///
Abramo Bagnara92141d22011-01-27 19:55:10 +00005290/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005291/// the type of the initializer expression or a superclass thereof.
5292///
James Dennett634962f2012-06-14 21:40:34 +00005293/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005294///
5295/// \param CurInit The initializer expression.
5296///
5297/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5298/// is permitted in C++03 (but not C++0x) when binding a reference to
5299/// an rvalue.
5300///
5301/// \returns An expression that copies the initializer expression into
5302/// a temporary object, or an error expression if a copy could not be
5303/// created.
John McCalldadc5752010-08-24 06:29:42 +00005304static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005305 QualType T,
5306 const InitializedEntity &Entity,
5307 ExprResult CurInit,
5308 bool IsExtraneousCopy) {
Fariborz Jahanian36f7f132015-01-28 22:08:10 +00005309 if (CurInit.isInvalid())
5310 return CurInit;
Douglas Gregor5ab11652010-04-17 22:01:05 +00005311 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00005312 Expr *CurInitExpr = (Expr *)CurInit.get();
Craig Topperc3ec1492014-05-26 06:22:03 +00005313 CXXRecordDecl *Class = nullptr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005314 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005315 Class = cast<CXXRecordDecl>(Record->getDecl());
5316 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005317 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005318
Douglas Gregor5d369002011-01-21 18:05:27 +00005319 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005320 // When certain criteria are met, an implementation is allowed to
5321 // omit the copy/move construction of a class object, even if the
5322 // copy/move constructor and/or destructor for the object have
5323 // side effects. [...]
5324 // - when a temporary class object that has not been bound to a
5325 // reference (12.2) would be copied/moved to a class object
5326 // with the same cv-unqualified type, the copy/move operation
5327 // can be omitted by constructing the temporary object
5328 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005329 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005330 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005331 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00005333 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00005334 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00005335 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00005336
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005337 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005338 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005339 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00005340
Douglas Gregorf282a762011-01-21 19:38:21 +00005341 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00005342 // Only consider constructors and constructor templates. Per
5343 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5344 // is direct-initialization.
Richard Smith100b24a2014-04-17 01:52:14 +00005345 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005346 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005347
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005348 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5349
Douglas Gregore1314a62009-12-18 05:02:21 +00005350 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00005351 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005352 case OR_Success:
5353 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregore1314a62009-12-18 05:02:21 +00005355 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005356 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5357 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5358 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005359 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005360 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005361 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005362 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00005363 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005364 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005365
Douglas Gregore1314a62009-12-18 05:02:21 +00005366 case OR_Ambiguous:
5367 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005368 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005369 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005370 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00005371 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372
Douglas Gregore1314a62009-12-18 05:02:21 +00005373 case OR_Deleted:
5374 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00005375 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00005376 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00005377 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00005378 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005379 }
5380
Douglas Gregor5ab11652010-04-17 22:01:05 +00005381 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00005382 SmallVector<Expr*, 8> ConstructorArgs;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005383 CurInit.get(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005384
Anders Carlssona01874b2010-04-21 18:47:17 +00005385 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00005386 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005387
5388 if (IsExtraneousCopy) {
5389 // If this is a totally extraneous copy for C++03 reference
5390 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005391 // expression. We don't generate an (elided) copy operation here
5392 // because doing so would require us to pass down a flag to avoid
5393 // infinite recursion, where each step adds another extraneous,
5394 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005395
Douglas Gregor30b52772010-04-18 07:57:34 +00005396 // Instantiate the default arguments of any extra parameters in
5397 // the selected copy constructor, as if we were going to create a
5398 // proper call to the copy constructor.
5399 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5400 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5401 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005402 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005403 break;
5404
5405 // Build the default argument expression; we don't actually care
5406 // if this succeeds or not, because this routine will complain
5407 // if there was a problem.
5408 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5409 }
5410
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005411 return CurInitExpr;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005413
Douglas Gregor5ab11652010-04-17 22:01:05 +00005414 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005415 // constructor call (we might have derived-to-base conversions, or
5416 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005417 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005418 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005419
Douglas Gregord0ace022010-04-25 00:55:24 +00005420 // Actually perform the constructor call.
5421 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005422 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005423 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005424 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005425 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005426 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005427 CXXConstructExpr::CK_Complete,
5428 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005429
Douglas Gregord0ace022010-04-25 00:55:24 +00005430 // If we're supposed to bind temporaries, do so.
5431 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005432 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005433 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005434}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005435
Richard Smithc620f552011-10-19 16:55:56 +00005436/// \brief Check whether elidable copy construction for binding a reference to
5437/// a temporary would have succeeded if we were building in C++98 mode, for
5438/// -Wc++98-compat.
5439static void CheckCXX98CompatAccessibleCopy(Sema &S,
5440 const InitializedEntity &Entity,
5441 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005442 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005443
5444 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5445 if (!Record)
5446 return;
5447
5448 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005449 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
Richard Smithc620f552011-10-19 16:55:56 +00005450 return;
5451
5452 // Find constructors which would have been considered.
Richard Smith100b24a2014-04-17 01:52:14 +00005453 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Richard Smithc620f552011-10-19 16:55:56 +00005454 LookupCopyAndMoveConstructors(
5455 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5456
5457 // Perform overload resolution.
5458 OverloadCandidateSet::iterator Best;
5459 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5460
5461 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5462 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5463 << CurInitExpr->getSourceRange();
5464
5465 switch (OR) {
5466 case OR_Success:
5467 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005468 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005469 // FIXME: Check default arguments as far as that's possible.
5470 break;
5471
5472 case OR_No_Viable_Function:
5473 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005474 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005475 break;
5476
5477 case OR_Ambiguous:
5478 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005479 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005480 break;
5481
5482 case OR_Deleted:
5483 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005484 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005485 break;
5486 }
5487}
5488
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005489void InitializationSequence::PrintInitLocationNote(Sema &S,
5490 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005491 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005492 if (Entity.getDecl()->getLocation().isInvalid())
5493 return;
5494
5495 if (Entity.getDecl()->getDeclName())
5496 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5497 << Entity.getDecl()->getDeclName();
5498 else
5499 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5500 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005501 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5502 Entity.getMethodDecl())
5503 S.Diag(Entity.getMethodDecl()->getLocation(),
5504 diag::note_method_return_type_change)
5505 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005506}
5507
Sebastian Redl112aa822011-07-14 19:07:55 +00005508static bool isReferenceBinding(const InitializationSequence::Step &s) {
5509 return s.Kind == InitializationSequence::SK_BindReference ||
5510 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5511}
5512
Jordan Rose6c0505e2013-05-06 16:48:12 +00005513/// Returns true if the parameters describe a constructor initialization of
5514/// an explicit temporary object, e.g. "Point(x, y)".
5515static bool isExplicitTemporary(const InitializedEntity &Entity,
5516 const InitializationKind &Kind,
5517 unsigned NumArgs) {
5518 switch (Entity.getKind()) {
5519 case InitializedEntity::EK_Temporary:
5520 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005521 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005522 break;
5523 default:
5524 return false;
5525 }
5526
5527 switch (Kind.getKind()) {
5528 case InitializationKind::IK_DirectList:
5529 return true;
5530 // FIXME: Hack to work around cast weirdness.
5531 case InitializationKind::IK_Direct:
5532 case InitializationKind::IK_Value:
5533 return NumArgs != 1;
5534 default:
5535 return false;
5536 }
5537}
5538
Sebastian Redled2e5322011-12-22 14:44:04 +00005539static ExprResult
5540PerformConstructorInitialization(Sema &S,
5541 const InitializedEntity &Entity,
5542 const InitializationKind &Kind,
5543 MultiExprArg Args,
5544 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005545 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005546 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005547 bool IsStdInitListInitialization,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005548 SourceLocation LBraceLoc,
5549 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005550 unsigned NumArgs = Args.size();
5551 CXXConstructorDecl *Constructor
5552 = cast<CXXConstructorDecl>(Step.Function.Function);
5553 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5554
5555 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005556 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005557 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5558 ? Kind.getEqualLoc()
5559 : Kind.getLocation();
5560
5561 if (Kind.getKind() == InitializationKind::IK_Default) {
5562 // Force even a trivial, implicit default constructor to be
5563 // semantically checked. We do this explicitly because we don't build
5564 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005565 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005566 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005567 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005568 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5569 }
5570
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005571 ExprResult CurInit((Expr *)nullptr);
Sebastian Redled2e5322011-12-22 14:44:04 +00005572
Douglas Gregor6073dca2012-02-24 23:56:31 +00005573 // C++ [over.match.copy]p1:
5574 // - When initializing a temporary to be bound to the first parameter
5575 // of a constructor that takes a reference to possibly cv-qualified
5576 // T as its first argument, called with a single argument in the
5577 // context of direct-initialization, explicit conversion functions
5578 // are also considered.
5579 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5580 Args.size() == 1 &&
5581 Constructor->isCopyOrMoveConstructor();
5582
Sebastian Redled2e5322011-12-22 14:44:04 +00005583 // Determine the arguments required to actually perform the constructor
5584 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005585 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005586 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005587 AllowExplicitConv,
5588 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005589 return ExprError();
5590
5591
Jordan Rose6c0505e2013-05-06 16:48:12 +00005592 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005593 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005594 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005595 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5596 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005597
5598 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5599 if (!TSInfo)
5600 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005601 SourceRange ParenOrBraceRange =
5602 (Kind.getKind() == InitializationKind::IK_DirectList)
5603 ? SourceRange(LBraceLoc, RBraceLoc)
5604 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005605
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005606 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5607 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5608 HadMultipleCandidates, IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005609 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
Sebastian Redled2e5322011-12-22 14:44:04 +00005610 } else {
5611 CXXConstructExpr::ConstructionKind ConstructKind =
5612 CXXConstructExpr::CK_Complete;
5613
5614 if (Entity.getKind() == InitializedEntity::EK_Base) {
5615 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5616 CXXConstructExpr::CK_VirtualBase :
5617 CXXConstructExpr::CK_NonVirtualBase;
5618 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5619 ConstructKind = CXXConstructExpr::CK_Delegating;
5620 }
5621
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005622 // Only get the parenthesis or brace range if it is a list initialization or
5623 // direct construction.
5624 SourceRange ParenOrBraceRange;
5625 if (IsListInitialization)
5626 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5627 else if (Kind.getKind() == InitializationKind::IK_Direct)
5628 ParenOrBraceRange = Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005629
5630 // If the entity allows NRVO, mark the construction as elidable
5631 // unconditionally.
5632 if (Entity.allowsNRVO())
5633 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5634 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005635 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005636 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005637 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005638 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005639 ConstructorInitRequiresZeroInit,
5640 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005641 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005642 else
5643 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5644 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005645 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005646 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005647 IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +00005648 IsStdInitListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005649 ConstructorInitRequiresZeroInit,
5650 ConstructKind,
Peter Collingbourneb8d17e72014-02-22 02:59:41 +00005651 ParenOrBraceRange);
Sebastian Redled2e5322011-12-22 14:44:04 +00005652 }
5653 if (CurInit.isInvalid())
5654 return ExprError();
5655
5656 // Only check access if all of that succeeded.
5657 S.CheckConstructorAccess(Loc, Constructor, Entity,
5658 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005659 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5660 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005661
5662 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005663 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redled2e5322011-12-22 14:44:04 +00005664
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005665 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005666}
5667
Richard Smitheb3cad52012-06-04 22:27:30 +00005668/// Determine whether the specified InitializedEntity definitely has a lifetime
5669/// longer than the current full-expression. Conservatively returns false if
5670/// it's unclear.
5671static bool
5672InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5673 const InitializedEntity *Top = &Entity;
5674 while (Top->getParent())
5675 Top = Top->getParent();
5676
5677 switch (Top->getKind()) {
5678 case InitializedEntity::EK_Variable:
5679 case InitializedEntity::EK_Result:
5680 case InitializedEntity::EK_Exception:
5681 case InitializedEntity::EK_Member:
5682 case InitializedEntity::EK_New:
5683 case InitializedEntity::EK_Base:
5684 case InitializedEntity::EK_Delegating:
5685 return true;
5686
5687 case InitializedEntity::EK_ArrayElement:
5688 case InitializedEntity::EK_VectorElement:
5689 case InitializedEntity::EK_BlockElement:
5690 case InitializedEntity::EK_ComplexElement:
5691 // Could not determine what the full initialization is. Assume it might not
5692 // outlive the full-expression.
5693 return false;
5694
5695 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005696 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005697 case InitializedEntity::EK_Temporary:
5698 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005699 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005700 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005701 // The entity being initialized might not outlive the full-expression.
5702 return false;
5703 }
5704
5705 llvm_unreachable("unknown entity kind");
5706}
5707
Richard Smithe6c01442013-06-05 00:46:14 +00005708/// Determine the declaration which an initialized entity ultimately refers to,
5709/// for the purpose of lifetime-extending a temporary bound to a reference in
5710/// the initialization of \p Entity.
David Majnemerdaff3702014-05-01 17:50:17 +00005711static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5712 const InitializedEntity *Entity,
Craig Topperc3ec1492014-05-26 06:22:03 +00005713 const InitializedEntity *FallbackDecl = nullptr) {
Richard Smithe6c01442013-06-05 00:46:14 +00005714 // C++11 [class.temporary]p5:
David Majnemerdaff3702014-05-01 17:50:17 +00005715 switch (Entity->getKind()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005716 case InitializedEntity::EK_Variable:
5717 // The temporary [...] persists for the lifetime of the reference
David Majnemerdaff3702014-05-01 17:50:17 +00005718 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005719
5720 case InitializedEntity::EK_Member:
5721 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005722 if (Entity->getParent())
5723 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5724 Entity);
Richard Smithe6c01442013-06-05 00:46:14 +00005725
5726 // except:
5727 // -- A temporary bound to a reference member in a constructor's
5728 // ctor-initializer persists until the constructor exits.
David Majnemerdaff3702014-05-01 17:50:17 +00005729 return Entity;
Richard Smithe6c01442013-06-05 00:46:14 +00005730
5731 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005732 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005733 // -- A temporary bound to a reference parameter in a function call
5734 // persists until the completion of the full-expression containing
5735 // the call.
5736 case InitializedEntity::EK_Result:
5737 // -- The lifetime of a temporary bound to the returned value in a
5738 // function return statement is not extended; the temporary is
5739 // destroyed at the end of the full-expression in the return statement.
5740 case InitializedEntity::EK_New:
5741 // -- A temporary bound to a reference in a new-initializer persists
5742 // until the completion of the full-expression containing the
5743 // new-initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005744 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005745
5746 case InitializedEntity::EK_Temporary:
5747 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005748 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005749 // We don't yet know the storage duration of the surrounding temporary.
5750 // Assume it's got full-expression duration for now, it will patch up our
5751 // storage duration if that's not correct.
David Majnemerdaff3702014-05-01 17:50:17 +00005752 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005753
5754 case InitializedEntity::EK_ArrayElement:
5755 // For subobjects, we look at the complete object.
David Majnemerdaff3702014-05-01 17:50:17 +00005756 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5757 FallbackDecl);
Richard Smithe6c01442013-06-05 00:46:14 +00005758
5759 case InitializedEntity::EK_Base:
5760 case InitializedEntity::EK_Delegating:
5761 // We can reach this case for aggregate initialization in a constructor:
5762 // struct A { int &&r; };
5763 // struct B : A { B() : A{0} {} };
5764 // In this case, use the innermost field decl as the context.
5765 return FallbackDecl;
5766
5767 case InitializedEntity::EK_BlockElement:
5768 case InitializedEntity::EK_LambdaCapture:
5769 case InitializedEntity::EK_Exception:
5770 case InitializedEntity::EK_VectorElement:
5771 case InitializedEntity::EK_ComplexElement:
David Majnemerdaff3702014-05-01 17:50:17 +00005772 return nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00005773 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005774 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005775}
5776
David Majnemerdaff3702014-05-01 17:50:17 +00005777static void performLifetimeExtension(Expr *Init,
5778 const InitializedEntity *ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005779
5780/// Update a glvalue expression that is used as the initializer of a reference
5781/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005782/// \return \c true if any temporary had its lifetime extended.
David Majnemerdaff3702014-05-01 17:50:17 +00005783static bool
5784performReferenceExtension(Expr *Init,
5785 const InitializedEntity *ExtendingEntity) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005786 // Walk past any constructs which we can lifetime-extend across.
5787 Expr *Old;
5788 do {
5789 Old = Init;
5790
Richard Smithdbc82492015-01-10 01:28:13 +00005791 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5792 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5793 // This is just redundant braces around an initializer. Step over it.
5794 Init = ILE->getInit(0);
5795 }
5796 }
5797
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005798 // Step over any subobject adjustments; we may have a materialized
5799 // temporary inside them.
5800 SmallVector<const Expr *, 2> CommaLHSs;
5801 SmallVector<SubobjectAdjustment, 2> Adjustments;
5802 Init = const_cast<Expr *>(
5803 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5804
5805 // Per current approach for DR1376, look through casts to reference type
5806 // when performing lifetime extension.
5807 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5808 if (CE->getSubExpr()->isGLValue())
5809 Init = CE->getSubExpr();
5810
5811 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5812 // It's unclear if binding a reference to that xvalue extends the array
5813 // temporary.
5814 } while (Init != Old);
5815
Richard Smithe6c01442013-06-05 00:46:14 +00005816 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5817 // Update the storage duration of the materialized temporary.
5818 // FIXME: Rebuild the expression instead of mutating it.
David Majnemerdaff3702014-05-01 17:50:17 +00005819 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5820 ExtendingEntity->allocateManglingNumber());
5821 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005822 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005823 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005824
5825 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005826}
5827
5828/// Update a prvalue expression that is going to be materialized as a
5829/// lifetime-extended temporary.
David Majnemerdaff3702014-05-01 17:50:17 +00005830static void performLifetimeExtension(Expr *Init,
5831 const InitializedEntity *ExtendingEntity) {
Richard Smithe6c01442013-06-05 00:46:14 +00005832 // Dig out the expression which constructs the extended temporary.
5833 SmallVector<const Expr *, 2> CommaLHSs;
5834 SmallVector<SubobjectAdjustment, 2> Adjustments;
5835 Init = const_cast<Expr *>(
5836 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5837
Richard Smith736a9472013-06-12 20:42:33 +00005838 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5839 Init = BTE->getSubExpr();
5840
Richard Smithcc1b96d2013-06-12 22:31:48 +00005841 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005842 dyn_cast<CXXStdInitializerListExpr>(Init)) {
David Majnemerdaff3702014-05-01 17:50:17 +00005843 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005844 return;
5845 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005846
Richard Smithe6c01442013-06-05 00:46:14 +00005847 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005848 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005849 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
David Majnemerdaff3702014-05-01 17:50:17 +00005850 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005851 return;
5852 }
5853
Richard Smithcc1b96d2013-06-12 22:31:48 +00005854 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005855 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5856
5857 // If we lifetime-extend a braced initializer which is initializing an
5858 // aggregate, and that aggregate contains reference members which are
5859 // bound to temporaries, those temporaries are also lifetime-extended.
5860 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5861 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005862 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005863 else {
5864 unsigned Index = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005865 for (const auto *I : RD->fields()) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005866 if (Index >= ILE->getNumInits())
5867 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005868 if (I->isUnnamedBitfield())
5869 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005870 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005871 if (I->getType()->isReferenceType())
David Majnemerdaff3702014-05-01 17:50:17 +00005872 performReferenceExtension(SubInit, ExtendingEntity);
Richard Smith8d7f11d2013-06-27 22:54:33 +00005873 else if (isa<InitListExpr>(SubInit) ||
5874 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005875 // This may be either aggregate-initialization of a member or
5876 // initialization of a std::initializer_list object. Either way,
5877 // we should recursively lifetime-extend that initializer.
David Majnemerdaff3702014-05-01 17:50:17 +00005878 performLifetimeExtension(SubInit, ExtendingEntity);
Richard Smithe6c01442013-06-05 00:46:14 +00005879 ++Index;
5880 }
5881 }
5882 }
5883 }
5884}
5885
Richard Smithcc1b96d2013-06-12 22:31:48 +00005886static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5887 const Expr *Init, bool IsInitializerList,
5888 const ValueDecl *ExtendingDecl) {
5889 // Warn if a field lifetime-extends a temporary.
5890 if (isa<FieldDecl>(ExtendingDecl)) {
5891 if (IsInitializerList) {
5892 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5893 << /*at end of constructor*/true;
5894 return;
5895 }
5896
5897 bool IsSubobjectMember = false;
5898 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5899 Ent = Ent->getParent()) {
5900 if (Ent->getKind() != InitializedEntity::EK_Base) {
5901 IsSubobjectMember = true;
5902 break;
5903 }
5904 }
5905 S.Diag(Init->getExprLoc(),
5906 diag::warn_bind_ref_member_to_temporary)
5907 << ExtendingDecl << Init->getSourceRange()
5908 << IsSubobjectMember << IsInitializerList;
5909 if (IsSubobjectMember)
5910 S.Diag(ExtendingDecl->getLocation(),
5911 diag::note_ref_subobject_of_member_declared_here);
5912 else
5913 S.Diag(ExtendingDecl->getLocation(),
5914 diag::note_ref_or_ptr_member_declared_here)
5915 << /*is pointer*/false;
5916 }
5917}
5918
Richard Smithaaa0ec42013-09-21 21:19:19 +00005919static void DiagnoseNarrowingInInitList(Sema &S,
5920 const ImplicitConversionSequence &ICS,
5921 QualType PreNarrowingType,
5922 QualType EntityType,
5923 const Expr *PostInit);
5924
Richard Trieuac3eca52015-04-29 01:52:17 +00005925/// Provide warnings when std::move is used on construction.
5926static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
5927 bool IsReturnStmt) {
5928 if (!InitExpr)
5929 return;
5930
5931 QualType DestType = InitExpr->getType();
5932 if (!DestType->isRecordType())
5933 return;
5934
5935 unsigned DiagID = 0;
5936 if (IsReturnStmt) {
5937 const CXXConstructExpr *CCE =
5938 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
5939 if (!CCE || CCE->getNumArgs() != 1)
5940 return;
5941
5942 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
5943 return;
5944
5945 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
5946
5947 // Remove implicit temporary and constructor nodes.
5948 if (const MaterializeTemporaryExpr *MTE =
5949 dyn_cast<MaterializeTemporaryExpr>(InitExpr)) {
5950 InitExpr = MTE->GetTemporaryExpr()->IgnoreImpCasts();
5951 while (const CXXConstructExpr *CCE =
5952 dyn_cast<CXXConstructExpr>(InitExpr)) {
5953 if (isa<CXXTemporaryObjectExpr>(CCE))
5954 return;
5955 if (CCE->getNumArgs() == 0)
5956 return;
5957 if (CCE->getNumArgs() > 1 && !isa<CXXDefaultArgExpr>(CCE->getArg(1)))
5958 return;
5959 InitExpr = CCE->getArg(0);
5960 }
5961 InitExpr = InitExpr->IgnoreImpCasts();
5962 DiagID = diag::warn_redundant_move_on_return;
5963 }
5964 }
5965
5966 // Find the std::move call and get the argument.
5967 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
5968 if (!CE || CE->getNumArgs() != 1)
5969 return;
5970
5971 const FunctionDecl *MoveFunction = CE->getDirectCallee();
5972 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
5973 !MoveFunction->getIdentifier() ||
5974 !MoveFunction->getIdentifier()->isStr("move"))
5975 return;
5976
5977 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
5978
5979 if (IsReturnStmt) {
5980 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
5981 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
5982 return;
5983
5984 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
5985 if (!VD || !VD->hasLocalStorage())
5986 return;
5987
Richard Trieu1d4911bc2015-05-18 19:54:08 +00005988 if (!VD->getType()->isRecordType())
5989 return;
5990
Davide Italiano7842c3f2015-07-18 01:15:19 +00005991 // If we're returning a function parameter, copy elision
5992 // is not possible.
5993 if (isa<ParmVarDecl>(VD))
5994 DiagID = diag::warn_redundant_move_on_return;
5995
Richard Trieuac3eca52015-04-29 01:52:17 +00005996 if (DiagID == 0) {
5997 DiagID = S.Context.hasSameUnqualifiedType(DestType, VD->getType())
5998 ? diag::warn_pessimizing_move_on_return
5999 : diag::warn_redundant_move_on_return;
6000 }
6001 } else {
6002 DiagID = diag::warn_pessimizing_move_on_initialization;
6003 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6004 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6005 return;
6006 }
6007
6008 S.Diag(CE->getLocStart(), DiagID);
6009
6010 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6011 // is within a macro.
6012 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6013 if (CallBegin.isMacroID())
6014 return;
6015 SourceLocation RParen = CE->getRParenLoc();
6016 if (RParen.isMacroID())
6017 return;
6018 SourceLocation LParen;
6019 SourceLocation ArgLoc = Arg->getLocStart();
6020
6021 // Special testing for the argument location. Since the fix-it needs the
6022 // location right before the argument, the argument location can be in a
6023 // macro only if it is at the beginning of the macro.
6024 while (ArgLoc.isMacroID() &&
6025 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6026 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6027 }
6028
6029 if (LParen.isMacroID())
6030 return;
6031
6032 LParen = ArgLoc.getLocWithOffset(-1);
6033
6034 S.Diag(CE->getLocStart(), diag::note_remove_move)
6035 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6036 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6037}
6038
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006039ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006040InitializationSequence::Perform(Sema &S,
6041 const InitializedEntity &Entity,
6042 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00006043 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006044 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006045 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006046 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00006047 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006048 }
Nico Weber337d5aa2015-04-17 08:32:38 +00006049 if (!ZeroInitializationFixit.empty()) {
6050 unsigned DiagID = diag::err_default_init_const;
6051 if (Decl *D = Entity.getDecl())
6052 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6053 DiagID = diag::ext_default_init_const;
6054
6055 // The initialization would have succeeded with this fixit. Since the fixit
6056 // is on the error, we need to build a valid AST in this case, so this isn't
6057 // handled in the Failed() branch above.
6058 QualType DestType = Entity.getType();
6059 S.Diag(Kind.getLocation(), DiagID)
6060 << DestType << (bool)DestType->getAs<RecordType>()
6061 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6062 ZeroInitializationFixit);
6063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006064
Sebastian Redld201edf2011-06-05 13:59:11 +00006065 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006066 // If the declaration is a non-dependent, incomplete array type
6067 // that has an initializer, then its type will be completed once
6068 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00006069 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00006070 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00006071 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006072 if (const IncompleteArrayType *ArrayT
6073 = S.Context.getAsIncompleteArrayType(DeclType)) {
6074 // FIXME: We don't currently have the ability to accurately
6075 // compute the length of an initializer list without
6076 // performing full type-checking of the initializer list
6077 // (since we have to determine where braces are implicitly
6078 // introduced and such). So, we fall back to making the array
6079 // type a dependently-sized array type with no specified
6080 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006081 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00006082 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00006083
Douglas Gregor51e77d52009-12-10 17:56:55 +00006084 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00006085 if (DeclaratorDecl *DD = Entity.getDecl()) {
6086 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6087 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00006088 if (IncompleteArrayTypeLoc ArrayLoc =
6089 TL.getAs<IncompleteArrayTypeLoc>())
6090 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00006091 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00006092 }
6093
6094 *ResultType
6095 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006096 /*NumElts=*/nullptr,
Douglas Gregor51e77d52009-12-10 17:56:55 +00006097 ArrayT->getSizeModifier(),
6098 ArrayT->getIndexTypeCVRQualifiers(),
6099 Brackets);
6100 }
6101
6102 }
6103 }
Sebastian Redla9351792012-02-11 23:51:47 +00006104 if (Kind.getKind() == InitializationKind::IK_Direct &&
6105 !Kind.isExplicitCast()) {
6106 // Rebuild the ParenListExpr.
6107 SourceRange ParenRange = Kind.getParenRange();
6108 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006109 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00006110 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00006111 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00006112 Kind.isExplicitCast() ||
6113 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006114 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006115 }
6116
Sebastian Redld201edf2011-06-05 13:59:11 +00006117 // No steps means no initialization.
6118 if (Steps.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006119 return ExprResult((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006120
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006121 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006122 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006123 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00006124 // Produce a C++98 compatibility warning if we are initializing a reference
6125 // from an initializer list. For parameters, we produce a better warning
6126 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006127 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00006128 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6129 << Init->getSourceRange();
6130 }
6131
Richard Smitheb3cad52012-06-04 22:27:30 +00006132 // Diagnose cases where we initialize a pointer to an array temporary, and the
6133 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006134 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00006135 Entity.getType()->isPointerType() &&
6136 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006137 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00006138 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6139 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6140 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6141 << Init->getSourceRange();
6142 }
6143
Douglas Gregor1b303932009-12-22 15:35:07 +00006144 QualType DestType = Entity.getType().getNonReferenceType();
6145 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00006146 // the same as Entity.getDecl()->getType() in cases involving type merging,
6147 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00006148 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00006149 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00006150 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006151
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006152 ExprResult CurInit((Expr *)nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006153
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00006155 // grab the only argument out the Args and place it into the "current"
6156 // initializer.
6157 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00006158 case SK_ResolveAddressOfOverloadedFunction:
6159 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006160 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006161 case SK_CastDerivedToBaseLValue:
6162 case SK_BindReference:
6163 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006164 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00006165 case SK_UserConversion:
6166 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006167 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006168 case SK_QualificationConversionRValue:
Richard Smith77be48a2014-07-31 06:31:19 +00006169 case SK_AtomicConversion:
Jordan Roseb1312a52013-04-11 00:58:58 +00006170 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00006171 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00006172 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00006173 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00006174 case SK_UnwrapInitList:
6175 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00006176 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00006177 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00006178 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00006179 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00006180 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00006181 case SK_PassByIndirectCopyRestore:
6182 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00006183 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006184 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00006185 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006186 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00006187 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006188 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00006189 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00006190 break;
John McCall34376a62010-12-04 03:47:34 +00006191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006192
Douglas Gregore1314a62009-12-18 05:02:21 +00006193 case SK_ConstructorInitialization:
Richard Smith53324112014-07-16 21:33:43 +00006194 case SK_ConstructorInitializationFromList:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006195 case SK_StdInitializerListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00006196 case SK_ZeroInitialization:
6197 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006199
6200 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006201 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006202 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006203 for (step_iterator Step = step_begin(), StepEnd = step_end();
6204 Step != StepEnd; ++Step) {
6205 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006206 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006207
John Wiegley01296292011-04-08 18:41:53 +00006208 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006209
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006210 switch (Step->Kind) {
6211 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006212 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006213 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00006214 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00006215 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6216 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006217 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00006218 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00006219 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006220 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006221
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006222 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006223 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006224 case SK_CastDerivedToBaseLValue: {
6225 // We have a derived-to-base cast that produces either an rvalue or an
6226 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006227
John McCallcf142162010-08-07 06:22:56 +00006228 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00006229
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006230 // Casts to inaccessible base classes are allowed with C-style casts.
6231 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6232 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00006233 CurInit.get()->getLocStart(),
6234 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00006235 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00006236 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006237
John McCall2536c6d2010-08-25 10:28:54 +00006238 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006239 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006240 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006241 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006242 VK_XValue :
6243 VK_RValue);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006244 CurInit =
6245 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6246 CurInit.get(), &BasePath, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006247 break;
6248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006250 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00006251 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
6252 if (CurInit.get()->refersToBitField()) {
6253 // We don't necessarily have an unambiguous source bit-field.
6254 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006255 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00006256 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00006257 << (BitField ? BitField->getDeclName() : DeclarationName())
Craig Topperc3ec1492014-05-26 06:22:03 +00006258 << (BitField != nullptr)
John Wiegley01296292011-04-08 18:41:53 +00006259 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00006260 if (BitField)
6261 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
6262
John McCallfaf5fb42010-08-26 23:41:50 +00006263 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006264 }
Anders Carlssona91be642010-01-29 02:47:33 +00006265
John Wiegley01296292011-04-08 18:41:53 +00006266 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00006267 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006268 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
6269 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00006270 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006271 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006272 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006275 // Reference binding does not have any corresponding ASTs.
6276
6277 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006278 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006279 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006280
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006281 // Even though we didn't materialize a temporary, the binding may still
6282 // extend the lifetime of a temporary. This happens if we bind a reference
6283 // to the result of a cast to reference type.
David Majnemerdaff3702014-05-01 17:50:17 +00006284 if (const InitializedEntity *ExtendingEntity =
6285 getEntityForTemporaryLifetimeExtension(&Entity))
6286 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6287 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6288 /*IsInitializerList=*/false,
6289 ExtendingEntity->getDecl());
Richard Smith6b6f8aa2013-06-15 00:30:29 +00006290
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006291 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00006292
Richard Smithe6c01442013-06-05 00:46:14 +00006293 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00006294 // Make sure the "temporary" is actually an rvalue.
6295 assert(CurInit.get()->isRValue() && "not a temporary");
6296
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006297 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00006298 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00006299 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006300
Douglas Gregorfe314812011-06-21 17:03:29 +00006301 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00006302 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00006303 Entity.getType().getNonReferenceType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006304 Entity.getType()->isLValueReferenceType());
6305
6306 // Maybe lifetime-extend the temporary's subobjects to match the
6307 // entity's lifetime.
6308 if (const InitializedEntity *ExtendingEntity =
6309 getEntityForTemporaryLifetimeExtension(&Entity))
6310 if (performReferenceExtension(MTE, ExtendingEntity))
6311 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
6312 ExtendingEntity->getDecl());
Douglas Gregor58df5092011-06-22 16:12:01 +00006313
6314 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00006315 // need cleanups. Likewise if we're extending this temporary to automatic
6316 // storage duration -- we need to register its cleanup during the
6317 // full-expression's cleanups.
6318 if ((S.getLangOpts().ObjCAutoRefCount &&
6319 MTE->getType()->isObjCLifetimeType()) ||
6320 (MTE->getStorageDuration() == SD_Automatic &&
6321 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00006322 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00006323
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006324 CurInit = MTE;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006325 break;
Richard Smithe6c01442013-06-05 00:46:14 +00006326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006328 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006329 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006330 /*IsExtraneousCopy=*/true);
6331 break;
6332
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006333 case SK_UserConversion: {
6334 // We have a user-defined conversion that invokes either a constructor
6335 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00006336 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00006337 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00006338 FunctionDecl *Fn = Step->Function.Function;
6339 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006340 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00006341 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00006342 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006343 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00006344 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00006345 SourceLocation Loc = CurInit.get()->getLocStart();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006346 CurInit.get(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00006347
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006348 // Determine the arguments required to actually perform the constructor
6349 // call.
John Wiegley01296292011-04-08 18:41:53 +00006350 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006351 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00006352 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006353 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00006354 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006355
Richard Smithb24f0672012-02-11 19:22:50 +00006356 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006357 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006358 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006359 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00006360 /*ListInit*/ false,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006361 /*StdInitListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00006362 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00006363 CXXConstructExpr::CK_Complete,
6364 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006365 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006366 return ExprError();
John McCall760af172010-02-01 03:16:54 +00006367
Anders Carlssona01874b2010-04-21 18:47:17 +00006368 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00006369 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00006370 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6371 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372
John McCalle3027922010-08-25 11:45:40 +00006373 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00006374 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6375 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6376 S.IsDerivedFrom(SourceType, Class))
6377 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378
Douglas Gregor95562572010-04-24 23:45:46 +00006379 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006380 } else {
6381 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00006382 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Craig Topperc3ec1492014-05-26 06:22:03 +00006383 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
John McCalla0296f72010-03-19 07:35:19 +00006384 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00006385 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6386 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006387
6388 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006389 // derived-to-base conversion? I believe the answer is "no", because
6390 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00006391 ExprResult CurInitExprRes =
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006392 S.PerformObjectArgumentInitialization(CurInit.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006393 /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006394 FoundFn, Conversion);
6395 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006396 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006397 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006398
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006399 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006400 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6401 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006402 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00006403 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404
John McCalle3027922010-08-25 11:45:40 +00006405 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006406
Alp Toker314cc812014-01-25 16:55:45 +00006407 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409
Sebastian Redl112aa822011-07-14 19:07:55 +00006410 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006411 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6412
6413 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00006414 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00006415 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006416 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00006417 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00006418 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00006419 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00006420 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00006421 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6422 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00006423 }
6424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006425
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006426 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6427 CastKind, CurInit.get(), nullptr,
6428 CurInit.get()->getValueKind());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00006429 if (MaybeBindToTemp)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006430 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006431 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006432 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006433 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006434 break;
6435 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006436
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006437 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006438 case SK_QualificationConversionXValue:
6439 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006440 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00006441 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006442 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006443 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006444 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00006445 VK_XValue :
6446 VK_RValue);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006447 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006448 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006449 }
6450
Richard Smith77be48a2014-07-31 06:31:19 +00006451 case SK_AtomicConversion: {
6452 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6453 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6454 CK_NonAtomicToAtomic, VK_RValue);
6455 break;
6456 }
6457
Jordan Roseb1312a52013-04-11 00:58:58 +00006458 case SK_LValueToRValue: {
6459 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006460 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6461 CK_LValueToRValue, CurInit.get(),
6462 /*BasePath=*/nullptr, VK_RValue);
Jordan Roseb1312a52013-04-11 00:58:58 +00006463 break;
6464 }
6465
Richard Smithaaa0ec42013-09-21 21:19:19 +00006466 case SK_ConversionSequence:
6467 case SK_ConversionSequenceNoNarrowing: {
6468 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00006469 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6470 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00006471 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00006472 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00006473 ExprResult CurInitExprRes =
6474 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00006475 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00006476 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006477 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006478 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00006479
6480 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6481 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6482 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6483 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006484 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00006485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006486
Douglas Gregor51e77d52009-12-10 17:56:55 +00006487 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00006488 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006489 // If we're not initializing the top-level entity, we need to create an
6490 // InitializeTemporary entity for our target type.
6491 QualType Ty = Step->Type;
6492 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00006493 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00006494 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6495 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00006496 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006497 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00006498 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00006499
Richard Smithcc1b96d2013-06-12 22:31:48 +00006500 // Hack: We must update *ResultType if available in order to set the
6501 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6502 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6503 if (ResultType &&
6504 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00006505 if ((*ResultType)->isRValueReferenceType())
6506 Ty = S.Context.getRValueReferenceType(Ty);
6507 else if ((*ResultType)->isLValueReferenceType())
6508 Ty = S.Context.getLValueReferenceType(Ty,
6509 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6510 *ResultType = Ty;
6511 }
6512
6513 InitListExpr *StructuredInitList =
6514 PerformInitList.getFullyStructuredList();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006515 CurInit.get();
Richard Smithd712d0d2013-02-02 01:13:06 +00006516 CurInit = shouldBindAsTemporary(InitEntity)
6517 ? S.MaybeBindToTemporary(StructuredInitList)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006518 : StructuredInitList;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006519 break;
6520 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006521
Richard Smith53324112014-07-16 21:33:43 +00006522 case SK_ConstructorInitializationFromList: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006523 // When an initializer list is passed for a parameter of type "reference
6524 // to object", we don't get an EK_Temporary entity, but instead an
6525 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006526 // FIXME: This is a hack. What we really should do is create a user
6527 // conversion step for this case, but this makes it considerably more
6528 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006529 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6530 Entity.getType().getNonReferenceType());
6531 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006532 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006533 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006534 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6535 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006536 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006537 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6538 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006539 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006540 ConstructorInitRequiresZeroInit,
Richard Smith53324112014-07-16 21:33:43 +00006541 /*IsListInitialization*/true,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006542 /*IsStdInitListInit*/false,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006543 InitList->getLBraceLoc(),
6544 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006545 break;
6546 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006547
Sebastian Redl29526f02011-11-27 16:50:07 +00006548 case SK_UnwrapInitList:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006549 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
Sebastian Redl29526f02011-11-27 16:50:07 +00006550 break;
6551
6552 case SK_RewrapInitList: {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006553 Expr *E = CurInit.get();
Sebastian Redl29526f02011-11-27 16:50:07 +00006554 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6555 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006556 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006557 ILE->setSyntacticForm(Syntactic);
6558 ILE->setType(E->getType());
6559 ILE->setValueKind(E->getValueKind());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006560 CurInit = ILE;
Sebastian Redl29526f02011-11-27 16:50:07 +00006561 break;
6562 }
6563
Richard Smith53324112014-07-16 21:33:43 +00006564 case SK_ConstructorInitialization:
Richard Smithf8adcdc2014-07-17 05:12:35 +00006565 case SK_StdInitializerListConstructorCall: {
Sebastian Redl99f66162012-02-19 12:27:56 +00006566 // When an initializer list is passed for a parameter of type "reference
6567 // to object", we don't get an EK_Temporary entity, but instead an
6568 // EK_Parameter entity with reference type.
6569 // FIXME: This is a hack. What we really should do is create a user
6570 // conversion step for this case, but this makes it considerably more
6571 // complicated. For now, this will do.
6572 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6573 Entity.getType().getNonReferenceType());
6574 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf8adcdc2014-07-17 05:12:35 +00006575 bool IsStdInitListInit =
6576 Step->Kind == SK_StdInitializerListConstructorCall;
Richard Smith53324112014-07-16 21:33:43 +00006577 CurInit = PerformConstructorInitialization(
6578 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6579 ConstructorInitRequiresZeroInit,
Richard Smithf8adcdc2014-07-17 05:12:35 +00006580 /*IsListInitialization*/IsStdInitListInit,
6581 /*IsStdInitListInitialization*/IsStdInitListInit,
Richard Smith53324112014-07-16 21:33:43 +00006582 /*LBraceLoc*/SourceLocation(),
6583 /*RBraceLoc*/SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006584 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006586
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006587 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006588 step_iterator NextStep = Step;
6589 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006590 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006591 (NextStep->Kind == SK_ConstructorInitialization ||
Richard Smith53324112014-07-16 21:33:43 +00006592 NextStep->Kind == SK_ConstructorInitializationFromList)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006593 // The need for zero-initialization is recorded directly into
6594 // the call to the object's constructor within the next step.
6595 ConstructorInitRequiresZeroInit = true;
6596 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006597 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006598 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006599 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6600 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006602 Kind.getRange().getBegin());
6603
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006604 CurInit = new (S.Context) CXXScalarValueInitExpr(
6605 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6606 Kind.getRange().getEnd());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006607 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006608 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006609 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006610 break;
6611 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006612
6613 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006614 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006615 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006616 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006617 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6618 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006619 if (Result.isInvalid())
6620 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006621 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006622
6623 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006624 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006625 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006626 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006627 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006628 == Sema::Compatible)
6629 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006630 if (CurInitExprRes.isInvalid())
6631 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006632 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006633
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006634 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006635 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6636 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006637 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006638 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006639 &Complained)) {
6640 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006641 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006642 } else if (Complained)
6643 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006644 break;
6645 }
Eli Friedman78275202009-12-19 08:11:05 +00006646
6647 case SK_StringInit: {
6648 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006649 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006650 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006651 break;
6652 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006653
6654 case SK_ObjCObjectConversion:
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006655 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006656 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006657 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006658 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006659
6660 case SK_ArrayInit:
6661 // Okay: we checked everything before creating this step. Note that
6662 // this is a GNU extension.
6663 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006664 << Step->Type << CurInit.get()->getType()
6665 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006666
6667 // If the destination type is an incomplete array type, update the
6668 // type accordingly.
6669 if (ResultType) {
6670 if (const IncompleteArrayType *IncompleteDest
6671 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6672 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006673 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006674 *ResultType = S.Context.getConstantArrayType(
6675 IncompleteDest->getElementType(),
6676 ConstantSource->getSize(),
6677 ArrayType::Normal, 0);
6678 }
6679 }
6680 }
John McCall31168b02011-06-15 23:02:42 +00006681 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006682
Richard Smithebeed412012-02-15 22:38:09 +00006683 case SK_ParenthesizedArrayInit:
6684 // Okay: we checked everything before creating this step. Note that
6685 // this is a GNU extension.
6686 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6687 << CurInit.get()->getSourceRange();
6688 break;
6689
John McCall31168b02011-06-15 23:02:42 +00006690 case SK_PassByIndirectCopyRestore:
6691 case SK_PassByIndirectRestore:
6692 checkIndirectCopyRestoreSource(S, CurInit.get());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006693 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6694 CurInit.get(), Step->Type,
6695 Step->Kind == SK_PassByIndirectCopyRestore);
John McCall31168b02011-06-15 23:02:42 +00006696 break;
6697
6698 case SK_ProduceObjCObject:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006699 CurInit =
6700 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6701 CurInit.get(), nullptr, VK_RValue);
Douglas Gregore2f943b2011-02-22 18:29:51 +00006702 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006703
6704 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006705 S.Diag(CurInit.get()->getExprLoc(),
6706 diag::warn_cxx98_compat_initializer_list_init)
6707 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006708
Richard Smithcc1b96d2013-06-12 22:31:48 +00006709 // Materialize the temporary into memory.
6710 MaterializeTemporaryExpr *MTE = new (S.Context)
6711 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
David Majnemerdaff3702014-05-01 17:50:17 +00006712 /*BoundToLvalueReference=*/false);
6713
6714 // Maybe lifetime-extend the array temporary's subobjects to match the
6715 // entity's lifetime.
6716 if (const InitializedEntity *ExtendingEntity =
6717 getEntityForTemporaryLifetimeExtension(&Entity))
6718 if (performReferenceExtension(MTE, ExtendingEntity))
6719 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6720 /*IsInitializerList=*/true,
6721 ExtendingEntity->getDecl());
Richard Smithcc1b96d2013-06-12 22:31:48 +00006722
6723 // Wrap it in a construction of a std::initializer_list<T>.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006724 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006725
6726 // Bind the result, in case the library has given initializer_list a
6727 // non-trivial destructor.
6728 if (shouldBindAsTemporary(Entity))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006729 CurInit = S.MaybeBindToTemporary(CurInit.get());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006730 break;
6731 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006732
Guy Benyei61054192013-02-07 10:55:47 +00006733 case SK_OCLSamplerInit: {
6734 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006735 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006736
6737 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006738
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006739 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006740 if (!SourceType->isSamplerT())
6741 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6742 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006743 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006744 llvm_unreachable("Invalid EntityKind!");
6745 }
6746
6747 break;
6748 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006749 case SK_OCLZeroEvent: {
6750 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006751 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006752
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006753 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006754 CK_ZeroToOCLEvent,
6755 CurInit.get()->getValueKind());
6756 break;
6757 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006758 }
6759 }
John McCall1f425642010-11-11 03:21:53 +00006760
6761 // Diagnose non-fatal problems with the completed initialization.
6762 if (Entity.getKind() == InitializedEntity::EK_Member &&
6763 cast<FieldDecl>(Entity.getDecl())->isBitField())
6764 S.CheckBitFieldInitialization(Kind.getLocation(),
6765 cast<FieldDecl>(Entity.getDecl()),
6766 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
Richard Trieuac3eca52015-04-29 01:52:17 +00006768 // Check for std::move on construction.
6769 if (const Expr *E = CurInit.get()) {
6770 CheckMoveOnConstruction(S, E,
6771 Entity.getKind() == InitializedEntity::EK_Result);
6772 }
6773
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006774 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006775}
6776
Richard Smith593f9932012-12-08 02:01:17 +00006777/// Somewhere within T there is an uninitialized reference subobject.
6778/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006779static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6780 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006781 if (T->isReferenceType()) {
6782 S.Diag(Loc, diag::err_reference_without_init)
6783 << T.getNonReferenceType();
6784 return true;
6785 }
6786
6787 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6788 if (!RD || !RD->hasUninitializedReferenceMember())
6789 return false;
6790
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006791 for (const auto *FI : RD->fields()) {
Richard Smith593f9932012-12-08 02:01:17 +00006792 if (FI->isUnnamedBitfield())
6793 continue;
6794
6795 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6796 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6797 return true;
6798 }
6799 }
6800
Aaron Ballman574705e2014-03-13 15:41:46 +00006801 for (const auto &BI : RD->bases()) {
6802 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
Richard Smith593f9932012-12-08 02:01:17 +00006803 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6804 return true;
6805 }
6806 }
6807
6808 return false;
6809}
6810
6811
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006812//===----------------------------------------------------------------------===//
6813// Diagnose initialization failures
6814//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006815
6816/// Emit notes associated with an initialization that failed due to a
6817/// "simple" conversion failure.
6818static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6819 Expr *op) {
6820 QualType destType = entity.getType();
6821 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6822 op->getType()->isObjCObjectPointerType()) {
6823
6824 // Emit a possible note about the conversion failing because the
6825 // operand is a message send with a related result type.
6826 S.EmitRelatedResultTypeNote(op);
6827
6828 // Emit a possible note about a return failing because we're
6829 // expecting a related result type.
6830 if (entity.getKind() == InitializedEntity::EK_Result)
6831 S.EmitRelatedResultTypeNoteForReturn(destType);
6832 }
6833}
6834
Richard Smith0449aaf2013-11-21 23:30:57 +00006835static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6836 InitListExpr *InitList) {
6837 QualType DestType = Entity.getType();
6838
6839 QualType E;
6840 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6841 QualType ArrayType = S.Context.getConstantArrayType(
6842 E.withConst(),
6843 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6844 InitList->getNumInits()),
6845 clang::ArrayType::Normal, 0);
6846 InitializedEntity HiddenArray =
6847 InitializedEntity::InitializeTemporary(ArrayType);
6848 return diagnoseListInit(S, HiddenArray, InitList);
6849 }
6850
Richard Smith8d082d12014-09-04 22:13:39 +00006851 if (DestType->isReferenceType()) {
6852 // A list-initialization failure for a reference means that we tried to
6853 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
6854 // inner initialization failed.
6855 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
6856 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
6857 SourceLocation Loc = InitList->getLocStart();
6858 if (auto *D = Entity.getDecl())
6859 Loc = D->getLocation();
6860 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
6861 return;
6862 }
6863
Richard Smith0449aaf2013-11-21 23:30:57 +00006864 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6865 /*VerifyOnly=*/false);
6866 assert(DiagnoseInitList.HadError() &&
6867 "Inconsistent init list check result.");
6868}
6869
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006870bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006871 const InitializedEntity &Entity,
6872 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006873 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006874 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006875 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876
Douglas Gregor1b303932009-12-22 15:35:07 +00006877 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006878 switch (Failure) {
6879 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006880 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006881 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006882 // Dig out the reference subobject which is uninitialized and diagnose it.
6883 // If this is value-initialization, this could be nested some way within
6884 // the target type.
6885 assert(Kind.getKind() == InitializationKind::IK_Value ||
6886 DestType->isReferenceType());
6887 bool Diagnosed =
6888 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6889 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6890 (void)Diagnosed;
6891 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006892 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006893 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006894 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006896 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006897 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006898 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006899 case FK_ArrayNeedsInitListOrStringLiteral:
6900 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6901 break;
6902 case FK_ArrayNeedsInitListOrWideStringLiteral:
6903 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6904 break;
6905 case FK_NarrowStringIntoWideCharArray:
6906 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6907 break;
6908 case FK_WideStringIntoCharArray:
6909 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6910 break;
6911 case FK_IncompatWideStringIntoWideChar:
6912 S.Diag(Kind.getLocation(),
6913 diag::err_array_init_incompat_wide_string_into_wchar);
6914 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006915 case FK_ArrayTypeMismatch:
6916 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006917 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006918 (Failure == FK_ArrayTypeMismatch
6919 ? diag::err_array_init_different_type
6920 : diag::err_array_init_non_constant_array))
6921 << DestType.getNonReferenceType()
6922 << Args[0]->getType()
6923 << Args[0]->getSourceRange();
6924 break;
6925
John McCalla59dc2f2012-01-05 00:13:19 +00006926 case FK_VariableLengthArrayHasInitializer:
6927 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6928 << Args[0]->getSourceRange();
6929 break;
6930
John McCall16df1e52010-03-30 21:47:33 +00006931 case FK_AddressOfOverloadFailed: {
6932 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006933 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006934 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006935 true,
6936 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006937 break;
John McCall16df1e52010-03-30 21:47:33 +00006938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006939
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006940 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006941 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006942 switch (FailedOverloadResult) {
6943 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006944 if (Failure == FK_UserConversionOverloadFailed)
6945 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6946 << Args[0]->getType() << DestType
6947 << Args[0]->getSourceRange();
6948 else
6949 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6950 << DestType << Args[0]->getType()
6951 << Args[0]->getSourceRange();
6952
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006953 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006954 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006955
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006956 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006957 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006958 DestType.getNonReferenceType(),
6959 diag::err_typecheck_nonviable_condition_incomplete,
6960 Args[0]->getType(), Args[0]->getSourceRange()))
6961 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6962 << Args[0]->getType() << Args[0]->getSourceRange()
6963 << DestType.getNonReferenceType();
6964
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006965 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006966 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006968 case OR_Deleted: {
6969 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6970 << Args[0]->getType() << DestType.getNonReferenceType()
6971 << Args[0]->getSourceRange();
6972 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006973 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006974 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6975 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006976 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006977 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006978 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006979 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006980 }
6981 break;
6982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006984 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006985 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006986 }
6987 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006989 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006990 if (isa<InitListExpr>(Args[0])) {
6991 S.Diag(Kind.getLocation(),
6992 diag::err_lvalue_reference_bind_to_initlist)
6993 << DestType.getNonReferenceType().isVolatileQualified()
6994 << DestType.getNonReferenceType()
6995 << Args[0]->getSourceRange();
6996 break;
6997 }
6998 // Intentional fallthrough
6999
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007000 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007001 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007002 Failure == FK_NonConstLValueReferenceBindingToTemporary
7003 ? diag::err_lvalue_reference_bind_to_temporary
7004 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00007005 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007006 << DestType.getNonReferenceType()
7007 << Args[0]->getType()
7008 << Args[0]->getSourceRange();
7009 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007011 case FK_RValueReferenceBindingToLValue:
7012 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00007013 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007014 << Args[0]->getSourceRange();
7015 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007016
Richard Trieuf956a492015-05-16 01:27:03 +00007017 case FK_ReferenceInitDropsQualifiers: {
7018 QualType SourceType = Args[0]->getType();
7019 QualType NonRefType = DestType.getNonReferenceType();
7020 Qualifiers DroppedQualifiers =
7021 SourceType.getQualifiers() - NonRefType.getQualifiers();
7022
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007023 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
Richard Trieuf956a492015-05-16 01:27:03 +00007024 << SourceType
7025 << NonRefType
7026 << DroppedQualifiers.getCVRQualifiers()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007027 << Args[0]->getSourceRange();
7028 break;
Richard Trieuf956a492015-05-16 01:27:03 +00007029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007031 case FK_ReferenceInitFailed:
7032 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7033 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00007034 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007035 << Args[0]->getType()
7036 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00007037 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007038 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039
Douglas Gregorb491ed32011-02-19 21:32:49 +00007040 case FK_ConversionFailed: {
7041 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00007042 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00007043 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007044 << DestType
John McCall086a4642010-11-24 05:12:34 +00007045 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00007046 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007047 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00007048 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7049 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00007050 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00007051 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007052 }
John Wiegley01296292011-04-08 18:41:53 +00007053
7054 case FK_ConversionFromPropertyFailed:
7055 // No-op. This error has already been reported.
7056 break;
7057
Douglas Gregor51e77d52009-12-10 17:56:55 +00007058 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00007059 SourceRange R;
7060
David Majnemerbd385442015-04-10 04:52:06 +00007061 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
7062 if (InitList && InitList->getNumInits() == 1)
7063 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007064 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007065 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00007066
Alp Tokerb6cc5922014-05-03 03:45:55 +00007067 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
Douglas Gregor8ec51732010-09-08 21:40:08 +00007068 if (Kind.isCStyleOrFunctionalCast())
7069 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7070 << R;
7071 else
7072 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7073 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00007074 break;
7075 }
7076
7077 case FK_ReferenceBindingToInitList:
7078 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7079 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7080 break;
7081
7082 case FK_InitListBadDestinationType:
7083 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7084 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7085 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007087 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007088 case FK_ConstructorOverloadFailed: {
7089 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007090 if (Args.size())
7091 ArgsRange = SourceRange(Args.front()->getLocStart(),
7092 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007094 if (Failure == FK_ListConstructorOverloadFailed) {
Nico Weber9709ebf2014-07-08 23:54:25 +00007095 assert(Args.size() == 1 &&
7096 "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007097 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007098 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00007099 }
7100
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007101 // FIXME: Using "DestType" for the entity we're printing is probably
7102 // bad.
7103 switch (FailedOverloadResult) {
7104 case OR_Ambiguous:
7105 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7106 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007107 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007110 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007111 if (Kind.getKind() == InitializationKind::IK_Default &&
7112 (Entity.getKind() == InitializedEntity::EK_Base ||
7113 Entity.getKind() == InitializedEntity::EK_Member) &&
7114 isa<CXXConstructorDecl>(S.CurContext)) {
7115 // This is implicit default initialization of a member or
7116 // base within a constructor. If no viable function was
7117 // found, notify the user that she needs to explicitly
7118 // initialize this base/member.
7119 CXXConstructorDecl *Constructor
7120 = cast<CXXConstructorDecl>(S.CurContext);
7121 if (Entity.getKind() == InitializedEntity::EK_Base) {
7122 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007123 << (Constructor->getInheritedConstructor() ? 2 :
7124 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007125 << S.Context.getTypeDeclType(Constructor->getParent())
7126 << /*base=*/0
7127 << Entity.getType();
7128
7129 RecordDecl *BaseDecl
7130 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7131 ->getDecl();
7132 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7133 << S.Context.getTagDeclType(BaseDecl);
7134 } else {
7135 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007136 << (Constructor->getInheritedConstructor() ? 2 :
7137 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007138 << S.Context.getTypeDeclType(Constructor->getParent())
7139 << /*member=*/1
7140 << Entity.getName();
Alp Toker2afa8782014-05-28 12:20:14 +00007141 S.Diag(Entity.getDecl()->getLocation(),
7142 diag::note_member_declared_at);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007143
7144 if (const RecordType *Record
7145 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007146 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007147 diag::note_previous_decl)
7148 << S.Context.getTagDeclType(Record->getDecl());
7149 }
7150 break;
7151 }
7152
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007153 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7154 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007155 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007156 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007157
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007158 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007159 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007160 OverloadingResult Ovl
7161 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00007162 if (Ovl != OR_Deleted) {
7163 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7164 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007165 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00007166 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007167 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00007168
7169 // If this is a defaulted or implicitly-declared function, then
7170 // it was implicitly deleted. Make it clear that the deletion was
7171 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00007172 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007173 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00007174 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00007175 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00007176 else
7177 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7178 << true << DestType << ArgsRange;
7179
7180 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007181 break;
7182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007184 case OR_Success:
7185 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007186 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00007187 }
David Blaikie60deeee2012-01-17 08:24:58 +00007188 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007189
Douglas Gregor85dabae2009-12-16 01:38:02 +00007190 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007191 if (Entity.getKind() == InitializedEntity::EK_Member &&
7192 isa<CXXConstructorDecl>(S.CurContext)) {
7193 // This is implicit default-initialization of a const member in
7194 // a constructor. Complain that it needs to be explicitly
7195 // initialized.
7196 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7197 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00007198 << (Constructor->getInheritedConstructor() ? 2 :
7199 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007200 << S.Context.getTypeDeclType(Constructor->getParent())
7201 << /*const=*/1
7202 << Entity.getName();
7203 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7204 << Entity.getName();
7205 } else {
7206 S.Diag(Kind.getLocation(), diag::err_default_init_const)
Nico Weber9386c822014-07-23 05:16:10 +00007207 << DestType << (bool)DestType->getAs<RecordType>();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007208 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00007209 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007210
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007211 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00007212 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007213 diag::err_init_incomplete_type);
7214 break;
7215
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007216 case FK_ListInitializationFailed: {
7217 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00007218 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7219 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007220 break;
7221 }
John McCall4124c492011-10-17 18:40:02 +00007222
7223 case FK_PlaceholderType: {
7224 // FIXME: Already diagnosed!
7225 break;
7226 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00007227
Sebastian Redl048a6d72012-04-01 19:54:59 +00007228 case FK_ExplicitConstructor: {
7229 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7230 << Args[0]->getSourceRange();
7231 OverloadCandidateSet::iterator Best;
7232 OverloadingResult Ovl
7233 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00007234 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00007235 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7236 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
7237 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
7238 break;
7239 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007241
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007242 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007243 return true;
7244}
Douglas Gregore1314a62009-12-18 05:02:21 +00007245
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007246void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007247 switch (SequenceKind) {
7248 case FailedSequence: {
7249 OS << "Failed sequence: ";
7250 switch (Failure) {
7251 case FK_TooManyInitsForReference:
7252 OS << "too many initializers for reference";
7253 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007254
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007255 case FK_ArrayNeedsInitList:
7256 OS << "array requires initializer list";
7257 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007258
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007259 case FK_ArrayNeedsInitListOrStringLiteral:
7260 OS << "array requires initializer list or string literal";
7261 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007262
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00007263 case FK_ArrayNeedsInitListOrWideStringLiteral:
7264 OS << "array requires initializer list or wide string literal";
7265 break;
7266
7267 case FK_NarrowStringIntoWideCharArray:
7268 OS << "narrow string into wide char array";
7269 break;
7270
7271 case FK_WideStringIntoCharArray:
7272 OS << "wide string into char array";
7273 break;
7274
7275 case FK_IncompatWideStringIntoWideChar:
7276 OS << "incompatible wide string into wide char array";
7277 break;
7278
Douglas Gregore2f943b2011-02-22 18:29:51 +00007279 case FK_ArrayTypeMismatch:
7280 OS << "array type mismatch";
7281 break;
7282
7283 case FK_NonConstantArrayInit:
7284 OS << "non-constant array initializer";
7285 break;
7286
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007287 case FK_AddressOfOverloadFailed:
7288 OS << "address of overloaded function failed";
7289 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007291 case FK_ReferenceInitOverloadFailed:
7292 OS << "overload resolution for reference initialization failed";
7293 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007294
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007295 case FK_NonConstLValueReferenceBindingToTemporary:
7296 OS << "non-const lvalue reference bound to temporary";
7297 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007298
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007299 case FK_NonConstLValueReferenceBindingToUnrelated:
7300 OS << "non-const lvalue reference bound to unrelated type";
7301 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007302
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007303 case FK_RValueReferenceBindingToLValue:
7304 OS << "rvalue reference bound to an lvalue";
7305 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007306
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007307 case FK_ReferenceInitDropsQualifiers:
7308 OS << "reference initialization drops qualifiers";
7309 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007310
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007311 case FK_ReferenceInitFailed:
7312 OS << "reference initialization failed";
7313 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007314
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007315 case FK_ConversionFailed:
7316 OS << "conversion failed";
7317 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007318
John Wiegley01296292011-04-08 18:41:53 +00007319 case FK_ConversionFromPropertyFailed:
7320 OS << "conversion from property failed";
7321 break;
7322
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007323 case FK_TooManyInitsForScalar:
7324 OS << "too many initializers for scalar";
7325 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007326
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007327 case FK_ReferenceBindingToInitList:
7328 OS << "referencing binding to initializer list";
7329 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007330
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007331 case FK_InitListBadDestinationType:
7332 OS << "initializer list for non-aggregate, non-scalar type";
7333 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007334
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007335 case FK_UserConversionOverloadFailed:
7336 OS << "overloading failed for user-defined conversion";
7337 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007338
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007339 case FK_ConstructorOverloadFailed:
7340 OS << "constructor overloading failed";
7341 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007343 case FK_DefaultInitOfConst:
7344 OS << "default initialization of a const variable";
7345 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007346
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00007347 case FK_Incomplete:
7348 OS << "initialization of incomplete type";
7349 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007350
7351 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00007352 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00007353 break;
7354
John McCalla59dc2f2012-01-05 00:13:19 +00007355 case FK_VariableLengthArrayHasInitializer:
7356 OS << "variable length array has an initializer";
7357 break;
7358
John McCall4124c492011-10-17 18:40:02 +00007359 case FK_PlaceholderType:
7360 OS << "initializer expression isn't contextually valid";
7361 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00007362
7363 case FK_ListConstructorOverloadFailed:
7364 OS << "list constructor overloading failed";
7365 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007366
Sebastian Redl048a6d72012-04-01 19:54:59 +00007367 case FK_ExplicitConstructor:
7368 OS << "list copy initialization chose explicit constructor";
7369 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007371 OS << '\n';
7372 return;
7373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007374
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007375 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00007376 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007377 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007378
Sebastian Redld201edf2011-06-05 13:59:11 +00007379 case NormalSequence:
7380 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007381 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007383
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007384 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
7385 if (S != step_begin()) {
7386 OS << " -> ";
7387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007388
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007389 switch (S->Kind) {
7390 case SK_ResolveAddressOfOverloadedFunction:
7391 OS << "resolve address of overloaded function";
7392 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007393
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007394 case SK_CastDerivedToBaseRValue:
7395 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007397
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007398 case SK_CastDerivedToBaseXValue:
7399 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7400 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007401
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007402 case SK_CastDerivedToBaseLValue:
7403 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7404 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007405
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007406 case SK_BindReference:
7407 OS << "bind reference to lvalue";
7408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007410 case SK_BindReferenceToTemporary:
7411 OS << "bind reference to a temporary";
7412 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007413
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00007414 case SK_ExtraneousCopyToTemporary:
7415 OS << "extraneous C++03 copy to temporary";
7416 break;
7417
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007418 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007419 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007420 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007421
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007422 case SK_QualificationConversionRValue:
7423 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007424 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007425
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007426 case SK_QualificationConversionXValue:
7427 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00007428 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007429
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007430 case SK_QualificationConversionLValue:
7431 OS << "qualification conversion (lvalue)";
7432 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007433
Richard Smith77be48a2014-07-31 06:31:19 +00007434 case SK_AtomicConversion:
7435 OS << "non-atomic-to-atomic conversion";
7436 break;
7437
Jordan Roseb1312a52013-04-11 00:58:58 +00007438 case SK_LValueToRValue:
7439 OS << "load (lvalue to rvalue)";
7440 break;
7441
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007442 case SK_ConversionSequence:
7443 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007444 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007445 OS << ")";
7446 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007447
Richard Smithaaa0ec42013-09-21 21:19:19 +00007448 case SK_ConversionSequenceNoNarrowing:
7449 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00007450 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00007451 OS << ")";
7452 break;
7453
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007454 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00007455 OS << "list aggregate initialization";
7456 break;
7457
Sebastian Redl29526f02011-11-27 16:50:07 +00007458 case SK_UnwrapInitList:
7459 OS << "unwrap reference initializer list";
7460 break;
7461
7462 case SK_RewrapInitList:
7463 OS << "rewrap reference initializer list";
7464 break;
7465
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007466 case SK_ConstructorInitialization:
7467 OS << "constructor initialization";
7468 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007469
Richard Smith53324112014-07-16 21:33:43 +00007470 case SK_ConstructorInitializationFromList:
7471 OS << "list initialization via constructor";
7472 break;
7473
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007474 case SK_ZeroInitialization:
7475 OS << "zero initialization";
7476 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007478 case SK_CAssignment:
7479 OS << "C assignment";
7480 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007481
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007482 case SK_StringInit:
7483 OS << "string initialization";
7484 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007485
7486 case SK_ObjCObjectConversion:
7487 OS << "Objective-C object conversion";
7488 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00007489
7490 case SK_ArrayInit:
7491 OS << "array initialization";
7492 break;
John McCall31168b02011-06-15 23:02:42 +00007493
Richard Smithebeed412012-02-15 22:38:09 +00007494 case SK_ParenthesizedArrayInit:
7495 OS << "parenthesized array initialization";
7496 break;
7497
John McCall31168b02011-06-15 23:02:42 +00007498 case SK_PassByIndirectCopyRestore:
7499 OS << "pass by indirect copy and restore";
7500 break;
7501
7502 case SK_PassByIndirectRestore:
7503 OS << "pass by indirect restore";
7504 break;
7505
7506 case SK_ProduceObjCObject:
7507 OS << "Objective-C object retension";
7508 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00007509
7510 case SK_StdInitializerList:
7511 OS << "std::initializer_list from initializer list";
7512 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007513
Richard Smithf8adcdc2014-07-17 05:12:35 +00007514 case SK_StdInitializerListConstructorCall:
7515 OS << "list initialization from std::initializer_list";
7516 break;
7517
Guy Benyei61054192013-02-07 10:55:47 +00007518 case SK_OCLSamplerInit:
7519 OS << "OpenCL sampler_t from integer constant";
7520 break;
7521
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007522 case SK_OCLZeroEvent:
7523 OS << "OpenCL event_t from zero";
7524 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007525 }
Richard Smith6b216962013-02-05 05:52:24 +00007526
7527 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007528 }
Richard Smith6b216962013-02-05 05:52:24 +00007529
7530 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00007531}
7532
7533void InitializationSequence::dump() const {
7534 dump(llvm::errs());
7535}
7536
Richard Smithaaa0ec42013-09-21 21:19:19 +00007537static void DiagnoseNarrowingInInitList(Sema &S,
7538 const ImplicitConversionSequence &ICS,
7539 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007540 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00007541 const Expr *PostInit) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007542 const StandardConversionSequence *SCS = nullptr;
Richard Smith66e05fe2012-01-18 05:21:49 +00007543 switch (ICS.getKind()) {
7544 case ImplicitConversionSequence::StandardConversion:
7545 SCS = &ICS.Standard;
7546 break;
7547 case ImplicitConversionSequence::UserDefinedConversion:
7548 SCS = &ICS.UserDefined.After;
7549 break;
7550 case ImplicitConversionSequence::AmbiguousConversion:
7551 case ImplicitConversionSequence::EllipsisConversion:
7552 case ImplicitConversionSequence::BadConversion:
7553 return;
7554 }
7555
Richard Smith66e05fe2012-01-18 05:21:49 +00007556 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7557 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007558 QualType ConstantType;
7559 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7560 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007561 case NK_Not_Narrowing:
7562 // No narrowing occurred.
7563 return;
7564
7565 case NK_Type_Narrowing:
7566 // This was a floating-to-integer conversion, which is always considered a
7567 // narrowing conversion even if the value is a constant and can be
7568 // represented exactly as an integer.
7569 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007570 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7571 ? diag::warn_init_list_type_narrowing
7572 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007573 << PostInit->getSourceRange()
7574 << PreNarrowingType.getLocalUnqualifiedType()
7575 << EntityType.getLocalUnqualifiedType();
7576 break;
7577
7578 case NK_Constant_Narrowing:
7579 // A constant value was narrowed.
7580 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007581 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7582 ? diag::warn_init_list_constant_narrowing
7583 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007584 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007585 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007586 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007587 break;
7588
7589 case NK_Variable_Narrowing:
7590 // A variable's value may have been narrowed.
7591 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007592 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7593 ? diag::warn_init_list_variable_narrowing
7594 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007595 << PostInit->getSourceRange()
7596 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007597 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007598 break;
7599 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007600
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007601 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007602 llvm::raw_svector_ostream OS(StaticCast);
7603 OS << "static_cast<";
7604 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7605 // It's important to use the typedef's name if there is one so that the
7606 // fixit doesn't break code using types like int64_t.
7607 //
7608 // FIXME: This will break if the typedef requires qualification. But
7609 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007610 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007611 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007612 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007613 else {
7614 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7615 // with a broken cast.
7616 return;
7617 }
7618 OS << ">(";
Alp Tokerb0869032014-05-17 01:13:18 +00007619 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007620 << PostInit->getSourceRange()
7621 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7622 << FixItHint::CreateInsertion(
7623 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007624}
7625
Douglas Gregore1314a62009-12-18 05:02:21 +00007626//===----------------------------------------------------------------------===//
7627// Initialization helper functions
7628//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007629bool
7630Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7631 ExprResult Init) {
7632 if (Init.isInvalid())
7633 return false;
7634
7635 Expr *InitE = Init.get();
7636 assert(InitE && "No initialization expression");
7637
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007638 InitializationKind Kind
7639 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007640 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007641 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007642}
7643
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007645Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7646 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007647 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007648 bool TopLevelOfInitList,
7649 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007650 if (Init.isInvalid())
7651 return ExprError();
7652
John McCall1f425642010-11-11 03:21:53 +00007653 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007654 assert(InitE && "No initialization expression?");
7655
7656 if (EqualLoc.isInvalid())
7657 EqualLoc = InitE->getLocStart();
7658
7659 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007660 EqualLoc,
7661 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007662 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007663
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007664 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007665
Richard Smith66e05fe2012-01-18 05:21:49 +00007666 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007667}