blob: 9ba873a0780b7b4ebe05ad3beb2fa56930817ef2 [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:
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002511 return DeclarationName(Capture.VarID);
Douglas Gregor19666fb2012-02-15 16:57:26 +00002512
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 ";
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00002613 OS << DeclarationName(Capture.VarID);
Richard Smithe6c01442013-06-05 00:46:14 +00002614 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];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004465 if (S.getLangOpts().ObjC1) {
4466 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4467 DestType, Initializer->getType(),
4468 Initializer) ||
4469 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4470 Args[0] = Initializer;
4471
4472 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004473 if (!isa<InitListExpr>(Initializer))
4474 SourceType = Initializer->getType();
4475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Sebastian Redl0501c632012-02-12 16:37:36 +00004477 // - If the initializer is a (non-parenthesized) braced-init-list, the
4478 // object is list-initialized (8.5.4).
4479 if (Kind.getKind() != InitializationKind::IK_Direct) {
4480 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4481 TryListInitialization(S, Entity, Kind, InitList, *this);
4482 return;
4483 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004486 // - If the destination type is a reference type, see 8.5.3.
4487 if (DestType->isReferenceType()) {
4488 // C++0x [dcl.init.ref]p1:
4489 // A variable declared to be a T& or T&&, that is, "reference to type T"
4490 // (8.3.2), shall be initialized by an object, or function, of type T or
4491 // by an object that can be converted into a T.
4492 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004493 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004494 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004495 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004496 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004497 return;
4498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004500 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004501 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004502 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004503 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004504 return;
4505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregor85dabae2009-12-16 01:38:02 +00004507 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004508 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004509 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004510 return;
4511 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004512
John McCall66884dd2011-02-21 07:22:22 +00004513 // - If the destination type is an array of characters, an array of
4514 // char16_t, an array of char32_t, or an array of wchar_t, and the
4515 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004517 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004518 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004519 if (Initializer && isa<VariableArrayType>(DestAT)) {
4520 SetFailed(FK_VariableLengthArrayHasInitializer);
4521 return;
4522 }
4523
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004524 if (Initializer) {
4525 switch (IsStringInit(Initializer, DestAT, Context)) {
4526 case SIF_None:
4527 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4528 return;
4529 case SIF_NarrowStringIntoWideChar:
4530 SetFailed(FK_NarrowStringIntoWideCharArray);
4531 return;
4532 case SIF_WideStringIntoChar:
4533 SetFailed(FK_WideStringIntoCharArray);
4534 return;
4535 case SIF_IncompatWideStringIntoWideChar:
4536 SetFailed(FK_IncompatWideStringIntoWideChar);
4537 return;
4538 case SIF_Other:
4539 break;
4540 }
John McCall66884dd2011-02-21 07:22:22 +00004541 }
4542
Douglas Gregore2f943b2011-02-22 18:29:51 +00004543 // Note: as an GNU C extension, we allow initialization of an
4544 // array from a compound literal that creates an array of the same
4545 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004546 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004547 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4548 Initializer->getType()->isArrayType()) {
4549 const ArrayType *SourceAT
4550 = Context.getAsArrayType(Initializer->getType());
4551 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004552 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004553 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004554 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004555 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004556 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004557 }
Richard Smithebeed412012-02-15 22:38:09 +00004558 }
Richard Smithd86812d2012-07-05 08:39:21 +00004559 // Note: as a GNU C++ extension, we allow list-initialization of a
4560 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004561 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004562 Entity.getKind() == InitializedEntity::EK_Member &&
4563 Initializer && isa<InitListExpr>(Initializer)) {
4564 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4565 *this);
4566 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004567 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004568 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004569 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4570 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004571 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004572 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004573
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004574 return;
4575 }
Eli Friedman78275202009-12-19 08:11:05 +00004576
John McCall31168b02011-06-15 23:02:42 +00004577 // Determine whether we should consider writeback conversions for
4578 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004579 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004580 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004581
4582 // We're at the end of the line for C: it's either a write-back conversion
4583 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004584 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004585 // If allowed, check whether this is an Objective-C writeback conversion.
4586 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004587 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004588 return;
4589 }
Guy Benyei61054192013-02-07 10:55:47 +00004590
4591 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4592 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004593
4594 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4595 return;
4596
John McCall31168b02011-06-15 23:02:42 +00004597 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004598 AddCAssignmentStep(DestType);
4599 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004600 return;
4601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602
David Blaikiebbafb8a2012-03-11 07:00:24 +00004603 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004604
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004605 // - If the destination type is a (possibly cv-qualified) class type:
4606 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607 // - If the initialization is direct-initialization, or if it is
4608 // copy-initialization where the cv-unqualified version of the
4609 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004610 // class of the destination, constructors are considered. [...]
4611 if (Kind.getKind() == InitializationKind::IK_Direct ||
4612 (Kind.getKind() == InitializationKind::IK_Copy &&
4613 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4614 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004615 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004616 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004618 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004620 // used) to a derived class thereof are enumerated as described in
4621 // 13.3.1.4, and the best one is chosen through overload resolution
4622 // (13.3).
4623 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004624 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4625 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004626 return;
4627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004628
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004629 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004630 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004631 return;
4632 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004633 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634
4635 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004636 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004637 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004638 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4639 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004640 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004641 return;
4642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004644 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004645 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004646 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004648 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004649
4650 ImplicitConversionSequence ICS
4651 = S.TryImplicitConversion(Initializer, Entity.getType(),
4652 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004653 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004654 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004655 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4656 allowObjCWritebackConversion);
4657
4658 if (ICS.isStandard() &&
4659 ICS.Standard.Second == ICK_Writeback_Conversion) {
4660 // Objective-C ARC writeback conversion.
4661
4662 // We should copy unless we're passing to an argument explicitly
4663 // marked 'out'.
4664 bool ShouldCopy = true;
4665 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4666 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4667
4668 // If there was an lvalue adjustment, add it as a separate conversion.
4669 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4670 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4671 ImplicitConversionSequence LvalueICS;
4672 LvalueICS.setStandard();
4673 LvalueICS.Standard.setAsIdentityConversion();
4674 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4675 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004676 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004677 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004678
4679 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004680 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004681 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004682 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4683 AddZeroInitializationStep(Entity.getType());
4684 } else if (Initializer->getType() == Context.OverloadTy &&
4685 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4686 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004687 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004688 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004689 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004690 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004691 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004692
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004693 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004694 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004695}
4696
4697InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004698 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004699 StepEnd = Steps.end();
4700 Step != StepEnd; ++Step)
4701 Step->Destroy();
4702}
4703
4704//===----------------------------------------------------------------------===//
4705// Perform initialization
4706//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004708getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004709 switch(Entity.getKind()) {
4710 case InitializedEntity::EK_Variable:
4711 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004712 case InitializedEntity::EK_Exception:
4713 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004714 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004715 return Sema::AA_Initializing;
4716
4717 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004718 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004719 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4720 return Sema::AA_Sending;
4721
Douglas Gregore1314a62009-12-18 05:02:21 +00004722 return Sema::AA_Passing;
4723
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004724 case InitializedEntity::EK_Parameter_CF_Audited:
4725 if (Entity.getDecl() &&
4726 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4727 return Sema::AA_Sending;
4728
4729 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4730
Douglas Gregore1314a62009-12-18 05:02:21 +00004731 case InitializedEntity::EK_Result:
4732 return Sema::AA_Returning;
4733
Douglas Gregore1314a62009-12-18 05:02:21 +00004734 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004735 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004736 // FIXME: Can we tell apart casting vs. converting?
4737 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Douglas Gregore1314a62009-12-18 05:02:21 +00004739 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004740 case InitializedEntity::EK_ArrayElement:
4741 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004742 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004743 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004744 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004745 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004746 return Sema::AA_Initializing;
4747 }
4748
David Blaikie8a40f702012-01-17 06:56:22 +00004749 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004750}
4751
Richard Smith27874d62013-01-08 00:08:23 +00004752/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004753/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004754static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004755 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004756 case InitializedEntity::EK_ArrayElement:
4757 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004758 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004759 case InitializedEntity::EK_New:
4760 case InitializedEntity::EK_Variable:
4761 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004762 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004763 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004764 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004765 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004766 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004767 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004768 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004769 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Douglas Gregore1314a62009-12-18 05:02:21 +00004771 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004772 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004773 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004774 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004775 return true;
4776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregore1314a62009-12-18 05:02:21 +00004778 llvm_unreachable("missed an InitializedEntity kind?");
4779}
4780
Douglas Gregor95562572010-04-24 23:45:46 +00004781/// \brief Whether the given entity, when initialized with an object
4782/// created for that initialization, requires destruction.
4783static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4784 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004785 case InitializedEntity::EK_Result:
4786 case InitializedEntity::EK_New:
4787 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004788 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004789 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004790 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004791 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004792 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004793 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004794
Richard Smith27874d62013-01-08 00:08:23 +00004795 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004796 case InitializedEntity::EK_Variable:
4797 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004798 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004799 case InitializedEntity::EK_Temporary:
4800 case InitializedEntity::EK_ArrayElement:
4801 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004802 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004803 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004804 return true;
4805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
4807 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004808}
4809
Richard Smithc620f552011-10-19 16:55:56 +00004810/// \brief Look for copy and move constructors and constructor templates, for
4811/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4812static void LookupCopyAndMoveConstructors(Sema &S,
4813 OverloadCandidateSet &CandidateSet,
4814 CXXRecordDecl *Class,
4815 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004816 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004817 // The container holding the constructors can under certain conditions
4818 // be changed while iterating (e.g. because of deserialization).
4819 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004820 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004821 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004822 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4823 NamedDecl *D = *CI;
Richard Smithc620f552011-10-19 16:55:56 +00004824 CXXConstructorDecl *Constructor = 0;
4825
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004826 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004827 // Handle copy/moveconstructors, only.
4828 if (!Constructor || Constructor->isInvalidDecl() ||
4829 !Constructor->isCopyOrMoveConstructor() ||
4830 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4831 continue;
4832
4833 DeclAccessPair FoundDecl
4834 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4835 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004836 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004837 continue;
4838 }
4839
4840 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004841 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004842 if (ConstructorTmpl->isInvalidDecl())
4843 continue;
4844
4845 Constructor = cast<CXXConstructorDecl>(
4846 ConstructorTmpl->getTemplatedDecl());
4847 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4848 continue;
4849
4850 // FIXME: Do we need to limit this to copy-constructor-like
4851 // candidates?
4852 DeclAccessPair FoundDecl
4853 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4854 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004855 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004856 }
4857}
4858
4859/// \brief Get the location at which initialization diagnostics should appear.
4860static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4861 Expr *Initializer) {
4862 switch (Entity.getKind()) {
4863 case InitializedEntity::EK_Result:
4864 return Entity.getReturnLoc();
4865
4866 case InitializedEntity::EK_Exception:
4867 return Entity.getThrowLoc();
4868
4869 case InitializedEntity::EK_Variable:
4870 return Entity.getDecl()->getLocation();
4871
Douglas Gregor19666fb2012-02-15 16:57:26 +00004872 case InitializedEntity::EK_LambdaCapture:
4873 return Entity.getCaptureLoc();
4874
Richard Smithc620f552011-10-19 16:55:56 +00004875 case InitializedEntity::EK_ArrayElement:
4876 case InitializedEntity::EK_Member:
4877 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004878 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00004879 case InitializedEntity::EK_Temporary:
4880 case InitializedEntity::EK_New:
4881 case InitializedEntity::EK_Base:
4882 case InitializedEntity::EK_Delegating:
4883 case InitializedEntity::EK_VectorElement:
4884 case InitializedEntity::EK_ComplexElement:
4885 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004886 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004887 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00004888 return Initializer->getLocStart();
4889 }
4890 llvm_unreachable("missed an InitializedEntity kind?");
4891}
4892
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004893/// \brief Make a (potentially elidable) temporary copy of the object
4894/// provided by the given initializer by calling the appropriate copy
4895/// constructor.
4896///
4897/// \param S The Sema object used for type-checking.
4898///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004899/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004900/// the type of the initializer expression or a superclass thereof.
4901///
James Dennett634962f2012-06-14 21:40:34 +00004902/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004903///
4904/// \param CurInit The initializer expression.
4905///
4906/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4907/// is permitted in C++03 (but not C++0x) when binding a reference to
4908/// an rvalue.
4909///
4910/// \returns An expression that copies the initializer expression into
4911/// a temporary object, or an error expression if a copy could not be
4912/// created.
John McCalldadc5752010-08-24 06:29:42 +00004913static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004914 QualType T,
4915 const InitializedEntity &Entity,
4916 ExprResult CurInit,
4917 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004918 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004919 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004920 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004921 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004922 Class = cast<CXXRecordDecl>(Record->getDecl());
4923 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004924 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004925
Douglas Gregor5d369002011-01-21 18:05:27 +00004926 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004927 // When certain criteria are met, an implementation is allowed to
4928 // omit the copy/move construction of a class object, even if the
4929 // copy/move constructor and/or destructor for the object have
4930 // side effects. [...]
4931 // - when a temporary class object that has not been bound to a
4932 // reference (12.2) would be copied/moved to a class object
4933 // with the same cv-unqualified type, the copy/move operation
4934 // can be omitted by constructing the temporary object
4935 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004937 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004938 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004940 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004941 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004942 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004943
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004945 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004946 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00004947
Douglas Gregorf282a762011-01-21 19:38:21 +00004948 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004949 // Only consider constructors and constructor templates. Per
4950 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4951 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004952 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004953 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004955 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4956
Douglas Gregore1314a62009-12-18 05:02:21 +00004957 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004958 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004959 case OR_Success:
4960 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004961
Douglas Gregore1314a62009-12-18 05:02:21 +00004962 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004963 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4964 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4965 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004966 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004967 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004968 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004969 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004970 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004971 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004972
Douglas Gregore1314a62009-12-18 05:02:21 +00004973 case OR_Ambiguous:
4974 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004975 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004976 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004977 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00004978 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979
Douglas Gregore1314a62009-12-18 05:02:21 +00004980 case OR_Deleted:
4981 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004982 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004983 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00004984 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00004985 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004986 }
4987
Douglas Gregor5ab11652010-04-17 22:01:05 +00004988 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00004989 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor5ab11652010-04-17 22:01:05 +00004990 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004991
Anders Carlssona01874b2010-04-21 18:47:17 +00004992 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004993 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004994
4995 if (IsExtraneousCopy) {
4996 // If this is a totally extraneous copy for C++03 reference
4997 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004998 // expression. We don't generate an (elided) copy operation here
4999 // because doing so would require us to pass down a flag to avoid
5000 // infinite recursion, where each step adds another extraneous,
5001 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005002
Douglas Gregor30b52772010-04-18 07:57:34 +00005003 // Instantiate the default arguments of any extra parameters in
5004 // the selected copy constructor, as if we were going to create a
5005 // proper call to the copy constructor.
5006 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5007 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5008 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005009 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005010 break;
5011
5012 // Build the default argument expression; we don't actually care
5013 // if this succeeds or not, because this routine will complain
5014 // if there was a problem.
5015 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5016 }
5017
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005018 return S.Owned(CurInitExpr);
5019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020
Douglas Gregor5ab11652010-04-17 22:01:05 +00005021 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005022 // constructor call (we might have derived-to-base conversions, or
5023 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005024 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005025 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005026
Douglas Gregord0ace022010-04-25 00:55:24 +00005027 // Actually perform the constructor call.
5028 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005029 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005030 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005031 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005032 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005033 CXXConstructExpr::CK_Complete,
5034 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005035
Douglas Gregord0ace022010-04-25 00:55:24 +00005036 // If we're supposed to bind temporaries, do so.
5037 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5038 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005039 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005040}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005041
Richard Smithc620f552011-10-19 16:55:56 +00005042/// \brief Check whether elidable copy construction for binding a reference to
5043/// a temporary would have succeeded if we were building in C++98 mode, for
5044/// -Wc++98-compat.
5045static void CheckCXX98CompatAccessibleCopy(Sema &S,
5046 const InitializedEntity &Entity,
5047 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005048 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005049
5050 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5051 if (!Record)
5052 return;
5053
5054 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5055 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5056 == DiagnosticsEngine::Ignored)
5057 return;
5058
5059 // Find constructors which would have been considered.
5060 OverloadCandidateSet CandidateSet(Loc);
5061 LookupCopyAndMoveConstructors(
5062 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5063
5064 // Perform overload resolution.
5065 OverloadCandidateSet::iterator Best;
5066 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5067
5068 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5069 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5070 << CurInitExpr->getSourceRange();
5071
5072 switch (OR) {
5073 case OR_Success:
5074 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005075 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005076 // FIXME: Check default arguments as far as that's possible.
5077 break;
5078
5079 case OR_No_Viable_Function:
5080 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005081 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005082 break;
5083
5084 case OR_Ambiguous:
5085 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005086 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005087 break;
5088
5089 case OR_Deleted:
5090 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005091 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005092 break;
5093 }
5094}
5095
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005096void InitializationSequence::PrintInitLocationNote(Sema &S,
5097 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005098 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005099 if (Entity.getDecl()->getLocation().isInvalid())
5100 return;
5101
5102 if (Entity.getDecl()->getDeclName())
5103 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5104 << Entity.getDecl()->getDeclName();
5105 else
5106 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5107 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005108 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5109 Entity.getMethodDecl())
5110 S.Diag(Entity.getMethodDecl()->getLocation(),
5111 diag::note_method_return_type_change)
5112 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005113}
5114
Sebastian Redl112aa822011-07-14 19:07:55 +00005115static bool isReferenceBinding(const InitializationSequence::Step &s) {
5116 return s.Kind == InitializationSequence::SK_BindReference ||
5117 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5118}
5119
Jordan Rose6c0505e2013-05-06 16:48:12 +00005120/// Returns true if the parameters describe a constructor initialization of
5121/// an explicit temporary object, e.g. "Point(x, y)".
5122static bool isExplicitTemporary(const InitializedEntity &Entity,
5123 const InitializationKind &Kind,
5124 unsigned NumArgs) {
5125 switch (Entity.getKind()) {
5126 case InitializedEntity::EK_Temporary:
5127 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005128 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005129 break;
5130 default:
5131 return false;
5132 }
5133
5134 switch (Kind.getKind()) {
5135 case InitializationKind::IK_DirectList:
5136 return true;
5137 // FIXME: Hack to work around cast weirdness.
5138 case InitializationKind::IK_Direct:
5139 case InitializationKind::IK_Value:
5140 return NumArgs != 1;
5141 default:
5142 return false;
5143 }
5144}
5145
Sebastian Redled2e5322011-12-22 14:44:04 +00005146static ExprResult
5147PerformConstructorInitialization(Sema &S,
5148 const InitializedEntity &Entity,
5149 const InitializationKind &Kind,
5150 MultiExprArg Args,
5151 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005152 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005153 bool IsListInitialization,
5154 SourceLocation LBraceLoc,
5155 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005156 unsigned NumArgs = Args.size();
5157 CXXConstructorDecl *Constructor
5158 = cast<CXXConstructorDecl>(Step.Function.Function);
5159 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5160
5161 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005162 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005163 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5164 ? Kind.getEqualLoc()
5165 : Kind.getLocation();
5166
5167 if (Kind.getKind() == InitializationKind::IK_Default) {
5168 // Force even a trivial, implicit default constructor to be
5169 // semantically checked. We do this explicitly because we don't build
5170 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005171 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005172 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005173 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005174 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5175 }
5176
5177 ExprResult CurInit = S.Owned((Expr *)0);
5178
Douglas Gregor6073dca2012-02-24 23:56:31 +00005179 // C++ [over.match.copy]p1:
5180 // - When initializing a temporary to be bound to the first parameter
5181 // of a constructor that takes a reference to possibly cv-qualified
5182 // T as its first argument, called with a single argument in the
5183 // context of direct-initialization, explicit conversion functions
5184 // are also considered.
5185 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5186 Args.size() == 1 &&
5187 Constructor->isCopyOrMoveConstructor();
5188
Sebastian Redled2e5322011-12-22 14:44:04 +00005189 // Determine the arguments required to actually perform the constructor
5190 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005191 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005192 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005193 AllowExplicitConv,
5194 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005195 return ExprError();
5196
5197
Jordan Rose6c0505e2013-05-06 16:48:12 +00005198 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005199 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005200 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005201 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5202 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005203
5204 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5205 if (!TSInfo)
5206 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005207 SourceRange ParenOrBraceRange =
5208 (Kind.getKind() == InitializationKind::IK_DirectList)
5209 ? SourceRange(LBraceLoc, RBraceLoc)
5210 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005211
Richard Smithd59b8322012-12-19 01:39:02 +00005212 CurInit = S.Owned(
5213 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5214 TSInfo, ConstructorArgs,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005215 ParenOrBraceRange,
Richard Smithd59b8322012-12-19 01:39:02 +00005216 HadMultipleCandidates,
Enea Zaffanella82a65fc2013-09-07 11:22:02 +00005217 IsListInitialization,
Richard Smithd59b8322012-12-19 01:39:02 +00005218 ConstructorInitRequiresZeroInit));
Sebastian Redled2e5322011-12-22 14:44:04 +00005219 } else {
5220 CXXConstructExpr::ConstructionKind ConstructKind =
5221 CXXConstructExpr::CK_Complete;
5222
5223 if (Entity.getKind() == InitializedEntity::EK_Base) {
5224 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5225 CXXConstructExpr::CK_VirtualBase :
5226 CXXConstructExpr::CK_NonVirtualBase;
5227 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5228 ConstructKind = CXXConstructExpr::CK_Delegating;
5229 }
5230
5231 // Only get the parenthesis range if it is a direct construction.
5232 SourceRange parenRange =
5233 Kind.getKind() == InitializationKind::IK_Direct ?
5234 Kind.getParenRange() : SourceRange();
5235
5236 // If the entity allows NRVO, mark the construction as elidable
5237 // unconditionally.
5238 if (Entity.allowsNRVO())
5239 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5240 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005241 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005242 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005243 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005244 ConstructorInitRequiresZeroInit,
5245 ConstructKind,
5246 parenRange);
5247 else
5248 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5249 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005250 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005251 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005252 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005253 ConstructorInitRequiresZeroInit,
5254 ConstructKind,
5255 parenRange);
5256 }
5257 if (CurInit.isInvalid())
5258 return ExprError();
5259
5260 // Only check access if all of that succeeded.
5261 S.CheckConstructorAccess(Loc, Constructor, Entity,
5262 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005263 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5264 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005265
5266 if (shouldBindAsTemporary(Entity))
Richard Smithcc1b96d2013-06-12 22:31:48 +00005267 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redled2e5322011-12-22 14:44:04 +00005268
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005269 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005270}
5271
Richard Smitheb3cad52012-06-04 22:27:30 +00005272/// Determine whether the specified InitializedEntity definitely has a lifetime
5273/// longer than the current full-expression. Conservatively returns false if
5274/// it's unclear.
5275static bool
5276InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5277 const InitializedEntity *Top = &Entity;
5278 while (Top->getParent())
5279 Top = Top->getParent();
5280
5281 switch (Top->getKind()) {
5282 case InitializedEntity::EK_Variable:
5283 case InitializedEntity::EK_Result:
5284 case InitializedEntity::EK_Exception:
5285 case InitializedEntity::EK_Member:
5286 case InitializedEntity::EK_New:
5287 case InitializedEntity::EK_Base:
5288 case InitializedEntity::EK_Delegating:
5289 return true;
5290
5291 case InitializedEntity::EK_ArrayElement:
5292 case InitializedEntity::EK_VectorElement:
5293 case InitializedEntity::EK_BlockElement:
5294 case InitializedEntity::EK_ComplexElement:
5295 // Could not determine what the full initialization is. Assume it might not
5296 // outlive the full-expression.
5297 return false;
5298
5299 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005300 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005301 case InitializedEntity::EK_Temporary:
5302 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005303 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005304 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005305 // The entity being initialized might not outlive the full-expression.
5306 return false;
5307 }
5308
5309 llvm_unreachable("unknown entity kind");
5310}
5311
Richard Smithe6c01442013-06-05 00:46:14 +00005312/// Determine the declaration which an initialized entity ultimately refers to,
5313/// for the purpose of lifetime-extending a temporary bound to a reference in
5314/// the initialization of \p Entity.
5315static const ValueDecl *
5316getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5317 const ValueDecl *FallbackDecl = 0) {
5318 // C++11 [class.temporary]p5:
5319 switch (Entity.getKind()) {
5320 case InitializedEntity::EK_Variable:
5321 // The temporary [...] persists for the lifetime of the reference
5322 return Entity.getDecl();
5323
5324 case InitializedEntity::EK_Member:
5325 // For subobjects, we look at the complete object.
5326 if (Entity.getParent())
5327 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5328 Entity.getDecl());
5329
5330 // except:
5331 // -- A temporary bound to a reference member in a constructor's
5332 // ctor-initializer persists until the constructor exits.
5333 return Entity.getDecl();
5334
5335 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005336 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005337 // -- A temporary bound to a reference parameter in a function call
5338 // persists until the completion of the full-expression containing
5339 // the call.
5340 case InitializedEntity::EK_Result:
5341 // -- The lifetime of a temporary bound to the returned value in a
5342 // function return statement is not extended; the temporary is
5343 // destroyed at the end of the full-expression in the return statement.
5344 case InitializedEntity::EK_New:
5345 // -- A temporary bound to a reference in a new-initializer persists
5346 // until the completion of the full-expression containing the
5347 // new-initializer.
5348 return 0;
5349
5350 case InitializedEntity::EK_Temporary:
5351 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005352 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005353 // We don't yet know the storage duration of the surrounding temporary.
5354 // Assume it's got full-expression duration for now, it will patch up our
5355 // storage duration if that's not correct.
5356 return 0;
5357
5358 case InitializedEntity::EK_ArrayElement:
5359 // For subobjects, we look at the complete object.
5360 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5361 FallbackDecl);
5362
5363 case InitializedEntity::EK_Base:
5364 case InitializedEntity::EK_Delegating:
5365 // We can reach this case for aggregate initialization in a constructor:
5366 // struct A { int &&r; };
5367 // struct B : A { B() : A{0} {} };
5368 // In this case, use the innermost field decl as the context.
5369 return FallbackDecl;
5370
5371 case InitializedEntity::EK_BlockElement:
5372 case InitializedEntity::EK_LambdaCapture:
5373 case InitializedEntity::EK_Exception:
5374 case InitializedEntity::EK_VectorElement:
5375 case InitializedEntity::EK_ComplexElement:
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005376 return 0;
Richard Smithe6c01442013-06-05 00:46:14 +00005377 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005378 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005379}
5380
5381static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5382
5383/// Update a glvalue expression that is used as the initializer of a reference
5384/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005385/// \return \c true if any temporary had its lifetime extended.
5386static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
Richard Smithe6c01442013-06-05 00:46:14 +00005387 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5388 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5389 // This is just redundant braces around an initializer. Step over it.
5390 Init = ILE->getInit(0);
5391 }
5392 }
5393
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005394 // Walk past any constructs which we can lifetime-extend across.
5395 Expr *Old;
5396 do {
5397 Old = Init;
5398
5399 // Step over any subobject adjustments; we may have a materialized
5400 // temporary inside them.
5401 SmallVector<const Expr *, 2> CommaLHSs;
5402 SmallVector<SubobjectAdjustment, 2> Adjustments;
5403 Init = const_cast<Expr *>(
5404 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5405
5406 // Per current approach for DR1376, look through casts to reference type
5407 // when performing lifetime extension.
5408 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5409 if (CE->getSubExpr()->isGLValue())
5410 Init = CE->getSubExpr();
5411
5412 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5413 // It's unclear if binding a reference to that xvalue extends the array
5414 // temporary.
5415 } while (Init != Old);
5416
Richard Smithe6c01442013-06-05 00:46:14 +00005417 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5418 // Update the storage duration of the materialized temporary.
5419 // FIXME: Rebuild the expression instead of mutating it.
5420 ME->setExtendingDecl(ExtendingD);
5421 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005422 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005423 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005424
5425 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005426}
5427
5428/// Update a prvalue expression that is going to be materialized as a
5429/// lifetime-extended temporary.
5430static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5431 // Dig out the expression which constructs the extended temporary.
5432 SmallVector<const Expr *, 2> CommaLHSs;
5433 SmallVector<SubobjectAdjustment, 2> Adjustments;
5434 Init = const_cast<Expr *>(
5435 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5436
Richard Smith736a9472013-06-12 20:42:33 +00005437 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5438 Init = BTE->getSubExpr();
5439
Richard Smithcc1b96d2013-06-12 22:31:48 +00005440 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005441 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5442 performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5443 return;
5444 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005445
Richard Smithe6c01442013-06-05 00:46:14 +00005446 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005447 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005448 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5449 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5450 return;
5451 }
5452
Richard Smithcc1b96d2013-06-12 22:31:48 +00005453 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005454 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5455
5456 // If we lifetime-extend a braced initializer which is initializing an
5457 // aggregate, and that aggregate contains reference members which are
5458 // bound to temporaries, those temporaries are also lifetime-extended.
5459 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5460 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5461 performReferenceExtension(ILE->getInit(0), ExtendingD);
5462 else {
5463 unsigned Index = 0;
5464 for (RecordDecl::field_iterator I = RD->field_begin(),
5465 E = RD->field_end();
5466 I != E; ++I) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005467 if (Index >= ILE->getNumInits())
5468 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005469 if (I->isUnnamedBitfield())
5470 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005471 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005472 if (I->getType()->isReferenceType())
Richard Smith8d7f11d2013-06-27 22:54:33 +00005473 performReferenceExtension(SubInit, ExtendingD);
5474 else if (isa<InitListExpr>(SubInit) ||
5475 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005476 // This may be either aggregate-initialization of a member or
5477 // initialization of a std::initializer_list object. Either way,
5478 // we should recursively lifetime-extend that initializer.
Richard Smith8d7f11d2013-06-27 22:54:33 +00005479 performLifetimeExtension(SubInit, ExtendingD);
Richard Smithe6c01442013-06-05 00:46:14 +00005480 ++Index;
5481 }
5482 }
5483 }
5484 }
5485}
5486
Richard Smithcc1b96d2013-06-12 22:31:48 +00005487static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5488 const Expr *Init, bool IsInitializerList,
5489 const ValueDecl *ExtendingDecl) {
5490 // Warn if a field lifetime-extends a temporary.
5491 if (isa<FieldDecl>(ExtendingDecl)) {
5492 if (IsInitializerList) {
5493 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5494 << /*at end of constructor*/true;
5495 return;
5496 }
5497
5498 bool IsSubobjectMember = false;
5499 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5500 Ent = Ent->getParent()) {
5501 if (Ent->getKind() != InitializedEntity::EK_Base) {
5502 IsSubobjectMember = true;
5503 break;
5504 }
5505 }
5506 S.Diag(Init->getExprLoc(),
5507 diag::warn_bind_ref_member_to_temporary)
5508 << ExtendingDecl << Init->getSourceRange()
5509 << IsSubobjectMember << IsInitializerList;
5510 if (IsSubobjectMember)
5511 S.Diag(ExtendingDecl->getLocation(),
5512 diag::note_ref_subobject_of_member_declared_here);
5513 else
5514 S.Diag(ExtendingDecl->getLocation(),
5515 diag::note_ref_or_ptr_member_declared_here)
5516 << /*is pointer*/false;
5517 }
5518}
5519
Richard Smithaaa0ec42013-09-21 21:19:19 +00005520static void DiagnoseNarrowingInInitList(Sema &S,
5521 const ImplicitConversionSequence &ICS,
5522 QualType PreNarrowingType,
5523 QualType EntityType,
5524 const Expr *PostInit);
5525
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005527InitializationSequence::Perform(Sema &S,
5528 const InitializedEntity &Entity,
5529 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005530 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005531 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005532 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005533 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005534 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005536
Sebastian Redld201edf2011-06-05 13:59:11 +00005537 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005538 // If the declaration is a non-dependent, incomplete array type
5539 // that has an initializer, then its type will be completed once
5540 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005541 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005542 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005543 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005544 if (const IncompleteArrayType *ArrayT
5545 = S.Context.getAsIncompleteArrayType(DeclType)) {
5546 // FIXME: We don't currently have the ability to accurately
5547 // compute the length of an initializer list without
5548 // performing full type-checking of the initializer list
5549 // (since we have to determine where braces are implicitly
5550 // introduced and such). So, we fall back to making the array
5551 // type a dependently-sized array type with no specified
5552 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005553 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005554 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005555
Douglas Gregor51e77d52009-12-10 17:56:55 +00005556 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005557 if (DeclaratorDecl *DD = Entity.getDecl()) {
5558 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5559 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005560 if (IncompleteArrayTypeLoc ArrayLoc =
5561 TL.getAs<IncompleteArrayTypeLoc>())
5562 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005563 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005564 }
5565
5566 *ResultType
5567 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5568 /*NumElts=*/0,
5569 ArrayT->getSizeModifier(),
5570 ArrayT->getIndexTypeCVRQualifiers(),
5571 Brackets);
5572 }
5573
5574 }
5575 }
Sebastian Redla9351792012-02-11 23:51:47 +00005576 if (Kind.getKind() == InitializationKind::IK_Direct &&
5577 !Kind.isExplicitCast()) {
5578 // Rebuild the ParenListExpr.
5579 SourceRange ParenRange = Kind.getParenRange();
5580 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005581 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005582 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005583 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005584 Kind.isExplicitCast() ||
5585 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005586 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005587 }
5588
Sebastian Redld201edf2011-06-05 13:59:11 +00005589 // No steps means no initialization.
5590 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00005591 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005593 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005594 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005595 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005596 // Produce a C++98 compatibility warning if we are initializing a reference
5597 // from an initializer list. For parameters, we produce a better warning
5598 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005599 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005600 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5601 << Init->getSourceRange();
5602 }
5603
Richard Smitheb3cad52012-06-04 22:27:30 +00005604 // Diagnose cases where we initialize a pointer to an array temporary, and the
5605 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005606 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005607 Entity.getType()->isPointerType() &&
5608 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005609 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005610 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5611 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5612 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5613 << Init->getSourceRange();
5614 }
5615
Douglas Gregor1b303932009-12-22 15:35:07 +00005616 QualType DestType = Entity.getType().getNonReferenceType();
5617 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005618 // the same as Entity.getDecl()->getType() in cases involving type merging,
5619 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005620 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005621 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005622 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005623
John McCalldadc5752010-08-24 06:29:42 +00005624 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005627 // grab the only argument out the Args and place it into the "current"
5628 // initializer.
5629 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005630 case SK_ResolveAddressOfOverloadedFunction:
5631 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005632 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005633 case SK_CastDerivedToBaseLValue:
5634 case SK_BindReference:
5635 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005636 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005637 case SK_UserConversion:
5638 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005639 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005640 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005641 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005642 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005643 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005644 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005645 case SK_UnwrapInitList:
5646 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005647 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005648 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005649 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005650 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005651 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005652 case SK_PassByIndirectCopyRestore:
5653 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005654 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005655 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005656 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005657 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005658 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005659 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005660 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005661 break;
John McCall34376a62010-12-04 03:47:34 +00005662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
Douglas Gregore1314a62009-12-18 05:02:21 +00005664 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00005665 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005666 case SK_ZeroInitialization:
5667 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005669
5670 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005671 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005672 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005673 for (step_iterator Step = step_begin(), StepEnd = step_end();
5674 Step != StepEnd; ++Step) {
5675 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005676 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677
John Wiegley01296292011-04-08 18:41:53 +00005678 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005679
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005680 switch (Step->Kind) {
5681 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005683 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005684 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005685 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5686 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005687 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005688 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005689 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005690 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005692 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005693 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005694 case SK_CastDerivedToBaseLValue: {
5695 // We have a derived-to-base cast that produces either an rvalue or an
5696 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697
John McCallcf142162010-08-07 06:22:56 +00005698 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005699
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005700 // Casts to inaccessible base classes are allowed with C-style casts.
5701 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5702 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005703 CurInit.get()->getLocStart(),
5704 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005705 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005706 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005707
Douglas Gregor88d292c2010-05-13 16:44:06 +00005708 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5709 QualType T = SourceType;
5710 if (const PointerType *Pointer = T->getAs<PointerType>())
5711 T = Pointer->getPointeeType();
5712 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005713 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005714 cast<CXXRecordDecl>(RecordTy->getDecl()));
5715 }
5716
John McCall2536c6d2010-08-25 10:28:54 +00005717 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005718 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005719 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005720 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005721 VK_XValue :
5722 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00005723 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5724 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005725 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00005726 CurInit.get(),
5727 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005728 break;
5729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005730
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005731 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005732 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5733 if (CurInit.get()->refersToBitField()) {
5734 // We don't necessarily have an unambiguous source bit-field.
5735 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005736 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005737 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005738 << (BitField ? BitField->getDeclName() : DeclarationName())
5739 << (BitField != NULL)
John Wiegley01296292011-04-08 18:41:53 +00005740 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005741 if (BitField)
5742 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5743
John McCallfaf5fb42010-08-26 23:41:50 +00005744 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005745 }
Anders Carlssona91be642010-01-29 02:47:33 +00005746
John Wiegley01296292011-04-08 18:41:53 +00005747 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005748 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005749 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5750 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005751 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005752 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005753 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005755
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005756 // Reference binding does not have any corresponding ASTs.
5757
5758 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005759 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005760 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005761
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005762 // Even though we didn't materialize a temporary, the binding may still
5763 // extend the lifetime of a temporary. This happens if we bind a reference
5764 // to the result of a cast to reference type.
5765 if (const ValueDecl *ExtendingDecl =
5766 getDeclForTemporaryLifetimeExtension(Entity)) {
5767 if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5768 warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5769 ExtendingDecl);
5770 }
5771
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005772 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005773
Richard Smithe6c01442013-06-05 00:46:14 +00005774 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005775 // Make sure the "temporary" is actually an rvalue.
5776 assert(CurInit.get()->isRValue() && "not a temporary");
5777
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005778 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005779 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005780 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005781
Richard Smithe6c01442013-06-05 00:46:14 +00005782 // Maybe lifetime-extend the temporary's subobjects to match the
5783 // entity's lifetime.
5784 const ValueDecl *ExtendingDecl =
5785 getDeclForTemporaryLifetimeExtension(Entity);
Richard Smithe3b28bc2013-06-12 21:51:50 +00005786 if (ExtendingDecl) {
Richard Smithe6c01442013-06-05 00:46:14 +00005787 performLifetimeExtension(CurInit.get(), ExtendingDecl);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005788 warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
Richard Smithe3b28bc2013-06-12 21:51:50 +00005789 }
5790
Douglas Gregorfe314812011-06-21 17:03:29 +00005791 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005792 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005793 Entity.getType().getNonReferenceType(), CurInit.get(),
5794 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregor58df5092011-06-22 16:12:01 +00005795
5796 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005797 // need cleanups. Likewise if we're extending this temporary to automatic
5798 // storage duration -- we need to register its cleanup during the
5799 // full-expression's cleanups.
5800 if ((S.getLangOpts().ObjCAutoRefCount &&
5801 MTE->getType()->isObjCLifetimeType()) ||
5802 (MTE->getStorageDuration() == SD_Automatic &&
5803 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005804 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005805
5806 CurInit = S.Owned(MTE);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005807 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005809
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005810 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005811 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005812 /*IsExtraneousCopy=*/true);
5813 break;
5814
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005815 case SK_UserConversion: {
5816 // We have a user-defined conversion that invokes either a constructor
5817 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005818 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005819 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005820 FunctionDecl *Fn = Step->Function.Function;
5821 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005822 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005823 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005824 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005825 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005826 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005827 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005828 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005829
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005830 // Determine the arguments required to actually perform the constructor
5831 // call.
John Wiegley01296292011-04-08 18:41:53 +00005832 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005833 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005834 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005835 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005836 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005837
Richard Smithb24f0672012-02-11 19:22:50 +00005838 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005839 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005840 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005841 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005842 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005843 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005844 CXXConstructExpr::CK_Complete,
5845 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005846 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005847 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005848
Anders Carlssona01874b2010-04-21 18:47:17 +00005849 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005850 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005851 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5852 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005853
John McCalle3027922010-08-25 11:45:40 +00005854 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005855 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5856 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5857 S.IsDerivedFrom(SourceType, Class))
5858 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005859
Douglas Gregor95562572010-04-24 23:45:46 +00005860 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005861 } else {
5862 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005863 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00005864 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00005865 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00005866 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5867 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005868
5869 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005870 // derived-to-base conversion? I believe the answer is "no", because
5871 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005872 ExprResult CurInitExprRes =
5873 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5874 FoundFn, Conversion);
5875 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005876 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005877 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005879 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005880 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5881 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005882 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005883 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005884
John McCalle3027922010-08-25 11:45:40 +00005885 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005886
Douglas Gregor95562572010-04-24 23:45:46 +00005887 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005889
Sebastian Redl112aa822011-07-14 19:07:55 +00005890 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005891 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5892
5893 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005894 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005895 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005896 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005897 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005898 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005899 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005900 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005901 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5902 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00005903 }
5904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005905
John McCallcf142162010-08-07 06:22:56 +00005906 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005907 CurInit.get()->getType(),
5908 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005909 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005910 if (MaybeBindToTemp)
5911 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005912 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005913 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005914 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005915 break;
5916 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005917
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005918 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005919 case SK_QualificationConversionXValue:
5920 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005921 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005922 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005923 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005924 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005925 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005926 VK_XValue :
5927 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005928 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005929 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005930 }
5931
Jordan Roseb1312a52013-04-11 00:58:58 +00005932 case SK_LValueToRValue: {
5933 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5934 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5935 CK_LValueToRValue,
5936 CurInit.take(),
5937 /*BasePath=*/0,
5938 VK_RValue));
5939 break;
5940 }
5941
Richard Smithaaa0ec42013-09-21 21:19:19 +00005942 case SK_ConversionSequence:
5943 case SK_ConversionSequenceNoNarrowing: {
5944 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00005945 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5946 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005947 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005948 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005949 ExprResult CurInitExprRes =
5950 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005951 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005952 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005953 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005954 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005955
5956 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5957 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5958 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5959 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005960 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005962
Douglas Gregor51e77d52009-12-10 17:56:55 +00005963 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005964 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00005965 // If we're not initializing the top-level entity, we need to create an
5966 // InitializeTemporary entity for our target type.
5967 QualType Ty = Step->Type;
5968 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00005969 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00005970 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5971 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00005972 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005973 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005974 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005975
Richard Smithcc1b96d2013-06-12 22:31:48 +00005976 // Hack: We must update *ResultType if available in order to set the
5977 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5978 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5979 if (ResultType &&
5980 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00005981 if ((*ResultType)->isRValueReferenceType())
5982 Ty = S.Context.getRValueReferenceType(Ty);
5983 else if ((*ResultType)->isLValueReferenceType())
5984 Ty = S.Context.getLValueReferenceType(Ty,
5985 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5986 *ResultType = Ty;
5987 }
5988
5989 InitListExpr *StructuredInitList =
5990 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005991 CurInit.release();
Richard Smithd712d0d2013-02-02 01:13:06 +00005992 CurInit = shouldBindAsTemporary(InitEntity)
5993 ? S.MaybeBindToTemporary(StructuredInitList)
5994 : S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005995 break;
5996 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00005997
Sebastian Redled2e5322011-12-22 14:44:04 +00005998 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00005999 // When an initializer list is passed for a parameter of type "reference
6000 // to object", we don't get an EK_Temporary entity, but instead an
6001 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006002 // FIXME: This is a hack. What we really should do is create a user
6003 // conversion step for this case, but this makes it considerably more
6004 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006005 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6006 Entity.getType().getNonReferenceType());
6007 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006008 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006009 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006010 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6011 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006012 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006013 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6014 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006015 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006016 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006017 /*IsListInitialization*/ true,
6018 InitList->getLBraceLoc(),
6019 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006020 break;
6021 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006022
Sebastian Redl29526f02011-11-27 16:50:07 +00006023 case SK_UnwrapInitList:
6024 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
6025 break;
6026
6027 case SK_RewrapInitList: {
6028 Expr *E = CurInit.take();
6029 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6030 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006031 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006032 ILE->setSyntacticForm(Syntactic);
6033 ILE->setType(E->getType());
6034 ILE->setValueKind(E->getValueKind());
6035 CurInit = S.Owned(ILE);
6036 break;
6037 }
6038
Sebastian Redl99f66162012-02-19 12:27:56 +00006039 case SK_ConstructorInitialization: {
6040 // When an initializer list is passed for a parameter of type "reference
6041 // to object", we don't get an EK_Temporary entity, but instead an
6042 // EK_Parameter entity with reference type.
6043 // FIXME: This is a hack. What we really should do is create a user
6044 // conversion step for this case, but this makes it considerably more
6045 // complicated. For now, this will do.
6046 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6047 Entity.getType().getNonReferenceType());
6048 bool UseTemporary = Entity.getType()->isReferenceType();
6049 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6050 : Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006051 Kind, Args, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006052 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006053 /*IsListInitialization*/ false,
6054 /*LBraceLoc*/ SourceLocation(),
6055 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006056 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006058
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006059 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006060 step_iterator NextStep = Step;
6061 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006062 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006063 (NextStep->Kind == SK_ConstructorInitialization ||
6064 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006065 // The need for zero-initialization is recorded directly into
6066 // the call to the object's constructor within the next step.
6067 ConstructorInitRequiresZeroInit = true;
6068 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006069 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006070 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006071 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6072 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006073 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006074 Kind.getRange().getBegin());
6075
6076 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6077 TSInfo->getType().getNonLValueExprType(S.Context),
6078 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006079 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006080 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006081 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006082 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006083 break;
6084 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006085
6086 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006087 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006088 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006089 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006090 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6091 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006092 if (Result.isInvalid())
6093 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006094 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006095
6096 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006097 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006098 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006099 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006100 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006101 == Sema::Compatible)
6102 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006103 if (CurInitExprRes.isInvalid())
6104 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006105 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006106
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006107 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006108 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6109 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006110 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006111 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006112 &Complained)) {
6113 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006114 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006115 } else if (Complained)
6116 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006117 break;
6118 }
Eli Friedman78275202009-12-19 08:11:05 +00006119
6120 case SK_StringInit: {
6121 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006122 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006123 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006124 break;
6125 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006126
6127 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00006128 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006129 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006130 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006131 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006132
6133 case SK_ArrayInit:
6134 // Okay: we checked everything before creating this step. Note that
6135 // this is a GNU extension.
6136 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006137 << Step->Type << CurInit.get()->getType()
6138 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006139
6140 // If the destination type is an incomplete array type, update the
6141 // type accordingly.
6142 if (ResultType) {
6143 if (const IncompleteArrayType *IncompleteDest
6144 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6145 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006146 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006147 *ResultType = S.Context.getConstantArrayType(
6148 IncompleteDest->getElementType(),
6149 ConstantSource->getSize(),
6150 ArrayType::Normal, 0);
6151 }
6152 }
6153 }
John McCall31168b02011-06-15 23:02:42 +00006154 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006155
Richard Smithebeed412012-02-15 22:38:09 +00006156 case SK_ParenthesizedArrayInit:
6157 // Okay: we checked everything before creating this step. Note that
6158 // this is a GNU extension.
6159 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6160 << CurInit.get()->getSourceRange();
6161 break;
6162
John McCall31168b02011-06-15 23:02:42 +00006163 case SK_PassByIndirectCopyRestore:
6164 case SK_PassByIndirectRestore:
6165 checkIndirectCopyRestoreSource(S, CurInit.get());
6166 CurInit = S.Owned(new (S.Context)
6167 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6168 Step->Kind == SK_PassByIndirectCopyRestore));
6169 break;
6170
6171 case SK_ProduceObjCObject:
6172 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00006173 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00006174 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00006175 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006176
6177 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006178 S.Diag(CurInit.get()->getExprLoc(),
6179 diag::warn_cxx98_compat_initializer_list_init)
6180 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006181
Richard Smithcc1b96d2013-06-12 22:31:48 +00006182 // Maybe lifetime-extend the array temporary's subobjects to match the
6183 // entity's lifetime.
6184 const ValueDecl *ExtendingDecl =
6185 getDeclForTemporaryLifetimeExtension(Entity);
6186 if (ExtendingDecl) {
6187 performLifetimeExtension(CurInit.get(), ExtendingDecl);
6188 warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
Sebastian Redl249dee52012-03-05 19:35:43 +00006189 }
6190
Richard Smithcc1b96d2013-06-12 22:31:48 +00006191 // Materialize the temporary into memory.
6192 MaterializeTemporaryExpr *MTE = new (S.Context)
6193 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6194 /*lvalue reference*/ false, ExtendingDecl);
6195
6196 // Wrap it in a construction of a std::initializer_list<T>.
6197 CurInit = S.Owned(
6198 new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6199
6200 // Bind the result, in case the library has given initializer_list a
6201 // non-trivial destructor.
6202 if (shouldBindAsTemporary(Entity))
6203 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006204 break;
6205 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006206
Guy Benyei61054192013-02-07 10:55:47 +00006207 case SK_OCLSamplerInit: {
6208 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006209 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006210
6211 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006212
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006213 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006214 if (!SourceType->isSamplerT())
6215 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6216 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006217 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006218 llvm_unreachable("Invalid EntityKind!");
6219 }
6220
6221 break;
6222 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006223 case SK_OCLZeroEvent: {
6224 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006225 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006226
6227 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6228 CK_ZeroToOCLEvent,
6229 CurInit.get()->getValueKind());
6230 break;
6231 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006232 }
6233 }
John McCall1f425642010-11-11 03:21:53 +00006234
6235 // Diagnose non-fatal problems with the completed initialization.
6236 if (Entity.getKind() == InitializedEntity::EK_Member &&
6237 cast<FieldDecl>(Entity.getDecl())->isBitField())
6238 S.CheckBitFieldInitialization(Kind.getLocation(),
6239 cast<FieldDecl>(Entity.getDecl()),
6240 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006241
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006242 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006243}
6244
Richard Smith593f9932012-12-08 02:01:17 +00006245/// Somewhere within T there is an uninitialized reference subobject.
6246/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006247static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6248 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006249 if (T->isReferenceType()) {
6250 S.Diag(Loc, diag::err_reference_without_init)
6251 << T.getNonReferenceType();
6252 return true;
6253 }
6254
6255 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6256 if (!RD || !RD->hasUninitializedReferenceMember())
6257 return false;
6258
6259 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6260 FE = RD->field_end(); FI != FE; ++FI) {
6261 if (FI->isUnnamedBitfield())
6262 continue;
6263
6264 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6265 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6266 return true;
6267 }
6268 }
6269
6270 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6271 BE = RD->bases_end();
6272 BI != BE; ++BI) {
6273 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6274 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6275 return true;
6276 }
6277 }
6278
6279 return false;
6280}
6281
6282
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006283//===----------------------------------------------------------------------===//
6284// Diagnose initialization failures
6285//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006286
6287/// Emit notes associated with an initialization that failed due to a
6288/// "simple" conversion failure.
6289static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6290 Expr *op) {
6291 QualType destType = entity.getType();
6292 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6293 op->getType()->isObjCObjectPointerType()) {
6294
6295 // Emit a possible note about the conversion failing because the
6296 // operand is a message send with a related result type.
6297 S.EmitRelatedResultTypeNote(op);
6298
6299 // Emit a possible note about a return failing because we're
6300 // expecting a related result type.
6301 if (entity.getKind() == InitializedEntity::EK_Result)
6302 S.EmitRelatedResultTypeNoteForReturn(destType);
6303 }
6304}
6305
Richard Smith0449aaf2013-11-21 23:30:57 +00006306static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6307 InitListExpr *InitList) {
6308 QualType DestType = Entity.getType();
6309
6310 QualType E;
6311 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6312 QualType ArrayType = S.Context.getConstantArrayType(
6313 E.withConst(),
6314 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6315 InitList->getNumInits()),
6316 clang::ArrayType::Normal, 0);
6317 InitializedEntity HiddenArray =
6318 InitializedEntity::InitializeTemporary(ArrayType);
6319 return diagnoseListInit(S, HiddenArray, InitList);
6320 }
6321
6322 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6323 /*VerifyOnly=*/false);
6324 assert(DiagnoseInitList.HadError() &&
6325 "Inconsistent init list check result.");
6326}
6327
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006328bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006329 const InitializedEntity &Entity,
6330 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006331 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006332 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006333 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006334
Douglas Gregor1b303932009-12-22 15:35:07 +00006335 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006336 switch (Failure) {
6337 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006338 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006339 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006340 // Dig out the reference subobject which is uninitialized and diagnose it.
6341 // If this is value-initialization, this could be nested some way within
6342 // the target type.
6343 assert(Kind.getKind() == InitializationKind::IK_Value ||
6344 DestType->isReferenceType());
6345 bool Diagnosed =
6346 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6347 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6348 (void)Diagnosed;
6349 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006350 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006351 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006352 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006353
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006354 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006355 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006356 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006357 case FK_ArrayNeedsInitListOrStringLiteral:
6358 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6359 break;
6360 case FK_ArrayNeedsInitListOrWideStringLiteral:
6361 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6362 break;
6363 case FK_NarrowStringIntoWideCharArray:
6364 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6365 break;
6366 case FK_WideStringIntoCharArray:
6367 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6368 break;
6369 case FK_IncompatWideStringIntoWideChar:
6370 S.Diag(Kind.getLocation(),
6371 diag::err_array_init_incompat_wide_string_into_wchar);
6372 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006373 case FK_ArrayTypeMismatch:
6374 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006375 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006376 (Failure == FK_ArrayTypeMismatch
6377 ? diag::err_array_init_different_type
6378 : diag::err_array_init_non_constant_array))
6379 << DestType.getNonReferenceType()
6380 << Args[0]->getType()
6381 << Args[0]->getSourceRange();
6382 break;
6383
John McCalla59dc2f2012-01-05 00:13:19 +00006384 case FK_VariableLengthArrayHasInitializer:
6385 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6386 << Args[0]->getSourceRange();
6387 break;
6388
John McCall16df1e52010-03-30 21:47:33 +00006389 case FK_AddressOfOverloadFailed: {
6390 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006391 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006392 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006393 true,
6394 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006395 break;
John McCall16df1e52010-03-30 21:47:33 +00006396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006398 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006399 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006400 switch (FailedOverloadResult) {
6401 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006402 if (Failure == FK_UserConversionOverloadFailed)
6403 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6404 << Args[0]->getType() << DestType
6405 << Args[0]->getSourceRange();
6406 else
6407 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6408 << DestType << Args[0]->getType()
6409 << Args[0]->getSourceRange();
6410
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006411 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006412 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006413
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006414 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006415 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006416 DestType.getNonReferenceType(),
6417 diag::err_typecheck_nonviable_condition_incomplete,
6418 Args[0]->getType(), Args[0]->getSourceRange()))
6419 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6420 << Args[0]->getType() << Args[0]->getSourceRange()
6421 << DestType.getNonReferenceType();
6422
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006423 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006424 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006425
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006426 case OR_Deleted: {
6427 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6428 << Args[0]->getType() << DestType.getNonReferenceType()
6429 << Args[0]->getSourceRange();
6430 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006431 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006432 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6433 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006434 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006435 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006436 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006437 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006438 }
6439 break;
6440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006441
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006442 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006443 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006444 }
6445 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006446
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006447 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006448 if (isa<InitListExpr>(Args[0])) {
6449 S.Diag(Kind.getLocation(),
6450 diag::err_lvalue_reference_bind_to_initlist)
6451 << DestType.getNonReferenceType().isVolatileQualified()
6452 << DestType.getNonReferenceType()
6453 << Args[0]->getSourceRange();
6454 break;
6455 }
6456 // Intentional fallthrough
6457
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006458 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006459 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006460 Failure == FK_NonConstLValueReferenceBindingToTemporary
6461 ? diag::err_lvalue_reference_bind_to_temporary
6462 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006463 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006464 << DestType.getNonReferenceType()
6465 << Args[0]->getType()
6466 << Args[0]->getSourceRange();
6467 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006468
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006469 case FK_RValueReferenceBindingToLValue:
6470 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006471 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006472 << Args[0]->getSourceRange();
6473 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006475 case FK_ReferenceInitDropsQualifiers:
6476 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6477 << DestType.getNonReferenceType()
6478 << Args[0]->getType()
6479 << Args[0]->getSourceRange();
6480 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006481
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006482 case FK_ReferenceInitFailed:
6483 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6484 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006485 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006486 << Args[0]->getType()
6487 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006488 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006489 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490
Douglas Gregorb491ed32011-02-19 21:32:49 +00006491 case FK_ConversionFailed: {
6492 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006493 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006494 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006495 << DestType
John McCall086a4642010-11-24 05:12:34 +00006496 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006497 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006498 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006499 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6500 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006501 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006502 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006503 }
John Wiegley01296292011-04-08 18:41:53 +00006504
6505 case FK_ConversionFromPropertyFailed:
6506 // No-op. This error has already been reported.
6507 break;
6508
Douglas Gregor51e77d52009-12-10 17:56:55 +00006509 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006510 SourceRange R;
6511
6512 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006513 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006514 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006515 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006516 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006517
Douglas Gregor8ec51732010-09-08 21:40:08 +00006518 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6519 if (Kind.isCStyleOrFunctionalCast())
6520 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6521 << R;
6522 else
6523 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6524 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006525 break;
6526 }
6527
6528 case FK_ReferenceBindingToInitList:
6529 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6530 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6531 break;
6532
6533 case FK_InitListBadDestinationType:
6534 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6535 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6536 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006537
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006538 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006539 case FK_ConstructorOverloadFailed: {
6540 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006541 if (Args.size())
6542 ArgsRange = SourceRange(Args.front()->getLocStart(),
6543 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006545 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006546 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006547 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006548 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006549 }
6550
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006551 // FIXME: Using "DestType" for the entity we're printing is probably
6552 // bad.
6553 switch (FailedOverloadResult) {
6554 case OR_Ambiguous:
6555 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6556 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006557 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006558 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006560 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006561 if (Kind.getKind() == InitializationKind::IK_Default &&
6562 (Entity.getKind() == InitializedEntity::EK_Base ||
6563 Entity.getKind() == InitializedEntity::EK_Member) &&
6564 isa<CXXConstructorDecl>(S.CurContext)) {
6565 // This is implicit default initialization of a member or
6566 // base within a constructor. If no viable function was
6567 // found, notify the user that she needs to explicitly
6568 // initialize this base/member.
6569 CXXConstructorDecl *Constructor
6570 = cast<CXXConstructorDecl>(S.CurContext);
6571 if (Entity.getKind() == InitializedEntity::EK_Base) {
6572 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006573 << (Constructor->getInheritedConstructor() ? 2 :
6574 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006575 << S.Context.getTypeDeclType(Constructor->getParent())
6576 << /*base=*/0
6577 << Entity.getType();
6578
6579 RecordDecl *BaseDecl
6580 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6581 ->getDecl();
6582 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6583 << S.Context.getTagDeclType(BaseDecl);
6584 } else {
6585 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006586 << (Constructor->getInheritedConstructor() ? 2 :
6587 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006588 << S.Context.getTypeDeclType(Constructor->getParent())
6589 << /*member=*/1
6590 << Entity.getName();
6591 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6592
6593 if (const RecordType *Record
6594 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006596 diag::note_previous_decl)
6597 << S.Context.getTagDeclType(Record->getDecl());
6598 }
6599 break;
6600 }
6601
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006602 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6603 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006604 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006605 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006606
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006607 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006608 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006609 OverloadingResult Ovl
6610 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006611 if (Ovl != OR_Deleted) {
6612 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6613 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006614 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006615 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006616 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006617
6618 // If this is a defaulted or implicitly-declared function, then
6619 // it was implicitly deleted. Make it clear that the deletion was
6620 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006621 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006622 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006623 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006624 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006625 else
6626 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6627 << true << DestType << ArgsRange;
6628
6629 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006630 break;
6631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006632
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006633 case OR_Success:
6634 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006635 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006636 }
David Blaikie60deeee2012-01-17 08:24:58 +00006637 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006638
Douglas Gregor85dabae2009-12-16 01:38:02 +00006639 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006640 if (Entity.getKind() == InitializedEntity::EK_Member &&
6641 isa<CXXConstructorDecl>(S.CurContext)) {
6642 // This is implicit default-initialization of a const member in
6643 // a constructor. Complain that it needs to be explicitly
6644 // initialized.
6645 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6646 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006647 << (Constructor->getInheritedConstructor() ? 2 :
6648 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006649 << S.Context.getTypeDeclType(Constructor->getParent())
6650 << /*const=*/1
6651 << Entity.getName();
6652 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6653 << Entity.getName();
6654 } else {
6655 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6656 << DestType << (bool)DestType->getAs<RecordType>();
6657 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006658 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006660 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006661 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006662 diag::err_init_incomplete_type);
6663 break;
6664
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006665 case FK_ListInitializationFailed: {
6666 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006667 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6668 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006669 break;
6670 }
John McCall4124c492011-10-17 18:40:02 +00006671
6672 case FK_PlaceholderType: {
6673 // FIXME: Already diagnosed!
6674 break;
6675 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006676
Sebastian Redl048a6d72012-04-01 19:54:59 +00006677 case FK_ExplicitConstructor: {
6678 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6679 << Args[0]->getSourceRange();
6680 OverloadCandidateSet::iterator Best;
6681 OverloadingResult Ovl
6682 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006683 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006684 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6685 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6686 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6687 break;
6688 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006690
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006691 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006692 return true;
6693}
Douglas Gregore1314a62009-12-18 05:02:21 +00006694
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006695void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006696 switch (SequenceKind) {
6697 case FailedSequence: {
6698 OS << "Failed sequence: ";
6699 switch (Failure) {
6700 case FK_TooManyInitsForReference:
6701 OS << "too many initializers for reference";
6702 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006704 case FK_ArrayNeedsInitList:
6705 OS << "array requires initializer list";
6706 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006708 case FK_ArrayNeedsInitListOrStringLiteral:
6709 OS << "array requires initializer list or string literal";
6710 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006711
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006712 case FK_ArrayNeedsInitListOrWideStringLiteral:
6713 OS << "array requires initializer list or wide string literal";
6714 break;
6715
6716 case FK_NarrowStringIntoWideCharArray:
6717 OS << "narrow string into wide char array";
6718 break;
6719
6720 case FK_WideStringIntoCharArray:
6721 OS << "wide string into char array";
6722 break;
6723
6724 case FK_IncompatWideStringIntoWideChar:
6725 OS << "incompatible wide string into wide char array";
6726 break;
6727
Douglas Gregore2f943b2011-02-22 18:29:51 +00006728 case FK_ArrayTypeMismatch:
6729 OS << "array type mismatch";
6730 break;
6731
6732 case FK_NonConstantArrayInit:
6733 OS << "non-constant array initializer";
6734 break;
6735
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006736 case FK_AddressOfOverloadFailed:
6737 OS << "address of overloaded function failed";
6738 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006739
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006740 case FK_ReferenceInitOverloadFailed:
6741 OS << "overload resolution for reference initialization failed";
6742 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006744 case FK_NonConstLValueReferenceBindingToTemporary:
6745 OS << "non-const lvalue reference bound to temporary";
6746 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006748 case FK_NonConstLValueReferenceBindingToUnrelated:
6749 OS << "non-const lvalue reference bound to unrelated type";
6750 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006752 case FK_RValueReferenceBindingToLValue:
6753 OS << "rvalue reference bound to an lvalue";
6754 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006756 case FK_ReferenceInitDropsQualifiers:
6757 OS << "reference initialization drops qualifiers";
6758 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006759
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006760 case FK_ReferenceInitFailed:
6761 OS << "reference initialization failed";
6762 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006764 case FK_ConversionFailed:
6765 OS << "conversion failed";
6766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
John Wiegley01296292011-04-08 18:41:53 +00006768 case FK_ConversionFromPropertyFailed:
6769 OS << "conversion from property failed";
6770 break;
6771
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006772 case FK_TooManyInitsForScalar:
6773 OS << "too many initializers for scalar";
6774 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006775
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006776 case FK_ReferenceBindingToInitList:
6777 OS << "referencing binding to initializer list";
6778 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006780 case FK_InitListBadDestinationType:
6781 OS << "initializer list for non-aggregate, non-scalar type";
6782 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006783
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006784 case FK_UserConversionOverloadFailed:
6785 OS << "overloading failed for user-defined conversion";
6786 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006787
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006788 case FK_ConstructorOverloadFailed:
6789 OS << "constructor overloading failed";
6790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006792 case FK_DefaultInitOfConst:
6793 OS << "default initialization of a const variable";
6794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006796 case FK_Incomplete:
6797 OS << "initialization of incomplete type";
6798 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006799
6800 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006801 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006802 break;
6803
John McCalla59dc2f2012-01-05 00:13:19 +00006804 case FK_VariableLengthArrayHasInitializer:
6805 OS << "variable length array has an initializer";
6806 break;
6807
John McCall4124c492011-10-17 18:40:02 +00006808 case FK_PlaceholderType:
6809 OS << "initializer expression isn't contextually valid";
6810 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006811
6812 case FK_ListConstructorOverloadFailed:
6813 OS << "list constructor overloading failed";
6814 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006815
Sebastian Redl048a6d72012-04-01 19:54:59 +00006816 case FK_ExplicitConstructor:
6817 OS << "list copy initialization chose explicit constructor";
6818 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006820 OS << '\n';
6821 return;
6822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006824 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006825 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006826 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827
Sebastian Redld201edf2011-06-05 13:59:11 +00006828 case NormalSequence:
6829 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006830 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006832
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006833 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6834 if (S != step_begin()) {
6835 OS << " -> ";
6836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006837
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006838 switch (S->Kind) {
6839 case SK_ResolveAddressOfOverloadedFunction:
6840 OS << "resolve address of overloaded function";
6841 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006843 case SK_CastDerivedToBaseRValue:
6844 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6845 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006847 case SK_CastDerivedToBaseXValue:
6848 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6849 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006850
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006851 case SK_CastDerivedToBaseLValue:
6852 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6853 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006855 case SK_BindReference:
6856 OS << "bind reference to lvalue";
6857 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006859 case SK_BindReferenceToTemporary:
6860 OS << "bind reference to a temporary";
6861 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006863 case SK_ExtraneousCopyToTemporary:
6864 OS << "extraneous C++03 copy to temporary";
6865 break;
6866
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006867 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006868 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006869 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006870
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006871 case SK_QualificationConversionRValue:
6872 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006873 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006874
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006875 case SK_QualificationConversionXValue:
6876 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006877 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006878
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006879 case SK_QualificationConversionLValue:
6880 OS << "qualification conversion (lvalue)";
6881 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006882
Jordan Roseb1312a52013-04-11 00:58:58 +00006883 case SK_LValueToRValue:
6884 OS << "load (lvalue to rvalue)";
6885 break;
6886
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006887 case SK_ConversionSequence:
6888 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006889 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006890 OS << ")";
6891 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892
Richard Smithaaa0ec42013-09-21 21:19:19 +00006893 case SK_ConversionSequenceNoNarrowing:
6894 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006895 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00006896 OS << ")";
6897 break;
6898
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006899 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006900 OS << "list aggregate initialization";
6901 break;
6902
6903 case SK_ListConstructorCall:
6904 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006905 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006906
Sebastian Redl29526f02011-11-27 16:50:07 +00006907 case SK_UnwrapInitList:
6908 OS << "unwrap reference initializer list";
6909 break;
6910
6911 case SK_RewrapInitList:
6912 OS << "rewrap reference initializer list";
6913 break;
6914
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006915 case SK_ConstructorInitialization:
6916 OS << "constructor initialization";
6917 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006919 case SK_ZeroInitialization:
6920 OS << "zero initialization";
6921 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006923 case SK_CAssignment:
6924 OS << "C assignment";
6925 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006926
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006927 case SK_StringInit:
6928 OS << "string initialization";
6929 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006930
6931 case SK_ObjCObjectConversion:
6932 OS << "Objective-C object conversion";
6933 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006934
6935 case SK_ArrayInit:
6936 OS << "array initialization";
6937 break;
John McCall31168b02011-06-15 23:02:42 +00006938
Richard Smithebeed412012-02-15 22:38:09 +00006939 case SK_ParenthesizedArrayInit:
6940 OS << "parenthesized array initialization";
6941 break;
6942
John McCall31168b02011-06-15 23:02:42 +00006943 case SK_PassByIndirectCopyRestore:
6944 OS << "pass by indirect copy and restore";
6945 break;
6946
6947 case SK_PassByIndirectRestore:
6948 OS << "pass by indirect restore";
6949 break;
6950
6951 case SK_ProduceObjCObject:
6952 OS << "Objective-C object retension";
6953 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006954
6955 case SK_StdInitializerList:
6956 OS << "std::initializer_list from initializer list";
6957 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006958
Guy Benyei61054192013-02-07 10:55:47 +00006959 case SK_OCLSamplerInit:
6960 OS << "OpenCL sampler_t from integer constant";
6961 break;
6962
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006963 case SK_OCLZeroEvent:
6964 OS << "OpenCL event_t from zero";
6965 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006966 }
Richard Smith6b216962013-02-05 05:52:24 +00006967
6968 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006969 }
Richard Smith6b216962013-02-05 05:52:24 +00006970
6971 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006972}
6973
6974void InitializationSequence::dump() const {
6975 dump(llvm::errs());
6976}
6977
Richard Smithaaa0ec42013-09-21 21:19:19 +00006978static void DiagnoseNarrowingInInitList(Sema &S,
6979 const ImplicitConversionSequence &ICS,
6980 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006981 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006982 const Expr *PostInit) {
Richard Smith66e05fe2012-01-18 05:21:49 +00006983 const StandardConversionSequence *SCS = 0;
6984 switch (ICS.getKind()) {
6985 case ImplicitConversionSequence::StandardConversion:
6986 SCS = &ICS.Standard;
6987 break;
6988 case ImplicitConversionSequence::UserDefinedConversion:
6989 SCS = &ICS.UserDefined.After;
6990 break;
6991 case ImplicitConversionSequence::AmbiguousConversion:
6992 case ImplicitConversionSequence::EllipsisConversion:
6993 case ImplicitConversionSequence::BadConversion:
6994 return;
6995 }
6996
Richard Smith66e05fe2012-01-18 05:21:49 +00006997 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6998 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00006999 QualType ConstantType;
7000 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7001 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007002 case NK_Not_Narrowing:
7003 // No narrowing occurred.
7004 return;
7005
7006 case NK_Type_Narrowing:
7007 // This was a floating-to-integer conversion, which is always considered a
7008 // narrowing conversion even if the value is a constant and can be
7009 // represented exactly as an integer.
7010 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007011 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7012 ? diag::warn_init_list_type_narrowing
7013 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007014 << PostInit->getSourceRange()
7015 << PreNarrowingType.getLocalUnqualifiedType()
7016 << EntityType.getLocalUnqualifiedType();
7017 break;
7018
7019 case NK_Constant_Narrowing:
7020 // A constant value was narrowed.
7021 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007022 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7023 ? diag::warn_init_list_constant_narrowing
7024 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007025 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007026 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007027 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007028 break;
7029
7030 case NK_Variable_Narrowing:
7031 // A variable's value may have been narrowed.
7032 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007033 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7034 ? diag::warn_init_list_variable_narrowing
7035 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007036 << PostInit->getSourceRange()
7037 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007038 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007039 break;
7040 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007041
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007042 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007043 llvm::raw_svector_ostream OS(StaticCast);
7044 OS << "static_cast<";
7045 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7046 // It's important to use the typedef's name if there is one so that the
7047 // fixit doesn't break code using types like int64_t.
7048 //
7049 // FIXME: This will break if the typedef requires qualification. But
7050 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007051 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007052 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007053 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007054 else {
7055 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7056 // with a broken cast.
7057 return;
7058 }
7059 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00007060 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
7061 << PostInit->getSourceRange()
7062 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007063 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00007064 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007065}
7066
Douglas Gregore1314a62009-12-18 05:02:21 +00007067//===----------------------------------------------------------------------===//
7068// Initialization helper functions
7069//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007070bool
7071Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7072 ExprResult Init) {
7073 if (Init.isInvalid())
7074 return false;
7075
7076 Expr *InitE = Init.get();
7077 assert(InitE && "No initialization expression");
7078
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007079 InitializationKind Kind
7080 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007081 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007082 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007083}
7084
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007085ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007086Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7087 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007088 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007089 bool TopLevelOfInitList,
7090 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007091 if (Init.isInvalid())
7092 return ExprError();
7093
John McCall1f425642010-11-11 03:21:53 +00007094 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007095 assert(InitE && "No initialization expression?");
7096
7097 if (EqualLoc.isInvalid())
7098 EqualLoc = InitE->getLocStart();
7099
7100 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007101 EqualLoc,
7102 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007103 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Douglas Gregore1314a62009-12-18 05:02:21 +00007104 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007105
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007106 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007107
Richard Smith66e05fe2012-01-18 05:21:49 +00007108 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007109}