blob: 75f60ba480fa8f5ea0592caf80c42584b1432819 [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(),
Aaron Ballmanb9bb2012014-01-03 14:54:10 +00001543 diag::warn_missing_field_initializers) << *it;
John McCalle40b58e2010-03-11 19:32:38 +00001544 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 Gregor68782142013-12-18 21:46:16 +00003525 DestType, CandidateSet,
3526 /*AllowObjCConversionOnExplicit=*/
3527 false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003528 else
John McCalla0296f72010-03-19 07:35:19 +00003529 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00003530 Initializer, DestType, CandidateSet,
3531 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 }
3533 }
3534 }
John McCall3696dcb2010-08-17 07:23:57 +00003535 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3536 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003537
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538 SourceLocation DeclLoc = Initializer->getLocStart();
3539
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003541 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003542 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003543 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003544 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003545
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003546 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00003547 // This is the overload that will be used for this initialization step if we
3548 // use this initialization. Mark it as referenced.
3549 Function->setReferenced();
Chandler Carruth30141632011-02-25 19:41:05 +00003550
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003551 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003552 if (isa<CXXConversionDecl>(Function))
Alp Toker314cc812014-01-25 16:55:45 +00003553 T2 = Function->getReturnType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003554 else
3555 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003556
3557 // Add the user-defined conversion step.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003558 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCalla0296f72010-03-19 07:35:19 +00003559 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara5001caa2011-11-19 11:44:21 +00003560 T2.getNonLValueExprType(S.Context),
3561 HadMultipleCandidates);
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003562
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00003564 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00003565 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003566 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00003567 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003568 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00003569 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003570
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003571 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003572 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003573 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003576 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00003577 NewDerivedToBase, NewObjCConversion,
3578 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00003579 if (NewRefRelationship == Sema::Ref_Incompatible) {
3580 // If the type we've converted to is not reference-related to the
3581 // type we're looking for, then there is another conversion step
3582 // we need to perform to produce a temporary of the right type
3583 // that we'll be binding to.
3584 ImplicitConversionSequence ICS;
3585 ICS.setStandard();
3586 ICS.Standard = Best->FinalConversion;
3587 T2 = ICS.Standard.getToType(2);
3588 Sequence.AddConversionSequenceStep(ICS, T2);
3589 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003590 Sequence.AddDerivedToBaseCastStep(
3591 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00003593 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003594 else if (NewObjCConversion)
3595 Sequence.AddObjCObjectConversionStep(
3596 S.Context.getQualifiedType(T1,
3597 T2.getNonReferenceType().getQualifiers()));
3598
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003599 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00003600 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003601
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003602 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3603 return OR_Success;
3604}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Richard Smithc620f552011-10-19 16:55:56 +00003606static void CheckCXX98CompatAccessibleCopy(Sema &S,
3607 const InitializedEntity &Entity,
3608 Expr *CurInitExpr);
3609
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3611static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003612 const InitializedEntity &Entity,
3613 const InitializationKind &Kind,
3614 Expr *Initializer,
3615 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003616 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003617 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003618 Qualifiers T1Quals;
3619 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003620 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00003621 Qualifiers T2Quals;
3622 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redld92badf2010-06-30 18:13:39 +00003623
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003624 // If the initializer is the address of an overloaded function, try
3625 // to resolve the overloaded function. If all goes well, T2 is the
3626 // type of the resulting function.
Sebastian Redl29526f02011-11-27 16:50:07 +00003627 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3628 T1, Sequence))
3629 return;
Sebastian Redld92badf2010-06-30 18:13:39 +00003630
Sebastian Redl29526f02011-11-27 16:50:07 +00003631 // Delegate everything else to a subfunction.
3632 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3633 T1Quals, cv2T2, T2, T2Quals, Sequence);
3634}
3635
Jordan Roseb1312a52013-04-11 00:58:58 +00003636/// Converts the target of reference initialization so that it has the
3637/// appropriate qualifiers and value kind.
3638///
3639/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3640/// \code
3641/// int x;
3642/// const int &r = x;
3643/// \endcode
3644///
3645/// In this case the reference is binding to a bitfield lvalue, which isn't
3646/// valid. Perform a load to create a lifetime-extended temporary instead.
3647/// \code
3648/// const int &r = someStruct.bitfield;
3649/// \endcode
3650static ExprValueKind
3651convertQualifiersAndValueKindIfNecessary(Sema &S,
3652 InitializationSequence &Sequence,
3653 Expr *Initializer,
3654 QualType cv1T1,
3655 Qualifiers T1Quals,
3656 Qualifiers T2Quals,
3657 bool IsLValueRef) {
John McCalld25db7e2013-05-06 21:39:12 +00003658 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Roseb1312a52013-04-11 00:58:58 +00003659 Initializer->refersToVectorElement();
3660
3661 if (IsNonAddressableType) {
3662 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3663 // lvalue reference to a non-volatile const type, or the reference shall be
3664 // an rvalue reference.
3665 //
3666 // If not, we can't make a temporary and bind to that. Give up and allow the
3667 // error to be diagnosed later.
3668 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3669 assert(Initializer->isGLValue());
3670 return Initializer->getValueKind();
3671 }
3672
3673 // Force a load so we can materialize a temporary.
3674 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3675 return VK_RValue;
3676 }
3677
3678 if (T1Quals != T2Quals) {
3679 Sequence.AddQualificationConversionStep(cv1T1,
3680 Initializer->getValueKind());
3681 }
3682
3683 return Initializer->getValueKind();
3684}
3685
3686
Sebastian Redl29526f02011-11-27 16:50:07 +00003687/// \brief Reference initialization without resolving overloaded functions.
3688static void TryReferenceInitializationCore(Sema &S,
3689 const InitializedEntity &Entity,
3690 const InitializationKind &Kind,
3691 Expr *Initializer,
3692 QualType cv1T1, QualType T1,
3693 Qualifiers T1Quals,
3694 QualType cv2T2, QualType T2,
3695 Qualifiers T2Quals,
3696 InitializationSequence &Sequence) {
3697 QualType DestType = Entity.getType();
3698 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003699 // Compute some basic properties of the types and the initializer.
3700 bool isLValueRef = DestType->isLValueReferenceType();
3701 bool isRValueRef = !isLValueRef;
3702 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003703 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003704 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003705 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003706 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003707 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003708 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00003709
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003710 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003711 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003712 // "cv2 T2" as follows:
3713 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003715 // expression
Richard Smith6c6ddab2013-09-21 21:23:47 +00003716 // Note the analogous bullet points for rvalue refs to functions. Because
Sebastian Redld92badf2010-06-30 18:13:39 +00003717 // there are no function rvalues in C++, rvalue refs to functions are treated
3718 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003719 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00003720 bool T1Function = T1->isFunctionType();
3721 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003723 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003724 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003725 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003727 // reference-compatible with "cv2 T2," or
3728 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003730 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003731 // can occur. However, we do pay attention to whether it is a bit-field
3732 // to decide whether we're actually binding to a temporary created from
3733 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003734 if (DerivedToBase)
3735 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00003737 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003738 else if (ObjCConversion)
3739 Sequence.AddObjCObjectConversionStep(
3740 S.Context.getQualifiedType(T1, T2Quals));
3741
Jordan Roseb1312a52013-04-11 00:58:58 +00003742 ExprValueKind ValueKind =
3743 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3744 cv1T1, T1Quals, T2Quals,
3745 isLValueRef);
3746 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003747 return;
3748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
3750 // - has a class type (i.e., T2 is a class type), where T1 is not
3751 // reference-related to T2, and can be implicitly converted to an
3752 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3753 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003754 // applicable conversion functions (13.3.1.6) and choosing the best
3755 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00003756 // If we have an rvalue ref to function type here, the rhs must be
Richard Smith6c6ddab2013-09-21 21:23:47 +00003757 // an rvalue. DR1287 removed the "implicitly" here.
Sebastian Redld92badf2010-06-30 18:13:39 +00003758 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3759 (isLValueRef || InitCategory.isRValue())) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003760 ConvOvlResult = TryRefInitWithConversionFunction(
3761 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003762 if (ConvOvlResult == OR_Success)
3763 return;
Richard Smith6c6ddab2013-09-21 21:23:47 +00003764 if (ConvOvlResult != OR_No_Viable_Function)
John McCall0d1da222010-01-12 00:44:57 +00003765 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003766 InitializationSequence::FK_ReferenceInitOverloadFailed,
3767 ConvOvlResult);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003768 }
3769 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003770
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003772 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00003773 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003774 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00003775 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3776 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3777 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 Sequence.SetOverloadFailure(
3779 InitializationSequence::FK_ReferenceInitOverloadFailed,
3780 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003781 else
Sebastian Redld92badf2010-06-30 18:13:39 +00003782 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003783 ? (RefRelationship == Sema::Ref_Related
3784 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3785 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3786 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00003787
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003788 return;
3789 }
Sebastian Redld92badf2010-06-30 18:13:39 +00003790
Douglas Gregor92e460e2011-01-20 16:44:54 +00003791 // - If the initializer expression
3792 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3793 // "cv1 T1" is reference-compatible with "cv2 T2"
3794 // Note: functions are handled below.
3795 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003796 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003798 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003799 (InitCategory.isXValue() ||
3800 (InitCategory.isPRValue() && T2->isRecordType()) ||
3801 (InitCategory.isPRValue() && T2->isArrayType()))) {
3802 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3803 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003804 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3805 // compiler the freedom to perform a copy here or bind to the
3806 // object, while C++0x requires that we bind directly to the
3807 // object. Hence, we always bind to the object without making an
3808 // extra copy. However, in C++03 requires that we check for the
3809 // presence of a suitable copy constructor:
3810 //
3811 // The constructor that would be used to make the copy shall
3812 // be callable whether or not the copy is actually done.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003813 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003814 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003815 else if (S.getLangOpts().CPlusPlus11)
Richard Smithc620f552011-10-19 16:55:56 +00003816 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818
Douglas Gregor92e460e2011-01-20 16:44:54 +00003819 if (DerivedToBase)
3820 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3821 ValueKind);
3822 else if (ObjCConversion)
3823 Sequence.AddObjCObjectConversionStep(
3824 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825
Jordan Roseb1312a52013-04-11 00:58:58 +00003826 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3827 Initializer, cv1T1,
3828 T1Quals, T2Quals,
3829 isLValueRef);
3830
3831 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
3835 // - has a class type (i.e., T2 is a class type), where T1 is not
3836 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003837 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3838 // where "cv1 T1" is reference-compatible with "cv3 T3",
Richard Smith6c6ddab2013-09-21 21:23:47 +00003839 //
3840 // DR1287 removes the "implicitly" here.
Douglas Gregor92e460e2011-01-20 16:44:54 +00003841 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003842 if (RefRelationship == Sema::Ref_Incompatible) {
Richard Smith6c6ddab2013-09-21 21:23:47 +00003843 ConvOvlResult = TryRefInitWithConversionFunction(
3844 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003845 if (ConvOvlResult)
3846 Sequence.SetOverloadFailure(
Richard Smith6c6ddab2013-09-21 21:23:47 +00003847 InitializationSequence::FK_ReferenceInitOverloadFailed,
3848 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003850 return;
3851 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003852
Douglas Gregor6fa6ab02013-03-26 23:59:23 +00003853 if ((RefRelationship == Sema::Ref_Compatible ||
3854 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3855 isRValueRef && InitCategory.isLValue()) {
3856 Sequence.SetFailed(
3857 InitializationSequence::FK_RValueReferenceBindingToLValue);
3858 return;
3859 }
3860
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003861 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3862 return;
3863 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003864
3865 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003866 // from the initializer expression using the rules for a non-reference
Richard Smith2eabf782013-06-13 00:57:57 +00003867 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003868 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003869
John McCallec6f4e92010-06-04 02:29:22 +00003870 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3871
Richard Smith2eabf782013-06-13 00:57:57 +00003872 // FIXME: Why do we use an implicit conversion here rather than trying
3873 // copy-initialization?
John McCall31168b02011-06-15 23:02:42 +00003874 ImplicitConversionSequence ICS
3875 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith2eabf782013-06-13 00:57:57 +00003876 /*SuppressUserConversions=*/false,
3877 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003878 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003879 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3880 /*AllowObjCWritebackConversion=*/false);
3881
3882 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003883 // FIXME: Use the conversion function set stored in ICS to turn
3884 // this into an overloading ambiguity diagnostic. However, we need
3885 // to keep that set as an OverloadCandidateSet rather than as some
3886 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003887 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3888 Sequence.SetOverloadFailure(
3889 InitializationSequence::FK_ReferenceInitOverloadFailed,
3890 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003891 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3892 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003893 else
3894 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003895 return;
John McCall31168b02011-06-15 23:02:42 +00003896 } else {
3897 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003898 }
3899
3900 // [...] If T1 is reference-related to T2, cv1 must be the
3901 // same cv-qualification as, or greater cv-qualification
3902 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003903 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3904 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003906 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003907 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3908 return;
3909 }
3910
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003912 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003914 InitCategory.isLValue()) {
3915 Sequence.SetFailed(
3916 InitializationSequence::FK_RValueReferenceBindingToLValue);
3917 return;
3918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003920 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3921 return;
3922}
3923
3924/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003925/// (C++ [dcl.init.string], C99 6.7.8).
3926static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003927 const InitializedEntity &Entity,
3928 const InitializationKind &Kind,
3929 Expr *Initializer,
3930 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003931 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003932}
3933
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003934/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003936 const InitializedEntity &Entity,
3937 const InitializationKind &Kind,
Richard Smithd86812d2012-07-05 08:39:21 +00003938 InitializationSequence &Sequence,
3939 InitListExpr *InitList) {
3940 assert((!InitList || InitList->getNumInits() == 0) &&
3941 "Shouldn't use value-init for non-empty init lists");
3942
Richard Smith1bfe0682012-02-14 21:14:13 +00003943 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003944 //
3945 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003946 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003948 // -- if T is an array type, then each element is value-initialized;
Richard Smith1bfe0682012-02-14 21:14:13 +00003949 T = S.Context.getBaseElementType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003951 if (const RecordType *RT = T->getAs<RecordType>()) {
3952 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithd86812d2012-07-05 08:39:21 +00003953 bool NeedZeroInitialization = true;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003954 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithd86812d2012-07-05 08:39:21 +00003955 // C++98:
3956 // -- if T is a class type (clause 9) with a user-declared constructor
3957 // (12.1), then the default constructor for T is called (and the
3958 // initialization is ill-formed if T has no accessible default
3959 // constructor);
Richard Smith1bfe0682012-02-14 21:14:13 +00003960 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithd86812d2012-07-05 08:39:21 +00003961 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003962 } else {
3963 // C++11:
3964 // -- if T is a class type (clause 9) with either no default constructor
3965 // (12.1 [class.ctor]) or a default constructor that is user-provided
3966 // or deleted, then the object is default-initialized;
3967 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3968 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithd86812d2012-07-05 08:39:21 +00003969 NeedZeroInitialization = false;
Richard Smith1bfe0682012-02-14 21:14:13 +00003970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971
Richard Smith1bfe0682012-02-14 21:14:13 +00003972 // -- if T is a (possibly cv-qualified) non-union class type without a
3973 // user-provided or deleted default constructor, then the object is
3974 // zero-initialized and, if T has a non-trivial default constructor,
3975 // default-initialized;
Richard Smithfb266522012-10-18 00:44:17 +00003976 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3977 // constructor' part was removed by DR1507.
Richard Smithd86812d2012-07-05 08:39:21 +00003978 if (NeedZeroInitialization)
3979 Sequence.AddZeroInitializationStep(Entity.getType());
3980
Richard Smith593f9932012-12-08 02:01:17 +00003981 // C++03:
3982 // -- if T is a non-union class type without a user-declared constructor,
3983 // then every non-static data member and base class component of T is
3984 // value-initialized;
3985 // [...] A program that calls for [...] value-initialization of an
3986 // entity of reference type is ill-formed.
3987 //
3988 // C++11 doesn't need this handling, because value-initialization does not
3989 // occur recursively there, and the implicit default constructor is
3990 // defined as deleted in the problematic cases.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003991 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smith593f9932012-12-08 02:01:17 +00003992 ClassDecl->hasUninitializedReferenceMember()) {
3993 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3994 return;
3995 }
3996
Richard Smithd86812d2012-07-05 08:39:21 +00003997 // If this is list-value-initialization, pass the empty init list on when
3998 // building the constructor call. This affects the semantics of a few
3999 // things (such as whether an explicit default constructor can be called).
4000 Expr *InitListAsExpr = InitList;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004001 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithd86812d2012-07-05 08:39:21 +00004002 bool InitListSyntax = InitList;
4003
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004004 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4005 InitListSyntax);
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004006 }
4007 }
4008
Douglas Gregor1b303932009-12-22 15:35:07 +00004009 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004010}
4011
Douglas Gregor85dabae2009-12-16 01:38:02 +00004012/// \brief Attempt default initialization (C++ [dcl.init]p6).
4013static void TryDefaultInitialization(Sema &S,
4014 const InitializedEntity &Entity,
4015 const InitializationKind &Kind,
4016 InitializationSequence &Sequence) {
4017 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregor85dabae2009-12-16 01:38:02 +00004019 // C++ [dcl.init]p6:
4020 // To default-initialize an object of type T means:
4021 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00004022 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4023
Douglas Gregor85dabae2009-12-16 01:38:02 +00004024 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4025 // constructor for T is called (and the initialization is ill-formed if
4026 // T has no accessible default constructor);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004027 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004028 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruthc9262402010-08-23 07:55:51 +00004029 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00004030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregor85dabae2009-12-16 01:38:02 +00004032 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004033
Douglas Gregor85dabae2009-12-16 01:38:02 +00004034 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00004036 // default constructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004037 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004038 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00004039 return;
4040 }
4041
4042 // If the destination type has a lifetime property, zero-initialize it.
4043 if (DestType.getQualifiers().hasObjCLifetime()) {
4044 Sequence.AddZeroInitializationStep(Entity.getType());
4045 return;
4046 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00004047}
4048
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004049/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4050/// which enumerates all conversion functions and performs overload resolution
4051/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004053 const InitializedEntity &Entity,
4054 const InitializationKind &Kind,
4055 Expr *Initializer,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004056 InitializationSequence &Sequence,
4057 bool TopLevelOfInitList) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004058 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004059 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4060 QualType SourceType = Initializer->getType();
4061 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4062 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063
Douglas Gregor540c3b02009-12-14 17:27:33 +00004064 // Build the candidate set directly in the initialization sequence
4065 // structure, so that it will persist if we fail.
4066 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4067 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068
Douglas Gregor540c3b02009-12-14 17:27:33 +00004069 // Determine whether we are allowed to call explicit constructors or
4070 // explicit conversion operators.
Sebastian Redl5a41f682012-02-12 16:37:24 +00004071 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
Douglas Gregor540c3b02009-12-14 17:27:33 +00004073 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4074 // The type we're converting to is a class type. Enumerate its constructors
4075 // to see if there is a suitable conversion.
4076 CXXRecordDecl *DestRecordDecl
4077 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078
Douglas Gregord9848152010-04-26 14:36:57 +00004079 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004080 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004081 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie12be6392012-10-18 16:57:32 +00004082 // The container holding the constructors can under certain conditions
4083 // be changed while iterating. To be safe we copy the lookup results
4084 // to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004085 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004086 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie12be6392012-10-18 16:57:32 +00004087 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregord9848152010-04-26 14:36:57 +00004088 Con != ConEnd; ++Con) {
4089 NamedDecl *D = *Con;
4090 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091
Douglas Gregord9848152010-04-26 14:36:57 +00004092 // Find the constructor (which may be a template).
4093 CXXConstructorDecl *Constructor = 0;
4094 FunctionTemplateDecl *ConstructorTmpl
4095 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004096 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00004097 Constructor = cast<CXXConstructorDecl>(
4098 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00004099 else
Douglas Gregord9848152010-04-26 14:36:57 +00004100 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101
Douglas Gregord9848152010-04-26 14:36:57 +00004102 if (!Constructor->isInvalidDecl() &&
4103 Constructor->isConvertingConstructor(AllowExplicit)) {
4104 if (ConstructorTmpl)
4105 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4106 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004107 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004108 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004109 else
4110 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004111 Initializer, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00004112 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00004113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114 }
Douglas Gregord9848152010-04-26 14:36:57 +00004115 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004116 }
Eli Friedman78275202009-12-19 08:11:05 +00004117
4118 SourceLocation DeclLoc = Initializer->getLocStart();
4119
Douglas Gregor540c3b02009-12-14 17:27:33 +00004120 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4121 // The type we're converting from is a class type, enumerate its conversion
4122 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00004123
Eli Friedman4afe9a32009-12-20 22:12:03 +00004124 // We can only enumerate the conversion functions for a complete type; if
4125 // the type isn't complete, simply skip this step.
4126 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4127 CXXRecordDecl *SourceRecordDecl
4128 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004129
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004130 std::pair<CXXRecordDecl::conversion_iterator,
4131 CXXRecordDecl::conversion_iterator>
4132 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4133 for (CXXRecordDecl::conversion_iterator
4134 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman4afe9a32009-12-20 22:12:03 +00004135 NamedDecl *D = *I;
4136 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4137 if (isa<UsingShadowDecl>(D))
4138 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004139
Eli Friedman4afe9a32009-12-20 22:12:03 +00004140 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4141 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00004142 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00004143 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00004144 else
John McCallda4458e2010-03-31 01:36:47 +00004145 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004146
Eli Friedman4afe9a32009-12-20 22:12:03 +00004147 if (AllowExplicit || !Conv->isExplicit()) {
4148 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00004149 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00004150 ActingDC, Initializer, DestType,
Douglas Gregor68782142013-12-18 21:46:16 +00004151 CandidateSet, AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004152 else
John McCalla0296f72010-03-19 07:35:19 +00004153 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor68782142013-12-18 21:46:16 +00004154 Initializer, DestType, CandidateSet,
4155 AllowExplicit);
Eli Friedman4afe9a32009-12-20 22:12:03 +00004156 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004157 }
4158 }
4159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
4161 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004162 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00004163 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00004164 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00004165 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004166 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00004167 Result);
4168 return;
4169 }
John McCall0d1da222010-01-12 00:44:57 +00004170
Douglas Gregor540c3b02009-12-14 17:27:33 +00004171 FunctionDecl *Function = Best->Function;
Nick Lewyckya096b142013-02-12 08:08:54 +00004172 Function->setReferenced();
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174
Douglas Gregor540c3b02009-12-14 17:27:33 +00004175 if (isa<CXXConstructorDecl>(Function)) {
4176 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithb24f0672012-02-11 19:22:50 +00004177 // subsumed by the initialization. Per DR5, the created temporary is of the
4178 // cv-unqualified type of the destination.
4179 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4180 DestType.getUnqualifiedType(),
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004181 HadMultipleCandidates);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004182 return;
4183 }
4184
4185 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004186 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004187 if (ConvType->getAs<RecordType>()) {
Richard Smithb24f0672012-02-11 19:22:50 +00004188 // If we're converting to a class type, there may be an copy of
Douglas Gregor5ab11652010-04-17 22:01:05 +00004189 // the resulting temporary object (possible to create an object of
4190 // a base class type). That copy is not a separate conversion, so
4191 // we just make a note of the actual destination type (possibly a
4192 // base class of the type returned by the conversion function) and
4193 // let the user-defined conversion step handle the conversion.
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004194 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4195 HadMultipleCandidates);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004196 return;
4197 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00004198
Abramo Bagnara5001caa2011-11-19 11:44:21 +00004199 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4200 HadMultipleCandidates);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004201
Douglas Gregor5ab11652010-04-17 22:01:05 +00004202 // If the conversion following the call to the conversion function
4203 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00004204 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4205 Best->FinalConversion.Third) {
4206 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00004207 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00004208 ICS.Standard = Best->FinalConversion;
Richard Smithaaa0ec42013-09-21 21:19:19 +00004209 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
Douglas Gregor540c3b02009-12-14 17:27:33 +00004210 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004211}
4212
Richard Smithf032001b2013-06-20 02:18:31 +00004213/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4214/// a function with a pointer return type contains a 'return false;' statement.
4215/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4216/// code using that header.
4217///
4218/// Work around this by treating 'return false;' as zero-initializing the result
4219/// if it's used in a pointer-returning function in a system header.
4220static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4221 const InitializedEntity &Entity,
4222 const Expr *Init) {
4223 return S.getLangOpts().CPlusPlus11 &&
4224 Entity.getKind() == InitializedEntity::EK_Result &&
4225 Entity.getType()->isPointerType() &&
4226 isa<CXXBoolLiteralExpr>(Init) &&
4227 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4228 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4229}
4230
John McCall31168b02011-06-15 23:02:42 +00004231/// The non-zero enum values here are indexes into diagnostic alternatives.
4232enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4233
4234/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00004235static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004236 bool isAddressOf, bool &isWeakAccess) {
John McCall31168b02011-06-15 23:02:42 +00004237 // Skip parens.
4238 e = e->IgnoreParens();
4239
4240 // Skip address-of nodes.
4241 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4242 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004243 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4244 isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004245
4246 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00004247 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4248 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00004249 case CK_Dependent:
4250 case CK_BitCast:
4251 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00004252 case CK_NoOp:
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004253 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004254
4255 case CK_ArrayToPointerDecay:
4256 return IIK_nonscalar;
4257
4258 case CK_NullToPointer:
4259 return IIK_okay;
4260
4261 default:
4262 break;
4263 }
4264
4265 // If we have a declaration reference, it had better be a local variable.
John McCall113bee02012-03-10 09:33:50 +00004266 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004267 // set isWeakAccess to true, to mean that there will be an implicit
4268 // load which requires a cleanup.
4269 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4270 isWeakAccess = true;
4271
John McCall63f84442011-06-27 23:59:58 +00004272 if (!isAddressOf) return IIK_nonlocal;
4273
John McCall113bee02012-03-10 09:33:50 +00004274 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4275 if (!var) return IIK_nonlocal;
John McCall63f84442011-06-27 23:59:58 +00004276
4277 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00004278
4279 // If we have a conditional operator, check both sides.
4280 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004281 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4282 isWeakAccess))
John McCall31168b02011-06-15 23:02:42 +00004283 return iik;
4284
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004285 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCall31168b02011-06-15 23:02:42 +00004286
4287 // These are never scalar.
4288 } else if (isa<ArraySubscriptExpr>(e)) {
4289 return IIK_nonscalar;
4290
4291 // Otherwise, it needs to be a null pointer constant.
4292 } else {
4293 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4294 ? IIK_okay : IIK_nonlocal);
4295 }
4296
4297 return IIK_nonlocal;
4298}
4299
4300/// Check whether the given expression is a valid operand for an
4301/// indirect copy/restore.
4302static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4303 assert(src->isRValue());
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00004304 bool isWeakAccess = false;
4305 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4306 // If isWeakAccess to true, there will be an implicit
4307 // load which requires a cleanup.
4308 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4309 S.ExprNeedsCleanups = true;
4310
John McCall31168b02011-06-15 23:02:42 +00004311 if (iik == IIK_okay) return;
4312
4313 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4314 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4315 << src->getSourceRange();
4316}
4317
Douglas Gregore2f943b2011-02-22 18:29:51 +00004318/// \brief Determine whether we have compatible array types for the
4319/// purposes of GNU by-copy array initialization.
4320static bool hasCompatibleArrayTypes(ASTContext &Context,
4321 const ArrayType *Dest,
4322 const ArrayType *Source) {
4323 // If the source and destination array types are equivalent, we're
4324 // done.
4325 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4326 return true;
4327
4328 // Make sure that the element types are the same.
4329 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4330 return false;
4331
4332 // The only mismatch we allow is when the destination is an
4333 // incomplete array type and the source is a constant array type.
4334 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4335}
4336
John McCall31168b02011-06-15 23:02:42 +00004337static bool tryObjCWritebackConversion(Sema &S,
4338 InitializationSequence &Sequence,
4339 const InitializedEntity &Entity,
4340 Expr *Initializer) {
4341 bool ArrayDecay = false;
4342 QualType ArgType = Initializer->getType();
4343 QualType ArgPointee;
4344 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4345 ArrayDecay = true;
4346 ArgPointee = ArgArrayType->getElementType();
4347 ArgType = S.Context.getPointerType(ArgPointee);
4348 }
4349
4350 // Handle write-back conversion.
4351 QualType ConvertedArgType;
4352 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4353 ConvertedArgType))
4354 return false;
4355
4356 // We should copy unless we're passing to an argument explicitly
4357 // marked 'out'.
4358 bool ShouldCopy = true;
4359 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4360 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4361
4362 // Do we need an lvalue conversion?
4363 if (ArrayDecay || Initializer->isGLValue()) {
4364 ImplicitConversionSequence ICS;
4365 ICS.setStandard();
4366 ICS.Standard.setAsIdentityConversion();
4367
4368 QualType ResultType;
4369 if (ArrayDecay) {
4370 ICS.Standard.First = ICK_Array_To_Pointer;
4371 ResultType = S.Context.getPointerType(ArgPointee);
4372 } else {
4373 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4374 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4375 }
4376
4377 Sequence.AddConversionSequenceStep(ICS, ResultType);
4378 }
4379
4380 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4381 return true;
4382}
4383
Guy Benyei61054192013-02-07 10:55:47 +00004384static bool TryOCLSamplerInitialization(Sema &S,
4385 InitializationSequence &Sequence,
4386 QualType DestType,
4387 Expr *Initializer) {
4388 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4389 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4390 return false;
4391
4392 Sequence.AddOCLSamplerInitStep(DestType);
4393 return true;
4394}
4395
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004396//
4397// OpenCL 1.2 spec, s6.12.10
4398//
4399// The event argument can also be used to associate the
4400// async_work_group_copy with a previous async copy allowing
4401// an event to be shared by multiple async copies; otherwise
4402// event should be zero.
4403//
4404static bool TryOCLZeroEventInitialization(Sema &S,
4405 InitializationSequence &Sequence,
4406 QualType DestType,
4407 Expr *Initializer) {
4408 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4409 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4410 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4411 return false;
4412
4413 Sequence.AddOCLZeroEventStep(DestType);
4414 return true;
4415}
4416
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004417InitializationSequence::InitializationSequence(Sema &S,
4418 const InitializedEntity &Entity,
4419 const InitializationKind &Kind,
Richard Smithaaa0ec42013-09-21 21:19:19 +00004420 MultiExprArg Args,
4421 bool TopLevelOfInitList)
John McCallbc077cf2010-02-08 23:07:23 +00004422 : FailedCandidateSet(Kind.getLocation()) {
Richard Smith089c3162013-09-21 21:55:46 +00004423 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4424}
4425
4426void InitializationSequence::InitializeFrom(Sema &S,
4427 const InitializedEntity &Entity,
4428 const InitializationKind &Kind,
4429 MultiExprArg Args,
4430 bool TopLevelOfInitList) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004431 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432
John McCall5e77d762013-04-16 07:28:30 +00004433 // Eliminate non-overload placeholder types in the arguments. We
4434 // need to do this before checking whether types are dependent
4435 // because lowering a pseudo-object expression might well give us
4436 // something of dependent type.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004437 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall5e77d762013-04-16 07:28:30 +00004438 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4439 // FIXME: should we be doing this here?
4440 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4441 if (result.isInvalid()) {
4442 SetFailed(FK_PlaceholderType);
4443 return;
4444 }
4445 Args[I] = result.take();
4446 }
4447
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004448 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449 // The semantics of initializers are as follows. The destination type is
4450 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004451 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004453 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004454 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004455
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004456 if (DestType->isDependentType() ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004457 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004458 SequenceKind = DependentSequence;
4459 return;
4460 }
4461
Sebastian Redld201edf2011-06-05 13:59:11 +00004462 // Almost everything is a normal sequence.
4463 setSequenceKind(NormalSequence);
4464
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004465 QualType SourceType;
4466 Expr *Initializer = 0;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004467 if (Args.size() == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004468 Initializer = Args[0];
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004469 if (S.getLangOpts().ObjC1) {
4470 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4471 DestType, Initializer->getType(),
4472 Initializer) ||
4473 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4474 Args[0] = Initializer;
4475
4476 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004477 if (!isa<InitListExpr>(Initializer))
4478 SourceType = Initializer->getType();
4479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
Sebastian Redl0501c632012-02-12 16:37:36 +00004481 // - If the initializer is a (non-parenthesized) braced-init-list, the
4482 // object is list-initialized (8.5.4).
4483 if (Kind.getKind() != InitializationKind::IK_Direct) {
4484 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4485 TryListInitialization(S, Entity, Kind, InitList, *this);
4486 return;
4487 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004490 // - If the destination type is a reference type, see 8.5.3.
4491 if (DestType->isReferenceType()) {
4492 // C++0x [dcl.init.ref]p1:
4493 // A variable declared to be a T& or T&&, that is, "reference to type T"
4494 // (8.3.2), shall be initialized by an object, or function, of type T or
4495 // by an object that can be converted into a T.
4496 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004497 if (Args.size() != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004498 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004499 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004500 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004501 return;
4502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004504 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004505 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004506 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004507 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004508 return;
4509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Douglas Gregor85dabae2009-12-16 01:38:02 +00004511 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00004512 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004513 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004514 return;
4515 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004516
John McCall66884dd2011-02-21 07:22:22 +00004517 // - If the destination type is an array of characters, an array of
4518 // char16_t, an array of char32_t, or an array of wchar_t, and the
4519 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004521 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00004522 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCalla59dc2f2012-01-05 00:13:19 +00004523 if (Initializer && isa<VariableArrayType>(DestAT)) {
4524 SetFailed(FK_VariableLengthArrayHasInitializer);
4525 return;
4526 }
4527
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004528 if (Initializer) {
4529 switch (IsStringInit(Initializer, DestAT, Context)) {
4530 case SIF_None:
4531 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4532 return;
4533 case SIF_NarrowStringIntoWideChar:
4534 SetFailed(FK_NarrowStringIntoWideCharArray);
4535 return;
4536 case SIF_WideStringIntoChar:
4537 SetFailed(FK_WideStringIntoCharArray);
4538 return;
4539 case SIF_IncompatWideStringIntoWideChar:
4540 SetFailed(FK_IncompatWideStringIntoWideChar);
4541 return;
4542 case SIF_Other:
4543 break;
4544 }
John McCall66884dd2011-02-21 07:22:22 +00004545 }
4546
Douglas Gregore2f943b2011-02-22 18:29:51 +00004547 // Note: as an GNU C extension, we allow initialization of an
4548 // array from a compound literal that creates an array of the same
4549 // type, so long as the initializer has no side effects.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004550 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregore2f943b2011-02-22 18:29:51 +00004551 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4552 Initializer->getType()->isArrayType()) {
4553 const ArrayType *SourceAT
4554 = Context.getAsArrayType(Initializer->getType());
4555 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004556 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004557 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004558 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004559 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004560 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00004561 }
Richard Smithebeed412012-02-15 22:38:09 +00004562 }
Richard Smithd86812d2012-07-05 08:39:21 +00004563 // Note: as a GNU C++ extension, we allow list-initialization of a
4564 // class member of array type from a parenthesized initializer list.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004565 else if (S.getLangOpts().CPlusPlus &&
Richard Smithebeed412012-02-15 22:38:09 +00004566 Entity.getKind() == InitializedEntity::EK_Member &&
4567 Initializer && isa<InitListExpr>(Initializer)) {
4568 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4569 *this);
4570 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004571 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004572 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00004573 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4574 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004575 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004576 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004578 return;
4579 }
Eli Friedman78275202009-12-19 08:11:05 +00004580
John McCall31168b02011-06-15 23:02:42 +00004581 // Determine whether we should consider writeback conversions for
4582 // Objective-C ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004583 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004584 Entity.isParameterKind();
John McCall31168b02011-06-15 23:02:42 +00004585
4586 // We're at the end of the line for C: it's either a write-back conversion
4587 // or it's a C assignment. There's no need to check anything else.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004588 if (!S.getLangOpts().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00004589 // If allowed, check whether this is an Objective-C writeback conversion.
4590 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004591 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00004592 return;
4593 }
Guy Benyei61054192013-02-07 10:55:47 +00004594
4595 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4596 return;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004597
4598 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4599 return;
4600
John McCall31168b02011-06-15 23:02:42 +00004601 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004602 AddCAssignmentStep(DestType);
4603 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00004604 return;
4605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
David Blaikiebbafb8a2012-03-11 07:00:24 +00004607 assert(S.getLangOpts().CPlusPlus);
John McCall31168b02011-06-15 23:02:42 +00004608
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004609 // - If the destination type is a (possibly cv-qualified) class type:
4610 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 // - If the initialization is direct-initialization, or if it is
4612 // copy-initialization where the cv-unqualified version of the
4613 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004614 // class of the destination, constructors are considered. [...]
4615 if (Kind.getKind() == InitializationKind::IK_Direct ||
4616 (Kind.getKind() == InitializationKind::IK_Copy &&
4617 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4618 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004619 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004620 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004622 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004624 // used) to a derived class thereof are enumerated as described in
4625 // 13.3.1.4, and the best one is chosen through overload resolution
4626 // (13.3).
4627 else
Richard Smithaaa0ec42013-09-21 21:19:19 +00004628 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4629 TopLevelOfInitList);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004630 return;
4631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004633 if (Args.size() > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004634 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004635 return;
4636 }
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004637 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638
4639 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004640 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00004641 if (!SourceType.isNull() && SourceType->isRecordType()) {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004642 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4643 TopLevelOfInitList);
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004644 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004645 return;
4646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004648 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00004649 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004650 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004651 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004652 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00004653
4654 ImplicitConversionSequence ICS
4655 = S.TryImplicitConversion(Initializer, Entity.getType(),
4656 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00004657 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00004658 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00004659 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4660 allowObjCWritebackConversion);
4661
4662 if (ICS.isStandard() &&
4663 ICS.Standard.Second == ICK_Writeback_Conversion) {
4664 // Objective-C ARC writeback conversion.
4665
4666 // We should copy unless we're passing to an argument explicitly
4667 // marked 'out'.
4668 bool ShouldCopy = true;
4669 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4670 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4671
4672 // If there was an lvalue adjustment, add it as a separate conversion.
4673 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4674 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4675 ImplicitConversionSequence LvalueICS;
4676 LvalueICS.setStandard();
4677 LvalueICS.Standard.setAsIdentityConversion();
4678 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4679 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004680 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00004681 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004682
4683 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00004684 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004685 DeclAccessPair dap;
Richard Smithf032001b2013-06-20 02:18:31 +00004686 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4687 AddZeroInitializationStep(Entity.getType());
4688 } else if (Initializer->getType() == Context.OverloadTy &&
4689 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4690 false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004691 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004692 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004693 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00004694 } else {
Richard Smithaaa0ec42013-09-21 21:19:19 +00004695 AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
John McCallfa272342011-06-16 23:24:51 +00004696
Rafael Espindola699fc4d2011-07-14 22:58:04 +00004697 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00004698 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004699}
4700
4701InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004702 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004703 StepEnd = Steps.end();
4704 Step != StepEnd; ++Step)
4705 Step->Destroy();
4706}
4707
4708//===----------------------------------------------------------------------===//
4709// Perform initialization
4710//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711static Sema::AssignmentAction
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004712getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004713 switch(Entity.getKind()) {
4714 case InitializedEntity::EK_Variable:
4715 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004716 case InitializedEntity::EK_Exception:
4717 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004718 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00004719 return Sema::AA_Initializing;
4720
4721 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00004723 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4724 return Sema::AA_Sending;
4725
Douglas Gregore1314a62009-12-18 05:02:21 +00004726 return Sema::AA_Passing;
4727
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00004728 case InitializedEntity::EK_Parameter_CF_Audited:
4729 if (Entity.getDecl() &&
4730 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4731 return Sema::AA_Sending;
4732
4733 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4734
Douglas Gregore1314a62009-12-18 05:02:21 +00004735 case InitializedEntity::EK_Result:
4736 return Sema::AA_Returning;
4737
Douglas Gregore1314a62009-12-18 05:02:21 +00004738 case InitializedEntity::EK_Temporary:
Fariborz Jahanian14e95412013-07-11 19:13:34 +00004739 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004740 // FIXME: Can we tell apart casting vs. converting?
4741 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004742
Douglas Gregore1314a62009-12-18 05:02:21 +00004743 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004744 case InitializedEntity::EK_ArrayElement:
4745 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004746 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004747 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004748 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004749 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004750 return Sema::AA_Initializing;
4751 }
4752
David Blaikie8a40f702012-01-17 06:56:22 +00004753 llvm_unreachable("Invalid EntityKind!");
Douglas Gregore1314a62009-12-18 05:02:21 +00004754}
4755
Richard Smith27874d62013-01-08 00:08:23 +00004756/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor95562572010-04-24 23:45:46 +00004757/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004758static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004759 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00004760 case InitializedEntity::EK_ArrayElement:
4761 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004762 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00004763 case InitializedEntity::EK_New:
4764 case InitializedEntity::EK_Variable:
4765 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004766 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004767 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004768 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00004769 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004770 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004771 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004772 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00004773 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004774
Douglas Gregore1314a62009-12-18 05:02:21 +00004775 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004776 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregore1314a62009-12-18 05:02:21 +00004777 case InitializedEntity::EK_Temporary:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004778 case InitializedEntity::EK_RelatedResult:
Douglas Gregore1314a62009-12-18 05:02:21 +00004779 return true;
4780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781
Douglas Gregore1314a62009-12-18 05:02:21 +00004782 llvm_unreachable("missed an InitializedEntity kind?");
4783}
4784
Douglas Gregor95562572010-04-24 23:45:46 +00004785/// \brief Whether the given entity, when initialized with an object
4786/// created for that initialization, requires destruction.
4787static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4788 switch (Entity.getKind()) {
Douglas Gregor95562572010-04-24 23:45:46 +00004789 case InitializedEntity::EK_Result:
4790 case InitializedEntity::EK_New:
4791 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004792 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00004793 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004794 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004795 case InitializedEntity::EK_BlockElement:
Douglas Gregor19666fb2012-02-15 16:57:26 +00004796 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor95562572010-04-24 23:45:46 +00004797 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Richard Smith27874d62013-01-08 00:08:23 +00004799 case InitializedEntity::EK_Member:
Douglas Gregor95562572010-04-24 23:45:46 +00004800 case InitializedEntity::EK_Variable:
4801 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004802 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor95562572010-04-24 23:45:46 +00004803 case InitializedEntity::EK_Temporary:
4804 case InitializedEntity::EK_ArrayElement:
4805 case InitializedEntity::EK_Exception:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004806 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004807 case InitializedEntity::EK_RelatedResult:
Douglas Gregor95562572010-04-24 23:45:46 +00004808 return true;
4809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004810
4811 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00004812}
4813
Richard Smithc620f552011-10-19 16:55:56 +00004814/// \brief Look for copy and move constructors and constructor templates, for
4815/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4816static void LookupCopyAndMoveConstructors(Sema &S,
4817 OverloadCandidateSet &CandidateSet,
4818 CXXRecordDecl *Class,
4819 Expr *CurInitExpr) {
David Blaikieff7d47a2012-12-19 00:45:41 +00004820 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004821 // The container holding the constructors can under certain conditions
4822 // be changed while iterating (e.g. because of deserialization).
4823 // To be safe we copy the lookup results to a new container.
David Blaikieff7d47a2012-12-19 00:45:41 +00004824 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper2341c0d2013-07-04 03:08:24 +00004825 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004826 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4827 NamedDecl *D = *CI;
Richard Smithc620f552011-10-19 16:55:56 +00004828 CXXConstructorDecl *Constructor = 0;
4829
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004830 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smithc620f552011-10-19 16:55:56 +00004831 // Handle copy/moveconstructors, only.
4832 if (!Constructor || Constructor->isInvalidDecl() ||
4833 !Constructor->isCopyOrMoveConstructor() ||
4834 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4835 continue;
4836
4837 DeclAccessPair FoundDecl
4838 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4839 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004840 CurInitExpr, CandidateSet);
Richard Smithc620f552011-10-19 16:55:56 +00004841 continue;
4842 }
4843
4844 // Handle constructor templates.
Argyrios Kyrtzidis243d82342012-11-13 05:07:23 +00004845 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smithc620f552011-10-19 16:55:56 +00004846 if (ConstructorTmpl->isInvalidDecl())
4847 continue;
4848
4849 Constructor = cast<CXXConstructorDecl>(
4850 ConstructorTmpl->getTemplatedDecl());
4851 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4852 continue;
4853
4854 // FIXME: Do we need to limit this to copy-constructor-like
4855 // candidates?
4856 DeclAccessPair FoundDecl
4857 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4858 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004859 CurInitExpr, CandidateSet, true);
Richard Smithc620f552011-10-19 16:55:56 +00004860 }
4861}
4862
4863/// \brief Get the location at which initialization diagnostics should appear.
4864static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4865 Expr *Initializer) {
4866 switch (Entity.getKind()) {
4867 case InitializedEntity::EK_Result:
4868 return Entity.getReturnLoc();
4869
4870 case InitializedEntity::EK_Exception:
4871 return Entity.getThrowLoc();
4872
4873 case InitializedEntity::EK_Variable:
4874 return Entity.getDecl()->getLocation();
4875
Douglas Gregor19666fb2012-02-15 16:57:26 +00004876 case InitializedEntity::EK_LambdaCapture:
4877 return Entity.getCaptureLoc();
4878
Richard Smithc620f552011-10-19 16:55:56 +00004879 case InitializedEntity::EK_ArrayElement:
4880 case InitializedEntity::EK_Member:
4881 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00004882 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithc620f552011-10-19 16:55:56 +00004883 case InitializedEntity::EK_Temporary:
4884 case InitializedEntity::EK_New:
4885 case InitializedEntity::EK_Base:
4886 case InitializedEntity::EK_Delegating:
4887 case InitializedEntity::EK_VectorElement:
4888 case InitializedEntity::EK_ComplexElement:
4889 case InitializedEntity::EK_BlockElement:
Jordan Rose6c0505e2013-05-06 16:48:12 +00004890 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00004891 case InitializedEntity::EK_RelatedResult:
Richard Smithc620f552011-10-19 16:55:56 +00004892 return Initializer->getLocStart();
4893 }
4894 llvm_unreachable("missed an InitializedEntity kind?");
4895}
4896
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004897/// \brief Make a (potentially elidable) temporary copy of the object
4898/// provided by the given initializer by calling the appropriate copy
4899/// constructor.
4900///
4901/// \param S The Sema object used for type-checking.
4902///
Abramo Bagnara92141d22011-01-27 19:55:10 +00004903/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004904/// the type of the initializer expression or a superclass thereof.
4905///
James Dennett634962f2012-06-14 21:40:34 +00004906/// \param Entity The entity being initialized.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004907///
4908/// \param CurInit The initializer expression.
4909///
4910/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4911/// is permitted in C++03 (but not C++0x) when binding a reference to
4912/// an rvalue.
4913///
4914/// \returns An expression that copies the initializer expression into
4915/// a temporary object, or an error expression if a copy could not be
4916/// created.
John McCalldadc5752010-08-24 06:29:42 +00004917static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00004918 QualType T,
4919 const InitializedEntity &Entity,
4920 ExprResult CurInit,
4921 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00004922 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00004923 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004925 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004926 Class = cast<CXXRecordDecl>(Record->getDecl());
4927 if (!Class)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004928 return CurInit;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004929
Douglas Gregor5d369002011-01-21 18:05:27 +00004930 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004931 // When certain criteria are met, an implementation is allowed to
4932 // omit the copy/move construction of a class object, even if the
4933 // copy/move constructor and/or destructor for the object have
4934 // side effects. [...]
4935 // - when a temporary class object that has not been bound to a
4936 // reference (12.2) would be copied/moved to a class object
4937 // with the same cv-unqualified type, the copy/move operation
4938 // can be omitted by constructing the temporary object
4939 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004941 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004942 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004944 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00004945 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smithc620f552011-10-19 16:55:56 +00004946 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregord5c231e2010-04-24 21:09:25 +00004947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004948 // Make sure that the type we are copying is complete.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004949 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004950 return CurInit;
Douglas Gregord5c231e2010-04-24 21:09:25 +00004951
Douglas Gregorf282a762011-01-21 19:38:21 +00004952 // Perform overload resolution using the class's copy/move constructors.
Richard Smithc620f552011-10-19 16:55:56 +00004953 // Only consider constructors and constructor templates. Per
4954 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4955 // is direct-initialization.
John McCallbc077cf2010-02-08 23:07:23 +00004956 OverloadCandidateSet CandidateSet(Loc);
Richard Smithc620f552011-10-19 16:55:56 +00004957 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004958
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004959 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4960
Douglas Gregore1314a62009-12-18 05:02:21 +00004961 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004962 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004963 case OR_Success:
4964 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Douglas Gregore1314a62009-12-18 05:02:21 +00004966 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004967 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4968 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4969 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004970 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004971 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004972 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004973 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004974 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004975 return CurInit;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004976
Douglas Gregore1314a62009-12-18 05:02:21 +00004977 case OR_Ambiguous:
4978 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004979 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004980 << CurInitExpr->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00004981 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallfaf5fb42010-08-26 23:41:50 +00004982 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983
Douglas Gregore1314a62009-12-18 05:02:21 +00004984 case OR_Deleted:
4985 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004986 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004987 << CurInitExpr->getSourceRange();
Richard Smith852265f2012-03-30 20:53:28 +00004988 S.NoteDeletedFunction(Best->Function);
John McCallfaf5fb42010-08-26 23:41:50 +00004989 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004990 }
4991
Douglas Gregor5ab11652010-04-17 22:01:05 +00004992 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramerf0623432012-08-23 22:51:59 +00004993 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor5ab11652010-04-17 22:01:05 +00004994 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004995
Anders Carlssona01874b2010-04-21 18:47:17 +00004996 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004997 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004998
4999 if (IsExtraneousCopy) {
5000 // If this is a totally extraneous copy for C++03 reference
5001 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00005002 // expression. We don't generate an (elided) copy operation here
5003 // because doing so would require us to pass down a flag to avoid
5004 // infinite recursion, where each step adds another extraneous,
5005 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005006
Douglas Gregor30b52772010-04-18 07:57:34 +00005007 // Instantiate the default arguments of any extra parameters in
5008 // the selected copy constructor, as if we were going to create a
5009 // proper call to the copy constructor.
5010 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5011 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5012 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005013 diag::err_call_incomplete_argument))
Douglas Gregor30b52772010-04-18 07:57:34 +00005014 break;
5015
5016 // Build the default argument expression; we don't actually care
5017 // if this succeeds or not, because this routine will complain
5018 // if there was a problem.
5019 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5020 }
5021
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005022 return S.Owned(CurInitExpr);
5023 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024
Douglas Gregor5ab11652010-04-17 22:01:05 +00005025 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005026 // constructor call (we might have derived-to-base conversions, or
5027 // the copy constructor may have default arguments).
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005028 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005029 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005030
Douglas Gregord0ace022010-04-25 00:55:24 +00005031 // Actually perform the constructor call.
5032 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005033 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005034 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005035 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005036 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005037 CXXConstructExpr::CK_Complete,
5038 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039
Douglas Gregord0ace022010-04-25 00:55:24 +00005040 // If we're supposed to bind temporaries, do so.
5041 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5042 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005043 return CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00005044}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005045
Richard Smithc620f552011-10-19 16:55:56 +00005046/// \brief Check whether elidable copy construction for binding a reference to
5047/// a temporary would have succeeded if we were building in C++98 mode, for
5048/// -Wc++98-compat.
5049static void CheckCXX98CompatAccessibleCopy(Sema &S,
5050 const InitializedEntity &Entity,
5051 Expr *CurInitExpr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005052 assert(S.getLangOpts().CPlusPlus11);
Richard Smithc620f552011-10-19 16:55:56 +00005053
5054 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5055 if (!Record)
5056 return;
5057
5058 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5059 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5060 == DiagnosticsEngine::Ignored)
5061 return;
5062
5063 // Find constructors which would have been considered.
5064 OverloadCandidateSet CandidateSet(Loc);
5065 LookupCopyAndMoveConstructors(
5066 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5067
5068 // Perform overload resolution.
5069 OverloadCandidateSet::iterator Best;
5070 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5071
5072 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5073 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5074 << CurInitExpr->getSourceRange();
5075
5076 switch (OR) {
5077 case OR_Success:
5078 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCall5dadb652012-04-07 03:04:20 +00005079 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smithc620f552011-10-19 16:55:56 +00005080 // FIXME: Check default arguments as far as that's possible.
5081 break;
5082
5083 case OR_No_Viable_Function:
5084 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005085 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005086 break;
5087
5088 case OR_Ambiguous:
5089 S.Diag(Loc, Diag);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005090 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smithc620f552011-10-19 16:55:56 +00005091 break;
5092
5093 case OR_Deleted:
5094 S.Diag(Loc, Diag);
Richard Smith852265f2012-03-30 20:53:28 +00005095 S.NoteDeletedFunction(Best->Function);
Richard Smithc620f552011-10-19 16:55:56 +00005096 break;
5097 }
5098}
5099
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005100void InitializationSequence::PrintInitLocationNote(Sema &S,
5101 const InitializedEntity &Entity) {
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005102 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005103 if (Entity.getDecl()->getLocation().isInvalid())
5104 return;
5105
5106 if (Entity.getDecl()->getDeclName())
5107 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5108 << Entity.getDecl()->getDeclName();
5109 else
5110 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5111 }
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005112 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5113 Entity.getMethodDecl())
5114 S.Diag(Entity.getMethodDecl()->getLocation(),
5115 diag::note_method_return_type_change)
5116 << Entity.getMethodDecl()->getDeclName();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005117}
5118
Sebastian Redl112aa822011-07-14 19:07:55 +00005119static bool isReferenceBinding(const InitializationSequence::Step &s) {
5120 return s.Kind == InitializationSequence::SK_BindReference ||
5121 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5122}
5123
Jordan Rose6c0505e2013-05-06 16:48:12 +00005124/// Returns true if the parameters describe a constructor initialization of
5125/// an explicit temporary object, e.g. "Point(x, y)".
5126static bool isExplicitTemporary(const InitializedEntity &Entity,
5127 const InitializationKind &Kind,
5128 unsigned NumArgs) {
5129 switch (Entity.getKind()) {
5130 case InitializedEntity::EK_Temporary:
5131 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005132 case InitializedEntity::EK_RelatedResult:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005133 break;
5134 default:
5135 return false;
5136 }
5137
5138 switch (Kind.getKind()) {
5139 case InitializationKind::IK_DirectList:
5140 return true;
5141 // FIXME: Hack to work around cast weirdness.
5142 case InitializationKind::IK_Direct:
5143 case InitializationKind::IK_Value:
5144 return NumArgs != 1;
5145 default:
5146 return false;
5147 }
5148}
5149
Sebastian Redled2e5322011-12-22 14:44:04 +00005150static ExprResult
5151PerformConstructorInitialization(Sema &S,
5152 const InitializedEntity &Entity,
5153 const InitializationKind &Kind,
5154 MultiExprArg Args,
5155 const InitializationSequence::Step& Step,
Richard Smithd59b8322012-12-19 01:39:02 +00005156 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005157 bool IsListInitialization,
5158 SourceLocation LBraceLoc,
5159 SourceLocation RBraceLoc) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005160 unsigned NumArgs = Args.size();
5161 CXXConstructorDecl *Constructor
5162 = cast<CXXConstructorDecl>(Step.Function.Function);
5163 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5164
5165 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005166 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redled2e5322011-12-22 14:44:04 +00005167 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5168 ? Kind.getEqualLoc()
5169 : Kind.getLocation();
5170
5171 if (Kind.getKind() == InitializationKind::IK_Default) {
5172 // Force even a trivial, implicit default constructor to be
5173 // semantically checked. We do this explicitly because we don't build
5174 // the definition for completely trivial constructors.
Matt Beaumont-Gay47ff1222012-02-24 08:37:56 +00005175 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redled2e5322011-12-22 14:44:04 +00005176 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregorf704ade2012-02-24 07:48:37 +00005177 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redled2e5322011-12-22 14:44:04 +00005178 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5179 }
5180
5181 ExprResult CurInit = S.Owned((Expr *)0);
5182
Douglas Gregor6073dca2012-02-24 23:56:31 +00005183 // C++ [over.match.copy]p1:
5184 // - When initializing a temporary to be bound to the first parameter
5185 // of a constructor that takes a reference to possibly cv-qualified
5186 // T as its first argument, called with a single argument in the
5187 // context of direct-initialization, explicit conversion functions
5188 // are also considered.
5189 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5190 Args.size() == 1 &&
5191 Constructor->isCopyOrMoveConstructor();
5192
Sebastian Redled2e5322011-12-22 14:44:04 +00005193 // Determine the arguments required to actually perform the constructor
5194 // call.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005195 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005196 Loc, ConstructorArgs,
Richard Smith6b216962013-02-05 05:52:24 +00005197 AllowExplicitConv,
5198 IsListInitialization))
Sebastian Redled2e5322011-12-22 14:44:04 +00005199 return ExprError();
5200
5201
Jordan Rose6c0505e2013-05-06 16:48:12 +00005202 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redled2e5322011-12-22 14:44:04 +00005203 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedmanfa0df832012-02-02 03:46:19 +00005204 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005205 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5206 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005207
5208 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5209 if (!TSInfo)
5210 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005211 SourceRange ParenOrBraceRange =
5212 (Kind.getKind() == InitializationKind::IK_DirectList)
5213 ? SourceRange(LBraceLoc, RBraceLoc)
5214 : Kind.getParenRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00005215
Richard Smithd59b8322012-12-19 01:39:02 +00005216 CurInit = S.Owned(
5217 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5218 TSInfo, ConstructorArgs,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00005219 ParenOrBraceRange,
Richard Smithd59b8322012-12-19 01:39:02 +00005220 HadMultipleCandidates,
Enea Zaffanella82a65fc2013-09-07 11:22:02 +00005221 IsListInitialization,
Richard Smithd59b8322012-12-19 01:39:02 +00005222 ConstructorInitRequiresZeroInit));
Sebastian Redled2e5322011-12-22 14:44:04 +00005223 } else {
5224 CXXConstructExpr::ConstructionKind ConstructKind =
5225 CXXConstructExpr::CK_Complete;
5226
5227 if (Entity.getKind() == InitializedEntity::EK_Base) {
5228 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5229 CXXConstructExpr::CK_VirtualBase :
5230 CXXConstructExpr::CK_NonVirtualBase;
5231 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5232 ConstructKind = CXXConstructExpr::CK_Delegating;
5233 }
5234
5235 // Only get the parenthesis range if it is a direct construction.
5236 SourceRange parenRange =
5237 Kind.getKind() == InitializationKind::IK_Direct ?
5238 Kind.getParenRange() : SourceRange();
5239
5240 // If the entity allows NRVO, mark the construction as elidable
5241 // unconditionally.
5242 if (Entity.allowsNRVO())
5243 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5244 Constructor, /*Elidable=*/true,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005245 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005246 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005247 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005248 ConstructorInitRequiresZeroInit,
5249 ConstructKind,
5250 parenRange);
5251 else
5252 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5253 Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005254 ConstructorArgs,
Sebastian Redled2e5322011-12-22 14:44:04 +00005255 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005256 IsListInitialization,
Sebastian Redled2e5322011-12-22 14:44:04 +00005257 ConstructorInitRequiresZeroInit,
5258 ConstructKind,
5259 parenRange);
5260 }
5261 if (CurInit.isInvalid())
5262 return ExprError();
5263
5264 // Only check access if all of that succeeded.
5265 S.CheckConstructorAccess(Loc, Constructor, Entity,
5266 Step.Function.FoundDecl.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005267 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5268 return ExprError();
Sebastian Redled2e5322011-12-22 14:44:04 +00005269
5270 if (shouldBindAsTemporary(Entity))
Richard Smithcc1b96d2013-06-12 22:31:48 +00005271 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redled2e5322011-12-22 14:44:04 +00005272
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005273 return CurInit;
Sebastian Redled2e5322011-12-22 14:44:04 +00005274}
5275
Richard Smitheb3cad52012-06-04 22:27:30 +00005276/// Determine whether the specified InitializedEntity definitely has a lifetime
5277/// longer than the current full-expression. Conservatively returns false if
5278/// it's unclear.
5279static bool
5280InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5281 const InitializedEntity *Top = &Entity;
5282 while (Top->getParent())
5283 Top = Top->getParent();
5284
5285 switch (Top->getKind()) {
5286 case InitializedEntity::EK_Variable:
5287 case InitializedEntity::EK_Result:
5288 case InitializedEntity::EK_Exception:
5289 case InitializedEntity::EK_Member:
5290 case InitializedEntity::EK_New:
5291 case InitializedEntity::EK_Base:
5292 case InitializedEntity::EK_Delegating:
5293 return true;
5294
5295 case InitializedEntity::EK_ArrayElement:
5296 case InitializedEntity::EK_VectorElement:
5297 case InitializedEntity::EK_BlockElement:
5298 case InitializedEntity::EK_ComplexElement:
5299 // Could not determine what the full initialization is. Assume it might not
5300 // outlive the full-expression.
5301 return false;
5302
5303 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005304 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smitheb3cad52012-06-04 22:27:30 +00005305 case InitializedEntity::EK_Temporary:
5306 case InitializedEntity::EK_LambdaCapture:
Jordan Rose6c0505e2013-05-06 16:48:12 +00005307 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005308 case InitializedEntity::EK_RelatedResult:
Richard Smitheb3cad52012-06-04 22:27:30 +00005309 // The entity being initialized might not outlive the full-expression.
5310 return false;
5311 }
5312
5313 llvm_unreachable("unknown entity kind");
5314}
5315
Richard Smithe6c01442013-06-05 00:46:14 +00005316/// Determine the declaration which an initialized entity ultimately refers to,
5317/// for the purpose of lifetime-extending a temporary bound to a reference in
5318/// the initialization of \p Entity.
5319static const ValueDecl *
5320getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5321 const ValueDecl *FallbackDecl = 0) {
5322 // C++11 [class.temporary]p5:
5323 switch (Entity.getKind()) {
5324 case InitializedEntity::EK_Variable:
5325 // The temporary [...] persists for the lifetime of the reference
5326 return Entity.getDecl();
5327
5328 case InitializedEntity::EK_Member:
5329 // For subobjects, we look at the complete object.
5330 if (Entity.getParent())
5331 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5332 Entity.getDecl());
5333
5334 // except:
5335 // -- A temporary bound to a reference member in a constructor's
5336 // ctor-initializer persists until the constructor exits.
5337 return Entity.getDecl();
5338
5339 case InitializedEntity::EK_Parameter:
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005340 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smithe6c01442013-06-05 00:46:14 +00005341 // -- A temporary bound to a reference parameter in a function call
5342 // persists until the completion of the full-expression containing
5343 // the call.
5344 case InitializedEntity::EK_Result:
5345 // -- The lifetime of a temporary bound to the returned value in a
5346 // function return statement is not extended; the temporary is
5347 // destroyed at the end of the full-expression in the return statement.
5348 case InitializedEntity::EK_New:
5349 // -- A temporary bound to a reference in a new-initializer persists
5350 // until the completion of the full-expression containing the
5351 // new-initializer.
5352 return 0;
5353
5354 case InitializedEntity::EK_Temporary:
5355 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00005356 case InitializedEntity::EK_RelatedResult:
Richard Smithe6c01442013-06-05 00:46:14 +00005357 // We don't yet know the storage duration of the surrounding temporary.
5358 // Assume it's got full-expression duration for now, it will patch up our
5359 // storage duration if that's not correct.
5360 return 0;
5361
5362 case InitializedEntity::EK_ArrayElement:
5363 // For subobjects, we look at the complete object.
5364 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5365 FallbackDecl);
5366
5367 case InitializedEntity::EK_Base:
5368 case InitializedEntity::EK_Delegating:
5369 // We can reach this case for aggregate initialization in a constructor:
5370 // struct A { int &&r; };
5371 // struct B : A { B() : A{0} {} };
5372 // In this case, use the innermost field decl as the context.
5373 return FallbackDecl;
5374
5375 case InitializedEntity::EK_BlockElement:
5376 case InitializedEntity::EK_LambdaCapture:
5377 case InitializedEntity::EK_Exception:
5378 case InitializedEntity::EK_VectorElement:
5379 case InitializedEntity::EK_ComplexElement:
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005380 return 0;
Richard Smithe6c01442013-06-05 00:46:14 +00005381 }
Benjamin Kramercabc8822013-06-05 15:37:50 +00005382 llvm_unreachable("unknown entity kind");
Richard Smithe6c01442013-06-05 00:46:14 +00005383}
5384
5385static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5386
5387/// Update a glvalue expression that is used as the initializer of a reference
5388/// to note that its lifetime is extended.
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005389/// \return \c true if any temporary had its lifetime extended.
5390static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
Richard Smithe6c01442013-06-05 00:46:14 +00005391 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5392 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5393 // This is just redundant braces around an initializer. Step over it.
5394 Init = ILE->getInit(0);
5395 }
5396 }
5397
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005398 // Walk past any constructs which we can lifetime-extend across.
5399 Expr *Old;
5400 do {
5401 Old = Init;
5402
5403 // Step over any subobject adjustments; we may have a materialized
5404 // temporary inside them.
5405 SmallVector<const Expr *, 2> CommaLHSs;
5406 SmallVector<SubobjectAdjustment, 2> Adjustments;
5407 Init = const_cast<Expr *>(
5408 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5409
5410 // Per current approach for DR1376, look through casts to reference type
5411 // when performing lifetime extension.
5412 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5413 if (CE->getSubExpr()->isGLValue())
5414 Init = CE->getSubExpr();
5415
5416 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5417 // It's unclear if binding a reference to that xvalue extends the array
5418 // temporary.
5419 } while (Init != Old);
5420
Richard Smithe6c01442013-06-05 00:46:14 +00005421 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5422 // Update the storage duration of the materialized temporary.
5423 // FIXME: Rebuild the expression instead of mutating it.
5424 ME->setExtendingDecl(ExtendingD);
5425 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005426 return true;
Richard Smithe6c01442013-06-05 00:46:14 +00005427 }
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005428
5429 return false;
Richard Smithe6c01442013-06-05 00:46:14 +00005430}
5431
5432/// Update a prvalue expression that is going to be materialized as a
5433/// lifetime-extended temporary.
5434static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5435 // Dig out the expression which constructs the extended temporary.
5436 SmallVector<const Expr *, 2> CommaLHSs;
5437 SmallVector<SubobjectAdjustment, 2> Adjustments;
5438 Init = const_cast<Expr *>(
5439 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5440
Richard Smith736a9472013-06-12 20:42:33 +00005441 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5442 Init = BTE->getSubExpr();
5443
Richard Smithcc1b96d2013-06-12 22:31:48 +00005444 if (CXXStdInitializerListExpr *ILE =
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005445 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5446 performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5447 return;
5448 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00005449
Richard Smithe6c01442013-06-05 00:46:14 +00005450 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smithcc1b96d2013-06-12 22:31:48 +00005451 if (ILE->getType()->isArrayType()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005452 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5453 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5454 return;
5455 }
5456
Richard Smithcc1b96d2013-06-12 22:31:48 +00005457 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smithe6c01442013-06-05 00:46:14 +00005458 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5459
5460 // If we lifetime-extend a braced initializer which is initializing an
5461 // aggregate, and that aggregate contains reference members which are
5462 // bound to temporaries, those temporaries are also lifetime-extended.
5463 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5464 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5465 performReferenceExtension(ILE->getInit(0), ExtendingD);
5466 else {
5467 unsigned Index = 0;
5468 for (RecordDecl::field_iterator I = RD->field_begin(),
5469 E = RD->field_end();
5470 I != E; ++I) {
Richard Smith0bca59d2013-07-01 06:08:20 +00005471 if (Index >= ILE->getNumInits())
5472 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005473 if (I->isUnnamedBitfield())
5474 continue;
Richard Smith8d7f11d2013-06-27 22:54:33 +00005475 Expr *SubInit = ILE->getInit(Index);
Richard Smithe6c01442013-06-05 00:46:14 +00005476 if (I->getType()->isReferenceType())
Richard Smith8d7f11d2013-06-27 22:54:33 +00005477 performReferenceExtension(SubInit, ExtendingD);
5478 else if (isa<InitListExpr>(SubInit) ||
5479 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smithe6c01442013-06-05 00:46:14 +00005480 // This may be either aggregate-initialization of a member or
5481 // initialization of a std::initializer_list object. Either way,
5482 // we should recursively lifetime-extend that initializer.
Richard Smith8d7f11d2013-06-27 22:54:33 +00005483 performLifetimeExtension(SubInit, ExtendingD);
Richard Smithe6c01442013-06-05 00:46:14 +00005484 ++Index;
5485 }
5486 }
5487 }
5488 }
5489}
5490
Richard Smithcc1b96d2013-06-12 22:31:48 +00005491static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5492 const Expr *Init, bool IsInitializerList,
5493 const ValueDecl *ExtendingDecl) {
5494 // Warn if a field lifetime-extends a temporary.
5495 if (isa<FieldDecl>(ExtendingDecl)) {
5496 if (IsInitializerList) {
5497 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5498 << /*at end of constructor*/true;
5499 return;
5500 }
5501
5502 bool IsSubobjectMember = false;
5503 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5504 Ent = Ent->getParent()) {
5505 if (Ent->getKind() != InitializedEntity::EK_Base) {
5506 IsSubobjectMember = true;
5507 break;
5508 }
5509 }
5510 S.Diag(Init->getExprLoc(),
5511 diag::warn_bind_ref_member_to_temporary)
5512 << ExtendingDecl << Init->getSourceRange()
5513 << IsSubobjectMember << IsInitializerList;
5514 if (IsSubobjectMember)
5515 S.Diag(ExtendingDecl->getLocation(),
5516 diag::note_ref_subobject_of_member_declared_here);
5517 else
5518 S.Diag(ExtendingDecl->getLocation(),
5519 diag::note_ref_or_ptr_member_declared_here)
5520 << /*is pointer*/false;
5521 }
5522}
5523
Richard Smithaaa0ec42013-09-21 21:19:19 +00005524static void DiagnoseNarrowingInInitList(Sema &S,
5525 const ImplicitConversionSequence &ICS,
5526 QualType PreNarrowingType,
5527 QualType EntityType,
5528 const Expr *PostInit);
5529
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005531InitializationSequence::Perform(Sema &S,
5532 const InitializedEntity &Entity,
5533 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00005534 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00005535 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00005536 if (Failed()) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005537 Diagnose(S, Entity, Kind, Args);
John McCallfaf5fb42010-08-26 23:41:50 +00005538 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005540
Sebastian Redld201edf2011-06-05 13:59:11 +00005541 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005542 // If the declaration is a non-dependent, incomplete array type
5543 // that has an initializer, then its type will be completed once
5544 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00005545 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00005546 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00005547 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005548 if (const IncompleteArrayType *ArrayT
5549 = S.Context.getAsIncompleteArrayType(DeclType)) {
5550 // FIXME: We don't currently have the ability to accurately
5551 // compute the length of an initializer list without
5552 // performing full type-checking of the initializer list
5553 // (since we have to determine where braces are implicitly
5554 // introduced and such). So, we fall back to making the array
5555 // type a dependently-sized array type with no specified
5556 // bound.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005557 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00005558 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00005559
Douglas Gregor51e77d52009-12-10 17:56:55 +00005560 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00005561 if (DeclaratorDecl *DD = Entity.getDecl()) {
5562 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5563 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00005564 if (IncompleteArrayTypeLoc ArrayLoc =
5565 TL.getAs<IncompleteArrayTypeLoc>())
5566 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregor1b303932009-12-22 15:35:07 +00005567 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00005568 }
5569
5570 *ResultType
5571 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5572 /*NumElts=*/0,
5573 ArrayT->getSizeModifier(),
5574 ArrayT->getIndexTypeCVRQualifiers(),
5575 Brackets);
5576 }
5577
5578 }
5579 }
Sebastian Redla9351792012-02-11 23:51:47 +00005580 if (Kind.getKind() == InitializationKind::IK_Direct &&
5581 !Kind.isExplicitCast()) {
5582 // Rebuild the ParenListExpr.
5583 SourceRange ParenRange = Kind.getParenRange();
5584 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005585 Args);
Sebastian Redla9351792012-02-11 23:51:47 +00005586 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00005587 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregorbf138952012-04-04 04:06:51 +00005588 Kind.isExplicitCast() ||
5589 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005590 return ExprResult(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005591 }
5592
Sebastian Redld201edf2011-06-05 13:59:11 +00005593 // No steps means no initialization.
5594 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00005595 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005597 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005598 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00005599 !Entity.isParameterKind()) {
Richard Smith2b349ae2012-04-19 06:58:00 +00005600 // Produce a C++98 compatibility warning if we are initializing a reference
5601 // from an initializer list. For parameters, we produce a better warning
5602 // elsewhere.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005603 Expr *Init = Args[0];
Richard Smith2b349ae2012-04-19 06:58:00 +00005604 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5605 << Init->getSourceRange();
5606 }
5607
Richard Smitheb3cad52012-06-04 22:27:30 +00005608 // Diagnose cases where we initialize a pointer to an array temporary, and the
5609 // pointer obviously outlives the temporary.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005610 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smitheb3cad52012-06-04 22:27:30 +00005611 Entity.getType()->isPointerType() &&
5612 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005613 Expr *Init = Args[0];
Richard Smitheb3cad52012-06-04 22:27:30 +00005614 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5615 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5616 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5617 << Init->getSourceRange();
5618 }
5619
Douglas Gregor1b303932009-12-22 15:35:07 +00005620 QualType DestType = Entity.getType().getNonReferenceType();
5621 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00005622 // the same as Entity.getDecl()->getType() in cases involving type merging,
5623 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00005624 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00005625 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00005626 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005627
John McCalldadc5752010-08-24 06:29:42 +00005628 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005630 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00005631 // grab the only argument out the Args and place it into the "current"
5632 // initializer.
5633 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005634 case SK_ResolveAddressOfOverloadedFunction:
5635 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005636 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005637 case SK_CastDerivedToBaseLValue:
5638 case SK_BindReference:
5639 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005640 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00005641 case SK_UserConversion:
5642 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005643 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005644 case SK_QualificationConversionRValue:
Jordan Roseb1312a52013-04-11 00:58:58 +00005645 case SK_LValueToRValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00005646 case SK_ConversionSequence:
Richard Smithaaa0ec42013-09-21 21:19:19 +00005647 case SK_ConversionSequenceNoNarrowing:
Douglas Gregore1314a62009-12-18 05:02:21 +00005648 case SK_ListInitialization:
Sebastian Redl29526f02011-11-27 16:50:07 +00005649 case SK_UnwrapInitList:
5650 case SK_RewrapInitList:
Douglas Gregore1314a62009-12-18 05:02:21 +00005651 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00005652 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00005653 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00005654 case SK_ArrayInit:
Richard Smithebeed412012-02-15 22:38:09 +00005655 case SK_ParenthesizedArrayInit:
John McCall31168b02011-06-15 23:02:42 +00005656 case SK_PassByIndirectCopyRestore:
5657 case SK_PassByIndirectRestore:
Sebastian Redlc1839b12012-01-17 22:49:42 +00005658 case SK_ProduceObjCObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005659 case SK_StdInitializerList:
Guy Benyei61054192013-02-07 10:55:47 +00005660 case SK_OCLSamplerInit:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005661 case SK_OCLZeroEvent: {
Douglas Gregore1314a62009-12-18 05:02:21 +00005662 assert(Args.size() == 1);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005663 CurInit = Args[0];
John Wiegley01296292011-04-08 18:41:53 +00005664 if (!CurInit.get()) return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00005665 break;
John McCall34376a62010-12-04 03:47:34 +00005666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Douglas Gregore1314a62009-12-18 05:02:21 +00005668 case SK_ConstructorInitialization:
Richard Smithd86812d2012-07-05 08:39:21 +00005669 case SK_ListConstructorCall:
Douglas Gregore1314a62009-12-18 05:02:21 +00005670 case SK_ZeroInitialization:
5671 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
5674 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005675 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005676 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005677 for (step_iterator Step = step_begin(), StepEnd = step_end();
5678 Step != StepEnd; ++Step) {
5679 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005680 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005681
John Wiegley01296292011-04-08 18:41:53 +00005682 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005684 switch (Step->Kind) {
5685 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005687 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00005688 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +00005689 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5690 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005691 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall16df1e52010-03-30 21:47:33 +00005692 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00005693 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005694 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005696 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005697 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005698 case SK_CastDerivedToBaseLValue: {
5699 // We have a derived-to-base cast that produces either an rvalue or an
5700 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701
John McCallcf142162010-08-07 06:22:56 +00005702 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00005703
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005704 // Casts to inaccessible base classes are allowed with C-style casts.
5705 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5706 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00005707 CurInit.get()->getLocStart(),
5708 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00005709 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00005710 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005711
Douglas Gregor88d292c2010-05-13 16:44:06 +00005712 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5713 QualType T = SourceType;
5714 if (const PointerType *Pointer = T->getAs<PointerType>())
5715 T = Pointer->getPointeeType();
5716 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00005717 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00005718 cast<CXXRecordDecl>(RecordTy->getDecl()));
5719 }
5720
John McCall2536c6d2010-08-25 10:28:54 +00005721 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005722 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005723 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005724 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005725 VK_XValue :
5726 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00005727 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5728 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00005729 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00005730 CurInit.get(),
5731 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005732 break;
5733 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005734
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005735 case SK_BindReference:
John McCalld25db7e2013-05-06 21:39:12 +00005736 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5737 if (CurInit.get()->refersToBitField()) {
5738 // We don't necessarily have an unambiguous source bit-field.
5739 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005740 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00005741 << Entity.getType().isVolatileQualified()
John McCalld25db7e2013-05-06 21:39:12 +00005742 << (BitField ? BitField->getDeclName() : DeclarationName())
5743 << (BitField != NULL)
John Wiegley01296292011-04-08 18:41:53 +00005744 << CurInit.get()->getSourceRange();
John McCalld25db7e2013-05-06 21:39:12 +00005745 if (BitField)
5746 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5747
John McCallfaf5fb42010-08-26 23:41:50 +00005748 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005749 }
Anders Carlssona91be642010-01-29 02:47:33 +00005750
John Wiegley01296292011-04-08 18:41:53 +00005751 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00005752 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005753 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5754 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00005755 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005756 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00005757 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005760 // Reference binding does not have any corresponding ASTs.
5761
5762 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005763 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005764 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005765
Richard Smith6b6f8aa2013-06-15 00:30:29 +00005766 // Even though we didn't materialize a temporary, the binding may still
5767 // extend the lifetime of a temporary. This happens if we bind a reference
5768 // to the result of a cast to reference type.
5769 if (const ValueDecl *ExtendingDecl =
5770 getDeclForTemporaryLifetimeExtension(Entity)) {
5771 if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5772 warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5773 ExtendingDecl);
5774 }
5775
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005776 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00005777
Richard Smithe6c01442013-06-05 00:46:14 +00005778 case SK_BindReferenceToTemporary: {
Jordan Roseb1312a52013-04-11 00:58:58 +00005779 // Make sure the "temporary" is actually an rvalue.
5780 assert(CurInit.get()->isRValue() && "not a temporary");
5781
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005782 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00005783 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00005784 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005785
Richard Smithe6c01442013-06-05 00:46:14 +00005786 // Maybe lifetime-extend the temporary's subobjects to match the
5787 // entity's lifetime.
5788 const ValueDecl *ExtendingDecl =
5789 getDeclForTemporaryLifetimeExtension(Entity);
Richard Smithe3b28bc2013-06-12 21:51:50 +00005790 if (ExtendingDecl) {
Richard Smithe6c01442013-06-05 00:46:14 +00005791 performLifetimeExtension(CurInit.get(), ExtendingDecl);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005792 warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
Richard Smithe3b28bc2013-06-12 21:51:50 +00005793 }
5794
Douglas Gregorfe314812011-06-21 17:03:29 +00005795 // Materialize the temporary into memory.
Richard Smith736a9472013-06-12 20:42:33 +00005796 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smithe6c01442013-06-05 00:46:14 +00005797 Entity.getType().getNonReferenceType(), CurInit.get(),
5798 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregor58df5092011-06-22 16:12:01 +00005799
5800 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith736a9472013-06-12 20:42:33 +00005801 // need cleanups. Likewise if we're extending this temporary to automatic
5802 // storage duration -- we need to register its cleanup during the
5803 // full-expression's cleanups.
5804 if ((S.getLangOpts().ObjCAutoRefCount &&
5805 MTE->getType()->isObjCLifetimeType()) ||
5806 (MTE->getStorageDuration() == SD_Automatic &&
5807 MTE->getType().isDestructedType()))
Douglas Gregor58df5092011-06-22 16:12:01 +00005808 S.ExprNeedsCleanups = true;
Richard Smith736a9472013-06-12 20:42:33 +00005809
5810 CurInit = S.Owned(MTE);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005811 break;
Richard Smithe6c01442013-06-05 00:46:14 +00005812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005813
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005814 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005815 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005816 /*IsExtraneousCopy=*/true);
5817 break;
5818
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005819 case SK_UserConversion: {
5820 // We have a user-defined conversion that invokes either a constructor
5821 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00005822 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00005823 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00005824 FunctionDecl *Fn = Step->Function.Function;
5825 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005826 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor95562572010-04-24 23:45:46 +00005827 bool CreatedObject = false;
John McCall760af172010-02-01 03:16:54 +00005828 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005829 // Build a call to the selected constructor.
Benjamin Kramerf0623432012-08-23 22:51:59 +00005830 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley01296292011-04-08 18:41:53 +00005831 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005832 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00005833
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005834 // Determine the arguments required to actually perform the constructor
5835 // call.
John Wiegley01296292011-04-08 18:41:53 +00005836 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005837 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00005838 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005839 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00005840 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005841
Richard Smithb24f0672012-02-11 19:22:50 +00005842 // Build an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005843 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005844 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005845 HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +00005846 /*ListInit*/ false,
John McCallbfd822c2010-08-24 07:32:53 +00005847 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00005848 CXXConstructExpr::CK_Complete,
5849 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005850 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005851 return ExprError();
John McCall760af172010-02-01 03:16:54 +00005852
Anders Carlssona01874b2010-04-21 18:47:17 +00005853 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00005854 FoundFn.getAccess());
Richard Smith22262ab2013-05-04 06:44:46 +00005855 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5856 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005857
John McCalle3027922010-08-25 11:45:40 +00005858 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00005859 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5860 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5861 S.IsDerivedFrom(SourceType, Class))
5862 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005863
Douglas Gregor95562572010-04-24 23:45:46 +00005864 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005865 } else {
5866 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00005867 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley01296292011-04-08 18:41:53 +00005868 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00005869 FoundFn);
Richard Smith22262ab2013-05-04 06:44:46 +00005870 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5871 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005872
5873 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005874 // derived-to-base conversion? I believe the answer is "no", because
5875 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00005876 ExprResult CurInitExprRes =
5877 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5878 FoundFn, Conversion);
5879 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005880 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005881 CurInit = CurInitExprRes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005882
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005883 // Build the actual call to the conversion function.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005884 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5885 HadMultipleCandidates);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005886 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00005887 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005888
John McCalle3027922010-08-25 11:45:40 +00005889 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005890
Alp Toker314cc812014-01-25 16:55:45 +00005891 CreatedObject = Conversion->getReturnType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893
Sebastian Redl112aa822011-07-14 19:07:55 +00005894 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005895 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5896
5897 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00005898 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00005899 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005900 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00005901 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00005902 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00005903 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedmanfa0df832012-02-02 03:46:19 +00005904 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith22262ab2013-05-04 06:44:46 +00005905 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5906 return ExprError();
Douglas Gregor95562572010-04-24 23:45:46 +00005907 }
5908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005909
John McCallcf142162010-08-07 06:22:56 +00005910 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00005911 CurInit.get()->getType(),
5912 CastKind, CurInit.get(), 0,
Eli Friedmanf272d402011-09-27 01:11:35 +00005913 CurInit.get()->getValueKind()));
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005914 if (MaybeBindToTemp)
5915 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005916 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005917 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005918 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005919 break;
5920 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005921
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005922 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005923 case SK_QualificationConversionXValue:
5924 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005925 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00005926 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005927 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005928 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005929 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00005930 VK_XValue :
5931 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005932 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005933 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005934 }
5935
Jordan Roseb1312a52013-04-11 00:58:58 +00005936 case SK_LValueToRValue: {
5937 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5938 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5939 CK_LValueToRValue,
5940 CurInit.take(),
5941 /*BasePath=*/0,
5942 VK_RValue));
5943 break;
5944 }
5945
Richard Smithaaa0ec42013-09-21 21:19:19 +00005946 case SK_ConversionSequence:
5947 case SK_ConversionSequenceNoNarrowing: {
5948 Sema::CheckedConversionKind CCK
John McCall31168b02011-06-15 23:02:42 +00005949 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5950 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smith507840d2011-11-29 22:48:16 +00005951 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCall31168b02011-06-15 23:02:42 +00005952 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00005953 ExprResult CurInitExprRes =
5954 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00005955 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00005956 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005957 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005958 CurInit = CurInitExprRes;
Richard Smithaaa0ec42013-09-21 21:19:19 +00005959
5960 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5961 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5962 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5963 CurInit.get());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005964 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00005965 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005966
Douglas Gregor51e77d52009-12-10 17:56:55 +00005967 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00005968 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smithcc1b96d2013-06-12 22:31:48 +00005969 // If we're not initializing the top-level entity, we need to create an
5970 // InitializeTemporary entity for our target type.
5971 QualType Ty = Step->Type;
5972 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl29526f02011-11-27 16:50:07 +00005973 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smithd712d0d2013-02-02 01:13:06 +00005974 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5975 InitListChecker PerformInitList(S, InitEntity,
Richard Smithde229232013-06-06 11:41:05 +00005976 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005977 if (PerformInitList.HadError())
John McCallfaf5fb42010-08-26 23:41:50 +00005978 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005979
Richard Smithcc1b96d2013-06-12 22:31:48 +00005980 // Hack: We must update *ResultType if available in order to set the
5981 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5982 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5983 if (ResultType &&
5984 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl29526f02011-11-27 16:50:07 +00005985 if ((*ResultType)->isRValueReferenceType())
5986 Ty = S.Context.getRValueReferenceType(Ty);
5987 else if ((*ResultType)->isLValueReferenceType())
5988 Ty = S.Context.getLValueReferenceType(Ty,
5989 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5990 *ResultType = Ty;
5991 }
5992
5993 InitListExpr *StructuredInitList =
5994 PerformInitList.getFullyStructuredList();
Douglas Gregor51e77d52009-12-10 17:56:55 +00005995 CurInit.release();
Richard Smithd712d0d2013-02-02 01:13:06 +00005996 CurInit = shouldBindAsTemporary(InitEntity)
5997 ? S.MaybeBindToTemporary(StructuredInitList)
5998 : S.Owned(StructuredInitList);
Douglas Gregor51e77d52009-12-10 17:56:55 +00005999 break;
6000 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006001
Sebastian Redled2e5322011-12-22 14:44:04 +00006002 case SK_ListConstructorCall: {
Sebastian Redl5a41f682012-02-12 16:37:24 +00006003 // When an initializer list is passed for a parameter of type "reference
6004 // to object", we don't get an EK_Temporary entity, but instead an
6005 // EK_Parameter entity with reference type.
Sebastian Redl99f66162012-02-19 12:27:56 +00006006 // FIXME: This is a hack. What we really should do is create a user
6007 // conversion step for this case, but this makes it considerably more
6008 // complicated. For now, this will do.
Sebastian Redl5a41f682012-02-12 16:37:24 +00006009 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6010 Entity.getType().getNonReferenceType());
6011 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithd86812d2012-07-05 08:39:21 +00006012 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006013 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith2b349ae2012-04-19 06:58:00 +00006014 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6015 << InitList->getSourceRange();
Sebastian Redled2e5322011-12-22 14:44:04 +00006016 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl5a41f682012-02-12 16:37:24 +00006017 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6018 Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006019 Kind, Arg, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006020 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006021 /*IsListInitialization*/ true,
6022 InitList->getLBraceLoc(),
6023 InitList->getRBraceLoc());
Sebastian Redled2e5322011-12-22 14:44:04 +00006024 break;
6025 }
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006026
Sebastian Redl29526f02011-11-27 16:50:07 +00006027 case SK_UnwrapInitList:
6028 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
6029 break;
6030
6031 case SK_RewrapInitList: {
6032 Expr *E = CurInit.take();
6033 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6034 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramerc215e762012-08-24 11:54:20 +00006035 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl29526f02011-11-27 16:50:07 +00006036 ILE->setSyntacticForm(Syntactic);
6037 ILE->setType(E->getType());
6038 ILE->setValueKind(E->getValueKind());
6039 CurInit = S.Owned(ILE);
6040 break;
6041 }
6042
Sebastian Redl99f66162012-02-19 12:27:56 +00006043 case SK_ConstructorInitialization: {
6044 // When an initializer list is passed for a parameter of type "reference
6045 // to object", we don't get an EK_Temporary entity, but instead an
6046 // EK_Parameter entity with reference type.
6047 // FIXME: This is a hack. What we really should do is create a user
6048 // conversion step for this case, but this makes it considerably more
6049 // complicated. For now, this will do.
6050 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6051 Entity.getType().getNonReferenceType());
6052 bool UseTemporary = Entity.getType()->isReferenceType();
6053 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6054 : Entity,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006055 Kind, Args, *Step,
Richard Smithd59b8322012-12-19 01:39:02 +00006056 ConstructorInitRequiresZeroInit,
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00006057 /*IsListInitialization*/ false,
6058 /*LBraceLoc*/ SourceLocation(),
6059 /*RBraceLoc*/ SourceLocation());
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006060 break;
Sebastian Redl99f66162012-02-19 12:27:56 +00006061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006062
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006063 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006064 step_iterator NextStep = Step;
6065 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006066 if (NextStep != StepEnd &&
Richard Smithd86812d2012-07-05 08:39:21 +00006067 (NextStep->Kind == SK_ConstructorInitialization ||
6068 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006069 // The need for zero-initialization is recorded directly into
6070 // the call to the object's constructor within the next step.
6071 ConstructorInitRequiresZeroInit = true;
6072 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006073 S.getLangOpts().CPlusPlus &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006074 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00006075 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6076 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006077 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00006078 Kind.getRange().getBegin());
6079
6080 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6081 TSInfo->getType().getNonLValueExprType(S.Context),
6082 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006083 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006084 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006085 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006086 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00006087 break;
6088 }
Douglas Gregore1314a62009-12-18 05:02:21 +00006089
6090 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00006091 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006092 ExprResult Result = CurInit;
Douglas Gregore1314a62009-12-18 05:02:21 +00006093 Sema::AssignConvertType ConvTy =
Fariborz Jahanian25eef192013-07-31 21:40:51 +00006094 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6095 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley01296292011-04-08 18:41:53 +00006096 if (Result.isInvalid())
6097 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006098 CurInit = Result;
Douglas Gregor96596c92009-12-22 07:24:36 +00006099
6100 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006101 ExprResult CurInitExprRes = CurInit;
Douglas Gregor96596c92009-12-22 07:24:36 +00006102 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006103 Entity.isParameterKind() &&
John Wiegley01296292011-04-08 18:41:53 +00006104 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00006105 == Sema::Compatible)
6106 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00006107 if (CurInitExprRes.isInvalid())
6108 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006109 CurInit = CurInitExprRes;
Douglas Gregor96596c92009-12-22 07:24:36 +00006110
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006111 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00006112 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6113 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00006114 CurInit.get(),
Fariborz Jahanian3a25d0d2013-07-31 23:19:34 +00006115 getAssignmentAction(Entity, true),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006116 &Complained)) {
6117 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00006118 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006119 } else if (Complained)
6120 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00006121 break;
6122 }
Eli Friedman78275202009-12-19 08:11:05 +00006123
6124 case SK_StringInit: {
6125 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00006126 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00006127 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00006128 break;
6129 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006130
6131 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00006132 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00006133 CK_ObjCObjectLValueCast,
Eli Friedmanbe4b3632011-09-27 21:58:52 +00006134 CurInit.get()->getValueKind());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006135 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006136
6137 case SK_ArrayInit:
6138 // Okay: we checked everything before creating this step. Note that
6139 // this is a GNU extension.
6140 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00006141 << Step->Type << CurInit.get()->getType()
6142 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00006143
6144 // If the destination type is an incomplete array type, update the
6145 // type accordingly.
6146 if (ResultType) {
6147 if (const IncompleteArrayType *IncompleteDest
6148 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6149 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00006150 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00006151 *ResultType = S.Context.getConstantArrayType(
6152 IncompleteDest->getElementType(),
6153 ConstantSource->getSize(),
6154 ArrayType::Normal, 0);
6155 }
6156 }
6157 }
John McCall31168b02011-06-15 23:02:42 +00006158 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006159
Richard Smithebeed412012-02-15 22:38:09 +00006160 case SK_ParenthesizedArrayInit:
6161 // Okay: we checked everything before creating this step. Note that
6162 // this is a GNU extension.
6163 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6164 << CurInit.get()->getSourceRange();
6165 break;
6166
John McCall31168b02011-06-15 23:02:42 +00006167 case SK_PassByIndirectCopyRestore:
6168 case SK_PassByIndirectRestore:
6169 checkIndirectCopyRestoreSource(S, CurInit.get());
6170 CurInit = S.Owned(new (S.Context)
6171 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6172 Step->Kind == SK_PassByIndirectCopyRestore));
6173 break;
6174
6175 case SK_ProduceObjCObject:
6176 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00006177 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00006178 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00006179 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006180
6181 case SK_StdInitializerList: {
Richard Smithcc1b96d2013-06-12 22:31:48 +00006182 S.Diag(CurInit.get()->getExprLoc(),
6183 diag::warn_cxx98_compat_initializer_list_init)
6184 << CurInit.get()->getSourceRange();
Sebastian Redl249dee52012-03-05 19:35:43 +00006185
Richard Smithcc1b96d2013-06-12 22:31:48 +00006186 // Maybe lifetime-extend the array temporary's subobjects to match the
6187 // entity's lifetime.
6188 const ValueDecl *ExtendingDecl =
6189 getDeclForTemporaryLifetimeExtension(Entity);
6190 if (ExtendingDecl) {
6191 performLifetimeExtension(CurInit.get(), ExtendingDecl);
6192 warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
Sebastian Redl249dee52012-03-05 19:35:43 +00006193 }
6194
Richard Smithcc1b96d2013-06-12 22:31:48 +00006195 // Materialize the temporary into memory.
6196 MaterializeTemporaryExpr *MTE = new (S.Context)
6197 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6198 /*lvalue reference*/ false, ExtendingDecl);
6199
6200 // Wrap it in a construction of a std::initializer_list<T>.
6201 CurInit = S.Owned(
6202 new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6203
6204 // Bind the result, in case the library has given initializer_list a
6205 // non-trivial destructor.
6206 if (shouldBindAsTemporary(Entity))
6207 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redlc1839b12012-01-17 22:49:42 +00006208 break;
6209 }
Richard Smithcc1b96d2013-06-12 22:31:48 +00006210
Guy Benyei61054192013-02-07 10:55:47 +00006211 case SK_OCLSamplerInit: {
6212 assert(Step->Type->isSamplerT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006213 "Sampler initialization on non-sampler type.");
Guy Benyei61054192013-02-07 10:55:47 +00006214
6215 QualType SourceType = CurInit.get()->getType();
Guy Benyei61054192013-02-07 10:55:47 +00006216
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006217 if (Entity.isParameterKind()) {
Guy Benyei61054192013-02-07 10:55:47 +00006218 if (!SourceType->isSamplerT())
6219 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6220 << SourceType;
Fariborz Jahanian131996b2013-07-31 18:21:45 +00006221 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei61054192013-02-07 10:55:47 +00006222 llvm_unreachable("Invalid EntityKind!");
6223 }
6224
6225 break;
6226 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006227 case SK_OCLZeroEvent: {
6228 assert(Step->Type->isEventT() &&
Alp Tokerd4733632013-12-05 04:47:09 +00006229 "Event initialization on non-event type.");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006230
6231 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6232 CK_ZeroToOCLEvent,
6233 CurInit.get()->getValueKind());
6234 break;
6235 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006236 }
6237 }
John McCall1f425642010-11-11 03:21:53 +00006238
6239 // Diagnose non-fatal problems with the completed initialization.
6240 if (Entity.getKind() == InitializedEntity::EK_Member &&
6241 cast<FieldDecl>(Entity.getDecl())->isBitField())
6242 S.CheckBitFieldInitialization(Kind.getLocation(),
6243 cast<FieldDecl>(Entity.getDecl()),
6244 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006245
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006246 return CurInit;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006247}
6248
Richard Smith593f9932012-12-08 02:01:17 +00006249/// Somewhere within T there is an uninitialized reference subobject.
6250/// Dig it out and diagnose it.
Benjamin Kramer3e350262013-02-15 12:30:38 +00006251static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6252 QualType T) {
Richard Smith593f9932012-12-08 02:01:17 +00006253 if (T->isReferenceType()) {
6254 S.Diag(Loc, diag::err_reference_without_init)
6255 << T.getNonReferenceType();
6256 return true;
6257 }
6258
6259 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6260 if (!RD || !RD->hasUninitializedReferenceMember())
6261 return false;
6262
6263 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6264 FE = RD->field_end(); FI != FE; ++FI) {
6265 if (FI->isUnnamedBitfield())
6266 continue;
6267
6268 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6269 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6270 return true;
6271 }
6272 }
6273
6274 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6275 BE = RD->bases_end();
6276 BI != BE; ++BI) {
6277 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6278 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6279 return true;
6280 }
6281 }
6282
6283 return false;
6284}
6285
6286
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006287//===----------------------------------------------------------------------===//
6288// Diagnose initialization failures
6289//===----------------------------------------------------------------------===//
John McCall5ec7e7d2013-03-19 07:04:25 +00006290
6291/// Emit notes associated with an initialization that failed due to a
6292/// "simple" conversion failure.
6293static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6294 Expr *op) {
6295 QualType destType = entity.getType();
6296 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6297 op->getType()->isObjCObjectPointerType()) {
6298
6299 // Emit a possible note about the conversion failing because the
6300 // operand is a message send with a related result type.
6301 S.EmitRelatedResultTypeNote(op);
6302
6303 // Emit a possible note about a return failing because we're
6304 // expecting a related result type.
6305 if (entity.getKind() == InitializedEntity::EK_Result)
6306 S.EmitRelatedResultTypeNoteForReturn(destType);
6307 }
6308}
6309
Richard Smith0449aaf2013-11-21 23:30:57 +00006310static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6311 InitListExpr *InitList) {
6312 QualType DestType = Entity.getType();
6313
6314 QualType E;
6315 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6316 QualType ArrayType = S.Context.getConstantArrayType(
6317 E.withConst(),
6318 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6319 InitList->getNumInits()),
6320 clang::ArrayType::Normal, 0);
6321 InitializedEntity HiddenArray =
6322 InitializedEntity::InitializeTemporary(ArrayType);
6323 return diagnoseListInit(S, HiddenArray, InitList);
6324 }
6325
6326 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6327 /*VerifyOnly=*/false);
6328 assert(DiagnoseInitList.HadError() &&
6329 "Inconsistent init list check result.");
6330}
6331
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006332bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006333 const InitializedEntity &Entity,
6334 const InitializationKind &Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006335 ArrayRef<Expr *> Args) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00006336 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006337 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006338
Douglas Gregor1b303932009-12-22 15:35:07 +00006339 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006340 switch (Failure) {
6341 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006342 // FIXME: Customize for the initialized entity?
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006343 if (Args.empty()) {
Richard Smith593f9932012-12-08 02:01:17 +00006344 // Dig out the reference subobject which is uninitialized and diagnose it.
6345 // If this is value-initialization, this could be nested some way within
6346 // the target type.
6347 assert(Kind.getKind() == InitializationKind::IK_Value ||
6348 DestType->isReferenceType());
6349 bool Diagnosed =
6350 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6351 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6352 (void)Diagnosed;
6353 } else // FIXME: diagnostic below could be better!
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006354 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006355 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006356 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006358 case FK_ArrayNeedsInitList:
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006359 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006360 break;
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006361 case FK_ArrayNeedsInitListOrStringLiteral:
6362 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6363 break;
6364 case FK_ArrayNeedsInitListOrWideStringLiteral:
6365 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6366 break;
6367 case FK_NarrowStringIntoWideCharArray:
6368 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6369 break;
6370 case FK_WideStringIntoCharArray:
6371 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6372 break;
6373 case FK_IncompatWideStringIntoWideChar:
6374 S.Diag(Kind.getLocation(),
6375 diag::err_array_init_incompat_wide_string_into_wchar);
6376 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006377 case FK_ArrayTypeMismatch:
6378 case FK_NonConstantArrayInit:
Richard Smith0449aaf2013-11-21 23:30:57 +00006379 S.Diag(Kind.getLocation(),
Douglas Gregore2f943b2011-02-22 18:29:51 +00006380 (Failure == FK_ArrayTypeMismatch
6381 ? diag::err_array_init_different_type
6382 : diag::err_array_init_non_constant_array))
6383 << DestType.getNonReferenceType()
6384 << Args[0]->getType()
6385 << Args[0]->getSourceRange();
6386 break;
6387
John McCalla59dc2f2012-01-05 00:13:19 +00006388 case FK_VariableLengthArrayHasInitializer:
6389 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6390 << Args[0]->getSourceRange();
6391 break;
6392
John McCall16df1e52010-03-30 21:47:33 +00006393 case FK_AddressOfOverloadFailed: {
6394 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006395 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006396 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00006397 true,
6398 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006399 break;
John McCall16df1e52010-03-30 21:47:33 +00006400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006402 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00006403 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006404 switch (FailedOverloadResult) {
6405 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00006406 if (Failure == FK_UserConversionOverloadFailed)
6407 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6408 << Args[0]->getType() << DestType
6409 << Args[0]->getSourceRange();
6410 else
6411 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6412 << DestType << Args[0]->getType()
6413 << Args[0]->getSourceRange();
6414
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006415 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006416 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006417
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006418 case OR_No_Viable_Function:
Larisse Voufo70bb43a2013-06-27 03:36:30 +00006419 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00006420 DestType.getNonReferenceType(),
6421 diag::err_typecheck_nonviable_condition_incomplete,
6422 Args[0]->getType(), Args[0]->getSourceRange()))
6423 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6424 << Args[0]->getType() << Args[0]->getSourceRange()
6425 << DestType.getNonReferenceType();
6426
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006427 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006428 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006429
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006430 case OR_Deleted: {
6431 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6432 << Args[0]->getType() << DestType.getNonReferenceType()
6433 << Args[0]->getSourceRange();
6434 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006435 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00006436 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6437 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006438 if (Ovl == OR_Deleted) {
Richard Smith852265f2012-03-30 20:53:28 +00006439 S.NoteDeletedFunction(Best->Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006440 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006441 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006442 }
6443 break;
6444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006446 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00006447 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006448 }
6449 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006450
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006451 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl29526f02011-11-27 16:50:07 +00006452 if (isa<InitListExpr>(Args[0])) {
6453 S.Diag(Kind.getLocation(),
6454 diag::err_lvalue_reference_bind_to_initlist)
6455 << DestType.getNonReferenceType().isVolatileQualified()
6456 << DestType.getNonReferenceType()
6457 << Args[0]->getSourceRange();
6458 break;
6459 }
6460 // Intentional fallthrough
6461
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006462 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006463 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006464 Failure == FK_NonConstLValueReferenceBindingToTemporary
6465 ? diag::err_lvalue_reference_bind_to_temporary
6466 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00006467 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006468 << DestType.getNonReferenceType()
6469 << Args[0]->getType()
6470 << Args[0]->getSourceRange();
6471 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006473 case FK_RValueReferenceBindingToLValue:
6474 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00006475 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006476 << Args[0]->getSourceRange();
6477 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006478
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006479 case FK_ReferenceInitDropsQualifiers:
6480 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6481 << DestType.getNonReferenceType()
6482 << Args[0]->getType()
6483 << Args[0]->getSourceRange();
6484 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006485
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006486 case FK_ReferenceInitFailed:
6487 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6488 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00006489 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006490 << Args[0]->getType()
6491 << Args[0]->getSourceRange();
John McCall5ec7e7d2013-03-19 07:04:25 +00006492 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006493 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006494
Douglas Gregorb491ed32011-02-19 21:32:49 +00006495 case FK_ConversionFailed: {
6496 QualType FromType = Args[0]->getType();
Richard Trieucaff2472011-11-23 22:32:32 +00006497 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregore1314a62009-12-18 05:02:21 +00006498 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006499 << DestType
John McCall086a4642010-11-24 05:12:34 +00006500 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00006501 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006502 << Args[0]->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00006503 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6504 S.Diag(Kind.getLocation(), PDiag);
John McCall5ec7e7d2013-03-19 07:04:25 +00006505 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00006506 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00006507 }
John Wiegley01296292011-04-08 18:41:53 +00006508
6509 case FK_ConversionFromPropertyFailed:
6510 // No-op. This error has already been reported.
6511 break;
6512
Douglas Gregor51e77d52009-12-10 17:56:55 +00006513 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00006514 SourceRange R;
6515
6516 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00006517 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00006518 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519 else
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006520 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00006521
Douglas Gregor8ec51732010-09-08 21:40:08 +00006522 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6523 if (Kind.isCStyleOrFunctionalCast())
6524 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6525 << R;
6526 else
6527 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6528 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00006529 break;
6530 }
6531
6532 case FK_ReferenceBindingToInitList:
6533 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6534 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6535 break;
6536
6537 case FK_InitListBadDestinationType:
6538 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6539 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6540 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006541
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006542 case FK_ListConstructorOverloadFailed:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006543 case FK_ConstructorOverloadFailed: {
6544 SourceRange ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006545 if (Args.size())
6546 ArgsRange = SourceRange(Args.front()->getLocStart(),
6547 Args.back()->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006549 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006550 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006551 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006552 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl6901c0d2011-12-22 18:58:38 +00006553 }
6554
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006555 // FIXME: Using "DestType" for the entity we're printing is probably
6556 // bad.
6557 switch (FailedOverloadResult) {
6558 case OR_Ambiguous:
6559 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6560 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006561 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006563
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006564 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006565 if (Kind.getKind() == InitializationKind::IK_Default &&
6566 (Entity.getKind() == InitializedEntity::EK_Base ||
6567 Entity.getKind() == InitializedEntity::EK_Member) &&
6568 isa<CXXConstructorDecl>(S.CurContext)) {
6569 // This is implicit default initialization of a member or
6570 // base within a constructor. If no viable function was
6571 // found, notify the user that she needs to explicitly
6572 // initialize this base/member.
6573 CXXConstructorDecl *Constructor
6574 = cast<CXXConstructorDecl>(S.CurContext);
6575 if (Entity.getKind() == InitializedEntity::EK_Base) {
6576 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006577 << (Constructor->getInheritedConstructor() ? 2 :
6578 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006579 << S.Context.getTypeDeclType(Constructor->getParent())
6580 << /*base=*/0
6581 << Entity.getType();
6582
6583 RecordDecl *BaseDecl
6584 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6585 ->getDecl();
6586 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6587 << S.Context.getTagDeclType(BaseDecl);
6588 } else {
6589 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006590 << (Constructor->getInheritedConstructor() ? 2 :
6591 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006592 << S.Context.getTypeDeclType(Constructor->getParent())
6593 << /*member=*/1
6594 << Entity.getName();
6595 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6596
6597 if (const RecordType *Record
6598 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006600 diag::note_previous_decl)
6601 << S.Context.getTagDeclType(Record->getDecl());
6602 }
6603 break;
6604 }
6605
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006606 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6607 << DestType << ArgsRange;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00006608 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006611 case OR_Deleted: {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006612 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006613 OverloadingResult Ovl
6614 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor74f7d502012-02-15 19:33:52 +00006615 if (Ovl != OR_Deleted) {
6616 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6617 << true << DestType << ArgsRange;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006618 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor74f7d502012-02-15 19:33:52 +00006619 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006620 }
Douglas Gregor74f7d502012-02-15 19:33:52 +00006621
6622 // If this is a defaulted or implicitly-declared function, then
6623 // it was implicitly deleted. Make it clear that the deletion was
6624 // implicit.
Richard Smith852265f2012-03-30 20:53:28 +00006625 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006626 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith852265f2012-03-30 20:53:28 +00006627 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregor74f7d502012-02-15 19:33:52 +00006628 << DestType << ArgsRange;
Richard Smith852265f2012-03-30 20:53:28 +00006629 else
6630 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6631 << true << DestType << ArgsRange;
6632
6633 S.NoteDeletedFunction(Best->Function);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006634 break;
6635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006637 case OR_Success:
6638 llvm_unreachable("Conversion did not fail!");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006639 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00006640 }
David Blaikie60deeee2012-01-17 08:24:58 +00006641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006642
Douglas Gregor85dabae2009-12-16 01:38:02 +00006643 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006644 if (Entity.getKind() == InitializedEntity::EK_Member &&
6645 isa<CXXConstructorDecl>(S.CurContext)) {
6646 // This is implicit default-initialization of a const member in
6647 // a constructor. Complain that it needs to be explicitly
6648 // initialized.
6649 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6650 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smithc2bc61b2013-03-18 21:12:30 +00006651 << (Constructor->getInheritedConstructor() ? 2 :
6652 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006653 << S.Context.getTypeDeclType(Constructor->getParent())
6654 << /*const=*/1
6655 << Entity.getName();
6656 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6657 << Entity.getName();
6658 } else {
6659 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6660 << DestType << (bool)DestType->getAs<RecordType>();
6661 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00006662 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006663
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006664 case FK_Incomplete:
Douglas Gregor85f34232012-04-10 20:43:46 +00006665 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006666 diag::err_init_incomplete_type);
6667 break;
6668
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006669 case FK_ListInitializationFailed: {
6670 // Run the init list checker again to emit diagnostics.
Richard Smith0449aaf2013-11-21 23:30:57 +00006671 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6672 diagnoseListInit(S, Entity, InitList);
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006673 break;
6674 }
John McCall4124c492011-10-17 18:40:02 +00006675
6676 case FK_PlaceholderType: {
6677 // FIXME: Already diagnosed!
6678 break;
6679 }
Sebastian Redlc1839b12012-01-17 22:49:42 +00006680
Sebastian Redl048a6d72012-04-01 19:54:59 +00006681 case FK_ExplicitConstructor: {
6682 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6683 << Args[0]->getSourceRange();
6684 OverloadCandidateSet::iterator Best;
6685 OverloadingResult Ovl
6686 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gay5dcce092012-04-02 19:05:35 +00006687 (void)Ovl;
Sebastian Redl048a6d72012-04-01 19:54:59 +00006688 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6689 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6690 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6691 break;
6692 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
Douglas Gregor4f4946a2010-04-22 00:20:18 +00006695 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006696 return true;
6697}
Douglas Gregore1314a62009-12-18 05:02:21 +00006698
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006699void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006700 switch (SequenceKind) {
6701 case FailedSequence: {
6702 OS << "Failed sequence: ";
6703 switch (Failure) {
6704 case FK_TooManyInitsForReference:
6705 OS << "too many initializers for reference";
6706 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006708 case FK_ArrayNeedsInitList:
6709 OS << "array requires initializer list";
6710 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006711
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006712 case FK_ArrayNeedsInitListOrStringLiteral:
6713 OS << "array requires initializer list or string literal";
6714 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715
Hans Wennborg8f62c5c2013-05-15 11:03:04 +00006716 case FK_ArrayNeedsInitListOrWideStringLiteral:
6717 OS << "array requires initializer list or wide string literal";
6718 break;
6719
6720 case FK_NarrowStringIntoWideCharArray:
6721 OS << "narrow string into wide char array";
6722 break;
6723
6724 case FK_WideStringIntoCharArray:
6725 OS << "wide string into char array";
6726 break;
6727
6728 case FK_IncompatWideStringIntoWideChar:
6729 OS << "incompatible wide string into wide char array";
6730 break;
6731
Douglas Gregore2f943b2011-02-22 18:29:51 +00006732 case FK_ArrayTypeMismatch:
6733 OS << "array type mismatch";
6734 break;
6735
6736 case FK_NonConstantArrayInit:
6737 OS << "non-constant array initializer";
6738 break;
6739
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006740 case FK_AddressOfOverloadFailed:
6741 OS << "address of overloaded function failed";
6742 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006744 case FK_ReferenceInitOverloadFailed:
6745 OS << "overload resolution for reference initialization failed";
6746 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006748 case FK_NonConstLValueReferenceBindingToTemporary:
6749 OS << "non-const lvalue reference bound to temporary";
6750 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006752 case FK_NonConstLValueReferenceBindingToUnrelated:
6753 OS << "non-const lvalue reference bound to unrelated type";
6754 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006756 case FK_RValueReferenceBindingToLValue:
6757 OS << "rvalue reference bound to an lvalue";
6758 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006759
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006760 case FK_ReferenceInitDropsQualifiers:
6761 OS << "reference initialization drops qualifiers";
6762 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006764 case FK_ReferenceInitFailed:
6765 OS << "reference initialization failed";
6766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006767
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006768 case FK_ConversionFailed:
6769 OS << "conversion failed";
6770 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006771
John Wiegley01296292011-04-08 18:41:53 +00006772 case FK_ConversionFromPropertyFailed:
6773 OS << "conversion from property failed";
6774 break;
6775
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006776 case FK_TooManyInitsForScalar:
6777 OS << "too many initializers for scalar";
6778 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006779
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006780 case FK_ReferenceBindingToInitList:
6781 OS << "referencing binding to initializer list";
6782 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006783
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006784 case FK_InitListBadDestinationType:
6785 OS << "initializer list for non-aggregate, non-scalar type";
6786 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006787
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006788 case FK_UserConversionOverloadFailed:
6789 OS << "overloading failed for user-defined conversion";
6790 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006791
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006792 case FK_ConstructorOverloadFailed:
6793 OS << "constructor overloading failed";
6794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006796 case FK_DefaultInitOfConst:
6797 OS << "default initialization of a const variable";
6798 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006799
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00006800 case FK_Incomplete:
6801 OS << "initialization of incomplete type";
6802 break;
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006803
6804 case FK_ListInitializationFailed:
Sebastian Redlb49c46c2011-09-24 17:48:00 +00006805 OS << "list initialization checker failure";
John McCall4124c492011-10-17 18:40:02 +00006806 break;
6807
John McCalla59dc2f2012-01-05 00:13:19 +00006808 case FK_VariableLengthArrayHasInitializer:
6809 OS << "variable length array has an initializer";
6810 break;
6811
John McCall4124c492011-10-17 18:40:02 +00006812 case FK_PlaceholderType:
6813 OS << "initializer expression isn't contextually valid";
6814 break;
Nick Lewycky097f47c2011-12-22 20:21:32 +00006815
6816 case FK_ListConstructorOverloadFailed:
6817 OS << "list constructor overloading failed";
6818 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006819
Sebastian Redl048a6d72012-04-01 19:54:59 +00006820 case FK_ExplicitConstructor:
6821 OS << "list copy initialization chose explicit constructor";
6822 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006823 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006824 OS << '\n';
6825 return;
6826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006827
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006828 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00006829 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006830 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831
Sebastian Redld201edf2011-06-05 13:59:11 +00006832 case NormalSequence:
6833 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006834 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006837 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6838 if (S != step_begin()) {
6839 OS << " -> ";
6840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006841
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006842 switch (S->Kind) {
6843 case SK_ResolveAddressOfOverloadedFunction:
6844 OS << "resolve address of overloaded function";
6845 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006846
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006847 case SK_CastDerivedToBaseRValue:
6848 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6849 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006850
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006851 case SK_CastDerivedToBaseXValue:
6852 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6853 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006854
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006855 case SK_CastDerivedToBaseLValue:
6856 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6857 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006859 case SK_BindReference:
6860 OS << "bind reference to lvalue";
6861 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006863 case SK_BindReferenceToTemporary:
6864 OS << "bind reference to a temporary";
6865 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006866
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00006867 case SK_ExtraneousCopyToTemporary:
6868 OS << "extraneous C++03 copy to temporary";
6869 break;
6870
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006871 case SK_UserConversion:
Benjamin Kramerb89514a2011-10-14 18:45:37 +00006872 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006873 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006874
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006875 case SK_QualificationConversionRValue:
6876 OS << "qualification conversion (rvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006877 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006878
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006879 case SK_QualificationConversionXValue:
6880 OS << "qualification conversion (xvalue)";
Sebastian Redl29526f02011-11-27 16:50:07 +00006881 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00006882
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006883 case SK_QualificationConversionLValue:
6884 OS << "qualification conversion (lvalue)";
6885 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886
Jordan Roseb1312a52013-04-11 00:58:58 +00006887 case SK_LValueToRValue:
6888 OS << "load (lvalue to rvalue)";
6889 break;
6890
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006891 case SK_ConversionSequence:
6892 OS << "implicit conversion sequence (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006893 S->ICS->dump(); // FIXME: use OS
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006894 OS << ")";
6895 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006896
Richard Smithaaa0ec42013-09-21 21:19:19 +00006897 case SK_ConversionSequenceNoNarrowing:
6898 OS << "implicit conversion sequence with narrowing prohibited (";
Douglas Gregor9f2ed472013-11-08 02:16:10 +00006899 S->ICS->dump(); // FIXME: use OS
Richard Smithaaa0ec42013-09-21 21:19:19 +00006900 OS << ")";
6901 break;
6902
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006903 case SK_ListInitialization:
Sebastian Redl7de1fb42011-09-24 17:47:52 +00006904 OS << "list aggregate initialization";
6905 break;
6906
6907 case SK_ListConstructorCall:
6908 OS << "list initialization via constructor";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006909 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006910
Sebastian Redl29526f02011-11-27 16:50:07 +00006911 case SK_UnwrapInitList:
6912 OS << "unwrap reference initializer list";
6913 break;
6914
6915 case SK_RewrapInitList:
6916 OS << "rewrap reference initializer list";
6917 break;
6918
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006919 case SK_ConstructorInitialization:
6920 OS << "constructor initialization";
6921 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006922
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006923 case SK_ZeroInitialization:
6924 OS << "zero initialization";
6925 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006926
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006927 case SK_CAssignment:
6928 OS << "C assignment";
6929 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006930
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006931 case SK_StringInit:
6932 OS << "string initialization";
6933 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006934
6935 case SK_ObjCObjectConversion:
6936 OS << "Objective-C object conversion";
6937 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00006938
6939 case SK_ArrayInit:
6940 OS << "array initialization";
6941 break;
John McCall31168b02011-06-15 23:02:42 +00006942
Richard Smithebeed412012-02-15 22:38:09 +00006943 case SK_ParenthesizedArrayInit:
6944 OS << "parenthesized array initialization";
6945 break;
6946
John McCall31168b02011-06-15 23:02:42 +00006947 case SK_PassByIndirectCopyRestore:
6948 OS << "pass by indirect copy and restore";
6949 break;
6950
6951 case SK_PassByIndirectRestore:
6952 OS << "pass by indirect restore";
6953 break;
6954
6955 case SK_ProduceObjCObject:
6956 OS << "Objective-C object retension";
6957 break;
Sebastian Redlc1839b12012-01-17 22:49:42 +00006958
6959 case SK_StdInitializerList:
6960 OS << "std::initializer_list from initializer list";
6961 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006962
Guy Benyei61054192013-02-07 10:55:47 +00006963 case SK_OCLSamplerInit:
6964 OS << "OpenCL sampler_t from integer constant";
6965 break;
6966
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006967 case SK_OCLZeroEvent:
6968 OS << "OpenCL event_t from zero";
6969 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006970 }
Richard Smith6b216962013-02-05 05:52:24 +00006971
6972 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006973 }
Richard Smith6b216962013-02-05 05:52:24 +00006974
6975 OS << '\n';
Douglas Gregor65eb86e2010-01-29 19:14:02 +00006976}
6977
6978void InitializationSequence::dump() const {
6979 dump(llvm::errs());
6980}
6981
Richard Smithaaa0ec42013-09-21 21:19:19 +00006982static void DiagnoseNarrowingInInitList(Sema &S,
6983 const ImplicitConversionSequence &ICS,
6984 QualType PreNarrowingType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006985 QualType EntityType,
Richard Smith66e05fe2012-01-18 05:21:49 +00006986 const Expr *PostInit) {
Richard Smith66e05fe2012-01-18 05:21:49 +00006987 const StandardConversionSequence *SCS = 0;
6988 switch (ICS.getKind()) {
6989 case ImplicitConversionSequence::StandardConversion:
6990 SCS = &ICS.Standard;
6991 break;
6992 case ImplicitConversionSequence::UserDefinedConversion:
6993 SCS = &ICS.UserDefined.After;
6994 break;
6995 case ImplicitConversionSequence::AmbiguousConversion:
6996 case ImplicitConversionSequence::EllipsisConversion:
6997 case ImplicitConversionSequence::BadConversion:
6998 return;
6999 }
7000
Richard Smith66e05fe2012-01-18 05:21:49 +00007001 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7002 APValue ConstantValue;
Richard Smith5614ca72012-03-23 23:55:39 +00007003 QualType ConstantType;
7004 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7005 ConstantType)) {
Richard Smith66e05fe2012-01-18 05:21:49 +00007006 case NK_Not_Narrowing:
7007 // No narrowing occurred.
7008 return;
7009
7010 case NK_Type_Narrowing:
7011 // This was a floating-to-integer conversion, which is always considered a
7012 // narrowing conversion even if the value is a constant and can be
7013 // represented exactly as an integer.
7014 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007015 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7016 ? diag::warn_init_list_type_narrowing
7017 : diag::ext_init_list_type_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007018 << PostInit->getSourceRange()
7019 << PreNarrowingType.getLocalUnqualifiedType()
7020 << EntityType.getLocalUnqualifiedType();
7021 break;
7022
7023 case NK_Constant_Narrowing:
7024 // A constant value was narrowed.
7025 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007026 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7027 ? diag::warn_init_list_constant_narrowing
7028 : diag::ext_init_list_constant_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007029 << PostInit->getSourceRange()
Richard Smith5614ca72012-03-23 23:55:39 +00007030 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007031 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007032 break;
7033
7034 case NK_Variable_Narrowing:
7035 // A variable's value may have been narrowed.
7036 S.Diag(PostInit->getLocStart(),
Richard Smith16e1b072013-11-12 02:41:45 +00007037 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7038 ? diag::warn_init_list_variable_narrowing
7039 : diag::ext_init_list_variable_narrowing)
Richard Smith66e05fe2012-01-18 05:21:49 +00007040 << PostInit->getSourceRange()
7041 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00007042 << EntityType.getLocalUnqualifiedType();
Richard Smith66e05fe2012-01-18 05:21:49 +00007043 break;
7044 }
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007045
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007046 SmallString<128> StaticCast;
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007047 llvm::raw_svector_ostream OS(StaticCast);
7048 OS << "static_cast<";
7049 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7050 // It's important to use the typedef's name if there is one so that the
7051 // fixit doesn't break code using types like int64_t.
7052 //
7053 // FIXME: This will break if the typedef requires qualification. But
7054 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb89514a2011-10-14 18:45:37 +00007055 OS << *TT->getDecl();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007056 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikiebbafb8a2012-03-11 07:00:24 +00007057 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007058 else {
7059 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7060 // with a broken cast.
7061 return;
7062 }
7063 OS << ">(";
Richard Smith66e05fe2012-01-18 05:21:49 +00007064 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
7065 << PostInit->getSourceRange()
7066 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007067 << FixItHint::CreateInsertion(
Richard Smith66e05fe2012-01-18 05:21:49 +00007068 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007069}
7070
Douglas Gregore1314a62009-12-18 05:02:21 +00007071//===----------------------------------------------------------------------===//
7072// Initialization helper functions
7073//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00007074bool
7075Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7076 ExprResult Init) {
7077 if (Init.isInvalid())
7078 return false;
7079
7080 Expr *InitE = Init.get();
7081 assert(InitE && "No initialization expression");
7082
Douglas Gregorf4cc61d2012-07-31 22:15:04 +00007083 InitializationKind Kind
7084 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007085 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00007086 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00007087}
7088
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007089ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00007090Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7091 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007092 ExprResult Init,
Douglas Gregor6073dca2012-02-24 23:56:31 +00007093 bool TopLevelOfInitList,
7094 bool AllowExplicit) {
Douglas Gregore1314a62009-12-18 05:02:21 +00007095 if (Init.isInvalid())
7096 return ExprError();
7097
John McCall1f425642010-11-11 03:21:53 +00007098 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00007099 assert(InitE && "No initialization expression?");
7100
7101 if (EqualLoc.isInvalid())
7102 EqualLoc = InitE->getLocStart();
7103
7104 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00007105 EqualLoc,
7106 AllowExplicit);
Richard Smithaaa0ec42013-09-21 21:19:19 +00007107 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
Douglas Gregore1314a62009-12-18 05:02:21 +00007108 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00007109
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00007110 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith66e05fe2012-01-18 05:21:49 +00007111
Richard Smith66e05fe2012-01-18 05:21:49 +00007112 return Result;
Douglas Gregore1314a62009-12-18 05:02:21 +00007113}