blob: 2728b26ef8dbdc1bb7b05f97917ccd8317e5490b [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
21#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);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +000073 if (SL == 0)
74 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.
152 uint64_t StrLength =
153 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
154
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(),
Eli Friedman554eba92011-04-11 00:23:45 +0000192 diag::warn_initializer_string_for_char_array_too_long)
193 << 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,
309 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000315
Douglas Gregor2bb07652009-12-22 00:05:34 +0000316 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
317 const InitializedEntity &ParentEntity,
318 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000319 void FillInValueInitializations(const InitializedEntity &Entity,
320 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000321 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
322 Expr *InitExpr, FieldDecl *Field,
323 bool TopLevelObject);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000324 void CheckValueInitializable(const InitializedEntity &Entity);
325
Douglas Gregor85df8d82009-01-29 00:45:39 +0000326public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000327 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smithde229232013-06-06 11:41:05 +0000328 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000329 bool HadError() { return hadError; }
330
331 // @brief Retrieves the fully-structured initializer list used for
332 // semantic analysis and code generation.
333 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
334};
Chris Lattner9ececce2009-02-24 22:48:58 +0000335} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000336
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000337void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
338 assert(VerifyOnly &&
339 "CheckValueInitializable is only inteded for verification mode.");
340
341 SourceLocation Loc;
342 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
343 true);
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000344 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +0000345 if (InitSeq.Failed())
346 hadError = true;
347}
348
Douglas Gregor2bb07652009-12-22 00:05:34 +0000349void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
350 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000351 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000352 bool &RequiresSecondPass) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000353 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000354 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000356 = InitializedEntity::InitializeMember(Field, &ParentEntity);
357 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smith852c9db2013-04-20 22:23:05 +0000358 // If there's no explicit initializer but we have a default initializer, use
359 // that. This only happens in C++1y, since classes with default
360 // initializers are not aggregates in C++11.
361 if (Field->hasInClassInitializer()) {
362 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
363 ILE->getRBraceLoc(), Field);
364 if (Init < NumInits)
365 ILE->setInit(Init, DIE);
366 else {
367 ILE->updateInit(SemaRef.Context, Init, DIE);
368 RequiresSecondPass = true;
369 }
370 return;
371 }
372
Douglas Gregor2bb07652009-12-22 00:05:34 +0000373 // FIXME: We probably don't need to handle references
374 // specially here, since value-initialization of references is
375 // handled in InitializationSequence.
376 if (Field->getType()->isReferenceType()) {
377 // C++ [dcl.init.aggr]p9:
378 // If an incomplete or empty initializer-list leaves a
379 // member of reference type uninitialized, the program is
380 // ill-formed.
381 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
382 << Field->getType()
383 << ILE->getSyntacticForm()->getSourceRange();
384 SemaRef.Diag(Field->getLocation(),
385 diag::note_uninit_reference_member);
386 hadError = true;
387 return;
388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregor2bb07652009-12-22 00:05:34 +0000390 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
391 true);
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000392 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000393 if (!InitSeq) {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000394 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000395 hadError = true;
396 return;
397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398
John McCalldadc5752010-08-24 06:29:42 +0000399 ExprResult MemberInit
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000400 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000401 if (MemberInit.isInvalid()) {
402 hadError = true;
403 return;
404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405
Douglas Gregor2bb07652009-12-22 00:05:34 +0000406 if (hadError) {
407 // Do nothing
408 } else if (Init < NumInits) {
409 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000410 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000411 // Value-initialization requires a constructor call, so
412 // extend the initializer list to include the constructor
413 // call and make a note that we'll need to take another pass
414 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000415 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000416 RequiresSecondPass = true;
417 }
418 } else if (InitListExpr *InnerILE
419 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420 FillInValueInitializations(MemberEntity, InnerILE,
421 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000422}
423
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000424/// Recursively replaces NULL values within the given initializer list
425/// with expressions that perform value-initialization of the
426/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427void
Douglas Gregor723796a2009-12-16 06:35:08 +0000428InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
429 InitListExpr *ILE,
430 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000432 "Should not have void type");
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000433 SourceLocation Loc = ILE->getLocStart();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000434 if (ILE->getSyntacticForm())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000435 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000436
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000437 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smith852c9db2013-04-20 22:23:05 +0000438 const RecordDecl *RDecl = RType->getDecl();
439 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000440 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
441 Entity, ILE, RequiresSecondPass);
Richard Smith852c9db2013-04-20 22:23:05 +0000442 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
443 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
444 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
445 FieldEnd = RDecl->field_end();
446 Field != FieldEnd; ++Field) {
447 if (Field->hasInClassInitializer()) {
448 FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
449 break;
450 }
451 }
452 } else {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000453 unsigned Init = 0;
Richard Smith852c9db2013-04-20 22:23:05 +0000454 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
455 FieldEnd = RDecl->field_end();
Douglas Gregor2bb07652009-12-22 00:05:34 +0000456 Field != FieldEnd; ++Field) {
457 if (Field->isUnnamedBitfield())
458 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000459
Douglas Gregor2bb07652009-12-22 00:05:34 +0000460 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000461 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000462
David Blaikie40ed2972012-06-06 20:45:41 +0000463 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000464 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000465 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000466
Douglas Gregor2bb07652009-12-22 00:05:34 +0000467 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000468
Douglas Gregor2bb07652009-12-22 00:05:34 +0000469 // Only look at the first initialization of a union.
Richard Smith852c9db2013-04-20 22:23:05 +0000470 if (RDecl->isUnion())
Douglas Gregor2bb07652009-12-22 00:05:34 +0000471 break;
472 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000473 }
474
475 return;
Mike Stump11289f42009-09-09 15:08:12 +0000476 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000477
478 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000479
Douglas Gregor723796a2009-12-16 06:35:08 +0000480 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000481 unsigned NumInits = ILE->getNumInits();
482 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000483 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000484 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000485 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
486 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000487 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000488 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000489 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000490 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000491 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000493 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000494 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000495 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000496
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000498 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000499 if (hadError)
500 return;
501
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000502 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
503 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000504 ElementEntity.setElementIndex(Init);
505
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000506 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
507 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000508 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
509 true);
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000510 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregor723796a2009-12-16 06:35:08 +0000511 if (!InitSeq) {
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000512 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000513 hadError = true;
514 return;
515 }
516
John McCalldadc5752010-08-24 06:29:42 +0000517 ExprResult ElementInit
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000518 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregor723796a2009-12-16 06:35:08 +0000519 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000520 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000521 return;
522 }
523
524 if (hadError) {
525 // Do nothing
526 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000527 // For arrays, just set the expression used for value-initialization
528 // of the "holes" in the array.
529 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
530 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
531 else
532 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000533 } else {
534 // For arrays, just set the expression used for value-initialization
535 // of the rest of elements and exit.
536 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
537 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
538 return;
539 }
540
Sebastian Redld201edf2011-06-05 13:59:11 +0000541 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000542 // Value-initialization requires a constructor call, so
543 // extend the initializer list to include the constructor
544 // call and make a note that we'll need to take another pass
545 // through the initializer list.
546 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
547 RequiresSecondPass = true;
548 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000549 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000550 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +0000551 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregor723796a2009-12-16 06:35:08 +0000552 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000553 }
554}
555
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000556
Douglas Gregor723796a2009-12-16 06:35:08 +0000557InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000558 InitListExpr *IL, QualType &T,
Richard Smithde229232013-06-06 11:41:05 +0000559 bool VerifyOnly)
560 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000561 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000562
Richard Smith4e0d2e42013-09-20 20:10:22 +0000563 FullyStructuredList =
564 getStructuredSubobjectInit(IL, 0, T, 0, 0, IL->getSourceRange());
565 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000566 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000567
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000568 if (!hadError && !VerifyOnly) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000569 bool RequiresSecondPass = false;
570 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000571 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000573 RequiresSecondPass);
574 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000575}
576
577int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000578 // FIXME: use a proper constant
579 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000580 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000581 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000582 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
583 }
584 return maxElements;
585}
586
587int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000588 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000589 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000590 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000591 Field = structDecl->field_begin(),
592 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000593 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000594 if (!Field->isUnnamedBitfield())
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 ++InitializableMembers;
596 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000597 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000598 return std::min(InitializableMembers, 1);
599 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000600}
601
Richard Smith4e0d2e42013-09-20 20:10:22 +0000602/// Check whether the range of the initializer \p ParentIList from element
603/// \p Index onwards can be used to initialize an object of type \p T. Update
604/// \p Index to indicate how many elements of the list were consumed.
605///
606/// This also fills in \p StructuredList, from element \p StructuredIndex
607/// onwards, with the fully-braced, desugared form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000608void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000609 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 QualType T, unsigned &Index,
611 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000612 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000613 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000614
Steve Narofff8ecff22008-05-01 22:18:59 +0000615 if (T->isArrayType())
616 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000617 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000618 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000619 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000620 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000621 else
David Blaikie83d382b2011-09-23 05:06:16 +0000622 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000623
Eli Friedmane0f832b2008-05-25 13:49:22 +0000624 if (maxElements == 0) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000625 if (!VerifyOnly)
626 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
627 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000628 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000629 hadError = true;
630 return;
631 }
632
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000633 // Build a structured initializer list corresponding to this subobject.
634 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000635 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
636 StructuredIndex,
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000637 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregor5741efb2009-03-01 17:12:46 +0000638 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000639 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000640
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000641 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000642 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000643 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000644 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000645 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000646 StructuredSubobjectInitIndex);
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000647
Richard Smithde229232013-06-06 11:41:05 +0000648 if (!VerifyOnly) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000649 StructuredSubobjectInitList->setType(T);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000650
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000651 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000652 // Update the structured sub-object initializer so that it's ending
653 // range corresponds with the end of the last initializer it used.
654 if (EndIndex < ParentIList->getNumInits()) {
655 SourceLocation EndLoc
656 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
657 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659
Sebastian Redl8b6412a2011-10-16 18:19:28 +0000660 // Complain about missing braces.
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000661 if (T->isArrayType() || T->isRecordType()) {
662 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smithde229232013-06-06 11:41:05 +0000663 diag::warn_missing_braces)
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000664 << StructuredSubobjectInitList->getSourceRange()
665 << FixItHint::CreateInsertion(
666 StructuredSubobjectInitList->getLocStart(), "{")
667 << FixItHint::CreateInsertion(
668 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000670 "}");
671 }
Tanya Lattner5029d562010-03-07 04:17:15 +0000672 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000673}
674
Richard Smith4e0d2e42013-09-20 20:10:22 +0000675/// Check whether the initializer \p IList (that was written with explicit
676/// braces) can be used to initialize an object of type \p T.
677///
678/// This also fills in \p StructuredList with the fully-braced, desugared
679/// form of the initialization.
Anders Carlsson6cabf312010-01-23 23:23:01 +0000680void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000681 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000682 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000683 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000684 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000685 if (!VerifyOnly) {
686 SyntacticToSemantic[IList] = StructuredList;
687 StructuredList->setSyntacticForm(IList);
688 }
Richard Smith4e0d2e42013-09-20 20:10:22 +0000689
690 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000692 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000693 if (!VerifyOnly) {
Eli Friedman91f5ae52012-02-23 02:25:10 +0000694 QualType ExprTy = T;
695 if (!ExprTy->isArrayType())
696 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000697 IList->setType(ExprTy);
698 StructuredList->setType(ExprTy);
699 }
Eli Friedman85f54972008-05-25 13:22:35 +0000700 if (hadError)
701 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000702
Eli Friedman85f54972008-05-25 13:22:35 +0000703 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000704 // We have leftover initializers
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000705 if (VerifyOnly) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000706 if (SemaRef.getLangOpts().CPlusPlus ||
707 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000708 IList->getType()->isVectorType())) {
709 hadError = true;
710 }
711 return;
712 }
713
Eli Friedmanbd327452009-05-29 20:20:05 +0000714 if (StructuredIndex == 1 &&
Hans Wennborg950f3182013-05-16 09:22:40 +0000715 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
716 SIF_None) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000717 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000718 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000719 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000720 hadError = true;
721 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000722 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000723 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000724 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000725 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000726 // Don't complain for incomplete types, since we'll get an error
727 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000728 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000729 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000730 CurrentObjectType->isArrayType()? 0 :
731 CurrentObjectType->isVectorType()? 1 :
732 CurrentObjectType->isScalarType()? 2 :
733 CurrentObjectType->isUnionType()? 3 :
734 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000735
736 unsigned DK = diag::warn_excess_initializers;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000737 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanbd327452009-05-29 20:20:05 +0000738 DK = diag::err_excess_initializers;
739 hadError = true;
740 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman425038c2009-07-07 21:53:06 +0000742 DK = diag::err_excess_initializers;
743 hadError = true;
744 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000745
Chris Lattnerb0912a52009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000747 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000748 }
749 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000750
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000751 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
752 !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000753 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000754 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000755 << FixItHint::CreateRemoval(IList->getLocStart())
756 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000757}
758
Anders Carlsson6cabf312010-01-23 23:23:01 +0000759void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000760 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000761 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000762 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000763 unsigned &Index,
764 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000765 unsigned &StructuredIndex,
766 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000767 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
768 // Explicitly braced initializer for complex type can be real+imaginary
769 // parts.
770 CheckComplexType(Entity, IList, DeclType, Index,
771 StructuredList, StructuredIndex);
772 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000773 CheckScalarType(Entity, IList, DeclType, Index,
774 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000775 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000776 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000777 StructuredList, StructuredIndex);
Richard Smithe20c83d2012-07-07 08:35:56 +0000778 } else if (DeclType->isRecordType()) {
779 assert(DeclType->isAggregateType() &&
780 "non-aggregate records should be handed in CheckSubElementType");
781 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
782 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
783 SubobjectIsDesignatorContext, Index,
784 StructuredList, StructuredIndex,
785 TopLevelObject);
786 } else if (DeclType->isArrayType()) {
787 llvm::APSInt Zero(
788 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
789 false);
790 CheckArrayType(Entity, IList, DeclType, Zero,
791 SubobjectIsDesignatorContext, Index,
792 StructuredList, StructuredIndex);
Steve Naroffeaf58532008-08-10 16:05:48 +0000793 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
794 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000795 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000796 if (!VerifyOnly)
797 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
798 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000799 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000800 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000801 CheckReferenceType(Entity, IList, DeclType, Index,
802 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000803 } else if (DeclType->isObjCObjectType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000804 if (!VerifyOnly)
805 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
806 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000807 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000808 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000809 if (!VerifyOnly)
810 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
811 << DeclType;
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000812 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000813 }
814}
815
Anders Carlsson6cabf312010-01-23 23:23:01 +0000816void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000817 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000818 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000819 unsigned &Index,
820 InitListExpr *StructuredList,
821 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000822 Expr *expr = IList->getInit(Index);
Richard Smith72752e82013-05-31 02:56:17 +0000823
824 if (ElemType->isReferenceType())
825 return CheckReferenceType(Entity, IList, ElemType, Index,
826 StructuredList, StructuredIndex);
827
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000828 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smithe20c83d2012-07-07 08:35:56 +0000829 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smith4e0d2e42013-09-20 20:10:22 +0000830 InitListExpr *InnerStructuredList
Richard Smithe20c83d2012-07-07 08:35:56 +0000831 = getStructuredSubobjectInit(IList, Index, ElemType,
832 StructuredList, StructuredIndex,
833 SubInitList->getSourceRange());
Richard Smith4e0d2e42013-09-20 20:10:22 +0000834 CheckExplicitInitList(Entity, SubInitList, ElemType,
835 InnerStructuredList);
Richard Smithe20c83d2012-07-07 08:35:56 +0000836 ++StructuredIndex;
837 ++Index;
838 return;
839 }
840 assert(SemaRef.getLangOpts().CPlusPlus &&
841 "non-aggregate records are only possible in C++");
842 // C++ initialization is handled later.
843 }
844
Eli Friedman4628cf72013-08-19 22:12:56 +0000845 // FIXME: Need to handle atomic aggregate types with implicit init lists.
846 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCall5decec92011-02-21 07:57:55 +0000847 return CheckScalarType(Entity, IList, ElemType, Index,
848 StructuredList, StructuredIndex);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000849
Eli Friedman4628cf72013-08-19 22:12:56 +0000850 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
851 ElemType->isArrayType()) && "Unexpected type");
852
John McCall5decec92011-02-21 07:57:55 +0000853 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
854 // arrayType can be incomplete if we're initializing a flexible
855 // array member. There's nothing we can do with the completed
856 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000858 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedmand8d7a372011-09-26 19:09:09 +0000859 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +0000860 CheckStringInit(expr, ElemType, arrayType, SemaRef);
861 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedmand8d7a372011-09-26 19:09:09 +0000862 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000863 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000864 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000865 }
John McCall5decec92011-02-21 07:57:55 +0000866
867 // Fall through for subaggregate initialization.
868
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCall5decec92011-02-21 07:57:55 +0000870 // C++ [dcl.init.aggr]p12:
871 // All implicit type conversions (clause 4) are considered when
Sebastian Redl26bcc942011-09-24 17:47:39 +0000872 // initializing the aggregate member with an initializer from
John McCall5decec92011-02-21 07:57:55 +0000873 // an initializer-list. If the initializer can initialize a
874 // member, the member is initialized. [...]
875
876 // FIXME: Better EqualLoc?
877 InitializationKind Kind =
878 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000879 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCall5decec92011-02-21 07:57:55 +0000880
881 if (Seq) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000882 if (!VerifyOnly) {
Richard Smith0f8ede12011-12-20 04:00:21 +0000883 ExprResult Result =
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000884 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smith0f8ede12011-12-20 04:00:21 +0000885 if (Result.isInvalid())
886 hadError = true;
John McCall5decec92011-02-21 07:57:55 +0000887
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000888 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smith0f8ede12011-12-20 04:00:21 +0000889 Result.takeAs<Expr>());
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000890 }
John McCall5decec92011-02-21 07:57:55 +0000891 ++Index;
892 return;
893 }
894
895 // Fall through for subaggregate initialization
896 } else {
897 // C99 6.7.8p13:
898 //
899 // The initializer for a structure or union object that has
900 // automatic storage duration shall be either an initializer
901 // list as described below, or a single expression that has
902 // compatible structure or union type. In the latter case, the
903 // initial value of the object, including unnamed members, is
904 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000905 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000906 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000907 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
908 !VerifyOnly)
Eli Friedmanb2a8d462013-09-17 04:07:04 +0000909 != Sema::Incompatible) {
John Wiegley01296292011-04-08 18:41:53 +0000910 if (ExprRes.isInvalid())
911 hadError = true;
912 else {
913 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000914 if (ExprRes.isInvalid())
915 hadError = true;
John Wiegley01296292011-04-08 18:41:53 +0000916 }
917 UpdateStructuredListElement(StructuredList, StructuredIndex,
918 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000919 ++Index;
920 return;
921 }
John Wiegley01296292011-04-08 18:41:53 +0000922 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000923 // Fall through for subaggregate initialization
924 }
925
926 // C++ [dcl.init.aggr]p12:
927 //
928 // [...] Otherwise, if the member is itself a non-empty
929 // subaggregate, brace elision is assumed and the initializer is
930 // considered for the initialization of the first member of
931 // the subaggregate.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000932 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +0000933 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000934 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
935 StructuredIndex);
936 ++StructuredIndex;
937 } else {
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000938 if (!VerifyOnly) {
939 // We cannot initialize this element, so let
940 // PerformCopyInitialization produce the appropriate diagnostic.
941 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
942 SemaRef.Owned(expr),
943 /*TopLevelOfInitList=*/true);
944 }
John McCall5decec92011-02-21 07:57:55 +0000945 hadError = true;
946 ++Index;
947 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000948 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000949}
950
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000951void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
952 InitListExpr *IList, QualType DeclType,
953 unsigned &Index,
954 InitListExpr *StructuredList,
955 unsigned &StructuredIndex) {
956 assert(Index == 0 && "Index in explicit init list must be zero");
957
958 // As an extension, clang supports complex initializers, which initialize
959 // a complex number component-wise. When an explicit initializer list for
960 // a complex number contains two two initializers, this extension kicks in:
961 // it exepcts the initializer list to contain two elements convertible to
962 // the element type of the complex type. The first element initializes
963 // the real part, and the second element intitializes the imaginary part.
964
965 if (IList->getNumInits() != 2)
966 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
967 StructuredIndex);
968
969 // This is an extension in C. (The builtin _Complex type does not exist
970 // in the C++ standard.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000971 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000972 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
973 << IList->getSourceRange();
974
975 // Initialize the complex number.
976 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
977 InitializedEntity ElementEntity =
978 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
979
980 for (unsigned i = 0; i < 2; ++i) {
981 ElementEntity.setElementIndex(Index);
982 CheckSubElementType(ElementEntity, IList, elementType, Index,
983 StructuredList, StructuredIndex);
984 }
985}
986
987
Anders Carlsson6cabf312010-01-23 23:23:01 +0000988void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000989 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000990 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000991 InitListExpr *StructuredList,
992 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000993 if (Index >= IList->getNumInits()) {
Richard Smithc8239732011-10-18 21:39:00 +0000994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000996 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smithc8239732011-10-18 21:39:00 +0000997 diag::warn_cxx98_compat_empty_scalar_initializer :
998 diag::err_empty_scalar_initializer)
999 << IList->getSourceRange();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001000 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001001 ++Index;
1002 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +00001003 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001004 }
John McCall643169b2010-11-11 00:46:36 +00001005
1006 Expr *expr = IList->getInit(Index);
1007 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Richard Smithfe9d2c02013-11-19 03:41:32 +00001008 // FIXME: This is invalid, and accepting it causes overload resolution
1009 // to pick the wrong overload in some corner cases.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001010 if (!VerifyOnly)
1011 SemaRef.Diag(SubIList->getLocStart(),
Richard Smithfe9d2c02013-11-19 03:41:32 +00001012 diag::ext_many_braces_around_scalar_init)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001013 << SubIList->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001014
1015 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1016 StructuredIndex);
1017 return;
1018 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001019 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001020 SemaRef.Diag(expr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001021 diag::err_designator_for_scalar_init)
1022 << DeclType << expr->getSourceRange();
John McCall643169b2010-11-11 00:46:36 +00001023 hadError = true;
1024 ++Index;
1025 ++StructuredIndex;
1026 return;
1027 }
1028
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001029 if (VerifyOnly) {
1030 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1031 hadError = true;
1032 ++Index;
1033 return;
1034 }
1035
John McCall643169b2010-11-11 00:46:36 +00001036 ExprResult Result =
1037 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001038 SemaRef.Owned(expr),
1039 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +00001040
1041 Expr *ResultExpr = 0;
1042
1043 if (Result.isInvalid())
1044 hadError = true; // types weren't compatible.
1045 else {
1046 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047
John McCall643169b2010-11-11 00:46:36 +00001048 if (ResultExpr != expr) {
1049 // The type was promoted, update initializer list.
1050 IList->setInit(Index, ResultExpr);
1051 }
1052 }
1053 if (hadError)
1054 ++StructuredIndex;
1055 else
1056 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1057 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001058}
1059
Anders Carlsson6cabf312010-01-23 23:23:01 +00001060void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1061 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +00001062 unsigned &Index,
1063 InitListExpr *StructuredList,
1064 unsigned &StructuredIndex) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001065 if (Index >= IList->getNumInits()) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001066 // FIXME: It would be wonderful if we could point at the actual member. In
1067 // general, it would be useful to pass location information down the stack,
1068 // so that we know the location (or decl) of the "current object" being
1069 // initialized.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001070 if (!VerifyOnly)
1071 SemaRef.Diag(IList->getLocStart(),
1072 diag::err_init_reference_member_uninitialized)
1073 << DeclType
1074 << IList->getSourceRange();
Douglas Gregord14247a2009-01-30 22:09:00 +00001075 hadError = true;
1076 ++Index;
1077 ++StructuredIndex;
1078 return;
1079 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001080
1081 Expr *expr = IList->getInit(Index);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001082 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001083 if (!VerifyOnly)
1084 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1085 << DeclType << IList->getSourceRange();
1086 hadError = true;
1087 ++Index;
1088 ++StructuredIndex;
1089 return;
1090 }
1091
1092 if (VerifyOnly) {
1093 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1094 hadError = true;
1095 ++Index;
1096 return;
1097 }
1098
1099 ExprResult Result =
1100 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1101 SemaRef.Owned(expr),
1102 /*TopLevelOfInitList=*/true);
1103
1104 if (Result.isInvalid())
1105 hadError = true;
1106
1107 expr = Result.takeAs<Expr>();
1108 IList->setInit(Index, expr);
1109
1110 if (hadError)
1111 ++StructuredIndex;
1112 else
1113 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1114 ++Index;
Douglas Gregord14247a2009-01-30 22:09:00 +00001115}
1116
Anders Carlsson6cabf312010-01-23 23:23:01 +00001117void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +00001118 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001119 unsigned &Index,
1120 InitListExpr *StructuredList,
1121 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +00001122 const VectorType *VT = DeclType->getAs<VectorType>();
1123 unsigned maxElements = VT->getNumElements();
1124 unsigned numEltsInit = 0;
1125 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +00001126
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001127 if (Index >= IList->getNumInits()) {
1128 // Make sure the element type can be value-initialized.
1129 if (VerifyOnly)
1130 CheckValueInitializable(
1131 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1132 return;
1133 }
1134
David Blaikiebbafb8a2012-03-11 07:00:24 +00001135 if (!SemaRef.getLangOpts().OpenCL) {
John McCall6a16b2f2010-10-30 00:11:39 +00001136 // If the initializing element is a vector, try to copy-initialize
1137 // instead of breaking it apart (which is doomed to failure anyway).
1138 Expr *Init = IList->getInit(Index);
1139 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001140 if (VerifyOnly) {
1141 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1142 hadError = true;
1143 ++Index;
1144 return;
1145 }
1146
John McCall6a16b2f2010-10-30 00:11:39 +00001147 ExprResult Result =
1148 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +00001149 SemaRef.Owned(Init),
1150 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +00001151
1152 Expr *ResultExpr = 0;
1153 if (Result.isInvalid())
1154 hadError = true; // types weren't compatible.
1155 else {
1156 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
John McCall6a16b2f2010-10-30 00:11:39 +00001158 if (ResultExpr != Init) {
1159 // The type was promoted, update initializer list.
1160 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00001161 }
1162 }
John McCall6a16b2f2010-10-30 00:11:39 +00001163 if (hadError)
1164 ++StructuredIndex;
1165 else
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001166 UpdateStructuredListElement(StructuredList, StructuredIndex,
1167 ResultExpr);
John McCall6a16b2f2010-10-30 00:11:39 +00001168 ++Index;
1169 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001170 }
Mike Stump11289f42009-09-09 15:08:12 +00001171
John McCall6a16b2f2010-10-30 00:11:39 +00001172 InitializedEntity ElementEntity =
1173 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001174
John McCall6a16b2f2010-10-30 00:11:39 +00001175 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1176 // Don't attempt to go past the end of the init list
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001177 if (Index >= IList->getNumInits()) {
1178 if (VerifyOnly)
1179 CheckValueInitializable(ElementEntity);
John McCall6a16b2f2010-10-30 00:11:39 +00001180 break;
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182
John McCall6a16b2f2010-10-30 00:11:39 +00001183 ElementEntity.setElementIndex(Index);
1184 CheckSubElementType(ElementEntity, IList, elementType, Index,
1185 StructuredList, StructuredIndex);
1186 }
1187 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001188 }
John McCall6a16b2f2010-10-30 00:11:39 +00001189
1190 InitializedEntity ElementEntity =
1191 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001192
John McCall6a16b2f2010-10-30 00:11:39 +00001193 // OpenCL initializers allows vectors to be constructed from vectors.
1194 for (unsigned i = 0; i < maxElements; ++i) {
1195 // Don't attempt to go past the end of the init list
1196 if (Index >= IList->getNumInits())
1197 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001198
John McCall6a16b2f2010-10-30 00:11:39 +00001199 ElementEntity.setElementIndex(Index);
1200
1201 QualType IType = IList->getInit(Index)->getType();
1202 if (!IType->isVectorType()) {
1203 CheckSubElementType(ElementEntity, IList, elementType, Index,
1204 StructuredList, StructuredIndex);
1205 ++numEltsInit;
1206 } else {
1207 QualType VecType;
1208 const VectorType *IVT = IType->getAs<VectorType>();
1209 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001210
John McCall6a16b2f2010-10-30 00:11:39 +00001211 if (IType->isExtVectorType())
1212 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1213 else
1214 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001215 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001216 CheckSubElementType(ElementEntity, IList, VecType, Index,
1217 StructuredList, StructuredIndex);
1218 numEltsInit += numIElts;
1219 }
1220 }
1221
1222 // OpenCL requires all elements to be initialized.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001223 if (numEltsInit != maxElements) {
1224 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001225 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001226 diag::err_vector_incorrect_num_initializers)
1227 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1228 hadError = true;
1229 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001230}
1231
Anders Carlsson6cabf312010-01-23 23:23:01 +00001232void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001233 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001234 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001235 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001236 unsigned &Index,
1237 InitListExpr *StructuredList,
1238 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001239 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1240
Steve Narofff8ecff22008-05-01 22:18:59 +00001241 // Check for the special-case of initializing an array with a string.
1242 if (Index < IList->getNumInits()) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001243 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1244 SIF_None) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001245 // We place the string literal directly into the resulting
1246 // initializer list. This is the only place where the structure
1247 // of the structured initializer list doesn't match exactly,
1248 // because doing so would involve allocating one character
1249 // constant for each string.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001250 if (!VerifyOnly) {
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00001251 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1252 UpdateStructuredListElement(StructuredList, StructuredIndex,
1253 IList->getInit(Index));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001254 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1255 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001256 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001257 return;
1258 }
1259 }
John McCall66884dd2011-02-21 07:22:22 +00001260 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001261 // Check for VLAs; in standard C it would be possible to check this
1262 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1263 // them in all sorts of strange places).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001264 if (!VerifyOnly)
1265 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1266 diag::err_variable_object_no_init)
1267 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001268 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001269 ++Index;
1270 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001271 return;
1272 }
1273
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001274 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001275 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1276 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001277 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001278 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001279 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001280 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001281 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001282 maxElementsKnown = true;
1283 }
1284
John McCall66884dd2011-02-21 07:22:22 +00001285 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001286 while (Index < IList->getNumInits()) {
1287 Expr *Init = IList->getInit(Index);
1288 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001289 // If we're not the subobject that matches up with the '{' for
1290 // the designator, we shouldn't be handling the
1291 // designator. Return immediately.
1292 if (!SubobjectIsDesignatorContext)
1293 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001294
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001295 // Handle this designated initializer. elementIndex will be
1296 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001297 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001298 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001299 StructuredList, StructuredIndex, true,
1300 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001301 hadError = true;
1302 continue;
1303 }
1304
Douglas Gregor033d1252009-01-23 16:54:12 +00001305 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001306 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001307 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001308 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001309 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001310
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001311 // If the array is of incomplete type, keep track of the number of
1312 // elements in the initializer.
1313 if (!maxElementsKnown && elementIndex > maxElements)
1314 maxElements = elementIndex;
1315
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001316 continue;
1317 }
1318
1319 // If we know the maximum number of elements, and we've already
1320 // hit it, stop consuming elements in the initializer list.
1321 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001322 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001323
Anders Carlsson6cabf312010-01-23 23:23:01 +00001324 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001326 Entity);
1327 // Check this element.
1328 CheckSubElementType(ElementEntity, IList, elementType, Index,
1329 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001330 ++elementIndex;
1331
1332 // If the array is of incomplete type, keep track of the number of
1333 // elements in the initializer.
1334 if (!maxElementsKnown && elementIndex > maxElements)
1335 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001336 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001337 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001338 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001339 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001340 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001341 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001342 // Sizing an array implicitly to zero is not allowed by ISO C,
1343 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001344 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001345 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001346 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001347
Mike Stump11289f42009-09-09 15:08:12 +00001348 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001349 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001350 }
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001351 if (!hadError && VerifyOnly) {
1352 // Check if there are any members of the array that get value-initialized.
1353 // If so, check if doing that is possible.
1354 // FIXME: This needs to detect holes left by designated initializers too.
1355 if (maxElementsKnown && elementIndex < maxElements)
1356 CheckValueInitializable(InitializedEntity::InitializeElement(
1357 SemaRef.Context, 0, Entity));
1358 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001359}
1360
Eli Friedman3fa64df2011-08-23 22:24:57 +00001361bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1362 Expr *InitExpr,
1363 FieldDecl *Field,
1364 bool TopLevelObject) {
1365 // Handle GNU flexible array initializers.
1366 unsigned FlexArrayDiag;
1367 if (isa<InitListExpr>(InitExpr) &&
1368 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1369 // Empty flexible array init always allowed as an extension
1370 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001371 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedman3fa64df2011-08-23 22:24:57 +00001372 // Disallow flexible array init in C++; it is not required for gcc
1373 // compatibility, and it needs work to IRGen correctly in general.
1374 FlexArrayDiag = diag::err_flexible_array_init;
1375 } else if (!TopLevelObject) {
1376 // Disallow flexible array init on non-top-level object
1377 FlexArrayDiag = diag::err_flexible_array_init;
1378 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1379 // Disallow flexible array init on anything which is not a variable.
1380 FlexArrayDiag = diag::err_flexible_array_init;
1381 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1382 // Disallow flexible array init on local variables.
1383 FlexArrayDiag = diag::err_flexible_array_init;
1384 } else {
1385 // Allow other cases.
1386 FlexArrayDiag = diag::ext_flexible_array_init;
1387 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001388
1389 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001390 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001391 FlexArrayDiag)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001392 << InitExpr->getLocStart();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001393 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1394 << Field;
1395 }
Eli Friedman3fa64df2011-08-23 22:24:57 +00001396
1397 return FlexArrayDiag != diag::ext_flexible_array_init;
1398}
1399
Anders Carlsson6cabf312010-01-23 23:23:01 +00001400void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001401 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001402 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001403 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001404 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001405 unsigned &Index,
1406 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001407 unsigned &StructuredIndex,
1408 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001409 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001410
Eli Friedman23a9e312008-05-19 19:16:24 +00001411 // If the record is invalid, some of it's members are invalid. To avoid
1412 // confusion, we forgo checking the intializer for the entire record.
1413 if (structDecl->isInvalidDecl()) {
Richard Smith845aa662012-09-28 21:23:50 +00001414 // Assume it was supposed to consume a single initializer.
1415 ++Index;
Eli Friedman23a9e312008-05-19 19:16:24 +00001416 hadError = true;
1417 return;
Mike Stump11289f42009-09-09 15:08:12 +00001418 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001419
1420 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001421 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001422
1423 // If there's a default initializer, use it.
1424 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1425 if (VerifyOnly)
1426 return;
1427 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1428 Field != FieldEnd; ++Field) {
1429 if (Field->hasInClassInitializer()) {
1430 StructuredList->setInitializedFieldInUnion(*Field);
1431 // FIXME: Actually build a CXXDefaultInitExpr?
1432 return;
1433 }
1434 }
1435 }
1436
1437 // Value-initialize the first named member of the union.
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001438 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1439 Field != FieldEnd; ++Field) {
1440 if (Field->getDeclName()) {
1441 if (VerifyOnly)
1442 CheckValueInitializable(
David Blaikie40ed2972012-06-06 20:45:41 +00001443 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001444 else
David Blaikie40ed2972012-06-06 20:45:41 +00001445 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001446 break;
Douglas Gregor0202cb42009-01-29 17:44:32 +00001447 }
1448 }
1449 return;
1450 }
1451
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001452 // If structDecl is a forward declaration, this loop won't do
1453 // anything except look at designated initializers; That's okay,
1454 // because an error should get printed out elsewhere. It might be
1455 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001456 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001457 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001458 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001459 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001460 while (Index < IList->getNumInits()) {
1461 Expr *Init = IList->getInit(Index);
1462
1463 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001464 // If we're not the subobject that matches up with the '{' for
1465 // the designator, we shouldn't be handling the
1466 // designator. Return immediately.
1467 if (!SubobjectIsDesignatorContext)
1468 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001469
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001470 // Handle this designated initializer. Field will be updated to
1471 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001472 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001473 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001474 StructuredList, StructuredIndex,
1475 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001476 hadError = true;
1477
Douglas Gregora9add4e2009-02-12 19:00:39 +00001478 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001479
1480 // Disable check for missing fields when designators are used.
1481 // This matches gcc behaviour.
1482 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001483 continue;
1484 }
1485
1486 if (Field == FieldEnd) {
1487 // We've run out of fields. We're done.
1488 break;
1489 }
1490
Douglas Gregora9add4e2009-02-12 19:00:39 +00001491 // We've already initialized a member of a union. We're done.
1492 if (InitializedSomething && DeclType->isUnionType())
1493 break;
1494
Douglas Gregor91f84212008-12-11 16:49:14 +00001495 // If we've hit the flexible array member at the end, we're done.
1496 if (Field->getType()->isIncompleteArrayType())
1497 break;
1498
Douglas Gregor51695702009-01-29 16:53:55 +00001499 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001500 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001501 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001502 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001503 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001504
Douglas Gregora82064c2011-06-29 21:51:31 +00001505 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001506 bool InvalidUse;
1507 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001508 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001509 else
David Blaikie40ed2972012-06-06 20:45:41 +00001510 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001511 IList->getInit(Index)->getLocStart());
1512 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001513 ++Index;
1514 ++Field;
1515 hadError = true;
1516 continue;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001517 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001518
Anders Carlsson6cabf312010-01-23 23:23:01 +00001519 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001520 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001521 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1522 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001523 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001524
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001525 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor51695702009-01-29 16:53:55 +00001526 // Initialize the first field within the union.
David Blaikie40ed2972012-06-06 20:45:41 +00001527 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001528 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001529
1530 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001531 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001532
John McCalle40b58e2010-03-11 19:32:38 +00001533 // Emit warnings for missing struct field initializers.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001534 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1535 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1536 !DeclType->isUnionType()) {
John McCalle40b58e2010-03-11 19:32:38 +00001537 // It is possible we have one or more unnamed bitfields remaining.
1538 // Find first (if any) named field and emit warning.
1539 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1540 it != end; ++it) {
Richard Smith852c9db2013-04-20 22:23:05 +00001541 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCalle40b58e2010-03-11 19:32:38 +00001542 SemaRef.Diag(IList->getSourceRange().getEnd(),
1543 diag::warn_missing_field_initializers) << it->getName();
1544 break;
1545 }
1546 }
1547 }
1548
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001549 // Check that any remaining fields can be value-initialized.
1550 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1551 !Field->getType()->isIncompleteArrayType()) {
1552 // FIXME: Should check for holes left by designated initializers too.
1553 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smith852c9db2013-04-20 22:23:05 +00001554 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001555 CheckValueInitializable(
David Blaikie40ed2972012-06-06 20:45:41 +00001556 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl2b47b7a2011-10-16 18:19:20 +00001557 }
1558 }
1559
Mike Stump11289f42009-09-09 15:08:12 +00001560 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001561 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001562 return;
1563
David Blaikie40ed2972012-06-06 20:45:41 +00001564 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001565 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001566 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001567 ++Index;
1568 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001569 }
1570
Anders Carlsson6cabf312010-01-23 23:23:01 +00001571 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001572 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001573
Anders Carlsson6cabf312010-01-23 23:23:01 +00001574 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001575 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001576 StructuredList, StructuredIndex);
1577 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001578 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001579 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001580}
Steve Narofff8ecff22008-05-01 22:18:59 +00001581
Douglas Gregord5846a12009-04-15 06:41:24 +00001582/// \brief Expand a field designator that refers to a member of an
1583/// anonymous struct or union into a series of field designators that
1584/// refers to the field within the appropriate subobject.
1585///
Douglas Gregord5846a12009-04-15 06:41:24 +00001586static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001587 DesignatedInitExpr *DIE,
1588 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001589 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001590 typedef DesignatedInitExpr::Designator Designator;
1591
Douglas Gregord5846a12009-04-15 06:41:24 +00001592 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001593 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001594 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1595 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1596 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001597 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001598 DIE->getDesignator(DesigIdx)->getDotLoc(),
1599 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1600 else
1601 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1602 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001603 assert(isa<FieldDecl>(*PI));
1604 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001605 }
1606
1607 // Expand the current designator into the set of replacement
1608 // designators, so we have a full subobject path down to where the
1609 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001610 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001611 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001612}
Mike Stump11289f42009-09-09 15:08:12 +00001613
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001615/// corresponds to FieldName.
1616static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1617 IdentifierInfo *FieldName) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001618 if (!FieldName)
1619 return 0;
1620
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001621 assert(AnonField->isAnonymousStructOrUnion());
1622 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman6d1bebb2012-02-09 22:16:56 +00001623 while (IndirectFieldDecl *IF =
1624 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidis54b10292012-09-10 22:04:26 +00001625 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001626 return IF;
1627 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001628 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001629 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001630}
1631
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001632static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1633 DesignatedInitExpr *DIE) {
1634 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1635 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1636 for (unsigned I = 0; I < NumIndexExprs; ++I)
1637 IndexExprs[I] = DIE->getSubExpr(I + 1);
1638 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001639 DIE->size(), IndexExprs,
1640 DIE->getEqualOrColonLoc(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001641 DIE->usesGNUSyntax(), DIE->getInit());
1642}
1643
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001644namespace {
1645
1646// Callback to only accept typo corrections that are for field members of
1647// the given struct or union.
1648class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1649 public:
1650 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1651 : Record(RD) {}
1652
1653 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1654 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1655 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1656 }
1657
1658 private:
1659 RecordDecl *Record;
1660};
1661
1662}
1663
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001664/// @brief Check the well-formedness of a C99 designated initializer.
1665///
1666/// Determines whether the designated initializer @p DIE, which
1667/// resides at the given @p Index within the initializer list @p
1668/// IList, is well-formed for a current object of type @p DeclType
1669/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001670/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001672///
1673/// @param IList The initializer list in which this designated
1674/// initializer occurs.
1675///
Douglas Gregora5324162009-04-15 04:56:10 +00001676/// @param DIE The designated initializer expression.
1677///
1678/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001679///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001680/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001681/// into which the designation in @p DIE should refer.
1682///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001683/// @param NextField If non-NULL and the first designator in @p DIE is
1684/// a field, this will be set to the field declaration corresponding
1685/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001686///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001687/// @param NextElementIndex If non-NULL and the first designator in @p
1688/// DIE is an array designator or GNU array-range designator, this
1689/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001690///
1691/// @param Index Index into @p IList where the designated initializer
1692/// @p DIE occurs.
1693///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001694/// @param StructuredList The initializer list expression that
1695/// describes all of the subobject initializers in the order they'll
1696/// actually be initialized.
1697///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001698/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001699bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001700InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001701 InitListExpr *IList,
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001702 DesignatedInitExpr *DIE,
1703 unsigned DesigIdx,
1704 QualType &CurrentObjectType,
1705 RecordDecl::field_iterator *NextField,
1706 llvm::APSInt *NextElementIndex,
1707 unsigned &Index,
1708 InitListExpr *StructuredList,
1709 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001710 bool FinishSubobjectInit,
1711 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001712 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001713 // Check the actual initialization for the designated object type.
1714 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001715
1716 // Temporarily remove the designator expression from the
1717 // initializer list that the child calls see, so that we don't try
1718 // to re-process the designator.
1719 unsigned OldIndex = Index;
1720 IList->setInit(OldIndex, DIE->getInit());
1721
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001722 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001723 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001724
1725 // Restore the designated initializer expression in the syntactic
1726 // form of the initializer list.
1727 if (IList->getInit(OldIndex) != DIE->getInit())
1728 DIE->setInit(IList->getInit(OldIndex));
1729 IList->setInit(OldIndex, DIE);
1730
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001731 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001732 }
1733
Douglas Gregora5324162009-04-15 04:56:10 +00001734 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001735 bool IsFirstDesignator = (DesigIdx == 0);
1736 if (!VerifyOnly) {
1737 assert((IsFirstDesignator || StructuredList) &&
1738 "Need a non-designated initializer list to start from");
1739
1740 // Determine the structural initializer list that corresponds to the
1741 // current subobject.
Benjamin Kramer6b441d62012-02-23 14:48:40 +00001742 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001743 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1744 StructuredList, StructuredIndex,
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001745 SourceRange(D->getLocStart(),
1746 DIE->getLocEnd()));
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001747 assert(StructuredList && "Expected a structured initializer list");
1748 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001749
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001750 if (D->isFieldDesignator()) {
1751 // C99 6.7.8p7:
1752 //
1753 // If a designator has the form
1754 //
1755 // . identifier
1756 //
1757 // then the current object (defined below) shall have
1758 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001759 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001760 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001761 if (!RT) {
1762 SourceLocation Loc = D->getDotLoc();
1763 if (Loc.isInvalid())
1764 Loc = D->getFieldLoc();
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001765 if (!VerifyOnly)
1766 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001767 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001768 ++Index;
1769 return true;
1770 }
1771
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001772 // Note: we perform a linear search of the fields here, despite
1773 // the fact that we have a faster lookup method, because we always
1774 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001775 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001776 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001777 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001778 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001779 Field = RT->getDecl()->field_begin(),
1780 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001781 for (; Field != FieldEnd; ++Field) {
1782 if (Field->isUnnamedBitfield())
1783 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001785 // If we find a field representing an anonymous field, look in the
1786 // IndirectFieldDecl that follow for the designated initializer.
1787 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1788 if (IndirectFieldDecl *IF =
David Blaikie40ed2972012-06-06 20:45:41 +00001789 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001790 // In verify mode, don't modify the original.
1791 if (VerifyOnly)
1792 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001793 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1794 D = DIE->getDesignator(DesigIdx);
1795 break;
1796 }
1797 }
David Blaikie40ed2972012-06-06 20:45:41 +00001798 if (KnownField && KnownField == *Field)
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001799 break;
1800 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001801 break;
1802
1803 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001804 }
1805
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001806 if (Field == FieldEnd) {
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001807 if (VerifyOnly) {
1808 ++Index;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001809 return true; // No typo correction when just trying this out.
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001810 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001811
Douglas Gregord5846a12009-04-15 06:41:24 +00001812 // There was no normal field in the struct with the designated
1813 // name. Perform another lookup for this name, which may find
1814 // something that we can't designate (e.g., a member function),
1815 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001816 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001817 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001818 FieldDecl *ReplacementField = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00001819 if (Lookup.empty()) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001820 // Name lookup didn't find anything. Determine whether this
1821 // was a typo for another field name.
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001822 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smithf9b15102013-08-17 00:46:16 +00001823 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1824 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1825 Sema::LookupMemberName, /*Scope=*/ 0, /*SS=*/ 0, Validator,
1826 RT->getDecl())) {
1827 SemaRef.diagnoseTypo(
1828 Corrected,
1829 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1830 << FieldName << CurrentObjectType);
Kaelyn Uhrainb02c5e92012-01-12 19:27:05 +00001831 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramerafe718f2011-09-25 02:41:26 +00001832 hadError = true;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001833 } else {
1834 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1835 << FieldName << CurrentObjectType;
1836 ++Index;
1837 return true;
1838 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001839 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001841 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001842 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001843 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001844 << FieldName;
David Blaikieff7d47a2012-12-19 00:45:41 +00001845 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001846 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001847 ++Index;
1848 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001849 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001850
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001851 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001852 // The replacement field comes from typo correction; find it
1853 // in the list of fields.
1854 FieldIndex = 0;
1855 Field = RT->getDecl()->field_begin();
1856 for (; Field != FieldEnd; ++Field) {
1857 if (Field->isUnnamedBitfield())
1858 continue;
1859
David Blaikie40ed2972012-06-06 20:45:41 +00001860 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001861 Field->getIdentifier() == ReplacementField->getIdentifier())
1862 break;
1863
1864 ++FieldIndex;
1865 }
1866 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001867 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001868
1869 // All of the fields of a union are located at the same place in
1870 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001871 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001872 FieldIndex = 0;
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001873 if (!VerifyOnly) {
1874 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1875 if (CurrentField && CurrentField != *Field) {
1876 assert(StructuredList->getNumInits() == 1
1877 && "A union should never have more than one initializer!");
1878
1879 // we're about to throw away an initializer, emit warning
1880 SemaRef.Diag(D->getFieldLoc(),
1881 diag::warn_initializer_overrides)
1882 << D->getSourceRange();
1883 Expr *ExistingInit = StructuredList->getInit(0);
1884 SemaRef.Diag(ExistingInit->getLocStart(),
1885 diag::note_previous_initializer)
1886 << /*FIXME:has side effects=*/0
1887 << ExistingInit->getSourceRange();
1888
1889 // remove existing initializer
1890 StructuredList->resizeInits(SemaRef.Context, 0);
1891 StructuredList->setInitializedFieldInUnion(0);
1892 }
1893
David Blaikie40ed2972012-06-06 20:45:41 +00001894 StructuredList->setInitializedFieldInUnion(*Field);
Matthew Curtis274a9cc2013-10-03 12:14:24 +00001895 }
Douglas Gregor51695702009-01-29 16:53:55 +00001896 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001897
Douglas Gregora82064c2011-06-29 21:51:31 +00001898 // Make sure we can use this declaration.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001899 bool InvalidUse;
1900 if (VerifyOnly)
David Blaikie40ed2972012-06-06 20:45:41 +00001901 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001902 else
David Blaikie40ed2972012-06-06 20:45:41 +00001903 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001904 if (InvalidUse) {
Douglas Gregora82064c2011-06-29 21:51:31 +00001905 ++Index;
1906 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001907 }
Douglas Gregora82064c2011-06-29 21:51:31 +00001908
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001909 if (!VerifyOnly) {
1910 // Update the designator with the field declaration.
David Blaikie40ed2972012-06-06 20:45:41 +00001911 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001913 // Make sure that our non-designated initializer list has space
1914 // for a subobject corresponding to this field.
1915 if (FieldIndex >= StructuredList->getNumInits())
1916 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1917 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001918
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001919 // This designator names a flexible array member.
1920 if (Field->getType()->isIncompleteArrayType()) {
1921 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001922 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001923 // We can't designate an object within the flexible array
1924 // member (because GCC doesn't allow it).
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001925 if (!VerifyOnly) {
1926 DesignatedInitExpr::Designator *NextD
1927 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001928 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001929 diag::err_designator_into_flexible_array_member)
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001930 << SourceRange(NextD->getLocStart(),
1931 DIE->getLocEnd());
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001932 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001933 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001934 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001935 Invalid = true;
1936 }
1937
Chris Lattner001b29c2010-10-10 17:49:49 +00001938 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1939 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001940 // The initializer is not an initializer list.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001941 if (!VerifyOnly) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001942 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001943 diag::err_flexible_array_init_needs_braces)
1944 << DIE->getInit()->getSourceRange();
1945 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie40ed2972012-06-06 20:45:41 +00001946 << *Field;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00001947 }
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001948 Invalid = true;
1949 }
1950
Eli Friedman3fa64df2011-08-23 22:24:57 +00001951 // Check GNU flexible array initializer.
David Blaikie40ed2972012-06-06 20:45:41 +00001952 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedman3fa64df2011-08-23 22:24:57 +00001953 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001954 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001955
1956 if (Invalid) {
1957 ++Index;
1958 return true;
1959 }
1960
1961 // Initialize the array.
1962 bool prevHadError = hadError;
1963 unsigned newStructuredIndex = FieldIndex;
1964 unsigned OldIndex = Index;
1965 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001966
1967 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001968 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001969 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001970 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001971
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001972 IList->setInit(OldIndex, DIE);
1973 if (hadError && !prevHadError) {
1974 ++Field;
1975 ++FieldIndex;
1976 if (NextField)
1977 *NextField = Field;
1978 StructuredIndex = FieldIndex;
1979 return true;
1980 }
1981 } else {
1982 // Recurse to check later designated subobjects.
David Blaikie2d7c57e2012-04-30 02:36:29 +00001983 QualType FieldType = Field->getType();
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001984 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001985
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001986 InitializedEntity MemberEntity =
David Blaikie40ed2972012-06-06 20:45:41 +00001987 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1989 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001990 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001991 true, false))
1992 return true;
1993 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001994
1995 // Find the position of the next field to be initialized in this
1996 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001997 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001998 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001999
2000 // If this the first designator, our caller will continue checking
2001 // the rest of this struct/class/union subobject.
2002 if (IsFirstDesignator) {
2003 if (NextField)
2004 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002005 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002006 return false;
2007 }
2008
Douglas Gregor17bd0942009-01-28 23:36:17 +00002009 if (!FinishSubobjectInit)
2010 return false;
2011
Douglas Gregord5846a12009-04-15 06:41:24 +00002012 // We've already initialized something in the union; we're done.
2013 if (RT->getDecl()->isUnion())
2014 return hadError;
2015
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002016 // Check the remaining fields within this class/struct/union subobject.
2017 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018
Anders Carlsson6cabf312010-01-23 23:23:01 +00002019 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002020 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002021 return hadError && !prevHadError;
2022 }
2023
2024 // C99 6.7.8p6:
2025 //
2026 // If a designator has the form
2027 //
2028 // [ constant-expression ]
2029 //
2030 // then the current object (defined below) shall have array
2031 // type and the expression shall be an integer constant
2032 // expression. If the array is of unknown size, any
2033 // nonnegative value is valid.
2034 //
2035 // Additionally, cope with the GNU extension that permits
2036 // designators of the form
2037 //
2038 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00002039 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002040 if (!AT) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002041 if (!VerifyOnly)
2042 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2043 << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002044 ++Index;
2045 return true;
2046 }
2047
2048 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00002049 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2050 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002051 IndexExpr = DIE->getArrayIndex(*D);
Richard Smithcaf33902011-10-10 18:28:20 +00002052 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002053 DesignatedEndIndex = DesignatedStartIndex;
2054 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002055 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00002056
Mike Stump11289f42009-09-09 15:08:12 +00002057 DesignatedStartIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002058 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002059 DesignatedEndIndex =
Richard Smithcaf33902011-10-10 18:28:20 +00002060 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002061 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00002062
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00002063 // Codegen can't handle evaluating array range designators that have side
2064 // effects, because we replicate the AST value for each initialized element.
2065 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2066 // elements with something that has a side effect, so codegen can emit an
2067 // "error unsupported" error instead of miscompiling the app.
2068 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002069 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregorbf7207a2009-01-29 19:42:23 +00002070 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002071 }
2072
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002073 if (isa<ConstantArrayType>(AT)) {
2074 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002075 DesignatedStartIndex
2076 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002077 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00002078 DesignatedEndIndex
2079 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002080 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2081 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmaned0f9162011-09-26 18:53:43 +00002082 if (!VerifyOnly)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002083 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002084 diag::err_array_designator_too_large)
2085 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2086 << IndexExpr->getSourceRange();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002087 ++Index;
2088 return true;
2089 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00002090 } else {
2091 // Make sure the bit-widths and signedness match.
2092 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002093 DesignatedEndIndex
2094 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002095 else if (DesignatedStartIndex.getBitWidth() <
2096 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002097 DesignatedStartIndex
2098 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00002099 DesignatedStartIndex.setIsUnsigned(true);
2100 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Eli Friedman1f16b742013-06-11 21:48:11 +00002103 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2104 // We're modifying a string literal init; we have to decompose the string
2105 // so we can modify the individual characters.
2106 ASTContext &Context = SemaRef.Context;
2107 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2108
2109 // Compute the character type
2110 QualType CharTy = AT->getElementType();
2111
2112 // Compute the type of the integer literals.
2113 QualType PromotedCharTy = CharTy;
2114 if (CharTy->isPromotableIntegerType())
2115 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2116 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2117
2118 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2119 // Get the length of the string.
2120 uint64_t StrLen = SL->getLength();
2121 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2122 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2123 StructuredList->resizeInits(Context, StrLen);
2124
2125 // Build a literal for each character in the string, and put them into
2126 // the init list.
2127 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2128 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2129 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002130 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002131 if (CharTy != PromotedCharTy)
2132 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2133 Init, 0, VK_RValue);
2134 StructuredList->updateInit(Context, i, Init);
2135 }
2136 } else {
2137 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2138 std::string Str;
2139 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2140
2141 // Get the length of the string.
2142 uint64_t StrLen = Str.size();
2143 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2144 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2145 StructuredList->resizeInits(Context, StrLen);
2146
2147 // Build a literal for each character in the string, and put them into
2148 // the init list.
2149 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2150 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2151 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman6cc05f72013-06-11 22:26:34 +00002152 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman1f16b742013-06-11 21:48:11 +00002153 if (CharTy != PromotedCharTy)
2154 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2155 Init, 0, VK_RValue);
2156 StructuredList->updateInit(Context, i, Init);
2157 }
2158 }
2159 }
2160
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002161 // Make sure that our non-designated initializer list has space
2162 // for a subobject corresponding to this array element.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002163 if (!VerifyOnly &&
2164 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00002165 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00002166 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002167
Douglas Gregor17bd0942009-01-28 23:36:17 +00002168 // Repeatedly perform subobject initializations in the range
2169 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002170
Douglas Gregor17bd0942009-01-28 23:36:17 +00002171 // Move to the next designator
2172 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2173 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002174
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002175 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00002176 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002177
Douglas Gregor17bd0942009-01-28 23:36:17 +00002178 while (DesignatedStartIndex <= DesignatedEndIndex) {
2179 // Recurse to check later designated subobjects.
2180 QualType ElementType = AT->getElementType();
2181 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002183 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2185 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00002186 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00002187 (DesignatedStartIndex == DesignatedEndIndex),
2188 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00002189 return true;
2190
2191 // Move to the next index in the array that we'll be initializing.
2192 ++DesignatedStartIndex;
2193 ElementIndex = DesignatedStartIndex.getZExtValue();
2194 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002195
2196 // If this the first designator, our caller will continue checking
2197 // the rest of this array subobject.
2198 if (IsFirstDesignator) {
2199 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00002200 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002201 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002202 return false;
2203 }
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregor17bd0942009-01-28 23:36:17 +00002205 if (!FinishSubobjectInit)
2206 return false;
2207
Douglas Gregord7fb85e2009-01-22 23:26:18 +00002208 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002209 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002210 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00002211 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002212 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002213 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002214}
2215
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002216// Get the structured initializer list for a subobject of type
2217// @p CurrentObjectType.
2218InitListExpr *
2219InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2220 QualType CurrentObjectType,
2221 InitListExpr *StructuredList,
2222 unsigned StructuredIndex,
2223 SourceRange InitRange) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00002224 if (VerifyOnly)
2225 return 0; // No structured list in verification-only mode.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002226 Expr *ExistingInit = 0;
2227 if (!StructuredList)
Benjamin Kramer6b441d62012-02-23 14:48:40 +00002228 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002229 else if (StructuredIndex < StructuredList->getNumInits())
2230 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00002231
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002232 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2233 return Result;
2234
2235 if (ExistingInit) {
2236 // We are creating an initializer list that initializes the
2237 // subobjects of the current object, but there was already an
2238 // initialization that completely initialized the current
2239 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00002240 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002241 // struct X { int a, b; };
2242 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00002243 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002244 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2245 // designated initializer re-initializes the whole
2246 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00002247 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00002248 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002249 << InitRange;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002250 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002251 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002252 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002253 << ExistingInit->getSourceRange();
2254 }
2255
Mike Stump11289f42009-09-09 15:08:12 +00002256 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00002257 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002258 InitRange.getBegin(), None,
Ted Kremenek013041e2010-02-19 01:50:18 +00002259 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00002260
Eli Friedman91f5ae52012-02-23 02:25:10 +00002261 QualType ResultType = CurrentObjectType;
2262 if (!ResultType->isArrayType())
2263 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2264 Result->setType(ResultType);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002265
Douglas Gregor6d00c992009-03-20 23:58:33 +00002266 // Pre-allocate storage for the structured initializer list.
2267 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00002268 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002269 bool GotNumInits = false;
2270 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002271 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002272 GotNumInits = true;
2273 } else if (Index < IList->getNumInits()) {
2274 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00002275 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002276 GotNumInits = true;
2277 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00002278 }
2279
Mike Stump11289f42009-09-09 15:08:12 +00002280 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00002281 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2282 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2283 NumElements = CAType->getSize().getZExtValue();
2284 // Simple heuristic so that we don't allocate a very large
2285 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00002286 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00002287 NumElements = 0;
2288 }
John McCall9dd450b2009-09-21 23:43:11 +00002289 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00002290 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002291 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00002292 RecordDecl *RDecl = RType->getDecl();
2293 if (RDecl->isUnion())
2294 NumElements = 1;
2295 else
Mike Stump11289f42009-09-09 15:08:12 +00002296 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002297 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00002298 }
2299
Ted Kremenekac034612010-04-13 23:39:13 +00002300 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002301
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002302 // Link this new initializer list into the structured initializer
2303 // lists.
2304 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00002305 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002306 else {
2307 Result->setSyntacticForm(IList);
2308 SyntacticToSemantic[IList] = Result;
2309 }
2310
2311 return Result;
2312}
2313
2314/// Update the initializer at index @p StructuredIndex within the
2315/// structured initializer list to the value @p expr.
2316void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2317 unsigned &StructuredIndex,
2318 Expr *expr) {
2319 // No structured initializer list to update
2320 if (!StructuredList)
2321 return;
2322
Ted Kremenekac034612010-04-13 23:39:13 +00002323 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2324 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002325 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002326 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002327 diag::warn_initializer_overrides)
2328 << expr->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002329 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002330 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00002331 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002332 << PrevInit->getSourceRange();
2333 }
Mike Stump11289f42009-09-09 15:08:12 +00002334
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002335 ++StructuredIndex;
2336}
2337
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002338/// Check that the given Index expression is a valid array designator
Richard Smithf4c51d92012-02-04 09:53:13 +00002339/// value. This is essentially just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002340/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002341/// and produces a reasonable diagnostic if there is a
Richard Smithf4c51d92012-02-04 09:53:13 +00002342/// failure. Returns the index expression, possibly with an implicit cast
2343/// added, on success. If everything went okay, Value will receive the
2344/// value of the constant expression.
2345static ExprResult
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002346CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002347 SourceLocation Loc = Index->getLocStart();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002348
2349 // Make sure this is an integer constant expression.
Richard Smithf4c51d92012-02-04 09:53:13 +00002350 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2351 if (Result.isInvalid())
2352 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002353
Chris Lattnerc71d08b2009-04-25 21:59:05 +00002354 if (Value.isSigned() && Value.isNegative())
2355 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002356 << Value.toString(10) << Index->getSourceRange();
2357
Douglas Gregor51650d32009-01-23 21:04:18 +00002358 Value.setIsUnsigned(true);
Richard Smithf4c51d92012-02-04 09:53:13 +00002359 return Result;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002360}
2361
John McCalldadc5752010-08-24 06:29:42 +00002362ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00002363 SourceLocation Loc,
2364 bool GNUSyntax,
2365 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002366 typedef DesignatedInitExpr::Designator ASTDesignator;
2367
2368 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002369 SmallVector<ASTDesignator, 32> Designators;
2370 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002371
2372 // Build designators and check array designator expressions.
2373 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2374 const Designator &D = Desig.getDesignator(Idx);
2375 switch (D.getKind()) {
2376 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002377 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002378 D.getFieldLoc()));
2379 break;
2380
2381 case Designator::ArrayDesignator: {
2382 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2383 llvm::APSInt IndexValue;
Richard Smithf4c51d92012-02-04 09:53:13 +00002384 if (!Index->isTypeDependent() && !Index->isValueDependent())
2385 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2386 if (!Index)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002387 Invalid = true;
2388 else {
2389 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002390 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002391 D.getRBracketLoc()));
2392 InitExpressions.push_back(Index);
2393 }
2394 break;
2395 }
2396
2397 case Designator::ArrayRangeDesignator: {
2398 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2399 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2400 llvm::APSInt StartValue;
2401 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002402 bool StartDependent = StartIndex->isTypeDependent() ||
2403 StartIndex->isValueDependent();
2404 bool EndDependent = EndIndex->isTypeDependent() ||
2405 EndIndex->isValueDependent();
Richard Smithf4c51d92012-02-04 09:53:13 +00002406 if (!StartDependent)
2407 StartIndex =
2408 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2409 if (!EndDependent)
2410 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2411
2412 if (!StartIndex || !EndIndex)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002413 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002414 else {
2415 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002416 if (StartDependent || EndDependent) {
2417 // Nothing to compute.
2418 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002419 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002420 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002421 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002422
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002423 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002424 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002425 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002426 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2427 Invalid = true;
2428 } else {
2429 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002430 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002431 D.getEllipsisLoc(),
2432 D.getRBracketLoc()));
2433 InitExpressions.push_back(StartIndex);
2434 InitExpressions.push_back(EndIndex);
2435 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002436 }
2437 break;
2438 }
2439 }
2440 }
2441
2442 if (Invalid || Init.isInvalid())
2443 return ExprError();
2444
2445 // Clear out the expressions within the designation.
2446 Desig.ClearExprs(*this);
2447
2448 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002449 = DesignatedInitExpr::Create(Context,
2450 Designators.data(), Designators.size(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002451 InitExpressions, Loc, GNUSyntax,
2452 Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002453
David Blaikiebbafb8a2012-03-11 07:00:24 +00002454 if (!getLangOpts().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002455 Diag(DIE->getLocStart(), diag::ext_designated_init)
2456 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002458 return Owned(DIE);
2459}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002460
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002461//===----------------------------------------------------------------------===//
2462// Initialization entity
2463//===----------------------------------------------------------------------===//
2464
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002465InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002466 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002467 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002468{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002469 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2470 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002471 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002472 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002473 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002474 Type = VT->getElementType();
2475 } else {
2476 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2477 assert(CT && "Unexpected type");
2478 Kind = EK_ComplexElement;
2479 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002480 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002481}
2482
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002483InitializedEntity
2484InitializedEntity::InitializeBase(ASTContext &Context,
2485 const CXXBaseSpecifier *Base,
2486 bool IsInheritedVirtualBase) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002487 InitializedEntity Result;
2488 Result.Kind = EK_Base;
Richard Smithe3b28bc2013-06-12 21:51:50 +00002489 Result.Parent = 0;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002490 Result.Base = reinterpret_cast<uintptr_t>(Base);
2491 if (IsInheritedVirtualBase)
2492 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002493
Douglas Gregor1b303932009-12-22 15:35:07 +00002494 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002495 return Result;
2496}
2497
Douglas Gregor85dabae2009-12-16 01:38:02 +00002498DeclarationName InitializedEntity::getName() const {
2499 switch (getKind()) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002500 case EK_Parameter:
2501 case EK_Parameter_CF_Audited: {
John McCall31168b02011-06-15 23:02:42 +00002502 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2503 return (D ? D->getDeclName() : DeclarationName());
2504 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002505
2506 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002507 case EK_Member:
2508 return VariableOrMember->getDeclName();
2509
Douglas Gregor19666fb2012-02-15 16:57:26 +00002510 case EK_LambdaCapture:
2511 return Capture.Var->getDeclName();
2512
Douglas Gregor85dabae2009-12-16 01:38:02 +00002513 case EK_Result:
2514 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002515 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002516 case EK_Temporary:
2517 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002518 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002519 case EK_ArrayElement:
2520 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002521 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002522 case EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002523 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002524 case EK_RelatedResult:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002525 return DeclarationName();
2526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002527
David Blaikie8a40f702012-01-17 06:56:22 +00002528 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor85dabae2009-12-16 01:38:02 +00002529}
2530
Douglas Gregora4b592a2009-12-19 03:01:41 +00002531DeclaratorDecl *InitializedEntity::getDecl() const {
2532 switch (getKind()) {
2533 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002534 case EK_Member:
2535 return VariableOrMember;
2536
John McCall31168b02011-06-15 23:02:42 +00002537 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002538 case EK_Parameter_CF_Audited:
John McCall31168b02011-06-15 23:02:42 +00002539 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2540
Douglas Gregora4b592a2009-12-19 03:01:41 +00002541 case EK_Result:
2542 case EK_Exception:
2543 case EK_New:
2544 case EK_Temporary:
2545 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002546 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002547 case EK_ArrayElement:
2548 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002549 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002550 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002551 case EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002552 case EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002553 case EK_RelatedResult:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002554 return 0;
2555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556
David Blaikie8a40f702012-01-17 06:56:22 +00002557 llvm_unreachable("Invalid EntityKind!");
Douglas Gregora4b592a2009-12-19 03:01:41 +00002558}
2559
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002560bool InitializedEntity::allowsNRVO() const {
2561 switch (getKind()) {
2562 case EK_Result:
2563 case EK_Exception:
2564 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002566 case EK_Variable:
2567 case EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002568 case EK_Parameter_CF_Audited:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002569 case EK_Member:
2570 case EK_New:
2571 case EK_Temporary:
Jordan Rose6c0505e2013-05-06 16:48:12 +00002572 case EK_CompoundLiteralInit:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002573 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002574 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002575 case EK_ArrayElement:
2576 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002577 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002578 case EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00002579 case EK_LambdaCapture:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002580 case EK_RelatedResult:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002581 break;
2582 }
2583
2584 return false;
2585}
2586
Richard Smithe6c01442013-06-05 00:46:14 +00002587unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smithe3b28bc2013-06-12 21:51:50 +00002588 assert(getParent() != this);
Richard Smithe6c01442013-06-05 00:46:14 +00002589 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2590 for (unsigned I = 0; I != Depth; ++I)
2591 OS << "`-";
2592
2593 switch (getKind()) {
2594 case EK_Variable: OS << "Variable"; break;
2595 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002596 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2597 break;
Richard Smithe6c01442013-06-05 00:46:14 +00002598 case EK_Result: OS << "Result"; break;
2599 case EK_Exception: OS << "Exception"; break;
2600 case EK_Member: OS << "Member"; break;
2601 case EK_New: OS << "New"; break;
2602 case EK_Temporary: OS << "Temporary"; break;
2603 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00002604 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smithe6c01442013-06-05 00:46:14 +00002605 case EK_Base: OS << "Base"; break;
2606 case EK_Delegating: OS << "Delegating"; break;
2607 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2608 case EK_VectorElement: OS << "VectorElement " << Index; break;
2609 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2610 case EK_BlockElement: OS << "Block"; break;
2611 case EK_LambdaCapture:
2612 OS << "LambdaCapture ";
2613 getCapturedVar()->printName(OS);
2614 break;
2615 }
2616
2617 if (Decl *D = getDecl()) {
2618 OS << " ";
2619 cast<NamedDecl>(D)->printQualifiedName(OS);
2620 }
2621
2622 OS << " '" << getType().getAsString() << "'\n";
2623
2624 return Depth + 1;
2625}
2626
2627void InitializedEntity::dump() const {
2628 dumpImpl(llvm::errs());
2629}
2630
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002631//===----------------------------------------------------------------------===//
2632// Initialization sequence
2633//===----------------------------------------------------------------------===//
2634
2635void InitializationSequence::Step::Destroy() {
2636 switch (Kind) {
2637 case SK_ResolveAddressOfOverloadedFunction:
2638 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002639 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002640 case SK_CastDerivedToBaseLValue:
2641 case SK_BindReference:
2642 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002643 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002644 case SK_UserConversion:
2645 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002646 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002647 case SK_QualificationConversionLValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00002648 case SK_LValueToRValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002649 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002650 case SK_ListConstructorCall:
Sebastian Redl29526f02011-11-27 16:50:07 +00002651 case SK_UnwrapInitList:
2652 case SK_RewrapInitList:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002653 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002654 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002655 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002656 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002657 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002658 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00002659 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002660 case SK_PassByIndirectCopyRestore:
2661 case SK_PassByIndirectRestore:
2662 case SK_ProduceObjCObject:
Sebastian Redlc1839b12012-01-17 22:49:42 +00002663 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00002664 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002665 case SK_OCLZeroEvent:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002666 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002667
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002668 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00002669 case SK_ConversionSequenceNoNarrowing:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002670 delete ICS;
2671 }
2672}
2673
Douglas Gregor838fcc32010-03-26 20:14:36 +00002674bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002675 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002676}
2677
2678bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002679 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002680 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002681
Douglas Gregor838fcc32010-03-26 20:14:36 +00002682 switch (getFailureKind()) {
2683 case FK_TooManyInitsForReference:
2684 case FK_ArrayNeedsInitList:
2685 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00002686 case FK_ArrayNeedsInitListOrWideStringLiteral:
2687 case FK_NarrowStringIntoWideCharArray:
2688 case FK_WideStringIntoCharArray:
2689 case FK_IncompatWideStringIntoWideChar:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002690 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2691 case FK_NonConstLValueReferenceBindingToTemporary:
2692 case FK_NonConstLValueReferenceBindingToUnrelated:
2693 case FK_RValueReferenceBindingToLValue:
2694 case FK_ReferenceInitDropsQualifiers:
2695 case FK_ReferenceInitFailed:
2696 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002697 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002698 case FK_TooManyInitsForScalar:
2699 case FK_ReferenceBindingToInitList:
2700 case FK_InitListBadDestinationType:
2701 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002702 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002703 case FK_ArrayTypeMismatch:
2704 case FK_NonConstantArrayInit:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00002705 case FK_ListInitializationFailed:
John McCalla59dc2f2012-01-05 00:13:19 +00002706 case FK_VariableLengthArrayHasInitializer:
John McCall4124c492011-10-17 18:40:02 +00002707 case FK_PlaceholderType:
Sebastian Redl048a6d72012-04-01 19:54:59 +00002708 case FK_ExplicitConstructor:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002709 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710
Douglas Gregor838fcc32010-03-26 20:14:36 +00002711 case FK_ReferenceInitOverloadFailed:
2712 case FK_UserConversionOverloadFailed:
2713 case FK_ConstructorOverloadFailed:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002714 case FK_ListConstructorOverloadFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002715 return FailedOverloadResult == OR_Ambiguous;
2716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002717
David Blaikie8a40f702012-01-17 06:56:22 +00002718 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor838fcc32010-03-26 20:14:36 +00002719}
2720
Douglas Gregorb33eed02010-04-16 22:09:46 +00002721bool InitializationSequence::isConstructorInitialization() const {
2722 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2723}
2724
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002725void
2726InitializationSequence
2727::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2728 DeclAccessPair Found,
2729 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002730 Step S;
2731 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2732 S.Type = Function->getType();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002733 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002734 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002735 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002736 Steps.push_back(S);
2737}
2738
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002739void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002740 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002741 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002742 switch (VK) {
2743 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2744 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2745 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002746 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002747 S.Type = BaseType;
2748 Steps.push_back(S);
2749}
2750
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002752 bool BindingTemporary) {
2753 Step S;
2754 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2755 S.Type = T;
2756 Steps.push_back(S);
2757}
2758
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002759void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2760 Step S;
2761 S.Kind = SK_ExtraneousCopyToTemporary;
2762 S.Type = T;
2763 Steps.push_back(S);
2764}
2765
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002766void
2767InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2768 DeclAccessPair FoundDecl,
2769 QualType T,
2770 bool HadMultipleCandidates) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002771 Step S;
2772 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002773 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002774 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002775 S.Function.Function = Function;
2776 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002777 Steps.push_back(S);
2778}
2779
2780void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002781 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002782 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002783 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002784 switch (VK) {
2785 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002786 S.Kind = SK_QualificationConversionRValue;
2787 break;
John McCall2536c6d2010-08-25 10:28:54 +00002788 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002789 S.Kind = SK_QualificationConversionXValue;
2790 break;
John McCall2536c6d2010-08-25 10:28:54 +00002791 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002792 S.Kind = SK_QualificationConversionLValue;
2793 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002794 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002795 S.Type = Ty;
2796 Steps.push_back(S);
2797}
2798
Jordan Roseb1312a52013-04-11 00:58:58 +00002799void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2800 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2801
2802 Step S;
2803 S.Kind = SK_LValueToRValue;
2804 S.Type = Ty;
2805 Steps.push_back(S);
2806}
2807
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002808void InitializationSequence::AddConversionSequenceStep(
Richard Smithaaa0ec42013-09-21 21:19:19 +00002809 const ImplicitConversionSequence &ICS, QualType T,
2810 bool TopLevelOfInitList) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002811 Step S;
Richard Smithaaa0ec42013-09-21 21:19:19 +00002812 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2813 : SK_ConversionSequence;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002814 S.Type = T;
2815 S.ICS = new ImplicitConversionSequence(ICS);
2816 Steps.push_back(S);
2817}
2818
Douglas Gregor51e77d52009-12-10 17:56:55 +00002819void InitializationSequence::AddListInitializationStep(QualType T) {
2820 Step S;
2821 S.Kind = SK_ListInitialization;
2822 S.Type = T;
2823 Steps.push_back(S);
2824}
2825
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826void
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002827InitializationSequence
2828::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2829 AccessSpecifier Access,
2830 QualType T,
Sebastian Redled2e5322011-12-22 14:44:04 +00002831 bool HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002832 bool FromInitList, bool AsInitList) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002833 Step S;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00002834 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2835 : SK_ConstructorInitialization;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002836 S.Type = T;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00002837 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCalla0296f72010-03-19 07:35:19 +00002838 S.Function.Function = Constructor;
2839 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002840 Steps.push_back(S);
2841}
2842
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002843void InitializationSequence::AddZeroInitializationStep(QualType T) {
2844 Step S;
2845 S.Kind = SK_ZeroInitialization;
2846 S.Type = T;
2847 Steps.push_back(S);
2848}
2849
Douglas Gregore1314a62009-12-18 05:02:21 +00002850void InitializationSequence::AddCAssignmentStep(QualType T) {
2851 Step S;
2852 S.Kind = SK_CAssignment;
2853 S.Type = T;
2854 Steps.push_back(S);
2855}
2856
Eli Friedman78275202009-12-19 08:11:05 +00002857void InitializationSequence::AddStringInitStep(QualType T) {
2858 Step S;
2859 S.Kind = SK_StringInit;
2860 S.Type = T;
2861 Steps.push_back(S);
2862}
2863
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002864void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2865 Step S;
2866 S.Kind = SK_ObjCObjectConversion;
2867 S.Type = T;
2868 Steps.push_back(S);
2869}
2870
Douglas Gregore2f943b2011-02-22 18:29:51 +00002871void InitializationSequence::AddArrayInitStep(QualType T) {
2872 Step S;
2873 S.Kind = SK_ArrayInit;
2874 S.Type = T;
2875 Steps.push_back(S);
2876}
2877
Richard Smithebeed412012-02-15 22:38:09 +00002878void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2879 Step S;
2880 S.Kind = SK_ParenthesizedArrayInit;
2881 S.Type = T;
2882 Steps.push_back(S);
2883}
2884
John McCall31168b02011-06-15 23:02:42 +00002885void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2886 bool shouldCopy) {
2887 Step s;
2888 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2889 : SK_PassByIndirectRestore);
2890 s.Type = type;
2891 Steps.push_back(s);
2892}
2893
2894void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2895 Step S;
2896 S.Kind = SK_ProduceObjCObject;
2897 S.Type = T;
2898 Steps.push_back(S);
2899}
2900
Sebastian Redlc1839b12012-01-17 22:49:42 +00002901void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2902 Step S;
2903 S.Kind = SK_StdInitializerList;
2904 S.Type = T;
2905 Steps.push_back(S);
2906}
2907
Guy Benyei61054192013-02-07 10:55:47 +00002908void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2909 Step S;
2910 S.Kind = SK_OCLSamplerInit;
2911 S.Type = T;
2912 Steps.push_back(S);
2913}
2914
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002915void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2916 Step S;
2917 S.Kind = SK_OCLZeroEvent;
2918 S.Type = T;
2919 Steps.push_back(S);
2920}
2921
Sebastian Redl29526f02011-11-27 16:50:07 +00002922void InitializationSequence::RewrapReferenceInitList(QualType T,
2923 InitListExpr *Syntactic) {
2924 assert(Syntactic->getNumInits() == 1 &&
2925 "Can only rewrap trivial init lists.");
2926 Step S;
2927 S.Kind = SK_UnwrapInitList;
2928 S.Type = Syntactic->getInit(0)->getType();
2929 Steps.insert(Steps.begin(), S);
2930
2931 S.Kind = SK_RewrapInitList;
2932 S.Type = T;
2933 S.WrappingSyntacticList = Syntactic;
2934 Steps.push_back(S);
2935}
2936
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002937void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002938 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002939 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002940 this->Failure = Failure;
2941 this->FailedOverloadResult = Result;
2942}
2943
2944//===----------------------------------------------------------------------===//
2945// Attempt initialization
2946//===----------------------------------------------------------------------===//
2947
John McCall31168b02011-06-15 23:02:42 +00002948static void MaybeProduceObjCObject(Sema &S,
2949 InitializationSequence &Sequence,
2950 const InitializedEntity &Entity) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002951 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCall31168b02011-06-15 23:02:42 +00002952
2953 /// When initializing a parameter, produce the value if it's marked
2954 /// __attribute__((ns_consumed)).
Fariborz Jahanian131996b2013-07-31 18:21:45 +00002955 if (Entity.isParameterKind()) {
John McCall31168b02011-06-15 23:02:42 +00002956 if (!Entity.isParameterConsumed())
2957 return;
2958
2959 assert(Entity.getType()->isObjCRetainableType() &&
2960 "consuming an object of unretainable type?");
2961 Sequence.AddProduceObjCObjectStep(Entity.getType());
2962
2963 /// When initializing a return value, if the return type is a
2964 /// retainable type, then returns need to immediately retain the
2965 /// object. If an autorelease is required, it will be done at the
2966 /// last instant.
2967 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2968 if (!Entity.getType()->isObjCRetainableType())
2969 return;
2970
2971 Sequence.AddProduceObjCObjectStep(Entity.getType());
2972 }
2973}
2974
Richard Smithcc1b96d2013-06-12 22:31:48 +00002975static void TryListInitialization(Sema &S,
2976 const InitializedEntity &Entity,
2977 const InitializationKind &Kind,
2978 InitListExpr *InitList,
2979 InitializationSequence &Sequence);
2980
Richard Smithd86812d2012-07-05 08:39:21 +00002981/// \brief When initializing from init list via constructor, handle
2982/// initialization of an object of type std::initializer_list<T>.
Sebastian Redled2e5322011-12-22 14:44:04 +00002983///
Richard Smithd86812d2012-07-05 08:39:21 +00002984/// \return true if we have handled initialization of an object of type
2985/// std::initializer_list<T>, false otherwise.
2986static bool TryInitializerListConstruction(Sema &S,
2987 InitListExpr *List,
2988 QualType DestType,
2989 InitializationSequence &Sequence) {
2990 QualType E;
2991 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1bfe0682012-02-14 21:14:13 +00002992 return false;
2993
Richard Smithcc1b96d2013-06-12 22:31:48 +00002994 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2995 Sequence.setIncompleteTypeFailure(E);
2996 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00002997 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00002998
2999 // Try initializing a temporary array from the init list.
3000 QualType ArrayType = S.Context.getConstantArrayType(
3001 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3002 List->getNumInits()),
3003 clang::ArrayType::Normal, 0);
3004 InitializedEntity HiddenArray =
3005 InitializedEntity::InitializeTemporary(ArrayType);
3006 InitializationKind Kind =
3007 InitializationKind::CreateDirectList(List->getExprLoc());
3008 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3009 if (Sequence)
3010 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithd86812d2012-07-05 08:39:21 +00003011 return true;
Sebastian Redled2e5322011-12-22 14:44:04 +00003012}
3013
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003014static OverloadingResult
3015ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003016 MultiExprArg Args,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003017 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003018 ArrayRef<NamedDecl *> Ctors,
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003019 OverloadCandidateSet::iterator &Best,
3020 bool CopyInitializing, bool AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003021 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003022 CandidateSet.clear();
3023
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003024 for (ArrayRef<NamedDecl *>::iterator
3025 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003026 NamedDecl *D = *Con;
3027 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3028 bool SuppressUserConversions = false;
3029
3030 // Find the constructor (which may be a template).
3031 CXXConstructorDecl *Constructor = 0;
3032 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3033 if (ConstructorTmpl)
3034 Constructor = cast<CXXConstructorDecl>(
3035 ConstructorTmpl->getTemplatedDecl());
3036 else {
3037 Constructor = cast<CXXConstructorDecl>(D);
3038
Richard Smith6c6ddab2013-09-21 21:23:47 +00003039 // C++11 [over.best.ics]p4:
3040 // However, when considering the argument of a constructor or
3041 // user-defined conversion function that is a candidate:
3042 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3043 // in the second step of a class copy-initialization,
3044 // -- by 13.3.1.7 when passing the initializer list as a single
3045 // argument or when the initializer list has exactly one elementand
3046 // a conversion to some class X or reference to (possibly
3047 // cv-qualified) X is considered for the first parameter of a
3048 // constructor of X, or
3049 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3050 // only standard conversion sequences and ellipsis conversion sequences
3051 // are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003052 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003053 Constructor->isCopyOrMoveConstructor())
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003054 SuppressUserConversions = true;
3055 }
3056
3057 if (!Constructor->isInvalidDecl() &&
3058 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003059 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003060 if (ConstructorTmpl)
3061 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003062 /*ExplicitArgs*/ 0, Args,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003063 CandidateSet, SuppressUserConversions);
Douglas Gregor6073dca2012-02-24 23:56:31 +00003064 else {
3065 // C++ [over.match.copy]p1:
3066 // - When initializing a temporary to be bound to the first parameter
3067 // of a constructor that takes a reference to possibly cv-qualified
3068 // T as its first argument, called with a single argument in the
3069 // context of direct-initialization, explicit conversion functions
3070 // are also considered.
3071 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003072 Args.size() == 1 &&
Douglas Gregor6073dca2012-02-24 23:56:31 +00003073 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003074 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003075 SuppressUserConversions,
3076 /*PartialOverloading=*/false,
3077 /*AllowExplicit=*/AllowExplicitConv);
3078 }
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003079 }
3080 }
3081
3082 // Perform overload resolution and return the result.
3083 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3084}
3085
Sebastian Redled2e5322011-12-22 14:44:04 +00003086/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3087/// enumerates the constructors of the initialized entity and performs overload
3088/// resolution to select the best.
Sebastian Redl88e4d492012-02-04 21:27:33 +00003089/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redled2e5322011-12-22 14:44:04 +00003090/// class type.
3091static void TryConstructorInitialization(Sema &S,
3092 const InitializedEntity &Entity,
3093 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003094 MultiExprArg Args, QualType DestType,
Sebastian Redled2e5322011-12-22 14:44:04 +00003095 InitializationSequence &Sequence,
Sebastian Redl88e4d492012-02-04 21:27:33 +00003096 bool InitListSyntax = false) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003097 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl88e4d492012-02-04 21:27:33 +00003098 "InitListSyntax must come with a single initializer list argument.");
3099
Sebastian Redled2e5322011-12-22 14:44:04 +00003100 // The type we're constructing needs to be complete.
3101 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003102 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003103 return;
Sebastian Redled2e5322011-12-22 14:44:04 +00003104 }
3105
3106 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3107 assert(DestRecordType && "Constructor initialization requires record type");
3108 CXXRecordDecl *DestRecordDecl
3109 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3110
Sebastian Redlab3f7a42012-02-04 21:27:39 +00003111 // Build the candidate set directly in the initialization sequence
3112 // structure, so that it will persist if we fail.
3113 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3114
3115 // Determine whether we are allowed to call explicit constructors or
3116 // explicit conversion operators.
Sebastian Redl048a6d72012-04-01 19:54:59 +00003117 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003118 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl88e4d492012-02-04 21:27:33 +00003119
Sebastian Redled2e5322011-12-22 14:44:04 +00003120 // - Otherwise, if T is a class type, constructors are considered. The
3121 // applicable constructors are enumerated, and the best one is chosen
3122 // through overload resolution.
David Blaikieff7d47a2012-12-19 00:45:41 +00003123 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003124 // The container holding the constructors can under certain conditions
3125 // be changed while iterating (e.g. because of deserialization).
3126 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003127 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redled2e5322011-12-22 14:44:04 +00003128
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003129 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redled2e5322011-12-22 14:44:04 +00003130 OverloadCandidateSet::iterator Best;
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003131 bool AsInitializerList = false;
3132
3133 // C++11 [over.match.list]p1:
3134 // When objects of non-aggregate type T are list-initialized, overload
3135 // resolution selects the constructor in two phases:
3136 // - Initially, the candidate functions are the initializer-list
3137 // constructors of the class T and the argument list consists of the
3138 // initializer list as a single argument.
3139 if (InitListSyntax) {
Richard Smithd86812d2012-07-05 08:39:21 +00003140 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003141 AsInitializerList = true;
Richard Smithd86812d2012-07-05 08:39:21 +00003142
3143 // If the initializer list has no elements and T has a default constructor,
3144 // the first phase is omitted.
Richard Smith2be35f52012-12-01 02:35:44 +00003145 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003146 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003147 CandidateSet, Ctors, Best,
Richard Smithd86812d2012-07-05 08:39:21 +00003148 CopyInitialization, AllowExplicit,
3149 /*OnlyListConstructor=*/true,
3150 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003151
3152 // Time to unwrap the init list.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003153 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003154 }
3155
3156 // C++11 [over.match.list]p1:
3157 // - If no viable initializer-list constructor is found, overload resolution
3158 // is performed again, where the candidate functions are all the
Richard Smithd86812d2012-07-05 08:39:21 +00003159 // constructors of the class T and the argument list consists of the
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003160 // elements of the initializer list.
3161 if (Result == OR_No_Viable_Function) {
3162 AsInitializerList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003163 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003164 CandidateSet, Ctors, Best,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003165 CopyInitialization, AllowExplicit,
Sebastian Redlc7b718e2012-02-29 12:47:43 +00003166 /*OnlyListConstructors=*/false,
3167 InitListSyntax);
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003168 }
3169 if (Result) {
Sebastian Redl88e4d492012-02-04 21:27:33 +00003170 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003171 InitializationSequence::FK_ListConstructorOverloadFailed :
3172 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redled2e5322011-12-22 14:44:04 +00003173 Result);
3174 return;
3175 }
3176
Richard Smithd86812d2012-07-05 08:39:21 +00003177 // C++11 [dcl.init]p6:
Sebastian Redled2e5322011-12-22 14:44:04 +00003178 // If a program calls for the default initialization of an object
3179 // of a const-qualified type T, T shall be a class type with a
3180 // user-provided default constructor.
3181 if (Kind.getKind() == InitializationKind::IK_Default &&
3182 Entity.getType().isConstQualified() &&
Aaron Ballman899b9c62012-07-31 22:40:31 +00003183 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redled2e5322011-12-22 14:44:04 +00003184 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3185 return;
3186 }
3187
Sebastian Redl048a6d72012-04-01 19:54:59 +00003188 // C++11 [over.match.list]p1:
3189 // In copy-list-initialization, if an explicit constructor is chosen, the
3190 // initializer is ill-formed.
3191 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3192 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3193 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3194 return;
3195 }
3196
Sebastian Redled2e5322011-12-22 14:44:04 +00003197 // Add the constructor initialization step. Any cv-qualification conversion is
3198 // subsumed by the initialization.
3199 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redled2e5322011-12-22 14:44:04 +00003200 Sequence.AddConstructorInitializationStep(CtorDecl,
3201 Best->FoundDecl.getAccess(),
3202 DestType, HadMultipleCandidates,
Sebastian Redl860eb7c2012-02-04 21:27:47 +00003203 InitListSyntax, AsInitializerList);
Sebastian Redled2e5322011-12-22 14:44:04 +00003204}
3205
Sebastian Redl29526f02011-11-27 16:50:07 +00003206static bool
3207ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3208 Expr *Initializer,
3209 QualType &SourceType,
3210 QualType &UnqualifiedSourceType,
3211 QualType UnqualifiedTargetType,
3212 InitializationSequence &Sequence) {
3213 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3214 S.Context.OverloadTy) {
3215 DeclAccessPair Found;
3216 bool HadMultipleCandidates = false;
3217 if (FunctionDecl *Fn
3218 = S.ResolveAddressOfOverloadedFunction(Initializer,
3219 UnqualifiedTargetType,
3220 false, Found,
3221 &HadMultipleCandidates)) {
3222 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3223 HadMultipleCandidates);
3224 SourceType = Fn->getType();
3225 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3226 } else if (!UnqualifiedTargetType->isRecordType()) {
3227 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3228 return true;
3229 }
3230 }
3231 return false;
3232}
3233
3234static void TryReferenceInitializationCore(Sema &S,
3235 const InitializedEntity &Entity,
3236 const InitializationKind &Kind,
3237 Expr *Initializer,
3238 QualType cv1T1, QualType T1,
3239 Qualifiers T1Quals,
3240 QualType cv2T2, QualType T2,
3241 Qualifiers T2Quals,
3242 InitializationSequence &Sequence);
3243
Richard Smithd86812d2012-07-05 08:39:21 +00003244static void TryValueInitialization(Sema &S,
3245 const InitializedEntity &Entity,
3246 const InitializationKind &Kind,
3247 InitializationSequence &Sequence,
3248 InitListExpr *InitList = 0);
3249
Sebastian Redl29526f02011-11-27 16:50:07 +00003250/// \brief Attempt list initialization of a reference.
3251static void TryReferenceListInitialization(Sema &S,
3252 const InitializedEntity &Entity,
3253 const InitializationKind &Kind,
3254 InitListExpr *InitList,
Richard Smithfaadef72013-06-08 00:02:08 +00003255 InitializationSequence &Sequence) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003256 // First, catch C++03 where this isn't possible.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003257 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003258 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3259 return;
3260 }
3261
3262 QualType DestType = Entity.getType();
3263 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3264 Qualifiers T1Quals;
3265 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3266
3267 // Reference initialization via an initializer list works thus:
3268 // If the initializer list consists of a single element that is
3269 // reference-related to the referenced type, bind directly to that element
3270 // (possibly creating temporaries).
3271 // Otherwise, initialize a temporary with the initializer list and
3272 // bind to that.
3273 if (InitList->getNumInits() == 1) {
3274 Expr *Initializer = InitList->getInit(0);
3275 QualType cv2T2 = Initializer->getType();
3276 Qualifiers T2Quals;
3277 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3278
3279 // If this fails, creating a temporary wouldn't work either.
3280 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3281 T1, Sequence))
3282 return;
3283
3284 SourceLocation DeclLoc = Initializer->getLocStart();
3285 bool dummy1, dummy2, dummy3;
3286 Sema::ReferenceCompareResult RefRelationship
3287 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3288 dummy2, dummy3);
3289 if (RefRelationship >= Sema::Ref_Related) {
3290 // Try to bind the reference here.
3291 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3292 T1Quals, cv2T2, T2, T2Quals, Sequence);
3293 if (Sequence)
3294 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3295 return;
3296 }
Richard Smith03d93932013-01-15 07:58:29 +00003297
3298 // Update the initializer if we've resolved an overloaded function.
3299 if (Sequence.step_begin() != Sequence.step_end())
3300 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl29526f02011-11-27 16:50:07 +00003301 }
3302
3303 // Not reference-related. Create a temporary and bind to that.
3304 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3305
3306 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3307 if (Sequence) {
3308 if (DestType->isRValueReferenceType() ||
3309 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3310 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3311 else
3312 Sequence.SetFailed(
3313 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3314 }
3315}
3316
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003317/// \brief Attempt list initialization (C++0x [dcl.init.list])
3318static void TryListInitialization(Sema &S,
3319 const InitializedEntity &Entity,
3320 const InitializationKind &Kind,
3321 InitListExpr *InitList,
3322 InitializationSequence &Sequence) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003323 QualType DestType = Entity.getType();
3324
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003325 // C++ doesn't allow scalar initialization with more than one argument.
3326 // But C99 complex numbers are scalars and it makes sense there.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003327 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003328 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3329 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3330 return;
3331 }
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003332 if (DestType->isReferenceType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00003333 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003334 return;
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003335 }
Sebastian Redl4f28b582012-02-19 12:27:43 +00003336 if (DestType->isRecordType()) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003337 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor85f34232012-04-10 20:43:46 +00003338 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003339 return;
3340 }
3341
Richard Smithd86812d2012-07-05 08:39:21 +00003342 // C++11 [dcl.init.list]p3:
3343 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redl4f28b582012-02-19 12:27:43 +00003344 if (!DestType->isAggregateType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003345 if (S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003346 // - Otherwise, if the initializer list has no elements and T is a
3347 // class type with a default constructor, the object is
3348 // value-initialized.
3349 if (InitList->getNumInits() == 0) {
3350 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smith2be35f52012-12-01 02:35:44 +00003351 if (RD->hasDefaultConstructor()) {
Richard Smithd86812d2012-07-05 08:39:21 +00003352 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3353 return;
3354 }
3355 }
3356
3357 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3358 // an initializer_list object constructed [...]
3359 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3360 return;
3361
3362 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003363 Expr *InitListAsExpr = InitList;
3364 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithd86812d2012-07-05 08:39:21 +00003365 Sequence, /*InitListSyntax*/true);
Sebastian Redl4f28b582012-02-19 12:27:43 +00003366 } else
3367 Sequence.SetFailed(
3368 InitializationSequence::FK_InitListBadDestinationType);
3369 return;
3370 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003371 }
Richard Smith089c3162013-09-21 21:55:46 +00003372 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3373 InitList->getNumInits() == 1 &&
3374 InitList->getInit(0)->getType()->isRecordType()) {
3375 // - Otherwise, if the initializer list has a single element of type E
3376 // [...references are handled above...], the object or reference is
3377 // initialized from that element; if a narrowing conversion is required
3378 // to convert the element to T, the program is ill-formed.
3379 //
3380 // Per core-24034, this is direct-initialization if we were performing
3381 // direct-list-initialization and copy-initialization otherwise.
3382 // We can't use InitListChecker for this, because it always performs
3383 // copy-initialization. This only matters if we might use an 'explicit'
3384 // conversion operator, so we only need to handle the cases where the source
3385 // is of record type.
3386 InitializationKind SubKind =
3387 Kind.getKind() == InitializationKind::IK_DirectList
3388 ? InitializationKind::CreateDirect(Kind.getLocation(),
3389 InitList->getLBraceLoc(),
3390 InitList->getRBraceLoc())
3391 : Kind;
3392 Expr *SubInit[1] = { InitList->getInit(0) };
3393 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3394 /*TopLevelOfInitList*/true);
3395 if (Sequence)
3396 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3397 return;
3398 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003399
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003400 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00003401 DestType, /*VerifyOnly=*/true);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00003402 if (CheckInitList.HadError()) {
3403 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3404 return;
3405 }
3406
3407 // Add the list initialization step with the built init list.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003408 Sequence.AddListInitializationStep(DestType);
3409}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003410
3411/// \brief Try a reference initialization that involves calling a conversion
3412/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003413static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3414 const InitializedEntity &Entity,
3415 const InitializationKind &Kind,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003416 Expr *Initializer,
3417 bool AllowRValues,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003418 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003419 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003420 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3421 QualType T1 = cv1T1.getUnqualifiedType();
3422 QualType cv2T2 = Initializer->getType();
3423 QualType T2 = cv2T2.getUnqualifiedType();
3424
3425 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003426 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003427 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003429 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003430 ObjCConversion,
3431 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003432 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00003433 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003434 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00003435 (void)ObjCLifetimeConversion;
3436
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003437 // Build the candidate set directly in the initialization sequence
3438 // structure, so that it will persist if we fail.
3439 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3440 CandidateSet.clear();
3441
3442 // Determine whether we are allowed to call explicit constructors or
3443 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00003444 bool AllowExplicit = Kind.AllowExplicit();
Richard Smith6c6ddab2013-09-21 21:23:47 +00003445 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3446
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003447 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00003448 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3449 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003450 // The type we're converting to is a class type. Enumerate its constructors
3451 // to see if there is a suitable conversion.
3452 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00003453
David Blaikieff7d47a2012-12-19 00:45:41 +00003454 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003455 // The container holding the constructors can under certain conditions
3456 // be changed while iterating (e.g. because of deserialization).
3457 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00003458 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00003459 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00003460 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3461 NamedDecl *D = *CI;
John McCalla0296f72010-03-19 07:35:19 +00003462 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3463
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003464 // Find the constructor (which may be a template).
3465 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003466 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467 if (ConstructorTmpl)
3468 Constructor = cast<CXXConstructorDecl>(
3469 ConstructorTmpl->getTemplatedDecl());
3470 else
John McCalla0296f72010-03-19 07:35:19 +00003471 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003473 if (!Constructor->isInvalidDecl() &&
3474 Constructor->isConvertingConstructor(AllowExplicit)) {
3475 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003476 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003477 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003478 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003479 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003480 else
John McCalla0296f72010-03-19 07:35:19 +00003481 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003482 Initializer, CandidateSet,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00003483 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003486 }
John McCall3696dcb2010-08-17 07:23:57 +00003487 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3488 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489
Douglas Gregor496e8b342010-05-07 19:42:26 +00003490 const RecordType *T2RecordType = 0;
3491 if ((T2RecordType = T2->getAs<RecordType>()) &&
3492 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003493 // The type we're converting from is a class type, enumerate its conversion
3494 // functions.
3495 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3496
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003497 std::pair<CXXRecordDecl::conversion_iterator,
3498 CXXRecordDecl::conversion_iterator>
3499 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3500 for (CXXRecordDecl::conversion_iterator
3501 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003502 NamedDecl *D = *I;
3503 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3504 if (isa<UsingShadowDecl>(D))
3505 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003507 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3508 CXXConversionDecl *Conv;
3509 if (ConvTemplate)
3510 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3511 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003512 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003514 // If the conversion function doesn't return a reference type,
3515 // it can't be considered for this conversion unless we're allowed to
3516 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517 // FIXME: Do we need to make sure that we only consider conversion
3518 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003519 // break recursion.
Douglas Gregor6073dca2012-02-24 23:56:31 +00003520 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003521 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3522 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003523 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003524 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00003525 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003526 else
John McCalla0296f72010-03-19 07:35:19 +00003527 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00003528 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003529 }
3530 }
3531 }
John McCall3696dcb2010-08-17 07:23:57 +00003532 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3533 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003535 SourceLocation DeclLoc = Initializer->getLocStart();
3536
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003540 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003541 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003542
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003544 // This is the overload that will be used for this initialization step if we
3545 // use this initialization. Mark it as referenced.
3546 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003547
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003548 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003549 if (isa<CXXConversionDecl>(Function))
3550 T2 = Function->getResultType();
3551 else
3552 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003553
3554 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003555 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003556 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003557 T2.getNonLValueExprType(S.Context),
3558 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003559
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003561 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003562 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003563 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003564 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003565 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003566 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003567
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003568 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003569 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003570 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003571 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003573 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003574 NewDerivedToBase, NewObjCConversion,
3575 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003576 if (NewRefRelationship == Sema::Ref_Incompatible) {
3577 // If the type we've converted to is not reference-related to the
3578 // type we're looking for, then there is another conversion step
3579 // we need to perform to produce a temporary of the right type
3580 // that we'll be binding to.
3581 ImplicitConversionSequence ICS;
3582 ICS.setStandard();
3583 ICS.Standard = Best->FinalConversion;
3584 T2 = ICS.Standard.getToType(2);
3585 Sequence.AddConversionSequenceStep(ICS, T2);
3586 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003587 Sequence.AddDerivedToBaseCastStep(
3588 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003589 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003590 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003591 else if (NewObjCConversion)
3592 Sequence.AddObjCObjectConversionStep(
3593 S.Context.getQualifiedType(T1,
3594 T2.getNonReferenceType().getQualifiers()));
3595
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003596 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003597 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003598
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003599 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3600 return OR_Success;
3601}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Richard Smithc620f552011-10-19 16:55:56 +00003603static void CheckCXX98CompatAccessibleCopy(Sema &S,
3604 const InitializedEntity &Entity,
3605 Expr *CurInitExpr);
3606
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3608static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003609 const InitializedEntity &Entity,
3610 const InitializationKind &Kind,
3611 Expr *Initializer,
3612 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003613 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003614 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003615 Qualifiers T1Quals;
3616 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003618 Qualifiers T2Quals;
3619 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003620
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 // If the initializer is the address of an overloaded function, try
3622 // to resolve the overloaded function. If all goes well, T2 is the
3623 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003624 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3625 T1, Sequence))
3626 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003627
Sebastian Redl29526f02011-11-27 16:50:07 +00003628 // Delegate everything else to a subfunction.
3629 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3630 T1Quals, cv2T2, T2, T2Quals, Sequence);
3631}
3632
Jordan Roseb1312a52013-04-11 00:58:58 +00003633/// Converts the target of reference initialization so that it has the
3634/// appropriate qualifiers and value kind.
3635///
3636/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3637/// \code
3638/// int x;
3639/// const int &r = x;
3640/// \endcode
3641///
3642/// In this case the reference is binding to a bitfield lvalue, which isn't
3643/// valid. Perform a load to create a lifetime-extended temporary instead.
3644/// \code
3645/// const int &r = someStruct.bitfield;
3646/// \endcode
3647static ExprValueKind
3648convertQualifiersAndValueKindIfNecessary(Sema &S,
3649 InitializationSequence &Sequence,
3650 Expr *Initializer,
3651 QualType cv1T1,
3652 Qualifiers T1Quals,
3653 Qualifiers T2Quals,
3654 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003655 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003656 Initializer->refersToVectorElement();
3657
3658 if (IsNonAddressableType) {
3659 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3660 // lvalue reference to a non-volatile const type, or the reference shall be
3661 // an rvalue reference.
3662 //
3663 // If not, we can't make a temporary and bind to that. Give up and allow the
3664 // error to be diagnosed later.
3665 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3666 assert(Initializer->isGLValue());
3667 return Initializer->getValueKind();
3668 }
3669
3670 // Force a load so we can materialize a temporary.
3671 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3672 return VK_RValue;
3673 }
3674
3675 if (T1Quals != T2Quals) {
3676 Sequence.AddQualificationConversionStep(cv1T1,
3677 Initializer->getValueKind());
3678 }
3679
3680 return Initializer->getValueKind();
3681}
3682
3683
Sebastian Redl29526f02011-11-27 16:50:07 +00003684/// \brief Reference initialization without resolving overloaded functions.
3685static void TryReferenceInitializationCore(Sema &S,
3686 const InitializedEntity &Entity,
3687 const InitializationKind &Kind,
3688 Expr *Initializer,
3689 QualType cv1T1, QualType T1,
3690 Qualifiers T1Quals,
3691 QualType cv2T2, QualType T2,
3692 Qualifiers T2Quals,
3693 InitializationSequence &Sequence) {
3694 QualType DestType = Entity.getType();
3695 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003696 // Compute some basic properties of the types and the initializer.
3697 bool isLValueRef = DestType->isLValueReferenceType();
3698 bool isRValueRef = !isLValueRef;
3699 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003700 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003701 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003702 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003703 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003704 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003705 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003706
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003707 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003709 // "cv2 T2" as follows:
3710 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003712 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003713 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003714 // there are no function rvalues in C++, rvalue refs to functions are treated
3715 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003716 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003717 bool T1Function = T1->isFunctionType();
3718 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003720 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003722 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003724 // reference-compatible with "cv2 T2," or
3725 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003728 // can occur. However, we do pay attention to whether it is a bit-field
3729 // to decide whether we're actually binding to a temporary created from
3730 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003731 if (DerivedToBase)
3732 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003734 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003735 else if (ObjCConversion)
3736 Sequence.AddObjCObjectConversionStep(
3737 S.Context.getQualifiedType(T1, T2Quals));
3738
Jordan Roseb1312a52013-04-11 00:58:58 +00003739 ExprValueKind ValueKind =
3740 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3741 cv1T1, T1Quals, T2Quals,
3742 isLValueRef);
3743 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003744 return;
3745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
3747 // - has a class type (i.e., T2 is a class type), where T1 is not
3748 // reference-related to T2, and can be implicitly converted to an
3749 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3750 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003751 // applicable conversion functions (13.3.1.6) and choosing the best
3752 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003753 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003754 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003755 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3756 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003757 ConvOvlResult = TryRefInitWithConversionFunction(
3758 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003759 if (ConvOvlResult == OR_Success)
3760 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003761 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003762 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003763 InitializationSequence::FK_ReferenceInitOverloadFailed,
3764 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003765 }
3766 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003767
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003769 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003770 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003771 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003772 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3773 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3774 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003775 Sequence.SetOverloadFailure(
3776 InitializationSequence::FK_ReferenceInitOverloadFailed,
3777 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003778 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003779 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003780 ? (RefRelationship == Sema::Ref_Related
3781 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3782 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3783 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003784
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003785 return;
3786 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003787
Douglas Gregor92e460e2011-01-20 16:44:54 +00003788 // - If the initializer expression
3789 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3790 // "cv1 T1" is reference-compatible with "cv2 T2"
3791 // Note: functions are handled below.
3792 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003793 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003795 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003796 (InitCategory.isXValue() ||
3797 (InitCategory.isPRValue() && T2->isRecordType()) ||
3798 (InitCategory.isPRValue() && T2->isArrayType()))) {
3799 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3800 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003801 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3802 // compiler the freedom to perform a copy here or bind to the
3803 // object, while C++0x requires that we bind directly to the
3804 // object. Hence, we always bind to the object without making an
3805 // extra copy. However, in C++03 requires that we check for the
3806 // presence of a suitable copy constructor:
3807 //
3808 // The constructor that would be used to make the copy shall
3809 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003810 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003811 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003812 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003813 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815
Douglas Gregor92e460e2011-01-20 16:44:54 +00003816 if (DerivedToBase)
3817 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3818 ValueKind);
3819 else if (ObjCConversion)
3820 Sequence.AddObjCObjectConversionStep(
3821 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Jordan Roseb1312a52013-04-11 00:58:58 +00003823 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3824 Initializer, cv1T1,
3825 T1Quals, T2Quals,
3826 isLValueRef);
3827
3828 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003831
3832 // - has a class type (i.e., T2 is a class type), where T1 is not
3833 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003834 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3835 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003836 //
3837 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003838 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003839 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003840 ConvOvlResult = TryRefInitWithConversionFunction(
3841 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003842 if (ConvOvlResult)
3843 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003844 InitializationSequence::FK_ReferenceInitOverloadFailed,
3845 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003847 return;
3848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003850 if ((RefRelationship == Sema::Ref_Compatible ||
3851 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3852 isRValueRef && InitCategory.isLValue()) {
3853 Sequence.SetFailed(
3854 InitializationSequence::FK_RValueReferenceBindingToLValue);
3855 return;
3856 }
3857
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003858 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3859 return;
3860 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003861
3862 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003863 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003864 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003865 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003866
John McCallec6f4e92010-06-04 02:29:22 +00003867 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3868
Richard Smith2eabf782013-06-13 00:57:57 +00003869 // FIXME: Why do we use an implicit conversion here rather than trying
3870 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00003871 ImplicitConversionSequence ICS
3872 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00003873 /*SuppressUserConversions=*/false,
3874 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003875 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003876 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3877 /*AllowObjCWritebackConversion=*/false);
3878
3879 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003880 // FIXME: Use the conversion function set stored in ICS to turn
3881 // this into an overloading ambiguity diagnostic. However, we need
3882 // to keep that set as an OverloadCandidateSet rather than as some
3883 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003884 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3885 Sequence.SetOverloadFailure(
3886 InitializationSequence::FK_ReferenceInitOverloadFailed,
3887 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003888 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3889 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003890 else
3891 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003892 return;
John McCall31168b02011-06-15 23:02:42 +00003893 } else {
3894 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003895 }
3896
3897 // [...] If T1 is reference-related to T2, cv1 must be the
3898 // same cv-qualification as, or greater cv-qualification
3899 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003900 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3901 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003902 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003903 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003904 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3905 return;
3906 }
3907
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003908 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003909 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003911 InitCategory.isLValue()) {
3912 Sequence.SetFailed(
3913 InitializationSequence::FK_RValueReferenceBindingToLValue);
3914 return;
3915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003917 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3918 return;
3919}
3920
3921/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922/// (C++ [dcl.init.string], C99 6.7.8).
3923static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003924 const InitializedEntity &Entity,
3925 const InitializationKind &Kind,
3926 Expr *Initializer,
3927 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003928 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003929}
3930
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003931/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003933 const InitializedEntity &Entity,
3934 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00003935 InitializationSequence &Sequence,
3936 InitListExpr *InitList) {
3937 assert((!InitList || InitList->getNumInits() == 0) &&
3938 "Shouldn't use value-init for non-empty init lists");
3939
Richard Smith1bfe0682012-02-14 21:14:13 +00003940 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003941 //
3942 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003943 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003944
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003945 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003946 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003948 if (const RecordType *RT = T->getAs<RecordType>()) {
3949 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00003950 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003951 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003952 // C++98:
3953 // -- if T is a class type (clause 9) with a user-declared constructor
3954 // (12.1), then the default constructor for T is called (and the
3955 // initialization is ill-formed if T has no accessible default
3956 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003957 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00003958 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003959 } else {
3960 // C++11:
3961 // -- if T is a class type (clause 9) with either no default constructor
3962 // (12.1 [class.ctor]) or a default constructor that is user-provided
3963 // or deleted, then the object is default-initialized;
3964 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3965 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00003966 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968
Richard Smith1bfe0682012-02-14 21:14:13 +00003969 // -- if T is a (possibly cv-qualified) non-union class type without a
3970 // user-provided or deleted default constructor, then the object is
3971 // zero-initialized and, if T has a non-trivial default constructor,
3972 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00003973 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3974 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00003975 if (NeedZeroInitialization)
3976 Sequence.AddZeroInitializationStep(Entity.getType());
3977
Richard Smith593f9932012-12-08 02:01:17 +00003978 // C++03:
3979 // -- if T is a non-union class type without a user-declared constructor,
3980 // then every non-static data member and base class component of T is
3981 // value-initialized;
3982 // [...] A program that calls for [...] value-initialization of an
3983 // entity of reference type is ill-formed.
3984 //
3985 // C++11 doesn't need this handling, because value-initialization does not
3986 // occur recursively there, and the implicit default constructor is
3987 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003988 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00003989 ClassDecl->hasUninitializedReferenceMember()) {
3990 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3991 return;
3992 }
3993
Richard Smithd86812d2012-07-05 08:39:21 +00003994 // If this is list-value-initialization, pass the empty init list on when
3995 // building the constructor call. This affects the semantics of a few
3996 // things (such as whether an explicit default constructor can be called).
3997 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003998 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00003999 bool InitListSyntax = InitList;
4000
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004001 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4002 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004003 }
4004 }
4005
Douglas Gregor1b303932009-12-22 15:35:07 +00004006 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004007}
4008
Douglas Gregor85dabae2009-12-16 01:38:02 +00004009/// \brief Attempt default initialization (C++ [dcl.init]p6).
4010static void TryDefaultInitialization(Sema &S,
4011 const InitializedEntity &Entity,
4012 const InitializationKind &Kind,
4013 InitializationSequence &Sequence) {
4014 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015
Douglas Gregor85dabae2009-12-16 01:38:02 +00004016 // C++ [dcl.init]p6:
4017 // To default-initialize an object of type T means:
4018 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004019 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4020
Douglas Gregor85dabae2009-12-16 01:38:02 +00004021 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4022 // constructor for T is called (and the initialization is ill-formed if
4023 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004024 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004025 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004026 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Douglas Gregor85dabae2009-12-16 01:38:02 +00004029 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030
Douglas Gregor85dabae2009-12-16 01:38:02 +00004031 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004033 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004034 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004035 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004036 return;
4037 }
4038
4039 // If the destination type has a lifetime property, zero-initialize it.
4040 if (DestType.getQualifiers().hasObjCLifetime()) {
4041 Sequence.AddZeroInitializationStep(Entity.getType());
4042 return;
4043 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004044}
4045
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004046/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4047/// which enumerates all conversion functions and performs overload resolution
4048/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004050 const InitializedEntity &Entity,
4051 const InitializationKind &Kind,
4052 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004053 InitializationSequence &Sequence,
4054 bool TopLevelOfInitList) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004055 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004056 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4057 QualType SourceType = Initializer->getType();
4058 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4059 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004060
Douglas Gregor540c3b02009-12-14 17:27:33 +00004061 // Build the candidate set directly in the initialization sequence
4062 // structure, so that it will persist if we fail.
4063 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4064 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065
Douglas Gregor540c3b02009-12-14 17:27:33 +00004066 // Determine whether we are allowed to call explicit constructors or
4067 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004068 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069
Douglas Gregor540c3b02009-12-14 17:27:33 +00004070 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4071 // The type we're converting to is a class type. Enumerate its constructors
4072 // to see if there is a suitable conversion.
4073 CXXRecordDecl *DestRecordDecl
4074 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075
Douglas Gregord9848152010-04-26 14:36:57 +00004076 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004077 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004078 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004079 // The container holding the constructors can under certain conditions
4080 // be changed while iterating. To be safe we copy the lookup results
4081 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004082 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004083 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004084 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004085 Con != ConEnd; ++Con) {
4086 NamedDecl *D = *Con;
4087 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004088
Douglas Gregord9848152010-04-26 14:36:57 +00004089 // Find the constructor (which may be a template).
4090 CXXConstructorDecl *Constructor = 0;
4091 FunctionTemplateDecl *ConstructorTmpl
4092 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004093 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004094 Constructor = cast<CXXConstructorDecl>(
4095 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004096 else
Douglas Gregord9848152010-04-26 14:36:57 +00004097 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098
Douglas Gregord9848152010-04-26 14:36:57 +00004099 if (!Constructor->isInvalidDecl() &&
4100 Constructor->isConvertingConstructor(AllowExplicit)) {
4101 if (ConstructorTmpl)
4102 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4103 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004104 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004105 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004106 else
4107 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004108 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004109 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 }
Douglas Gregord9848152010-04-26 14:36:57 +00004112 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004113 }
Eli Friedman78275202009-12-19 08:11:05 +00004114
4115 SourceLocation DeclLoc = Initializer->getLocStart();
4116
Douglas Gregor540c3b02009-12-14 17:27:33 +00004117 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4118 // The type we're converting from is a class type, enumerate its conversion
4119 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004120
Eli Friedman4afe9a32009-12-20 22:12:03 +00004121 // We can only enumerate the conversion functions for a complete type; if
4122 // the type isn't complete, simply skip this step.
4123 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4124 CXXRecordDecl *SourceRecordDecl
4125 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004126
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004127 std::pair<CXXRecordDecl::conversion_iterator,
4128 CXXRecordDecl::conversion_iterator>
4129 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4130 for (CXXRecordDecl::conversion_iterator
4131 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004132 NamedDecl *D = *I;
4133 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4134 if (isa<UsingShadowDecl>(D))
4135 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136
Eli Friedman4afe9a32009-12-20 22:12:03 +00004137 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4138 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004139 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004140 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004141 else
John McCallda4458e2010-03-31 01:36:47 +00004142 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143
Eli Friedman4afe9a32009-12-20 22:12:03 +00004144 if (AllowExplicit || !Conv->isExplicit()) {
4145 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004146 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004147 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00004148 CandidateSet);
4149 else
John McCalla0296f72010-03-19 07:35:19 +00004150 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00004151 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004152 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004153 }
4154 }
4155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156
4157 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004158 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004159 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004160 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004161 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004162 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004163 Result);
4164 return;
4165 }
John McCall0d1da222010-01-12 00:44:57 +00004166
Douglas Gregor540c3b02009-12-14 17:27:33 +00004167 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004168 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004169 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregor540c3b02009-12-14 17:27:33 +00004171 if (isa<CXXConstructorDecl>(Function)) {
4172 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004173 // subsumed by the initialization. Per DR5, the created temporary is of the
4174 // cv-unqualified type of the destination.
4175 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4176 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004177 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004178 return;
4179 }
4180
4181 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004182 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004183 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004184 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004185 // the resulting temporary object (possible to create an object of
4186 // a base class type). That copy is not a separate conversion, so
4187 // we just make a note of the actual destination type (possibly a
4188 // base class of the type returned by the conversion function) and
4189 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004190 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4191 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004192 return;
4193 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004194
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004195 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4196 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
Douglas Gregor5ab11652010-04-17 22:01:05 +00004198 // If the conversion following the call to the conversion function
4199 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004200 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4201 Best->FinalConversion.Third) {
4202 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004203 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004204 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004205 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004206 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004207}
4208
Richard Smithf032001b2013-06-20 02:18:31 +00004209/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4210/// a function with a pointer return type contains a 'return false;' statement.
4211/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4212/// code using that header.
4213///
4214/// Work around this by treating 'return false;' as zero-initializing the result
4215/// if it's used in a pointer-returning function in a system header.
4216static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4217 const InitializedEntity &Entity,
4218 const Expr *Init) {
4219 return S.getLangOpts().CPlusPlus11 &&
4220 Entity.getKind() == InitializedEntity::EK_Result &&
4221 Entity.getType()->isPointerType() &&
4222 isa<CXXBoolLiteralExpr>(Init) &&
4223 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4224 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4225}
4226
John McCall31168b02011-06-15 23:02:42 +00004227/// The non-zero enum values here are indexes into diagnostic alternatives.
4228enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4229
4230/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004231static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004232 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004233 // Skip parens.
4234 e = e->IgnoreParens();
4235
4236 // Skip address-of nodes.
4237 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4238 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004239 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4240 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004241
4242 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004243 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4244 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004245 case CK_Dependent:
4246 case CK_BitCast:
4247 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004248 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004249 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004250
4251 case CK_ArrayToPointerDecay:
4252 return IIK_nonscalar;
4253
4254 case CK_NullToPointer:
4255 return IIK_okay;
4256
4257 default:
4258 break;
4259 }
4260
4261 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004262 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004263 // set isWeakAccess to true, to mean that there will be an implicit
4264 // load which requires a cleanup.
4265 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4266 isWeakAccess = true;
4267
John McCall63f84442011-06-27 23:59:58 +00004268 if (!isAddressOf) return IIK_nonlocal;
4269
John McCall113bee02012-03-10 09:33:50 +00004270 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4271 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004272
4273 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004274
4275 // If we have a conditional operator, check both sides.
4276 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004277 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4278 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004279 return iik;
4280
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004281 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004282
4283 // These are never scalar.
4284 } else if (isa<ArraySubscriptExpr>(e)) {
4285 return IIK_nonscalar;
4286
4287 // Otherwise, it needs to be a null pointer constant.
4288 } else {
4289 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4290 ? IIK_okay : IIK_nonlocal);
4291 }
4292
4293 return IIK_nonlocal;
4294}
4295
4296/// Check whether the given expression is a valid operand for an
4297/// indirect copy/restore.
4298static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4299 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004300 bool isWeakAccess = false;
4301 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4302 // If isWeakAccess to true, there will be an implicit
4303 // load which requires a cleanup.
4304 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4305 S.ExprNeedsCleanups = true;
4306
John McCall31168b02011-06-15 23:02:42 +00004307 if (iik == IIK_okay) return;
4308
4309 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4310 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4311 << src->getSourceRange();
4312}
4313
Douglas Gregore2f943b2011-02-22 18:29:51 +00004314/// \brief Determine whether we have compatible array types for the
4315/// purposes of GNU by-copy array initialization.
4316static bool hasCompatibleArrayTypes(ASTContext &Context,
4317 const ArrayType *Dest,
4318 const ArrayType *Source) {
4319 // If the source and destination array types are equivalent, we're
4320 // done.
4321 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4322 return true;
4323
4324 // Make sure that the element types are the same.
4325 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4326 return false;
4327
4328 // The only mismatch we allow is when the destination is an
4329 // incomplete array type and the source is a constant array type.
4330 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4331}
4332
John McCall31168b02011-06-15 23:02:42 +00004333static bool tryObjCWritebackConversion(Sema &S,
4334 InitializationSequence &Sequence,
4335 const InitializedEntity &Entity,
4336 Expr *Initializer) {
4337 bool ArrayDecay = false;
4338 QualType ArgType = Initializer->getType();
4339 QualType ArgPointee;
4340 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4341 ArrayDecay = true;
4342 ArgPointee = ArgArrayType->getElementType();
4343 ArgType = S.Context.getPointerType(ArgPointee);
4344 }
4345
4346 // Handle write-back conversion.
4347 QualType ConvertedArgType;
4348 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4349 ConvertedArgType))
4350 return false;
4351
4352 // We should copy unless we're passing to an argument explicitly
4353 // marked 'out'.
4354 bool ShouldCopy = true;
4355 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4356 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4357
4358 // Do we need an lvalue conversion?
4359 if (ArrayDecay || Initializer->isGLValue()) {
4360 ImplicitConversionSequence ICS;
4361 ICS.setStandard();
4362 ICS.Standard.setAsIdentityConversion();
4363
4364 QualType ResultType;
4365 if (ArrayDecay) {
4366 ICS.Standard.First = ICK_Array_To_Pointer;
4367 ResultType = S.Context.getPointerType(ArgPointee);
4368 } else {
4369 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4370 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4371 }
4372
4373 Sequence.AddConversionSequenceStep(ICS, ResultType);
4374 }
4375
4376 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4377 return true;
4378}
4379
Guy Benyei61054192013-02-07 10:55:47 +00004380static bool TryOCLSamplerInitialization(Sema &S,
4381 InitializationSequence &Sequence,
4382 QualType DestType,
4383 Expr *Initializer) {
4384 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4385 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4386 return false;
4387
4388 Sequence.AddOCLSamplerInitStep(DestType);
4389 return true;
4390}
4391
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004392//
4393// OpenCL 1.2 spec, s6.12.10
4394//
4395// The event argument can also be used to associate the
4396// async_work_group_copy with a previous async copy allowing
4397// an event to be shared by multiple async copies; otherwise
4398// event should be zero.
4399//
4400static bool TryOCLZeroEventInitialization(Sema &S,
4401 InitializationSequence &Sequence,
4402 QualType DestType,
4403 Expr *Initializer) {
4404 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4405 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4406 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4407 return false;
4408
4409 Sequence.AddOCLZeroEventStep(DestType);
4410 return true;
4411}
4412
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004413InitializationSequence::InitializationSequence(Sema &S,
4414 const InitializedEntity &Entity,
4415 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004416 MultiExprArg Args,
4417 bool TopLevelOfInitList)
John McCallbc077cf2010-02-08 23:07:23 +00004418 : FailedCandidateSet(Kind.getLocation()) {
Richard Smith089c3162013-09-21 21:55:46 +00004419 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4420}
4421
4422void InitializationSequence::InitializeFrom(Sema &S,
4423 const InitializedEntity &Entity,
4424 const InitializationKind &Kind,
4425 MultiExprArg Args,
4426 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004427 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004428
John McCall5e77d762013-04-16 07:28:30 +00004429 // Eliminate non-overload placeholder types in the arguments. We
4430 // need to do this before checking whether types are dependent
4431 // because lowering a pseudo-object expression might well give us
4432 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004433 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004434 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4435 // FIXME: should we be doing this here?
4436 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4437 if (result.isInvalid()) {
4438 SetFailed(FK_PlaceholderType);
4439 return;
4440 }
4441 Args[I] = result.take();
4442 }
4443
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004444 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445 // The semantics of initializers are as follows. The destination type is
4446 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004447 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004449 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004450 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004451
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004452 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004453 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004454 SequenceKind = DependentSequence;
4455 return;
4456 }
4457
Sebastian Redld201edf2011-06-05 13:59:11 +00004458 // Almost everything is a normal sequence.
4459 setSequenceKind(NormalSequence);
4460
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004461 QualType SourceType;
4462 Expr *Initializer = 0;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004463 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004464 Initializer = Args[0];
4465 if (!isa<InitListExpr>(Initializer))
4466 SourceType = Initializer->getType();
4467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Sebastian Redl0501c632012-02-12 16:37:36 +00004469 // - If the initializer is a (non-parenthesized) braced-init-list, the
4470 // object is list-initialized (8.5.4).
4471 if (Kind.getKind() != InitializationKind::IK_Direct) {
4472 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4473 TryListInitialization(S, Entity, Kind, InitList, *this);
4474 return;
4475 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004478 // - If the destination type is a reference type, see 8.5.3.
4479 if (DestType->isReferenceType()) {
4480 // C++0x [dcl.init.ref]p1:
4481 // A variable declared to be a T& or T&&, that is, "reference to type T"
4482 // (8.3.2), shall be initialized by an object, or function, of type T or
4483 // by an object that can be converted into a T.
4484 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004485 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004486 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004487 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004488 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004489 return;
4490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004492 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004493 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004494 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004495 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004496 return;
4497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregor85dabae2009-12-16 01:38:02 +00004499 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004500 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004501 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004502 return;
4503 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004504
John McCall66884dd2011-02-21 07:22:22 +00004505 // - If the destination type is an array of characters, an array of
4506 // char16_t, an array of char32_t, or an array of wchar_t, and the
4507 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004509 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004510 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004511 if (Initializer && isa<VariableArrayType>(DestAT)) {
4512 SetFailed(FK_VariableLengthArrayHasInitializer);
4513 return;
4514 }
4515
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004516 if (Initializer) {
4517 switch (IsStringInit(Initializer, DestAT, Context)) {
4518 case SIF_None:
4519 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4520 return;
4521 case SIF_NarrowStringIntoWideChar:
4522 SetFailed(FK_NarrowStringIntoWideCharArray);
4523 return;
4524 case SIF_WideStringIntoChar:
4525 SetFailed(FK_WideStringIntoCharArray);
4526 return;
4527 case SIF_IncompatWideStringIntoWideChar:
4528 SetFailed(FK_IncompatWideStringIntoWideChar);
4529 return;
4530 case SIF_Other:
4531 break;
4532 }
John McCall66884dd2011-02-21 07:22:22 +00004533 }
4534
Douglas Gregore2f943b2011-02-22 18:29:51 +00004535 // Note: as an GNU C extension, we allow initialization of an
4536 // array from a compound literal that creates an array of the same
4537 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004538 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004539 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4540 Initializer->getType()->isArrayType()) {
4541 const ArrayType *SourceAT
4542 = Context.getAsArrayType(Initializer->getType());
4543 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004544 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004545 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004546 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004547 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004548 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004549 }
Richard Smithebeed412012-02-15 22:38:09 +00004550 }
Richard Smithd86812d2012-07-05 08:39:21 +00004551 // Note: as a GNU C++ extension, we allow list-initialization of a
4552 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004553 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004554 Entity.getKind() == InitializedEntity::EK_Member &&
4555 Initializer && isa<InitListExpr>(Initializer)) {
4556 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4557 *this);
4558 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004559 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004560 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004561 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4562 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004563 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004564 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004565
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004566 return;
4567 }
Eli Friedman78275202009-12-19 08:11:05 +00004568
John McCall31168b02011-06-15 23:02:42 +00004569 // Determine whether we should consider writeback conversions for
4570 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004571 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004572 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004573
4574 // We're at the end of the line for C: it's either a write-back conversion
4575 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004576 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004577 // If allowed, check whether this is an Objective-C writeback conversion.
4578 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004579 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004580 return;
4581 }
Guy Benyei61054192013-02-07 10:55:47 +00004582
4583 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4584 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004585
4586 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4587 return;
4588
John McCall31168b02011-06-15 23:02:42 +00004589 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004590 AddCAssignmentStep(DestType);
4591 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004592 return;
4593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
David Blaikiebbafb8a2012-03-11 07:00:24 +00004595 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004596
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004597 // - If the destination type is a (possibly cv-qualified) class type:
4598 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004599 // - If the initialization is direct-initialization, or if it is
4600 // copy-initialization where the cv-unqualified version of the
4601 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004602 // class of the destination, constructors are considered. [...]
4603 if (Kind.getKind() == InitializationKind::IK_Direct ||
4604 (Kind.getKind() == InitializationKind::IK_Copy &&
4605 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4606 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004607 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004608 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004612 // used) to a derived class thereof are enumerated as described in
4613 // 13.3.1.4, and the best one is chosen through overload resolution
4614 // (13.3).
4615 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004616 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4617 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004618 return;
4619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004621 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004622 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004623 return;
4624 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004625 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
4627 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004628 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004629 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004630 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4631 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004632 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004633 return;
4634 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004637 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004638 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004640 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004641
4642 ImplicitConversionSequence ICS
4643 = S.TryImplicitConversion(Initializer, Entity.getType(),
4644 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004645 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004646 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004647 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4648 allowObjCWritebackConversion);
4649
4650 if (ICS.isStandard() &&
4651 ICS.Standard.Second == ICK_Writeback_Conversion) {
4652 // Objective-C ARC writeback conversion.
4653
4654 // We should copy unless we're passing to an argument explicitly
4655 // marked 'out'.
4656 bool ShouldCopy = true;
4657 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4658 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4659
4660 // If there was an lvalue adjustment, add it as a separate conversion.
4661 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4662 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4663 ImplicitConversionSequence LvalueICS;
4664 LvalueICS.setStandard();
4665 LvalueICS.Standard.setAsIdentityConversion();
4666 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4667 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004668 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004669 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004670
4671 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004672 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004673 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004674 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4675 AddZeroInitializationStep(Entity.getType());
4676 } else if (Initializer->getType() == Context.OverloadTy &&
4677 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4678 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004679 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004680 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004681 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004682 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004683 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004684
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004685 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004686 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004687}
4688
4689InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004690 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004691 StepEnd = Steps.end();
4692 Step != StepEnd; ++Step)
4693 Step->Destroy();
4694}
4695
4696//===----------------------------------------------------------------------===//
4697// Perform initialization
4698//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004699static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004700getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004701 switch(Entity.getKind()) {
4702 case InitializedEntity::EK_Variable:
4703 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004704 case InitializedEntity::EK_Exception:
4705 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004706 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004707 return Sema::AA_Initializing;
4708
4709 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004711 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4712 return Sema::AA_Sending;
4713
Douglas Gregore1314a62009-12-18 05:02:21 +00004714 return Sema::AA_Passing;
4715
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004716 case InitializedEntity::EK_Parameter_CF_Audited:
4717 if (Entity.getDecl() &&
4718 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4719 return Sema::AA_Sending;
4720
4721 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4722
Douglas Gregore1314a62009-12-18 05:02:21 +00004723 case InitializedEntity::EK_Result:
4724 return Sema::AA_Returning;
4725
Douglas Gregore1314a62009-12-18 05:02:21 +00004726 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004727 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004728 // FIXME: Can we tell apart casting vs. converting?
4729 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730
Douglas Gregore1314a62009-12-18 05:02:21 +00004731 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004732 case InitializedEntity::EK_ArrayElement:
4733 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004734 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004735 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004736 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004737 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004738 return Sema::AA_Initializing;
4739 }
4740
David Blaikie8a40f702012-01-17 06:56:22 +00004741 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004742}
4743
Richard Smith27874d62013-01-08 00:08:23 +00004744/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004745/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004746static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004747 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004748 case InitializedEntity::EK_ArrayElement:
4749 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004750 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004751 case InitializedEntity::EK_New:
4752 case InitializedEntity::EK_Variable:
4753 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004754 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004755 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004756 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004757 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004758 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004759 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004760 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004761 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762
Douglas Gregore1314a62009-12-18 05:02:21 +00004763 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004764 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004765 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004766 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004767 return true;
4768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
Douglas Gregore1314a62009-12-18 05:02:21 +00004770 llvm_unreachable("missed an InitializedEntity kind?");
4771}
4772
Douglas Gregor95562572010-04-24 23:45:46 +00004773/// \brief Whether the given entity, when initialized with an object
4774/// created for that initialization, requires destruction.
4775static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4776 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004777 case InitializedEntity::EK_Result:
4778 case InitializedEntity::EK_New:
4779 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004780 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004781 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004782 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004783 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004784 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004785 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786
Richard Smith27874d62013-01-08 00:08:23 +00004787 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004788 case InitializedEntity::EK_Variable:
4789 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004790 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004791 case InitializedEntity::EK_Temporary:
4792 case InitializedEntity::EK_ArrayElement:
4793 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004794 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004795 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004796 return true;
4797 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
4799 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004800}
4801
Richard Smithc620f552011-10-19 16:55:56 +00004802/// \brief Look for copy and move constructors and constructor templates, for
4803/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4804static void LookupCopyAndMoveConstructors(Sema &S,
4805 OverloadCandidateSet &CandidateSet,
4806 CXXRecordDecl *Class,
4807 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004808 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004809 // The container holding the constructors can under certain conditions
4810 // be changed while iterating (e.g. because of deserialization).
4811 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004812 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004813 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004814 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4815 NamedDecl *D = *CI;
Richard Smithc620f552011-10-19 16:55:56 +00004816 CXXConstructorDecl *Constructor = 0;
4817
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004818 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004819 // Handle copy/moveconstructors, only.
4820 if (!Constructor || Constructor->isInvalidDecl() ||
4821 !Constructor->isCopyOrMoveConstructor() ||
4822 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4823 continue;
4824
4825 DeclAccessPair FoundDecl
4826 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4827 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004828 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004829 continue;
4830 }
4831
4832 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004833 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004834 if (ConstructorTmpl->isInvalidDecl())
4835 continue;
4836
4837 Constructor = cast<CXXConstructorDecl>(
4838 ConstructorTmpl->getTemplatedDecl());
4839 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4840 continue;
4841
4842 // FIXME: Do we need to limit this to copy-constructor-like
4843 // candidates?
4844 DeclAccessPair FoundDecl
4845 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4846 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004847 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004848 }
4849}
4850
4851/// \brief Get the location at which initialization diagnostics should appear.
4852static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4853 Expr *Initializer) {
4854 switch (Entity.getKind()) {
4855 case InitializedEntity::EK_Result:
4856 return Entity.getReturnLoc();
4857
4858 case InitializedEntity::EK_Exception:
4859 return Entity.getThrowLoc();
4860
4861 case InitializedEntity::EK_Variable:
4862 return Entity.getDecl()->getLocation();
4863
Douglas Gregor19666fb2012-02-15 16:57:26 +00004864 case InitializedEntity::EK_LambdaCapture:
4865 return Entity.getCaptureLoc();
4866
Richard Smithc620f552011-10-19 16:55:56 +00004867 case InitializedEntity::EK_ArrayElement:
4868 case InitializedEntity::EK_Member:
4869 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004870 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00004871 case InitializedEntity::EK_Temporary:
4872 case InitializedEntity::EK_New:
4873 case InitializedEntity::EK_Base:
4874 case InitializedEntity::EK_Delegating:
4875 case InitializedEntity::EK_VectorElement:
4876 case InitializedEntity::EK_ComplexElement:
4877 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004878 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004879 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00004880 return Initializer->getLocStart();
4881 }
4882 llvm_unreachable("missed an InitializedEntity kind?");
4883}
4884
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004885/// \brief Make a (potentially elidable) temporary copy of the object
4886/// provided by the given initializer by calling the appropriate copy
4887/// constructor.
4888///
4889/// \param S The Sema object used for type-checking.
4890///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004891/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004892/// the type of the initializer expression or a superclass thereof.
4893///
James Dennett634962f2012-06-14 21:40:34 +00004894/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004895///
4896/// \param CurInit The initializer expression.
4897///
4898/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4899/// is permitted in C++03 (but not C++0x) when binding a reference to
4900/// an rvalue.
4901///
4902/// \returns An expression that copies the initializer expression into
4903/// a temporary object, or an error expression if a copy could not be
4904/// created.
John McCalldadc5752010-08-24 06:29:42 +00004905static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004906 QualType T,
4907 const InitializedEntity &Entity,
4908 ExprResult CurInit,
4909 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004910 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004911 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004912 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004913 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004914 Class = cast<CXXRecordDecl>(Record->getDecl());
4915 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004916 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004917
Douglas Gregor5d369002011-01-21 18:05:27 +00004918 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004919 // When certain criteria are met, an implementation is allowed to
4920 // omit the copy/move construction of a class object, even if the
4921 // copy/move constructor and/or destructor for the object have
4922 // side effects. [...]
4923 // - when a temporary class object that has not been bound to a
4924 // reference (12.2) would be copied/moved to a class object
4925 // with the same cv-unqualified type, the copy/move operation
4926 // can be omitted by constructing the temporary object
4927 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004929 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004930 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004932 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004933 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004934 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004935
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004937 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004938 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00004939
Douglas Gregorf282a762011-01-21 19:38:21 +00004940 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004941 // Only consider constructors and constructor templates. Per
4942 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4943 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004944 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004945 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004947 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4948
Douglas Gregore1314a62009-12-18 05:02:21 +00004949 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004950 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004951 case OR_Success:
4952 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregore1314a62009-12-18 05:02:21 +00004954 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004955 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4956 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4957 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004958 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004959 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004960 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004961 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004962 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004963 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004964
Douglas Gregore1314a62009-12-18 05:02:21 +00004965 case OR_Ambiguous:
4966 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004967 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004968 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004969 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00004970 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004971
Douglas Gregore1314a62009-12-18 05:02:21 +00004972 case OR_Deleted:
4973 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004974 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004975 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00004976 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00004977 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004978 }
4979
Douglas Gregor5ab11652010-04-17 22:01:05 +00004980 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00004981 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor5ab11652010-04-17 22:01:05 +00004982 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004983
Anders Carlssona01874b2010-04-21 18:47:17 +00004984 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004985 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004986
4987 if (IsExtraneousCopy) {
4988 // If this is a totally extraneous copy for C++03 reference
4989 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004990 // expression. We don't generate an (elided) copy operation here
4991 // because doing so would require us to pass down a flag to avoid
4992 // infinite recursion, where each step adds another extraneous,
4993 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004994
Douglas Gregor30b52772010-04-18 07:57:34 +00004995 // Instantiate the default arguments of any extra parameters in
4996 // the selected copy constructor, as if we were going to create a
4997 // proper call to the copy constructor.
4998 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4999 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5000 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005001 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005002 break;
5003
5004 // Build the default argument expression; we don't actually care
5005 // if this succeeds or not, because this routine will complain
5006 // if there was a problem.
5007 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5008 }
5009
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005010 return S.Owned(CurInitExpr);
5011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012
Douglas Gregor5ab11652010-04-17 22:01:05 +00005013 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005014 // constructor call (we might have derived-to-base conversions, or
5015 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005016 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005017 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005018
Douglas Gregord0ace022010-04-25 00:55:24 +00005019 // Actually perform the constructor call.
5020 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005021 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005022 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005023 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005024 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005025 CXXConstructExpr::CK_Complete,
5026 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027
Douglas Gregord0ace022010-04-25 00:55:24 +00005028 // If we're supposed to bind temporaries, do so.
5029 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5030 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005031 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005032}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005033
Richard Smithc620f552011-10-19 16:55:56 +00005034/// \brief Check whether elidable copy construction for binding a reference to
5035/// a temporary would have succeeded if we were building in C++98 mode, for
5036/// -Wc++98-compat.
5037static void CheckCXX98CompatAccessibleCopy(Sema &S,
5038 const InitializedEntity &Entity,
5039 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005040 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005041
5042 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5043 if (!Record)
5044 return;
5045
5046 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5047 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5048 == DiagnosticsEngine::Ignored)
5049 return;
5050
5051 // Find constructors which would have been considered.
5052 OverloadCandidateSet CandidateSet(Loc);
5053 LookupCopyAndMoveConstructors(
5054 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5055
5056 // Perform overload resolution.
5057 OverloadCandidateSet::iterator Best;
5058 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5059
5060 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5061 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5062 << CurInitExpr->getSourceRange();
5063
5064 switch (OR) {
5065 case OR_Success:
5066 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005067 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005068 // FIXME: Check default arguments as far as that's possible.
5069 break;
5070
5071 case OR_No_Viable_Function:
5072 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005073 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005074 break;
5075
5076 case OR_Ambiguous:
5077 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005078 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005079 break;
5080
5081 case OR_Deleted:
5082 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005083 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005084 break;
5085 }
5086}
5087
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005088void InitializationSequence::PrintInitLocationNote(Sema &S,
5089 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005090 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005091 if (Entity.getDecl()->getLocation().isInvalid())
5092 return;
5093
5094 if (Entity.getDecl()->getDeclName())
5095 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5096 << Entity.getDecl()->getDeclName();
5097 else
5098 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5099 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005100 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5101 Entity.getMethodDecl())
5102 S.Diag(Entity.getMethodDecl()->getLocation(),
5103 diag::note_method_return_type_change)
5104 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005105}
5106
Sebastian Redl112aa822011-07-14 19:07:55 +00005107static bool isReferenceBinding(const InitializationSequence::Step &s) {
5108 return s.Kind == InitializationSequence::SK_BindReference ||
5109 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5110}
5111
Jordan Rose6c0505e2013-05-06 16:48:12 +00005112/// Returns true if the parameters describe a constructor initialization of
5113/// an explicit temporary object, e.g. "Point(x, y)".
5114static bool isExplicitTemporary(const InitializedEntity &Entity,
5115 const InitializationKind &Kind,
5116 unsigned NumArgs) {
5117 switch (Entity.getKind()) {
5118 case InitializedEntity::EK_Temporary:
5119 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005120 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005121 break;
5122 default:
5123 return false;
5124 }
5125
5126 switch (Kind.getKind()) {
5127 case InitializationKind::IK_DirectList:
5128 return true;
5129 // FIXME: Hack to work around cast weirdness.
5130 case InitializationKind::IK_Direct:
5131 case InitializationKind::IK_Value:
5132 return NumArgs != 1;
5133 default:
5134 return false;
5135 }
5136}
5137
Sebastian Redled2e5322011-12-22 14:44:04 +00005138static ExprResult
5139PerformConstructorInitialization(Sema &S,
5140 const InitializedEntity &Entity,
5141 const InitializationKind &Kind,
5142 MultiExprArg Args,
5143 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005144 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005145 bool IsListInitialization,
5146 SourceLocation LBraceLoc,
5147 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005148 unsigned NumArgs = Args.size();
5149 CXXConstructorDecl *Constructor
5150 = cast<CXXConstructorDecl>(Step.Function.Function);
5151 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5152
5153 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005154 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005155 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5156 ? Kind.getEqualLoc()
5157 : Kind.getLocation();
5158
5159 if (Kind.getKind() == InitializationKind::IK_Default) {
5160 // Force even a trivial, implicit default constructor to be
5161 // semantically checked. We do this explicitly because we don't build
5162 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005163 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005164 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005165 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005166 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5167 }
5168
5169 ExprResult CurInit = S.Owned((Expr *)0);
5170
Douglas Gregor6073dca2012-02-24 23:56:31 +00005171 // C++ [over.match.copy]p1:
5172 // - When initializing a temporary to be bound to the first parameter
5173 // of a constructor that takes a reference to possibly cv-qualified
5174 // T as its first argument, called with a single argument in the
5175 // context of direct-initialization, explicit conversion functions
5176 // are also considered.
5177 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5178 Args.size() == 1 &&
5179 Constructor->isCopyOrMoveConstructor();
5180
Sebastian Redled2e5322011-12-22 14:44:04 +00005181 // Determine the arguments required to actually perform the constructor
5182 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005183 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005184 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005185 AllowExplicitConv,
5186 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005187 return ExprError();
5188
5189
Jordan Rose6c0505e2013-05-06 16:48:12 +00005190 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005191 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005192 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005193 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5194 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005195
5196 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5197 if (!TSInfo)
5198 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005199 SourceRange ParenOrBraceRange =
5200 (Kind.getKind() == InitializationKind::IK_DirectList)
5201 ? SourceRange(LBraceLoc, RBraceLoc)
5202 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005203
Richard Smithd59b8322012-12-19 01:39:02 +00005204 CurInit = S.Owned(
5205 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5206 TSInfo, ConstructorArgs,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005207 ParenOrBraceRange,
Richard Smithd59b8322012-12-19 01:39:02 +00005208 HadMultipleCandidates,
Enea Zaffanella82a65fc2013-09-07 11:22:02 +00005209 IsListInitialization,
Richard Smithd59b8322012-12-19 01:39:02 +00005210 ConstructorInitRequiresZeroInit));
Sebastian Redled2e5322011-12-22 14:44:04 +00005211 } else {
5212 CXXConstructExpr::ConstructionKind ConstructKind =
5213 CXXConstructExpr::CK_Complete;
5214
5215 if (Entity.getKind() == InitializedEntity::EK_Base) {
5216 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5217 CXXConstructExpr::CK_VirtualBase :
5218 CXXConstructExpr::CK_NonVirtualBase;
5219 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5220 ConstructKind = CXXConstructExpr::CK_Delegating;
5221 }
5222
5223 // Only get the parenthesis range if it is a direct construction.
5224 SourceRange parenRange =
5225 Kind.getKind() == InitializationKind::IK_Direct ?
5226 Kind.getParenRange() : SourceRange();
5227
5228 // If the entity allows NRVO, mark the construction as elidable
5229 // unconditionally.
5230 if (Entity.allowsNRVO())
5231 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5232 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005233 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005234 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005235 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005236 ConstructorInitRequiresZeroInit,
5237 ConstructKind,
5238 parenRange);
5239 else
5240 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5241 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005242 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005243 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005244 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005245 ConstructorInitRequiresZeroInit,
5246 ConstructKind,
5247 parenRange);
5248 }
5249 if (CurInit.isInvalid())
5250 return ExprError();
5251
5252 // Only check access if all of that succeeded.
5253 S.CheckConstructorAccess(Loc, Constructor, Entity,
5254 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005255 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5256 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005257
5258 if (shouldBindAsTemporary(Entity))
Richard Smithcc1b96d2013-06-12 22:31:48 +00005259 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redled2e5322011-12-22 14:44:04 +00005260
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005261 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005262}
5263
Richard Smitheb3cad52012-06-04 22:27:30 +00005264/// Determine whether the specified InitializedEntity definitely has a lifetime
5265/// longer than the current full-expression. Conservatively returns false if
5266/// it's unclear.
5267static bool
5268InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5269 const InitializedEntity *Top = &Entity;
5270 while (Top->getParent())
5271 Top = Top->getParent();
5272
5273 switch (Top->getKind()) {
5274 case InitializedEntity::EK_Variable:
5275 case InitializedEntity::EK_Result:
5276 case InitializedEntity::EK_Exception:
5277 case InitializedEntity::EK_Member:
5278 case InitializedEntity::EK_New:
5279 case InitializedEntity::EK_Base:
5280 case InitializedEntity::EK_Delegating:
5281 return true;
5282
5283 case InitializedEntity::EK_ArrayElement:
5284 case InitializedEntity::EK_VectorElement:
5285 case InitializedEntity::EK_BlockElement:
5286 case InitializedEntity::EK_ComplexElement:
5287 // Could not determine what the full initialization is. Assume it might not
5288 // outlive the full-expression.
5289 return false;
5290
5291 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005292 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005293 case InitializedEntity::EK_Temporary:
5294 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005295 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005296 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005297 // The entity being initialized might not outlive the full-expression.
5298 return false;
5299 }
5300
5301 llvm_unreachable("unknown entity kind");
5302}
5303
Richard Smithe6c01442013-06-05 00:46:14 +00005304/// Determine the declaration which an initialized entity ultimately refers to,
5305/// for the purpose of lifetime-extending a temporary bound to a reference in
5306/// the initialization of \p Entity.
5307static const ValueDecl *
5308getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5309 const ValueDecl *FallbackDecl = 0) {
5310 // C++11 [class.temporary]p5:
5311 switch (Entity.getKind()) {
5312 case InitializedEntity::EK_Variable:
5313 // The temporary [...] persists for the lifetime of the reference
5314 return Entity.getDecl();
5315
5316 case InitializedEntity::EK_Member:
5317 // For subobjects, we look at the complete object.
5318 if (Entity.getParent())
5319 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5320 Entity.getDecl());
5321
5322 // except:
5323 // -- A temporary bound to a reference member in a constructor's
5324 // ctor-initializer persists until the constructor exits.
5325 return Entity.getDecl();
5326
5327 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005328 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005329 // -- A temporary bound to a reference parameter in a function call
5330 // persists until the completion of the full-expression containing
5331 // the call.
5332 case InitializedEntity::EK_Result:
5333 // -- The lifetime of a temporary bound to the returned value in a
5334 // function return statement is not extended; the temporary is
5335 // destroyed at the end of the full-expression in the return statement.
5336 case InitializedEntity::EK_New:
5337 // -- A temporary bound to a reference in a new-initializer persists
5338 // until the completion of the full-expression containing the
5339 // new-initializer.
5340 return 0;
5341
5342 case InitializedEntity::EK_Temporary:
5343 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005344 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005345 // We don't yet know the storage duration of the surrounding temporary.
5346 // Assume it's got full-expression duration for now, it will patch up our
5347 // storage duration if that's not correct.
5348 return 0;
5349
5350 case InitializedEntity::EK_ArrayElement:
5351 // For subobjects, we look at the complete object.
5352 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5353 FallbackDecl);
5354
5355 case InitializedEntity::EK_Base:
5356 case InitializedEntity::EK_Delegating:
5357 // We can reach this case for aggregate initialization in a constructor:
5358 // struct A { int &&r; };
5359 // struct B : A { B() : A{0} {} };
5360 // In this case, use the innermost field decl as the context.
5361 return FallbackDecl;
5362
5363 case InitializedEntity::EK_BlockElement:
5364 case InitializedEntity::EK_LambdaCapture:
5365 case InitializedEntity::EK_Exception:
5366 case InitializedEntity::EK_VectorElement:
5367 case InitializedEntity::EK_ComplexElement:
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005368 return 0;
Richard Smithe6c01442013-06-05 00:46:14 +00005369 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005370 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005371}
5372
5373static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5374
5375/// Update a glvalue expression that is used as the initializer of a reference
5376/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005377/// \return \c true if any temporary had its lifetime extended.
5378static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
Richard Smithe6c01442013-06-05 00:46:14 +00005379 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5380 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5381 // This is just redundant braces around an initializer. Step over it.
5382 Init = ILE->getInit(0);
5383 }
5384 }
5385
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005386 // Walk past any constructs which we can lifetime-extend across.
5387 Expr *Old;
5388 do {
5389 Old = Init;
5390
5391 // Step over any subobject adjustments; we may have a materialized
5392 // temporary inside them.
5393 SmallVector<const Expr *, 2> CommaLHSs;
5394 SmallVector<SubobjectAdjustment, 2> Adjustments;
5395 Init = const_cast<Expr *>(
5396 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5397
5398 // Per current approach for DR1376, look through casts to reference type
5399 // when performing lifetime extension.
5400 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5401 if (CE->getSubExpr()->isGLValue())
5402 Init = CE->getSubExpr();
5403
5404 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5405 // It's unclear if binding a reference to that xvalue extends the array
5406 // temporary.
5407 } while (Init != Old);
5408
Richard Smithe6c01442013-06-05 00:46:14 +00005409 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5410 // Update the storage duration of the materialized temporary.
5411 // FIXME: Rebuild the expression instead of mutating it.
5412 ME->setExtendingDecl(ExtendingD);
5413 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005414 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005415 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005416
5417 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005418}
5419
5420/// Update a prvalue expression that is going to be materialized as a
5421/// lifetime-extended temporary.
5422static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5423 // Dig out the expression which constructs the extended temporary.
5424 SmallVector<const Expr *, 2> CommaLHSs;
5425 SmallVector<SubobjectAdjustment, 2> Adjustments;
5426 Init = const_cast<Expr *>(
5427 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5428
Richard Smith736a9472013-06-12 20:42:33 +00005429 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5430 Init = BTE->getSubExpr();
5431
Richard Smithcc1b96d2013-06-12 22:31:48 +00005432 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005433 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5434 performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5435 return;
5436 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005437
Richard Smithe6c01442013-06-05 00:46:14 +00005438 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005439 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005440 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5441 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5442 return;
5443 }
5444
Richard Smithcc1b96d2013-06-12 22:31:48 +00005445 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005446 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5447
5448 // If we lifetime-extend a braced initializer which is initializing an
5449 // aggregate, and that aggregate contains reference members which are
5450 // bound to temporaries, those temporaries are also lifetime-extended.
5451 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5452 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5453 performReferenceExtension(ILE->getInit(0), ExtendingD);
5454 else {
5455 unsigned Index = 0;
5456 for (RecordDecl::field_iterator I = RD->field_begin(),
5457 E = RD->field_end();
5458 I != E; ++I) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005459 if (Index >= ILE->getNumInits())
5460 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005461 if (I->isUnnamedBitfield())
5462 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005463 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005464 if (I->getType()->isReferenceType())
Richard Smith8d7f11d2013-06-27 22:54:33 +00005465 performReferenceExtension(SubInit, ExtendingD);
5466 else if (isa<InitListExpr>(SubInit) ||
5467 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005468 // This may be either aggregate-initialization of a member or
5469 // initialization of a std::initializer_list object. Either way,
5470 // we should recursively lifetime-extend that initializer.
Richard Smith8d7f11d2013-06-27 22:54:33 +00005471 performLifetimeExtension(SubInit, ExtendingD);
Richard Smithe6c01442013-06-05 00:46:14 +00005472 ++Index;
5473 }
5474 }
5475 }
5476 }
5477}
5478
Richard Smithcc1b96d2013-06-12 22:31:48 +00005479static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5480 const Expr *Init, bool IsInitializerList,
5481 const ValueDecl *ExtendingDecl) {
5482 // Warn if a field lifetime-extends a temporary.
5483 if (isa<FieldDecl>(ExtendingDecl)) {
5484 if (IsInitializerList) {
5485 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5486 << /*at end of constructor*/true;
5487 return;
5488 }
5489
5490 bool IsSubobjectMember = false;
5491 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5492 Ent = Ent->getParent()) {
5493 if (Ent->getKind() != InitializedEntity::EK_Base) {
5494 IsSubobjectMember = true;
5495 break;
5496 }
5497 }
5498 S.Diag(Init->getExprLoc(),
5499 diag::warn_bind_ref_member_to_temporary)
5500 << ExtendingDecl << Init->getSourceRange()
5501 << IsSubobjectMember << IsInitializerList;
5502 if (IsSubobjectMember)
5503 S.Diag(ExtendingDecl->getLocation(),
5504 diag::note_ref_subobject_of_member_declared_here);
5505 else
5506 S.Diag(ExtendingDecl->getLocation(),
5507 diag::note_ref_or_ptr_member_declared_here)
5508 << /*is pointer*/false;
5509 }
5510}
5511
Richard Smithaaa0ec42013-09-21 21:19:19 +00005512static void DiagnoseNarrowingInInitList(Sema &S,
5513 const ImplicitConversionSequence &ICS,
5514 QualType PreNarrowingType,
5515 QualType EntityType,
5516 const Expr *PostInit);
5517
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005519InitializationSequence::Perform(Sema &S,
5520 const InitializedEntity &Entity,
5521 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005522 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005523 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005524 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005525 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005526 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005527 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005528
Sebastian Redld201edf2011-06-05 13:59:11 +00005529 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005530 // If the declaration is a non-dependent, incomplete array type
5531 // that has an initializer, then its type will be completed once
5532 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005533 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005534 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005535 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005536 if (const IncompleteArrayType *ArrayT
5537 = S.Context.getAsIncompleteArrayType(DeclType)) {
5538 // FIXME: We don't currently have the ability to accurately
5539 // compute the length of an initializer list without
5540 // performing full type-checking of the initializer list
5541 // (since we have to determine where braces are implicitly
5542 // introduced and such). So, we fall back to making the array
5543 // type a dependently-sized array type with no specified
5544 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005545 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005546 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005547
Douglas Gregor51e77d52009-12-10 17:56:55 +00005548 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005549 if (DeclaratorDecl *DD = Entity.getDecl()) {
5550 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5551 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005552 if (IncompleteArrayTypeLoc ArrayLoc =
5553 TL.getAs<IncompleteArrayTypeLoc>())
5554 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005555 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005556 }
5557
5558 *ResultType
5559 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5560 /*NumElts=*/0,
5561 ArrayT->getSizeModifier(),
5562 ArrayT->getIndexTypeCVRQualifiers(),
5563 Brackets);
5564 }
5565
5566 }
5567 }
Sebastian Redla9351792012-02-11 23:51:47 +00005568 if (Kind.getKind() == InitializationKind::IK_Direct &&
5569 !Kind.isExplicitCast()) {
5570 // Rebuild the ParenListExpr.
5571 SourceRange ParenRange = Kind.getParenRange();
5572 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005573 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005574 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005575 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005576 Kind.isExplicitCast() ||
5577 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005578 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005579 }
5580
Sebastian Redld201edf2011-06-05 13:59:11 +00005581 // No steps means no initialization.
5582 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00005583 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005585 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005586 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005587 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005588 // Produce a C++98 compatibility warning if we are initializing a reference
5589 // from an initializer list. For parameters, we produce a better warning
5590 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005591 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005592 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5593 << Init->getSourceRange();
5594 }
5595
Richard Smitheb3cad52012-06-04 22:27:30 +00005596 // Diagnose cases where we initialize a pointer to an array temporary, and the
5597 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005598 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005599 Entity.getType()->isPointerType() &&
5600 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005601 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005602 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5603 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5604 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5605 << Init->getSourceRange();
5606 }
5607
Douglas Gregor1b303932009-12-22 15:35:07 +00005608 QualType DestType = Entity.getType().getNonReferenceType();
5609 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005610 // the same as Entity.getDecl()->getType() in cases involving type merging,
5611 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005612 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005613 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005614 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005615
John McCalldadc5752010-08-24 06:29:42 +00005616 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005617
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005619 // grab the only argument out the Args and place it into the "current"
5620 // initializer.
5621 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005622 case SK_ResolveAddressOfOverloadedFunction:
5623 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005624 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005625 case SK_CastDerivedToBaseLValue:
5626 case SK_BindReference:
5627 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005628 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005629 case SK_UserConversion:
5630 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005631 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005632 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005633 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005634 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005635 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005636 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005637 case SK_UnwrapInitList:
5638 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005639 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005640 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005641 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005642 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005643 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005644 case SK_PassByIndirectCopyRestore:
5645 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005646 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005647 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005648 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005649 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005650 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005651 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005652 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005653 break;
John McCall34376a62010-12-04 03:47:34 +00005654 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005655
Douglas Gregore1314a62009-12-18 05:02:21 +00005656 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00005657 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005658 case SK_ZeroInitialization:
5659 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005660 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005661
5662 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005663 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005664 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005665 for (step_iterator Step = step_begin(), StepEnd = step_end();
5666 Step != StepEnd; ++Step) {
5667 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005668 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
John Wiegley01296292011-04-08 18:41:53 +00005670 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005672 switch (Step->Kind) {
5673 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005674 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005675 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005676 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005677 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5678 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005679 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005680 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005681 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005682 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005684 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005685 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005686 case SK_CastDerivedToBaseLValue: {
5687 // We have a derived-to-base cast that produces either an rvalue or an
5688 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689
John McCallcf142162010-08-07 06:22:56 +00005690 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005692 // Casts to inaccessible base classes are allowed with C-style casts.
5693 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5694 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005695 CurInit.get()->getLocStart(),
5696 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005697 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005698 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699
Douglas Gregor88d292c2010-05-13 16:44:06 +00005700 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5701 QualType T = SourceType;
5702 if (const PointerType *Pointer = T->getAs<PointerType>())
5703 T = Pointer->getPointeeType();
5704 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005705 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005706 cast<CXXRecordDecl>(RecordTy->getDecl()));
5707 }
5708
John McCall2536c6d2010-08-25 10:28:54 +00005709 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005710 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005711 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005712 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005713 VK_XValue :
5714 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00005715 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5716 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005717 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00005718 CurInit.get(),
5719 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005720 break;
5721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005723 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005724 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5725 if (CurInit.get()->refersToBitField()) {
5726 // We don't necessarily have an unambiguous source bit-field.
5727 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005728 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005729 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005730 << (BitField ? BitField->getDeclName() : DeclarationName())
5731 << (BitField != NULL)
John Wiegley01296292011-04-08 18:41:53 +00005732 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005733 if (BitField)
5734 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5735
John McCallfaf5fb42010-08-26 23:41:50 +00005736 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005737 }
Anders Carlssona91be642010-01-29 02:47:33 +00005738
John Wiegley01296292011-04-08 18:41:53 +00005739 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005740 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005741 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5742 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005743 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005744 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005745 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005748 // Reference binding does not have any corresponding ASTs.
5749
5750 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005751 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005752 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005753
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005754 // Even though we didn't materialize a temporary, the binding may still
5755 // extend the lifetime of a temporary. This happens if we bind a reference
5756 // to the result of a cast to reference type.
5757 if (const ValueDecl *ExtendingDecl =
5758 getDeclForTemporaryLifetimeExtension(Entity)) {
5759 if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5760 warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5761 ExtendingDecl);
5762 }
5763
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005764 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005765
Richard Smithe6c01442013-06-05 00:46:14 +00005766 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005767 // Make sure the "temporary" is actually an rvalue.
5768 assert(CurInit.get()->isRValue() && "not a temporary");
5769
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005770 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005771 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005772 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005773
Richard Smithe6c01442013-06-05 00:46:14 +00005774 // Maybe lifetime-extend the temporary's subobjects to match the
5775 // entity's lifetime.
5776 const ValueDecl *ExtendingDecl =
5777 getDeclForTemporaryLifetimeExtension(Entity);
Richard Smithe3b28bc2013-06-12 21:51:50 +00005778 if (ExtendingDecl) {
Richard Smithe6c01442013-06-05 00:46:14 +00005779 performLifetimeExtension(CurInit.get(), ExtendingDecl);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005780 warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
Richard Smithe3b28bc2013-06-12 21:51:50 +00005781 }
5782
Douglas Gregorfe314812011-06-21 17:03:29 +00005783 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005784 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005785 Entity.getType().getNonReferenceType(), CurInit.get(),
5786 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregor58df5092011-06-22 16:12:01 +00005787
5788 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005789 // need cleanups. Likewise if we're extending this temporary to automatic
5790 // storage duration -- we need to register its cleanup during the
5791 // full-expression's cleanups.
5792 if ((S.getLangOpts().ObjCAutoRefCount &&
5793 MTE->getType()->isObjCLifetimeType()) ||
5794 (MTE->getStorageDuration() == SD_Automatic &&
5795 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005796 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005797
5798 CurInit = S.Owned(MTE);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005799 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005801
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005802 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005803 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005804 /*IsExtraneousCopy=*/true);
5805 break;
5806
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005807 case SK_UserConversion: {
5808 // We have a user-defined conversion that invokes either a constructor
5809 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005810 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005811 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005812 FunctionDecl *Fn = Step->Function.Function;
5813 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005814 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005815 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005816 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005817 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005818 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005819 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005820 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005821
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005822 // Determine the arguments required to actually perform the constructor
5823 // call.
John Wiegley01296292011-04-08 18:41:53 +00005824 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005825 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005826 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005827 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005828 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829
Richard Smithb24f0672012-02-11 19:22:50 +00005830 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005831 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005832 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005833 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005834 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005835 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005836 CXXConstructExpr::CK_Complete,
5837 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005838 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005839 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005840
Anders Carlssona01874b2010-04-21 18:47:17 +00005841 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005842 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005843 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5844 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005845
John McCalle3027922010-08-25 11:45:40 +00005846 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005847 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5848 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5849 S.IsDerivedFrom(SourceType, Class))
5850 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851
Douglas Gregor95562572010-04-24 23:45:46 +00005852 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005853 } else {
5854 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005855 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00005856 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00005857 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00005858 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5859 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005860
5861 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005862 // derived-to-base conversion? I believe the answer is "no", because
5863 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005864 ExprResult CurInitExprRes =
5865 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5866 FoundFn, Conversion);
5867 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005868 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005869 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005870
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005871 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005872 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5873 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005874 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005875 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005876
John McCalle3027922010-08-25 11:45:40 +00005877 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878
Douglas Gregor95562572010-04-24 23:45:46 +00005879 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005881
Sebastian Redl112aa822011-07-14 19:07:55 +00005882 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005883 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5884
5885 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005886 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005887 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005888 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005889 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005890 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005891 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005892 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005893 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5894 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00005895 }
5896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005897
John McCallcf142162010-08-07 06:22:56 +00005898 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005899 CurInit.get()->getType(),
5900 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005901 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005902 if (MaybeBindToTemp)
5903 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005904 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005905 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005906 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005907 break;
5908 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005909
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005910 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005911 case SK_QualificationConversionXValue:
5912 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005913 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005914 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005915 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005916 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005917 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005918 VK_XValue :
5919 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005920 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005921 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005922 }
5923
Jordan Roseb1312a52013-04-11 00:58:58 +00005924 case SK_LValueToRValue: {
5925 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5926 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5927 CK_LValueToRValue,
5928 CurInit.take(),
5929 /*BasePath=*/0,
5930 VK_RValue));
5931 break;
5932 }
5933
Richard Smithaaa0ec42013-09-21 21:19:19 +00005934 case SK_ConversionSequence:
5935 case SK_ConversionSequenceNoNarrowing: {
5936 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00005937 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5938 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005939 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005940 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005941 ExprResult CurInitExprRes =
5942 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005943 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005944 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005945 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005946 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005947
5948 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5949 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5950 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5951 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005952 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005954
Douglas Gregor51e77d52009-12-10 17:56:55 +00005955 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005956 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00005957 // If we're not initializing the top-level entity, we need to create an
5958 // InitializeTemporary entity for our target type.
5959 QualType Ty = Step->Type;
5960 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00005961 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00005962 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5963 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00005964 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005965 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005966 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005967
Richard Smithcc1b96d2013-06-12 22:31:48 +00005968 // Hack: We must update *ResultType if available in order to set the
5969 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5970 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5971 if (ResultType &&
5972 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00005973 if ((*ResultType)->isRValueReferenceType())
5974 Ty = S.Context.getRValueReferenceType(Ty);
5975 else if ((*ResultType)->isLValueReferenceType())
5976 Ty = S.Context.getLValueReferenceType(Ty,
5977 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5978 *ResultType = Ty;
5979 }
5980
5981 InitListExpr *StructuredInitList =
5982 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005983 CurInit.release();
Richard Smithd712d0d2013-02-02 01:13:06 +00005984 CurInit = shouldBindAsTemporary(InitEntity)
5985 ? S.MaybeBindToTemporary(StructuredInitList)
5986 : S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005987 break;
5988 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005989
Sebastian Redled2e5322011-12-22 14:44:04 +00005990 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00005991 // When an initializer list is passed for a parameter of type "reference
5992 // to object", we don't get an EK_Temporary entity, but instead an
5993 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00005994 // FIXME: This is a hack. What we really should do is create a user
5995 // conversion step for this case, but this makes it considerably more
5996 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00005997 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5998 Entity.getType().getNonReferenceType());
5999 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006000 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006001 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006002 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6003 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006004 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006005 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6006 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006007 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006008 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006009 /*IsListInitialization*/ true,
6010 InitList->getLBraceLoc(),
6011 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006012 break;
6013 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006014
Sebastian Redl29526f02011-11-27 16:50:07 +00006015 case SK_UnwrapInitList:
6016 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
6017 break;
6018
6019 case SK_RewrapInitList: {
6020 Expr *E = CurInit.take();
6021 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6022 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006023 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006024 ILE->setSyntacticForm(Syntactic);
6025 ILE->setType(E->getType());
6026 ILE->setValueKind(E->getValueKind());
6027 CurInit = S.Owned(ILE);
6028 break;
6029 }
6030
Sebastian Redl99f66162012-02-19 12:27:56 +00006031 case SK_ConstructorInitialization: {
6032 // When an initializer list is passed for a parameter of type "reference
6033 // to object", we don't get an EK_Temporary entity, but instead an
6034 // EK_Parameter entity with reference type.
6035 // FIXME: This is a hack. What we really should do is create a user
6036 // conversion step for this case, but this makes it considerably more
6037 // complicated. For now, this will do.
6038 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6039 Entity.getType().getNonReferenceType());
6040 bool UseTemporary = Entity.getType()->isReferenceType();
6041 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6042 : Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006043 Kind, Args, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006044 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006045 /*IsListInitialization*/ false,
6046 /*LBraceLoc*/ SourceLocation(),
6047 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006048 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006050
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006051 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006052 step_iterator NextStep = Step;
6053 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006054 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006055 (NextStep->Kind == SK_ConstructorInitialization ||
6056 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006057 // The need for zero-initialization is recorded directly into
6058 // the call to the object's constructor within the next step.
6059 ConstructorInitRequiresZeroInit = true;
6060 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006061 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006062 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006063 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6064 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006065 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006066 Kind.getRange().getBegin());
6067
6068 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6069 TSInfo->getType().getNonLValueExprType(S.Context),
6070 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006071 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006072 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006073 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006074 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006075 break;
6076 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006077
6078 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006079 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006080 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006081 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006082 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6083 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006084 if (Result.isInvalid())
6085 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006086 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006087
6088 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006089 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006090 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006091 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006092 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006093 == Sema::Compatible)
6094 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006095 if (CurInitExprRes.isInvalid())
6096 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006097 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006098
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006099 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006100 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6101 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006102 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006103 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006104 &Complained)) {
6105 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006106 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006107 } else if (Complained)
6108 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006109 break;
6110 }
Eli Friedman78275202009-12-19 08:11:05 +00006111
6112 case SK_StringInit: {
6113 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006114 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006115 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006116 break;
6117 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006118
6119 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00006120 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006121 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006122 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006123 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006124
6125 case SK_ArrayInit:
6126 // Okay: we checked everything before creating this step. Note that
6127 // this is a GNU extension.
6128 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006129 << Step->Type << CurInit.get()->getType()
6130 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006131
6132 // If the destination type is an incomplete array type, update the
6133 // type accordingly.
6134 if (ResultType) {
6135 if (const IncompleteArrayType *IncompleteDest
6136 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6137 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006138 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006139 *ResultType = S.Context.getConstantArrayType(
6140 IncompleteDest->getElementType(),
6141 ConstantSource->getSize(),
6142 ArrayType::Normal, 0);
6143 }
6144 }
6145 }
John McCall31168b02011-06-15 23:02:42 +00006146 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006147
Richard Smithebeed412012-02-15 22:38:09 +00006148 case SK_ParenthesizedArrayInit:
6149 // Okay: we checked everything before creating this step. Note that
6150 // this is a GNU extension.
6151 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6152 << CurInit.get()->getSourceRange();
6153 break;
6154
John McCall31168b02011-06-15 23:02:42 +00006155 case SK_PassByIndirectCopyRestore:
6156 case SK_PassByIndirectRestore:
6157 checkIndirectCopyRestoreSource(S, CurInit.get());
6158 CurInit = S.Owned(new (S.Context)
6159 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6160 Step->Kind == SK_PassByIndirectCopyRestore));
6161 break;
6162
6163 case SK_ProduceObjCObject:
6164 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00006165 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00006166 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00006167 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006168
6169 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006170 S.Diag(CurInit.get()->getExprLoc(),
6171 diag::warn_cxx98_compat_initializer_list_init)
6172 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006173
Richard Smithcc1b96d2013-06-12 22:31:48 +00006174 // Maybe lifetime-extend the array temporary's subobjects to match the
6175 // entity's lifetime.
6176 const ValueDecl *ExtendingDecl =
6177 getDeclForTemporaryLifetimeExtension(Entity);
6178 if (ExtendingDecl) {
6179 performLifetimeExtension(CurInit.get(), ExtendingDecl);
6180 warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
Sebastian Redl249dee52012-03-05 19:35:43 +00006181 }
6182
Richard Smithcc1b96d2013-06-12 22:31:48 +00006183 // Materialize the temporary into memory.
6184 MaterializeTemporaryExpr *MTE = new (S.Context)
6185 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6186 /*lvalue reference*/ false, ExtendingDecl);
6187
6188 // Wrap it in a construction of a std::initializer_list<T>.
6189 CurInit = S.Owned(
6190 new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6191
6192 // Bind the result, in case the library has given initializer_list a
6193 // non-trivial destructor.
6194 if (shouldBindAsTemporary(Entity))
6195 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006196 break;
6197 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006198
Guy Benyei61054192013-02-07 10:55:47 +00006199 case SK_OCLSamplerInit: {
6200 assert(Step->Type->isSamplerT() &&
6201 "Sampler initialization on non sampler type.");
6202
6203 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006204
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006205 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006206 if (!SourceType->isSamplerT())
6207 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6208 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006209 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006210 llvm_unreachable("Invalid EntityKind!");
6211 }
6212
6213 break;
6214 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006215 case SK_OCLZeroEvent: {
6216 assert(Step->Type->isEventT() &&
6217 "Event initialization on non event type.");
6218
6219 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6220 CK_ZeroToOCLEvent,
6221 CurInit.get()->getValueKind());
6222 break;
6223 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006224 }
6225 }
John McCall1f425642010-11-11 03:21:53 +00006226
6227 // Diagnose non-fatal problems with the completed initialization.
6228 if (Entity.getKind() == InitializedEntity::EK_Member &&
6229 cast<FieldDecl>(Entity.getDecl())->isBitField())
6230 S.CheckBitFieldInitialization(Kind.getLocation(),
6231 cast<FieldDecl>(Entity.getDecl()),
6232 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006233
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006234 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006235}
6236
Richard Smith593f9932012-12-08 02:01:17 +00006237/// Somewhere within T there is an uninitialized reference subobject.
6238/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006239static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6240 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006241 if (T->isReferenceType()) {
6242 S.Diag(Loc, diag::err_reference_without_init)
6243 << T.getNonReferenceType();
6244 return true;
6245 }
6246
6247 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6248 if (!RD || !RD->hasUninitializedReferenceMember())
6249 return false;
6250
6251 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6252 FE = RD->field_end(); FI != FE; ++FI) {
6253 if (FI->isUnnamedBitfield())
6254 continue;
6255
6256 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6257 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6258 return true;
6259 }
6260 }
6261
6262 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6263 BE = RD->bases_end();
6264 BI != BE; ++BI) {
6265 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6266 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6267 return true;
6268 }
6269 }
6270
6271 return false;
6272}
6273
6274
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006275//===----------------------------------------------------------------------===//
6276// Diagnose initialization failures
6277//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006278
6279/// Emit notes associated with an initialization that failed due to a
6280/// "simple" conversion failure.
6281static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6282 Expr *op) {
6283 QualType destType = entity.getType();
6284 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6285 op->getType()->isObjCObjectPointerType()) {
6286
6287 // Emit a possible note about the conversion failing because the
6288 // operand is a message send with a related result type.
6289 S.EmitRelatedResultTypeNote(op);
6290
6291 // Emit a possible note about a return failing because we're
6292 // expecting a related result type.
6293 if (entity.getKind() == InitializedEntity::EK_Result)
6294 S.EmitRelatedResultTypeNoteForReturn(destType);
6295 }
6296}
6297
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006298bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006299 const InitializedEntity &Entity,
6300 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006301 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006302 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006303 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006304
Douglas Gregor1b303932009-12-22 15:35:07 +00006305 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006306 switch (Failure) {
6307 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006308 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006309 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006310 // Dig out the reference subobject which is uninitialized and diagnose it.
6311 // If this is value-initialization, this could be nested some way within
6312 // the target type.
6313 assert(Kind.getKind() == InitializationKind::IK_Value ||
6314 DestType->isReferenceType());
6315 bool Diagnosed =
6316 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6317 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6318 (void)Diagnosed;
6319 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006320 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006321 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006322 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006323
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006324 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006325 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006326 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006327 case FK_ArrayNeedsInitListOrStringLiteral:
6328 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6329 break;
6330 case FK_ArrayNeedsInitListOrWideStringLiteral:
6331 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6332 break;
6333 case FK_NarrowStringIntoWideCharArray:
6334 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6335 break;
6336 case FK_WideStringIntoCharArray:
6337 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6338 break;
6339 case FK_IncompatWideStringIntoWideChar:
6340 S.Diag(Kind.getLocation(),
6341 diag::err_array_init_incompat_wide_string_into_wchar);
6342 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006343 case FK_ArrayTypeMismatch:
6344 case FK_NonConstantArrayInit:
6345 S.Diag(Kind.getLocation(),
6346 (Failure == FK_ArrayTypeMismatch
6347 ? diag::err_array_init_different_type
6348 : diag::err_array_init_non_constant_array))
6349 << DestType.getNonReferenceType()
6350 << Args[0]->getType()
6351 << Args[0]->getSourceRange();
6352 break;
6353
John McCalla59dc2f2012-01-05 00:13:19 +00006354 case FK_VariableLengthArrayHasInitializer:
6355 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6356 << Args[0]->getSourceRange();
6357 break;
6358
John McCall16df1e52010-03-30 21:47:33 +00006359 case FK_AddressOfOverloadFailed: {
6360 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006361 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006362 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006363 true,
6364 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006365 break;
John McCall16df1e52010-03-30 21:47:33 +00006366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006368 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006369 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006370 switch (FailedOverloadResult) {
6371 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006372 if (Failure == FK_UserConversionOverloadFailed)
6373 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6374 << Args[0]->getType() << DestType
6375 << Args[0]->getSourceRange();
6376 else
6377 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6378 << DestType << Args[0]->getType()
6379 << Args[0]->getSourceRange();
6380
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006381 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006382 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006383
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006384 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006385 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006386 DestType.getNonReferenceType(),
6387 diag::err_typecheck_nonviable_condition_incomplete,
6388 Args[0]->getType(), Args[0]->getSourceRange()))
6389 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6390 << Args[0]->getType() << Args[0]->getSourceRange()
6391 << DestType.getNonReferenceType();
6392
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006393 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006394 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006395
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006396 case OR_Deleted: {
6397 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6398 << Args[0]->getType() << DestType.getNonReferenceType()
6399 << Args[0]->getSourceRange();
6400 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006401 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006402 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6403 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006404 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006405 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006406 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006407 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006408 }
6409 break;
6410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006411
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006412 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006413 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006414 }
6415 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006416
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006417 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006418 if (isa<InitListExpr>(Args[0])) {
6419 S.Diag(Kind.getLocation(),
6420 diag::err_lvalue_reference_bind_to_initlist)
6421 << DestType.getNonReferenceType().isVolatileQualified()
6422 << DestType.getNonReferenceType()
6423 << Args[0]->getSourceRange();
6424 break;
6425 }
6426 // Intentional fallthrough
6427
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006428 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006429 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006430 Failure == FK_NonConstLValueReferenceBindingToTemporary
6431 ? diag::err_lvalue_reference_bind_to_temporary
6432 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006433 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006434 << DestType.getNonReferenceType()
6435 << Args[0]->getType()
6436 << Args[0]->getSourceRange();
6437 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006439 case FK_RValueReferenceBindingToLValue:
6440 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006441 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006442 << Args[0]->getSourceRange();
6443 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006445 case FK_ReferenceInitDropsQualifiers:
6446 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6447 << DestType.getNonReferenceType()
6448 << Args[0]->getType()
6449 << Args[0]->getSourceRange();
6450 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006451
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006452 case FK_ReferenceInitFailed:
6453 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6454 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006455 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006456 << Args[0]->getType()
6457 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006458 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006459 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006460
Douglas Gregorb491ed32011-02-19 21:32:49 +00006461 case FK_ConversionFailed: {
6462 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006463 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006464 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006465 << DestType
John McCall086a4642010-11-24 05:12:34 +00006466 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006467 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006468 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006469 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6470 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006471 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006472 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006473 }
John Wiegley01296292011-04-08 18:41:53 +00006474
6475 case FK_ConversionFromPropertyFailed:
6476 // No-op. This error has already been reported.
6477 break;
6478
Douglas Gregor51e77d52009-12-10 17:56:55 +00006479 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006480 SourceRange R;
6481
6482 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006483 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006484 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006485 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006486 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006487
Douglas Gregor8ec51732010-09-08 21:40:08 +00006488 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6489 if (Kind.isCStyleOrFunctionalCast())
6490 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6491 << R;
6492 else
6493 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6494 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006495 break;
6496 }
6497
6498 case FK_ReferenceBindingToInitList:
6499 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6500 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6501 break;
6502
6503 case FK_InitListBadDestinationType:
6504 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6505 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6506 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006507
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006508 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006509 case FK_ConstructorOverloadFailed: {
6510 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006511 if (Args.size())
6512 ArgsRange = SourceRange(Args.front()->getLocStart(),
6513 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006514
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006515 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006516 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006517 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006518 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006519 }
6520
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006521 // FIXME: Using "DestType" for the entity we're printing is probably
6522 // bad.
6523 switch (FailedOverloadResult) {
6524 case OR_Ambiguous:
6525 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6526 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006527 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006528 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006529
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006530 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006531 if (Kind.getKind() == InitializationKind::IK_Default &&
6532 (Entity.getKind() == InitializedEntity::EK_Base ||
6533 Entity.getKind() == InitializedEntity::EK_Member) &&
6534 isa<CXXConstructorDecl>(S.CurContext)) {
6535 // This is implicit default initialization of a member or
6536 // base within a constructor. If no viable function was
6537 // found, notify the user that she needs to explicitly
6538 // initialize this base/member.
6539 CXXConstructorDecl *Constructor
6540 = cast<CXXConstructorDecl>(S.CurContext);
6541 if (Entity.getKind() == InitializedEntity::EK_Base) {
6542 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006543 << (Constructor->getInheritedConstructor() ? 2 :
6544 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006545 << S.Context.getTypeDeclType(Constructor->getParent())
6546 << /*base=*/0
6547 << Entity.getType();
6548
6549 RecordDecl *BaseDecl
6550 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6551 ->getDecl();
6552 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6553 << S.Context.getTagDeclType(BaseDecl);
6554 } else {
6555 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006556 << (Constructor->getInheritedConstructor() ? 2 :
6557 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006558 << S.Context.getTypeDeclType(Constructor->getParent())
6559 << /*member=*/1
6560 << Entity.getName();
6561 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6562
6563 if (const RecordType *Record
6564 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006565 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006566 diag::note_previous_decl)
6567 << S.Context.getTagDeclType(Record->getDecl());
6568 }
6569 break;
6570 }
6571
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006572 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6573 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006574 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006575 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006577 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006578 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006579 OverloadingResult Ovl
6580 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006581 if (Ovl != OR_Deleted) {
6582 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6583 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006584 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006585 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006586 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006587
6588 // If this is a defaulted or implicitly-declared function, then
6589 // it was implicitly deleted. Make it clear that the deletion was
6590 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006591 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006592 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006593 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006594 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006595 else
6596 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6597 << true << DestType << ArgsRange;
6598
6599 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006600 break;
6601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006603 case OR_Success:
6604 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006605 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006606 }
David Blaikie60deeee2012-01-17 08:24:58 +00006607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006608
Douglas Gregor85dabae2009-12-16 01:38:02 +00006609 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006610 if (Entity.getKind() == InitializedEntity::EK_Member &&
6611 isa<CXXConstructorDecl>(S.CurContext)) {
6612 // This is implicit default-initialization of a const member in
6613 // a constructor. Complain that it needs to be explicitly
6614 // initialized.
6615 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6616 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006617 << (Constructor->getInheritedConstructor() ? 2 :
6618 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006619 << S.Context.getTypeDeclType(Constructor->getParent())
6620 << /*const=*/1
6621 << Entity.getName();
6622 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6623 << Entity.getName();
6624 } else {
6625 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6626 << DestType << (bool)DestType->getAs<RecordType>();
6627 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006628 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006629
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006630 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006631 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006632 diag::err_init_incomplete_type);
6633 break;
6634
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006635 case FK_ListInitializationFailed: {
6636 // Run the init list checker again to emit diagnostics.
6637 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6638 QualType DestType = Entity.getType();
6639 InitListChecker DiagnoseInitList(S, Entity, InitList,
Richard Smithde229232013-06-06 11:41:05 +00006640 DestType, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006641 assert(DiagnoseInitList.HadError() &&
6642 "Inconsistent init list check result.");
6643 break;
6644 }
John McCall4124c492011-10-17 18:40:02 +00006645
6646 case FK_PlaceholderType: {
6647 // FIXME: Already diagnosed!
6648 break;
6649 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006650
Sebastian Redl048a6d72012-04-01 19:54:59 +00006651 case FK_ExplicitConstructor: {
6652 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6653 << Args[0]->getSourceRange();
6654 OverloadCandidateSet::iterator Best;
6655 OverloadingResult Ovl
6656 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006657 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006658 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6659 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6660 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6661 break;
6662 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006665 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006666 return true;
6667}
Douglas Gregore1314a62009-12-18 05:02:21 +00006668
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006669void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006670 switch (SequenceKind) {
6671 case FailedSequence: {
6672 OS << "Failed sequence: ";
6673 switch (Failure) {
6674 case FK_TooManyInitsForReference:
6675 OS << "too many initializers for reference";
6676 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006677
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006678 case FK_ArrayNeedsInitList:
6679 OS << "array requires initializer list";
6680 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006682 case FK_ArrayNeedsInitListOrStringLiteral:
6683 OS << "array requires initializer list or string literal";
6684 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006686 case FK_ArrayNeedsInitListOrWideStringLiteral:
6687 OS << "array requires initializer list or wide string literal";
6688 break;
6689
6690 case FK_NarrowStringIntoWideCharArray:
6691 OS << "narrow string into wide char array";
6692 break;
6693
6694 case FK_WideStringIntoCharArray:
6695 OS << "wide string into char array";
6696 break;
6697
6698 case FK_IncompatWideStringIntoWideChar:
6699 OS << "incompatible wide string into wide char array";
6700 break;
6701
Douglas Gregore2f943b2011-02-22 18:29:51 +00006702 case FK_ArrayTypeMismatch:
6703 OS << "array type mismatch";
6704 break;
6705
6706 case FK_NonConstantArrayInit:
6707 OS << "non-constant array initializer";
6708 break;
6709
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006710 case FK_AddressOfOverloadFailed:
6711 OS << "address of overloaded function failed";
6712 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006713
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006714 case FK_ReferenceInitOverloadFailed:
6715 OS << "overload resolution for reference initialization failed";
6716 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006718 case FK_NonConstLValueReferenceBindingToTemporary:
6719 OS << "non-const lvalue reference bound to temporary";
6720 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006722 case FK_NonConstLValueReferenceBindingToUnrelated:
6723 OS << "non-const lvalue reference bound to unrelated type";
6724 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006725
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006726 case FK_RValueReferenceBindingToLValue:
6727 OS << "rvalue reference bound to an lvalue";
6728 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006729
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006730 case FK_ReferenceInitDropsQualifiers:
6731 OS << "reference initialization drops qualifiers";
6732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006733
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006734 case FK_ReferenceInitFailed:
6735 OS << "reference initialization failed";
6736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006737
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006738 case FK_ConversionFailed:
6739 OS << "conversion failed";
6740 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006741
John Wiegley01296292011-04-08 18:41:53 +00006742 case FK_ConversionFromPropertyFailed:
6743 OS << "conversion from property failed";
6744 break;
6745
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006746 case FK_TooManyInitsForScalar:
6747 OS << "too many initializers for scalar";
6748 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006749
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006750 case FK_ReferenceBindingToInitList:
6751 OS << "referencing binding to initializer list";
6752 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006753
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006754 case FK_InitListBadDestinationType:
6755 OS << "initializer list for non-aggregate, non-scalar type";
6756 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006757
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006758 case FK_UserConversionOverloadFailed:
6759 OS << "overloading failed for user-defined conversion";
6760 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006761
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006762 case FK_ConstructorOverloadFailed:
6763 OS << "constructor overloading failed";
6764 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006766 case FK_DefaultInitOfConst:
6767 OS << "default initialization of a const variable";
6768 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006769
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006770 case FK_Incomplete:
6771 OS << "initialization of incomplete type";
6772 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006773
6774 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006775 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006776 break;
6777
John McCalla59dc2f2012-01-05 00:13:19 +00006778 case FK_VariableLengthArrayHasInitializer:
6779 OS << "variable length array has an initializer";
6780 break;
6781
John McCall4124c492011-10-17 18:40:02 +00006782 case FK_PlaceholderType:
6783 OS << "initializer expression isn't contextually valid";
6784 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006785
6786 case FK_ListConstructorOverloadFailed:
6787 OS << "list constructor overloading failed";
6788 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006789
Sebastian Redl048a6d72012-04-01 19:54:59 +00006790 case FK_ExplicitConstructor:
6791 OS << "list copy initialization chose explicit constructor";
6792 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006794 OS << '\n';
6795 return;
6796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006797
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006798 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006799 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006800 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801
Sebastian Redld201edf2011-06-05 13:59:11 +00006802 case NormalSequence:
6803 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006804 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006807 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6808 if (S != step_begin()) {
6809 OS << " -> ";
6810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006812 switch (S->Kind) {
6813 case SK_ResolveAddressOfOverloadedFunction:
6814 OS << "resolve address of overloaded function";
6815 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006816
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006817 case SK_CastDerivedToBaseRValue:
6818 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6819 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006821 case SK_CastDerivedToBaseXValue:
6822 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6823 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006824
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006825 case SK_CastDerivedToBaseLValue:
6826 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6827 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006828
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006829 case SK_BindReference:
6830 OS << "bind reference to lvalue";
6831 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006832
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006833 case SK_BindReferenceToTemporary:
6834 OS << "bind reference to a temporary";
6835 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006837 case SK_ExtraneousCopyToTemporary:
6838 OS << "extraneous C++03 copy to temporary";
6839 break;
6840
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006841 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006842 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006843 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006844
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006845 case SK_QualificationConversionRValue:
6846 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006847 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006848
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006849 case SK_QualificationConversionXValue:
6850 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006851 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006852
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006853 case SK_QualificationConversionLValue:
6854 OS << "qualification conversion (lvalue)";
6855 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006856
Jordan Roseb1312a52013-04-11 00:58:58 +00006857 case SK_LValueToRValue:
6858 OS << "load (lvalue to rvalue)";
6859 break;
6860
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006861 case SK_ConversionSequence:
6862 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006863 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006864 OS << ")";
6865 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866
Richard Smithaaa0ec42013-09-21 21:19:19 +00006867 case SK_ConversionSequenceNoNarrowing:
6868 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006869 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00006870 OS << ")";
6871 break;
6872
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006873 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006874 OS << "list aggregate initialization";
6875 break;
6876
6877 case SK_ListConstructorCall:
6878 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006879 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
Sebastian Redl29526f02011-11-27 16:50:07 +00006881 case SK_UnwrapInitList:
6882 OS << "unwrap reference initializer list";
6883 break;
6884
6885 case SK_RewrapInitList:
6886 OS << "rewrap reference initializer list";
6887 break;
6888
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006889 case SK_ConstructorInitialization:
6890 OS << "constructor initialization";
6891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006893 case SK_ZeroInitialization:
6894 OS << "zero initialization";
6895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006897 case SK_CAssignment:
6898 OS << "C assignment";
6899 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006901 case SK_StringInit:
6902 OS << "string initialization";
6903 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006904
6905 case SK_ObjCObjectConversion:
6906 OS << "Objective-C object conversion";
6907 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006908
6909 case SK_ArrayInit:
6910 OS << "array initialization";
6911 break;
John McCall31168b02011-06-15 23:02:42 +00006912
Richard Smithebeed412012-02-15 22:38:09 +00006913 case SK_ParenthesizedArrayInit:
6914 OS << "parenthesized array initialization";
6915 break;
6916
John McCall31168b02011-06-15 23:02:42 +00006917 case SK_PassByIndirectCopyRestore:
6918 OS << "pass by indirect copy and restore";
6919 break;
6920
6921 case SK_PassByIndirectRestore:
6922 OS << "pass by indirect restore";
6923 break;
6924
6925 case SK_ProduceObjCObject:
6926 OS << "Objective-C object retension";
6927 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006928
6929 case SK_StdInitializerList:
6930 OS << "std::initializer_list from initializer list";
6931 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006932
Guy Benyei61054192013-02-07 10:55:47 +00006933 case SK_OCLSamplerInit:
6934 OS << "OpenCL sampler_t from integer constant";
6935 break;
6936
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006937 case SK_OCLZeroEvent:
6938 OS << "OpenCL event_t from zero";
6939 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006940 }
Richard Smith6b216962013-02-05 05:52:24 +00006941
6942 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006943 }
Richard Smith6b216962013-02-05 05:52:24 +00006944
6945 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006946}
6947
6948void InitializationSequence::dump() const {
6949 dump(llvm::errs());
6950}
6951
Richard Smithaaa0ec42013-09-21 21:19:19 +00006952static void DiagnoseNarrowingInInitList(Sema &S,
6953 const ImplicitConversionSequence &ICS,
6954 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006955 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006956 const Expr *PostInit) {
Richard Smith66e05fe2012-01-18 05:21:49 +00006957 const StandardConversionSequence *SCS = 0;
6958 switch (ICS.getKind()) {
6959 case ImplicitConversionSequence::StandardConversion:
6960 SCS = &ICS.Standard;
6961 break;
6962 case ImplicitConversionSequence::UserDefinedConversion:
6963 SCS = &ICS.UserDefined.After;
6964 break;
6965 case ImplicitConversionSequence::AmbiguousConversion:
6966 case ImplicitConversionSequence::EllipsisConversion:
6967 case ImplicitConversionSequence::BadConversion:
6968 return;
6969 }
6970
Richard Smith66e05fe2012-01-18 05:21:49 +00006971 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6972 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00006973 QualType ConstantType;
6974 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6975 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00006976 case NK_Not_Narrowing:
6977 // No narrowing occurred.
6978 return;
6979
6980 case NK_Type_Narrowing:
6981 // This was a floating-to-integer conversion, which is always considered a
6982 // narrowing conversion even if the value is a constant and can be
6983 // represented exactly as an integer.
6984 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00006985 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
6986 ? diag::warn_init_list_type_narrowing
6987 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006988 << PostInit->getSourceRange()
6989 << PreNarrowingType.getLocalUnqualifiedType()
6990 << EntityType.getLocalUnqualifiedType();
6991 break;
6992
6993 case NK_Constant_Narrowing:
6994 // A constant value was narrowed.
6995 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00006996 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
6997 ? diag::warn_init_list_constant_narrowing
6998 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00006999 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007000 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007001 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007002 break;
7003
7004 case NK_Variable_Narrowing:
7005 // A variable's value may have been narrowed.
7006 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007007 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7008 ? diag::warn_init_list_variable_narrowing
7009 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007010 << PostInit->getSourceRange()
7011 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007012 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007013 break;
7014 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007015
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007016 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007017 llvm::raw_svector_ostream OS(StaticCast);
7018 OS << "static_cast<";
7019 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7020 // It's important to use the typedef's name if there is one so that the
7021 // fixit doesn't break code using types like int64_t.
7022 //
7023 // FIXME: This will break if the typedef requires qualification. But
7024 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007025 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007026 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007027 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007028 else {
7029 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7030 // with a broken cast.
7031 return;
7032 }
7033 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00007034 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
7035 << PostInit->getSourceRange()
7036 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007037 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00007038 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007039}
7040
Douglas Gregore1314a62009-12-18 05:02:21 +00007041//===----------------------------------------------------------------------===//
7042// Initialization helper functions
7043//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007044bool
7045Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7046 ExprResult Init) {
7047 if (Init.isInvalid())
7048 return false;
7049
7050 Expr *InitE = Init.get();
7051 assert(InitE && "No initialization expression");
7052
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007053 InitializationKind Kind
7054 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007055 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007056 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007057}
7058
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007060Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7061 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007062 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007063 bool TopLevelOfInitList,
7064 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007065 if (Init.isInvalid())
7066 return ExprError();
7067
John McCall1f425642010-11-11 03:21:53 +00007068 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007069 assert(InitE && "No initialization expression?");
7070
7071 if (EqualLoc.isInvalid())
7072 EqualLoc = InitE->getLocStart();
7073
7074 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007075 EqualLoc,
7076 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007077 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Douglas Gregore1314a62009-12-18 05:02:21 +00007078 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007079
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007080 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007081
Richard Smith66e05fe2012-01-18 05:21:49 +00007082 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007083}