blob: 5319f404f395549fb54cfdb0c8d5b4a562e160d6 [file] [log] [blame]
Steve Naroff0cca7492008-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 Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Initialization.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000015#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000017#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth55fc8732012-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 Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
Hans Wennborg0ff50742013-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 Friedman8718a6a2009-05-29 18:22:49 +000061 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
Hans Wennborg0ff50742013-05-15 11:03:04 +000062 return SIF_Other;
Eli Friedman8718a6a2009-05-29 18:22:49 +000063
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner8879e3b2009-02-26 23:26:43 +000067 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
Hans Wennborg0ff50742013-05-15 11:03:04 +000069 return SIF_None;
Chris Lattner8879e3b2009-02-26 23:26:43 +000070
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Hans Wennborg0ff50742013-05-15 11:03:04 +000073 if (SL == 0)
74 return SIF_Other;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000075
Hans Wennborg0ff50742013-05-15 11:03:04 +000076 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
Douglas Gregor5cee1192011-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 Wennborg0ff50742013-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 Gregor5cee1192011-07-27 05:40:30 +000094 case StringLiteral::UTF16:
Hans Wennborg0ff50742013-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 Gregor5cee1192011-07-27 05:40:30 +0000102 case StringLiteral::UTF32:
Hans Wennborg0ff50742013-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 Gregor5cee1192011-07-27 05:40:30 +0000110 case StringLiteral::Wide:
Hans Wennborg0ff50742013-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 Gregor5cee1192011-07-27 05:40:30 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Douglas Gregor5cee1192011-07-27 05:40:30 +0000120 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000121}
122
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
John McCallce6c9b72011-02-21 07:22:22 +0000125 const ArrayType *arrayType = Context.getAsArrayType(declType);
Hans Wennborg0ff50742013-05-15 11:03:04 +0000126 if (!arrayType)
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000127 return SIF_Other;
128 return IsStringInit(init, arrayType, Context);
John McCallce6c9b72011-02-21 07:22:22 +0000129}
130
Richard Smith30ae1ed2013-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 Smith27f9cf32013-05-06 00:35:47 +0000134 while (true) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000135 E->setType(Ty);
Richard Smith27f9cf32013-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 Smith30ae1ed2013-05-05 16:40:13 +0000146 }
Richard Smith30ae1ed2013-05-05 16:40:13 +0000147}
148
John McCallfef8b342011-02-21 07:57:55 +0000149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150 Sema &S) {
Chris Lattner79e079d2009-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 Stump1eb44332009-09-09 15:08:12 +0000155
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000156 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000157 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000158 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +0000159 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000160 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000161 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162 ConstVal,
163 ArrayType::Normal, 0);
Richard Smith30ae1ed2013-05-05 16:40:13 +0000164 updateStringLiteralType(Str, DeclT);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000165 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Eli Friedman8718a6a2009-05-29 18:22:49 +0000168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000170 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-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 Blaikie4e4d0842012-03-11 07:00:24 +0000173 if (S.getLangOpts().CPlusPlus) {
Richard Smith30ae1ed2013-05-05 16:40:13 +0000174 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
Anders Carlssonb8fc45f2011-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 Friedmanbc34b1d2011-04-11 00:23:45 +0000183 // [dcl.init.string]p2
184 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000185 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-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 Dunbar96a00142012-03-09 18:35:03 +0000191 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000192 diag::warn_initializer_string_for_char_array_too_long)
193 << Str->getSourceRange();
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Eli Friedman8718a6a2009-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 Smith30ae1ed2013-05-05 16:40:13 +0000200 updateStringLiteralType(Str, DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000201}
202
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
Douglas Gregor9e80f722009-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 Bagnara63e7d252011-01-27 19:55:10 +0000221/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-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 Lattner8b419b92009-02-24 22:48:58 +0000234namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000236 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000237 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000238 bool VerifyOnly; // no diagnostics, no structure building
Benjamin Kramera7894162012-02-23 14:48:40 +0000239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000242 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000243 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000245 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000246 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000247 InitListExpr *IList, QualType &T,
Richard Smithb9bf3122013-09-20 20:10:22 +0000248 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000249 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000250 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000251 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000252 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000253 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000257 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000258 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000259 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Eli Friedman0c706c22011-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 Carlsson8ff9e862010-01-23 23:23:01 +0000267 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000268 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000269 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000274 unsigned &Index,
275 InitListExpr *StructuredList,
276 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000277 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000278 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000281 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000282 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000283 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000284 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000286 unsigned &StructuredIndex,
287 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000288 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000289 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000290 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
293 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000294 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000295 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000296 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000297 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
300 unsigned &Index,
301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000303 bool FinishSubobjectInit,
304 bool TopLevelObject);
Douglas Gregorc34ee5e2009-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 Gregor9e80f722009-01-29 01:05:33 +0000310 void UpdateStructuredListElement(InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000312 Expr *expr);
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000315
Douglas Gregord6d37de2009-12-22 00:05:34 +0000316 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
317 const InitializedEntity &ParentEntity,
318 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000319 void FillInValueInitializations(const InitializedEntity &Entity,
320 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000321 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
322 Expr *InitExpr, FieldDecl *Field,
323 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000324 void CheckValueInitializable(const InitializedEntity &Entity);
325
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000326public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000327 InitListChecker(Sema &S, const InitializedEntity &Entity,
Richard Smith40cba902013-06-06 11:41:05 +0000328 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-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 Lattner8b419b92009-02-24 22:48:58 +0000335} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000336
Sebastian Redl3ff5c862011-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 Gribenko62ed8892013-05-05 20:40:26 +0000344 InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000345 if (InitSeq.Failed())
346 hadError = true;
347}
348
Douglas Gregord6d37de2009-12-22 00:05:34 +0000349void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
350 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000351 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000352 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000353 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000354 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000355 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000356 = InitializedEntity::InitializeMember(Field, &ParentEntity);
357 if (Init >= NumInits || !ILE->getInit(Init)) {
Richard Smithc3bf52c2013-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 Gregord6d37de2009-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 Takumidfbb02a2011-01-27 07:10:08 +0000389
Douglas Gregord6d37de2009-12-22 00:05:34 +0000390 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
391 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000392 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000393 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000394 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000395 hadError = true;
396 return;
397 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398
John McCall60d7b3a2010-08-24 06:29:42 +0000399 ExprResult MemberInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000400 = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000401 if (MemberInit.isInvalid()) {
402 hadError = true;
403 return;
404 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405
Douglas Gregord6d37de2009-12-22 00:05:34 +0000406 if (hadError) {
407 // Do nothing
408 } else if (Init < NumInits) {
409 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000410 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-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 Kremenek709210f2010-04-13 23:39:13 +0000415 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000416 RequiresSecondPass = true;
417 }
418 } else if (InitListExpr *InnerILE
419 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000420 FillInValueInitializations(MemberEntity, InnerILE,
421 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000422}
423
Douglas Gregor4c678342009-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 Takumidfbb02a2011-01-27 07:10:08 +0000427void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000428InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
429 InitListExpr *ILE,
430 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000431 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000432 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000433 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000434 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000435 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Ted Kremenek6217b802009-07-29 21:53:49 +0000437 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +0000438 const RecordDecl *RDecl = RType->getDecl();
439 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000440 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
441 Entity, ILE, RequiresSecondPass);
Richard Smithc3bf52c2013-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 Gregord6d37de2009-12-22 00:05:34 +0000453 unsigned Init = 0;
Richard Smithc3bf52c2013-04-20 22:23:05 +0000454 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
455 FieldEnd = RDecl->field_end();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000456 Field != FieldEnd; ++Field) {
457 if (Field->isUnnamedBitfield())
458 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000459
Douglas Gregord6d37de2009-12-22 00:05:34 +0000460 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000461 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000462
David Blaikie581deb32012-06-06 20:45:41 +0000463 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000464 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000465 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000466
Douglas Gregord6d37de2009-12-22 00:05:34 +0000467 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468
Douglas Gregord6d37de2009-12-22 00:05:34 +0000469 // Only look at the first initialization of a union.
Richard Smithc3bf52c2013-04-20 22:23:05 +0000470 if (RDecl->isUnion())
Douglas Gregord6d37de2009-12-22 00:05:34 +0000471 break;
472 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 }
474
475 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000476 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000477
478 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000480 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000481 unsigned NumInits = ILE->getNumInits();
482 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000483 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000485 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
486 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000487 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000488 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000489 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000490 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000492 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000493 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000494 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000496
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000497
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000499 if (hadError)
500 return;
501
Anders Carlssond3d824d2010-01-23 04:34:47 +0000502 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
503 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000504 ElementEntity.setElementIndex(Init);
505
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000506 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
507 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000508 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
509 true);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000510 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000511 if (!InitSeq) {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000512 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000513 hadError = true;
514 return;
515 }
516
John McCall60d7b3a2010-08-24 06:29:42 +0000517 ExprResult ElementInit
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000518 = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000519 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000520 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000521 return;
522 }
523
524 if (hadError) {
525 // Do nothing
526 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-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 Kyrtzidis4423ac02011-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 Redl7491c492011-06-05 13:59:11 +0000541 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-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 Gregorcb57fb92009-12-16 06:35:08 +0000549 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000550 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000551 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000552 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 }
554}
555
Chris Lattner68355a52009-01-29 05:10:57 +0000556
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000557InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000558 InitListExpr *IL, QualType &T,
Richard Smith40cba902013-06-06 11:41:05 +0000559 bool VerifyOnly)
560 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000561 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000562
Richard Smithb9bf3122013-09-20 20:10:22 +0000563 FullyStructuredList =
564 getStructuredSubobjectInit(IL, 0, T, 0, 0, IL->getSourceRange());
565 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000566 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000567
Sebastian Redl14b0c192011-09-24 17:48:00 +0000568 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000569 bool RequiresSecondPass = false;
570 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000571 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000573 RequiresSecondPass);
574 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000575}
576
577int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000578 // FIXME: use a proper constant
579 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000580 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000581 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-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 Kremenek6217b802009-07-29 21:53:49 +0000588 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000589 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000590 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000591 Field = structDecl->field_begin(),
592 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000593 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000594 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 ++InitializableMembers;
596 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000597 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000598 return std::min(InitializableMembers, 1);
599 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000600}
601
Richard Smithb9bf3122013-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 Carlsson8ff9e862010-01-23 23:23:01 +0000608void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000609 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000610 QualType T, unsigned &Index,
611 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000612 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000613 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Steve Naroff0cca7492008-05-01 22:18:59 +0000615 if (T->isArrayType())
616 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000617 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000618 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000619 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000620 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000621 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000622 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000623
Eli Friedman402256f2008-05-25 13:49:22 +0000624 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000625 if (!VerifyOnly)
626 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
627 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000628 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000629 hadError = true;
630 return;
631 }
632
Douglas Gregor4c678342009-01-28 21:54:33 +0000633 // Build a structured initializer list corresponding to this subobject.
634 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000635 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
636 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000637 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000638 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000640
Douglas Gregor4c678342009-01-28 21:54:33 +0000641 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000642 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000643 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000644 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000646 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000647
Richard Smith40cba902013-06-06 11:41:05 +0000648 if (!VerifyOnly) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000649 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000650
Sebastian Redlc2235182011-10-16 18:19:28 +0000651 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-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 Takumidfbb02a2011-01-27 07:10:08 +0000659
Sebastian Redlc2235182011-10-16 18:19:28 +0000660 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000661 if (T->isArrayType() || T->isRecordType()) {
662 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Richard Smith40cba902013-06-06 11:41:05 +0000663 diag::warn_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000664 << StructuredSubobjectInitList->getSourceRange()
665 << FixItHint::CreateInsertion(
666 StructuredSubobjectInitList->getLocStart(), "{")
667 << FixItHint::CreateInsertion(
668 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000670 "}");
671 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000672 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000673}
674
Richard Smithb9bf3122013-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 Carlsson8ff9e862010-01-23 23:23:01 +0000680void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000681 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000682 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000683 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000684 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000685 if (!VerifyOnly) {
686 SyntacticToSemantic[IList] = StructuredList;
687 StructuredList->setSyntacticForm(IList);
688 }
Richard Smithb9bf3122013-09-20 20:10:22 +0000689
690 unsigned Index = 0, StructuredIndex = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000692 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000693 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000694 QualType ExprTy = T;
695 if (!ExprTy->isArrayType())
696 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000697 IList->setType(ExprTy);
698 StructuredList->setType(ExprTy);
699 }
Eli Friedman638e1442008-05-25 13:22:35 +0000700 if (hadError)
701 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000702
Eli Friedman638e1442008-05-25 13:22:35 +0000703 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000704 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000705 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (SemaRef.getLangOpts().CPlusPlus ||
707 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000708 IList->getType()->isVectorType())) {
709 hadError = true;
710 }
711 return;
712 }
713
Eli Friedmane5408582009-05-29 20:20:05 +0000714 if (StructuredIndex == 1 &&
Hans Wennborgc1fb1e02013-05-16 09:22:40 +0000715 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
716 SIF_None) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000717 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000718 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000719 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000720 hadError = true;
721 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000722 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000723 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000724 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000725 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000726 // Don't complain for incomplete types, since we'll get an error
727 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000728 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000729 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000730 CurrentObjectType->isArrayType()? 0 :
731 CurrentObjectType->isVectorType()? 1 :
732 CurrentObjectType->isScalarType()? 2 :
733 CurrentObjectType->isUnionType()? 3 :
734 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000735
736 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000737 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000738 DK = diag::err_excess_initializers;
739 hadError = true;
740 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000741 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000742 DK = diag::err_excess_initializers;
743 hadError = true;
744 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000745
Chris Lattner08202542009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000747 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000748 }
749 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000750
Sebastian Redl14b0c192011-09-24 17:48:00 +0000751 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
752 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000753 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000754 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000755 << FixItHint::CreateRemoval(IList->getLocStart())
756 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000757}
758
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000759void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000760 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000761 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000762 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000763 unsigned &Index,
764 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000765 unsigned &StructuredIndex,
766 bool TopLevelObject) {
Eli Friedman0c706c22011-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 Carlsson46f46592010-01-23 19:55:29 +0000773 CheckScalarType(Entity, IList, DeclType, Index,
774 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000775 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000776 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000777 StructuredList, StructuredIndex);
Richard Smith20599392012-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 Naroff61353522008-08-10 16:05:48 +0000793 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
794 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000795 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000796 if (!VerifyOnly)
797 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
798 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000799 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000800 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000801 CheckReferenceType(Entity, IList, DeclType, Index,
802 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000803 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000804 if (!VerifyOnly)
805 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
806 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000807 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000808 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000809 if (!VerifyOnly)
810 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
811 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000812 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000813 }
814}
815
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000816void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000817 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000818 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000819 unsigned &Index,
820 InitListExpr *StructuredList,
821 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000822 Expr *expr = IList->getInit(Index);
Richard Smith6242a452013-05-31 02:56:17 +0000823
824 if (ElemType->isReferenceType())
825 return CheckReferenceType(Entity, IList, ElemType, Index,
826 StructuredList, StructuredIndex);
827
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000828 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000829 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
Richard Smithb9bf3122013-09-20 20:10:22 +0000830 InitListExpr *InnerStructuredList
Richard Smith20599392012-07-07 08:35:56 +0000831 = getStructuredSubobjectInit(IList, Index, ElemType,
832 StructuredList, StructuredIndex,
833 SubInitList->getSourceRange());
Richard Smithb9bf3122013-09-20 20:10:22 +0000834 CheckExplicitInitList(Entity, SubInitList, ElemType,
835 InnerStructuredList);
Richard Smith20599392012-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 Friedman48a2a3a2013-08-19 22:12:56 +0000845 // FIXME: Need to handle atomic aggregate types with implicit init lists.
846 if (ElemType->isScalarType() || ElemType->isAtomicType())
John McCallfef8b342011-02-21 07:57:55 +0000847 return CheckScalarType(Entity, IList, ElemType, Index,
848 StructuredList, StructuredIndex);
Anders Carlssond28b4282009-08-27 17:18:13 +0000849
Eli Friedman48a2a3a2013-08-19 22:12:56 +0000850 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
851 ElemType->isArrayType()) && "Unexpected type");
852
John McCallfef8b342011-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 Takumidfbb02a2011-01-27 07:10:08 +0000857
Hans Wennborg0ff50742013-05-15 11:03:04 +0000858 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000859 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +0000860 CheckStringInit(expr, ElemType, arrayType, SemaRef);
861 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Eli Friedman8a5d9292011-09-26 19:09:09 +0000862 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000863 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000864 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000865 }
John McCallfef8b342011-02-21 07:57:55 +0000866
867 // Fall through for subaggregate initialization.
868
David Blaikie4e4d0842012-03-11 07:00:24 +0000869 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000870 // C++ [dcl.init.aggr]p12:
871 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000872 // initializing the aggregate member with an initializer from
John McCallfef8b342011-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 Gribenko1f78a502013-05-03 15:05:50 +0000879 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
John McCallfef8b342011-02-21 07:57:55 +0000880
881 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000882 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000883 ExprResult Result =
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000884 Seq.Perform(SemaRef, Entity, Kind, expr);
Richard Smithb6f8d282011-12-20 04:00:21 +0000885 if (Result.isInvalid())
886 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000887
Sebastian Redl14b0c192011-09-24 17:48:00 +0000888 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000889 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000890 }
John McCallfef8b342011-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 Wiegley429bb272011-04-08 18:41:53 +0000905 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000906 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000907 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
908 !VerifyOnly)
Eli Friedman08f0bbc2013-09-17 04:07:04 +0000909 != Sema::Incompatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000910 if (ExprRes.isInvalid())
911 hadError = true;
912 else {
913 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000914 if (ExprRes.isInvalid())
915 hadError = true;
John Wiegley429bb272011-04-08 18:41:53 +0000916 }
917 UpdateStructuredListElement(StructuredList, StructuredIndex,
918 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000919 ++Index;
920 return;
921 }
John Wiegley429bb272011-04-08 18:41:53 +0000922 ExprRes.release();
John McCallfef8b342011-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 Blaikie4e4d0842012-03-11 07:00:24 +0000932 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000933 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000934 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
935 StructuredIndex);
936 ++StructuredIndex;
937 } else {
Sebastian Redl14b0c192011-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 McCallfef8b342011-02-21 07:57:55 +0000945 hadError = true;
946 ++Index;
947 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000948 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000949}
950
Eli Friedman0c706c22011-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 Blaikie4e4d0842012-03-11 07:00:24 +0000971 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-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 Carlsson8ff9e862010-01-23 23:23:01 +0000988void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000989 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000990 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000991 InitListExpr *StructuredList,
992 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000993 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000996 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith6b130222011-10-18 21:39:00 +0000997 diag::warn_cxx98_compat_empty_scalar_initializer :
998 diag::err_empty_scalar_initializer)
999 << IList->getSourceRange();
Richard Smith80ad52f2013-01-02 11:42:31 +00001000 hadError = !SemaRef.getLangOpts().CPlusPlus11;
Douglas Gregor4c678342009-01-28 21:54:33 +00001001 ++Index;
1002 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +00001003 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001004 }
John McCallb934c2d2010-11-11 00:46:36 +00001005
1006 Expr *expr = IList->getInit(Index);
1007 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001008 if (!VerifyOnly)
1009 SemaRef.Diag(SubIList->getLocStart(),
1010 diag::warn_many_braces_around_scalar_init)
1011 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001012
1013 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1014 StructuredIndex);
1015 return;
1016 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001017 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001018 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001019 diag::err_designator_for_scalar_init)
1020 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +00001021 hadError = true;
1022 ++Index;
1023 ++StructuredIndex;
1024 return;
1025 }
1026
Sebastian Redl14b0c192011-09-24 17:48:00 +00001027 if (VerifyOnly) {
1028 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1029 hadError = true;
1030 ++Index;
1031 return;
1032 }
1033
John McCallb934c2d2010-11-11 00:46:36 +00001034 ExprResult Result =
1035 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001036 SemaRef.Owned(expr),
1037 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +00001038
1039 Expr *ResultExpr = 0;
1040
1041 if (Result.isInvalid())
1042 hadError = true; // types weren't compatible.
1043 else {
1044 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001045
John McCallb934c2d2010-11-11 00:46:36 +00001046 if (ResultExpr != expr) {
1047 // The type was promoted, update initializer list.
1048 IList->setInit(Index, ResultExpr);
1049 }
1050 }
1051 if (hadError)
1052 ++StructuredIndex;
1053 else
1054 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1055 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001056}
1057
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001058void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1059 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +00001060 unsigned &Index,
1061 InitListExpr *StructuredList,
1062 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001063 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001064 // FIXME: It would be wonderful if we could point at the actual member. In
1065 // general, it would be useful to pass location information down the stack,
1066 // so that we know the location (or decl) of the "current object" being
1067 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001068 if (!VerifyOnly)
1069 SemaRef.Diag(IList->getLocStart(),
1070 diag::err_init_reference_member_uninitialized)
1071 << DeclType
1072 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001073 hadError = true;
1074 ++Index;
1075 ++StructuredIndex;
1076 return;
1077 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001078
1079 Expr *expr = IList->getInit(Index);
Richard Smith80ad52f2013-01-02 11:42:31 +00001080 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001081 if (!VerifyOnly)
1082 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1083 << DeclType << IList->getSourceRange();
1084 hadError = true;
1085 ++Index;
1086 ++StructuredIndex;
1087 return;
1088 }
1089
1090 if (VerifyOnly) {
1091 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1092 hadError = true;
1093 ++Index;
1094 return;
1095 }
1096
1097 ExprResult Result =
1098 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1099 SemaRef.Owned(expr),
1100 /*TopLevelOfInitList=*/true);
1101
1102 if (Result.isInvalid())
1103 hadError = true;
1104
1105 expr = Result.takeAs<Expr>();
1106 IList->setInit(Index, expr);
1107
1108 if (hadError)
1109 ++StructuredIndex;
1110 else
1111 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1112 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001113}
1114
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001115void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001116 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001117 unsigned &Index,
1118 InitListExpr *StructuredList,
1119 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001120 const VectorType *VT = DeclType->getAs<VectorType>();
1121 unsigned maxElements = VT->getNumElements();
1122 unsigned numEltsInit = 0;
1123 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001124
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001125 if (Index >= IList->getNumInits()) {
1126 // Make sure the element type can be value-initialized.
1127 if (VerifyOnly)
1128 CheckValueInitializable(
1129 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1130 return;
1131 }
1132
David Blaikie4e4d0842012-03-11 07:00:24 +00001133 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001134 // If the initializing element is a vector, try to copy-initialize
1135 // instead of breaking it apart (which is doomed to failure anyway).
1136 Expr *Init = IList->getInit(Index);
1137 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001138 if (VerifyOnly) {
1139 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1140 hadError = true;
1141 ++Index;
1142 return;
1143 }
1144
John McCall20e047a2010-10-30 00:11:39 +00001145 ExprResult Result =
1146 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001147 SemaRef.Owned(Init),
1148 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001149
1150 Expr *ResultExpr = 0;
1151 if (Result.isInvalid())
1152 hadError = true; // types weren't compatible.
1153 else {
1154 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155
John McCall20e047a2010-10-30 00:11:39 +00001156 if (ResultExpr != Init) {
1157 // The type was promoted, update initializer list.
1158 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001159 }
1160 }
John McCall20e047a2010-10-30 00:11:39 +00001161 if (hadError)
1162 ++StructuredIndex;
1163 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001164 UpdateStructuredListElement(StructuredList, StructuredIndex,
1165 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001166 ++Index;
1167 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
John McCall20e047a2010-10-30 00:11:39 +00001170 InitializedEntity ElementEntity =
1171 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001172
John McCall20e047a2010-10-30 00:11:39 +00001173 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1174 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001175 if (Index >= IList->getNumInits()) {
1176 if (VerifyOnly)
1177 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001178 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001179 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001180
John McCall20e047a2010-10-30 00:11:39 +00001181 ElementEntity.setElementIndex(Index);
1182 CheckSubElementType(ElementEntity, IList, elementType, Index,
1183 StructuredList, StructuredIndex);
1184 }
1185 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001186 }
John McCall20e047a2010-10-30 00:11:39 +00001187
1188 InitializedEntity ElementEntity =
1189 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190
John McCall20e047a2010-10-30 00:11:39 +00001191 // OpenCL initializers allows vectors to be constructed from vectors.
1192 for (unsigned i = 0; i < maxElements; ++i) {
1193 // Don't attempt to go past the end of the init list
1194 if (Index >= IList->getNumInits())
1195 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001196
John McCall20e047a2010-10-30 00:11:39 +00001197 ElementEntity.setElementIndex(Index);
1198
1199 QualType IType = IList->getInit(Index)->getType();
1200 if (!IType->isVectorType()) {
1201 CheckSubElementType(ElementEntity, IList, elementType, Index,
1202 StructuredList, StructuredIndex);
1203 ++numEltsInit;
1204 } else {
1205 QualType VecType;
1206 const VectorType *IVT = IType->getAs<VectorType>();
1207 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001208
John McCall20e047a2010-10-30 00:11:39 +00001209 if (IType->isExtVectorType())
1210 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1211 else
1212 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001213 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001214 CheckSubElementType(ElementEntity, IList, VecType, Index,
1215 StructuredList, StructuredIndex);
1216 numEltsInit += numIElts;
1217 }
1218 }
1219
1220 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001221 if (numEltsInit != maxElements) {
1222 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001223 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001224 diag::err_vector_incorrect_num_initializers)
1225 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1226 hadError = true;
1227 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001228}
1229
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001230void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001231 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001232 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001233 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001234 unsigned &Index,
1235 InitListExpr *StructuredList,
1236 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001237 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1238
Steve Naroff0cca7492008-05-01 22:18:59 +00001239 // Check for the special-case of initializing an array with a string.
1240 if (Index < IList->getNumInits()) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001241 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1242 SIF_None) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001243 // We place the string literal directly into the resulting
1244 // initializer list. This is the only place where the structure
1245 // of the structured initializer list doesn't match exactly,
1246 // because doing so would involve allocating one character
1247 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001248 if (!VerifyOnly) {
Hans Wennborg0ff50742013-05-15 11:03:04 +00001249 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1250 UpdateStructuredListElement(StructuredList, StructuredIndex,
1251 IList->getInit(Index));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001252 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1253 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001254 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001255 return;
1256 }
1257 }
John McCallce6c9b72011-02-21 07:22:22 +00001258 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001259 // Check for VLAs; in standard C it would be possible to check this
1260 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1261 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001262 if (!VerifyOnly)
1263 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1264 diag::err_variable_object_no_init)
1265 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001266 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001267 ++Index;
1268 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001269 return;
1270 }
1271
Douglas Gregor05c13a32009-01-22 00:58:24 +00001272 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001273 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1274 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001275 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001276 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001277 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001278 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001279 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001280 maxElementsKnown = true;
1281 }
1282
John McCallce6c9b72011-02-21 07:22:22 +00001283 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001284 while (Index < IList->getNumInits()) {
1285 Expr *Init = IList->getInit(Index);
1286 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001287 // If we're not the subobject that matches up with the '{' for
1288 // the designator, we shouldn't be handling the
1289 // designator. Return immediately.
1290 if (!SubobjectIsDesignatorContext)
1291 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001292
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001293 // Handle this designated initializer. elementIndex will be
1294 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001295 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001297 StructuredList, StructuredIndex, true,
1298 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001299 hadError = true;
1300 continue;
1301 }
1302
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001303 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001304 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001305 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001306 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001307 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001308
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001309 // If the array is of incomplete type, keep track of the number of
1310 // elements in the initializer.
1311 if (!maxElementsKnown && elementIndex > maxElements)
1312 maxElements = elementIndex;
1313
Douglas Gregor05c13a32009-01-22 00:58:24 +00001314 continue;
1315 }
1316
1317 // If we know the maximum number of elements, and we've already
1318 // hit it, stop consuming elements in the initializer list.
1319 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001320 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001321
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001322 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001323 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001324 Entity);
1325 // Check this element.
1326 CheckSubElementType(ElementEntity, IList, elementType, Index,
1327 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001328 ++elementIndex;
1329
1330 // If the array is of incomplete type, keep track of the number of
1331 // elements in the initializer.
1332 if (!maxElementsKnown && elementIndex > maxElements)
1333 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001334 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001335 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001336 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001337 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001338 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001339 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001340 // Sizing an array implicitly to zero is not allowed by ISO C,
1341 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001342 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001343 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001344 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001345
Mike Stump1eb44332009-09-09 15:08:12 +00001346 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001347 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001348 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001349 if (!hadError && VerifyOnly) {
1350 // Check if there are any members of the array that get value-initialized.
1351 // If so, check if doing that is possible.
1352 // FIXME: This needs to detect holes left by designated initializers too.
1353 if (maxElementsKnown && elementIndex < maxElements)
1354 CheckValueInitializable(InitializedEntity::InitializeElement(
1355 SemaRef.Context, 0, Entity));
1356 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001357}
1358
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001359bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1360 Expr *InitExpr,
1361 FieldDecl *Field,
1362 bool TopLevelObject) {
1363 // Handle GNU flexible array initializers.
1364 unsigned FlexArrayDiag;
1365 if (isa<InitListExpr>(InitExpr) &&
1366 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1367 // Empty flexible array init always allowed as an extension
1368 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001369 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001370 // Disallow flexible array init in C++; it is not required for gcc
1371 // compatibility, and it needs work to IRGen correctly in general.
1372 FlexArrayDiag = diag::err_flexible_array_init;
1373 } else if (!TopLevelObject) {
1374 // Disallow flexible array init on non-top-level object
1375 FlexArrayDiag = diag::err_flexible_array_init;
1376 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1377 // Disallow flexible array init on anything which is not a variable.
1378 FlexArrayDiag = diag::err_flexible_array_init;
1379 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1380 // Disallow flexible array init on local variables.
1381 FlexArrayDiag = diag::err_flexible_array_init;
1382 } else {
1383 // Allow other cases.
1384 FlexArrayDiag = diag::ext_flexible_array_init;
1385 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001386
1387 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001388 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001389 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001390 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001391 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1392 << Field;
1393 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001394
1395 return FlexArrayDiag != diag::ext_flexible_array_init;
1396}
1397
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001398void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001399 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001400 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001401 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001402 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 unsigned &Index,
1404 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001405 unsigned &StructuredIndex,
1406 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001407 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Eli Friedmanb85f7072008-05-19 19:16:24 +00001409 // If the record is invalid, some of it's members are invalid. To avoid
1410 // confusion, we forgo checking the intializer for the entire record.
1411 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001412 // Assume it was supposed to consume a single initializer.
1413 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001414 hadError = true;
1415 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001416 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001417
1418 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001419 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001420
1421 // If there's a default initializer, use it.
1422 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1423 if (VerifyOnly)
1424 return;
1425 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1426 Field != FieldEnd; ++Field) {
1427 if (Field->hasInClassInitializer()) {
1428 StructuredList->setInitializedFieldInUnion(*Field);
1429 // FIXME: Actually build a CXXDefaultInitExpr?
1430 return;
1431 }
1432 }
1433 }
1434
1435 // Value-initialize the first named member of the union.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001436 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1437 Field != FieldEnd; ++Field) {
1438 if (Field->getDeclName()) {
1439 if (VerifyOnly)
1440 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001441 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001442 else
David Blaikie581deb32012-06-06 20:45:41 +00001443 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001444 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001445 }
1446 }
1447 return;
1448 }
1449
Douglas Gregor05c13a32009-01-22 00:58:24 +00001450 // If structDecl is a forward declaration, this loop won't do
1451 // anything except look at designated initializers; That's okay,
1452 // because an error should get printed out elsewhere. It might be
1453 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001454 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001455 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001456 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001457 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001458 while (Index < IList->getNumInits()) {
1459 Expr *Init = IList->getInit(Index);
1460
1461 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001462 // If we're not the subobject that matches up with the '{' for
1463 // the designator, we shouldn't be handling the
1464 // designator. Return immediately.
1465 if (!SubobjectIsDesignatorContext)
1466 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001467
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001468 // Handle this designated initializer. Field will be updated to
1469 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001470 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001471 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001472 StructuredList, StructuredIndex,
1473 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001474 hadError = true;
1475
Douglas Gregordfb5e592009-02-12 19:00:39 +00001476 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001477
1478 // Disable check for missing fields when designators are used.
1479 // This matches gcc behaviour.
1480 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001481 continue;
1482 }
1483
1484 if (Field == FieldEnd) {
1485 // We've run out of fields. We're done.
1486 break;
1487 }
1488
Douglas Gregordfb5e592009-02-12 19:00:39 +00001489 // We've already initialized a member of a union. We're done.
1490 if (InitializedSomething && DeclType->isUnionType())
1491 break;
1492
Douglas Gregor44b43212008-12-11 16:49:14 +00001493 // If we've hit the flexible array member at the end, we're done.
1494 if (Field->getType()->isIncompleteArrayType())
1495 break;
1496
Douglas Gregor0bb76892009-01-29 16:53:55 +00001497 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001498 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001499 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001500 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001501 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001502
Douglas Gregor54001c12011-06-29 21:51:31 +00001503 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001504 bool InvalidUse;
1505 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001506 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001507 else
David Blaikie581deb32012-06-06 20:45:41 +00001508 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001509 IList->getInit(Index)->getLocStart());
1510 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001511 ++Index;
1512 ++Field;
1513 hadError = true;
1514 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001515 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001516
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001517 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001518 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001519 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1520 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001521 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001522
Sebastian Redl14b0c192011-09-24 17:48:00 +00001523 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001524 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001525 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001526 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001527
1528 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001529 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001530
John McCall80639de2010-03-11 19:32:38 +00001531 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001532 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1533 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1534 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001535 // It is possible we have one or more unnamed bitfields remaining.
1536 // Find first (if any) named field and emit warning.
1537 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1538 it != end; ++it) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001539 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
John McCall80639de2010-03-11 19:32:38 +00001540 SemaRef.Diag(IList->getSourceRange().getEnd(),
1541 diag::warn_missing_field_initializers) << it->getName();
1542 break;
1543 }
1544 }
1545 }
1546
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001547 // Check that any remaining fields can be value-initialized.
1548 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1549 !Field->getType()->isIncompleteArrayType()) {
1550 // FIXME: Should check for holes left by designated initializers too.
1551 for (; Field != FieldEnd && !hadError; ++Field) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00001552 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001553 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001554 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001555 }
1556 }
1557
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001559 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001560 return;
1561
David Blaikie581deb32012-06-06 20:45:41 +00001562 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001563 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001564 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001565 ++Index;
1566 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001567 }
1568
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001569 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001570 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001571
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001572 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001573 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001574 StructuredList, StructuredIndex);
1575 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001576 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001577 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001578}
Steve Naroff0cca7492008-05-01 22:18:59 +00001579
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001580/// \brief Expand a field designator that refers to a member of an
1581/// anonymous struct or union into a series of field designators that
1582/// refers to the field within the appropriate subobject.
1583///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001584static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001585 DesignatedInitExpr *DIE,
1586 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001587 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001588 typedef DesignatedInitExpr::Designator Designator;
1589
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001590 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001591 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001592 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1593 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1594 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001595 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001596 DIE->getDesignator(DesigIdx)->getDotLoc(),
1597 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1598 else
1599 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1600 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001601 assert(isa<FieldDecl>(*PI));
1602 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001603 }
1604
1605 // Expand the current designator into the set of replacement
1606 // designators, so we have a full subobject path down to where the
1607 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001608 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001609 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001610}
Mike Stump1eb44332009-09-09 15:08:12 +00001611
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001612/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001613/// corresponds to FieldName.
1614static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1615 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001616 if (!FieldName)
1617 return 0;
1618
Francois Picheta0e27f02010-12-22 03:46:10 +00001619 assert(AnonField->isAnonymousStructOrUnion());
1620 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001621 while (IndirectFieldDecl *IF =
1622 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001623 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001624 return IF;
1625 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001626 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001627 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001628}
1629
Sebastian Redl14b0c192011-09-24 17:48:00 +00001630static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1631 DesignatedInitExpr *DIE) {
1632 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1633 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1634 for (unsigned I = 0; I < NumIndexExprs; ++I)
1635 IndexExprs[I] = DIE->getSubExpr(I + 1);
1636 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001637 DIE->size(), IndexExprs,
1638 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001639 DIE->usesGNUSyntax(), DIE->getInit());
1640}
1641
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001642namespace {
1643
1644// Callback to only accept typo corrections that are for field members of
1645// the given struct or union.
1646class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1647 public:
1648 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1649 : Record(RD) {}
1650
1651 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1652 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1653 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1654 }
1655
1656 private:
1657 RecordDecl *Record;
1658};
1659
1660}
1661
Douglas Gregor05c13a32009-01-22 00:58:24 +00001662/// @brief Check the well-formedness of a C99 designated initializer.
1663///
1664/// Determines whether the designated initializer @p DIE, which
1665/// resides at the given @p Index within the initializer list @p
1666/// IList, is well-formed for a current object of type @p DeclType
1667/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001668/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001669/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001670///
1671/// @param IList The initializer list in which this designated
1672/// initializer occurs.
1673///
Douglas Gregor71199712009-04-15 04:56:10 +00001674/// @param DIE The designated initializer expression.
1675///
1676/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001677///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001678/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001679/// into which the designation in @p DIE should refer.
1680///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001681/// @param NextField If non-NULL and the first designator in @p DIE is
1682/// a field, this will be set to the field declaration corresponding
1683/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001684///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001685/// @param NextElementIndex If non-NULL and the first designator in @p
1686/// DIE is an array designator or GNU array-range designator, this
1687/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001688///
1689/// @param Index Index into @p IList where the designated initializer
1690/// @p DIE occurs.
1691///
Douglas Gregor4c678342009-01-28 21:54:33 +00001692/// @param StructuredList The initializer list expression that
1693/// describes all of the subobject initializers in the order they'll
1694/// actually be initialized.
1695///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001696/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001697bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001698InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001699 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001700 DesignatedInitExpr *DIE,
1701 unsigned DesigIdx,
1702 QualType &CurrentObjectType,
1703 RecordDecl::field_iterator *NextField,
1704 llvm::APSInt *NextElementIndex,
1705 unsigned &Index,
1706 InitListExpr *StructuredList,
1707 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001708 bool FinishSubobjectInit,
1709 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001710 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001711 // Check the actual initialization for the designated object type.
1712 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001713
1714 // Temporarily remove the designator expression from the
1715 // initializer list that the child calls see, so that we don't try
1716 // to re-process the designator.
1717 unsigned OldIndex = Index;
1718 IList->setInit(OldIndex, DIE->getInit());
1719
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001720 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001721 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001722
1723 // Restore the designated initializer expression in the syntactic
1724 // form of the initializer list.
1725 if (IList->getInit(OldIndex) != DIE->getInit())
1726 DIE->setInit(IList->getInit(OldIndex));
1727 IList->setInit(OldIndex, DIE);
1728
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001729 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001730 }
1731
Douglas Gregor71199712009-04-15 04:56:10 +00001732 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001733 bool IsFirstDesignator = (DesigIdx == 0);
1734 if (!VerifyOnly) {
1735 assert((IsFirstDesignator || StructuredList) &&
1736 "Need a non-designated initializer list to start from");
1737
1738 // Determine the structural initializer list that corresponds to the
1739 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001740 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001741 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1742 StructuredList, StructuredIndex,
Erik Verbruggen65d78312012-12-25 14:51:39 +00001743 SourceRange(D->getLocStart(),
1744 DIE->getLocEnd()));
Sebastian Redl14b0c192011-09-24 17:48:00 +00001745 assert(StructuredList && "Expected a structured initializer list");
1746 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001747
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001748 if (D->isFieldDesignator()) {
1749 // C99 6.7.8p7:
1750 //
1751 // If a designator has the form
1752 //
1753 // . identifier
1754 //
1755 // then the current object (defined below) shall have
1756 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001757 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001758 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001759 if (!RT) {
1760 SourceLocation Loc = D->getDotLoc();
1761 if (Loc.isInvalid())
1762 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001763 if (!VerifyOnly)
1764 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001765 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001766 ++Index;
1767 return true;
1768 }
1769
Douglas Gregor4c678342009-01-28 21:54:33 +00001770 // Note: we perform a linear search of the fields here, despite
1771 // the fact that we have a faster lookup method, because we always
1772 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001773 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001774 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001775 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001776 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001777 Field = RT->getDecl()->field_begin(),
1778 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001779 for (; Field != FieldEnd; ++Field) {
1780 if (Field->isUnnamedBitfield())
1781 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782
Francois Picheta0e27f02010-12-22 03:46:10 +00001783 // If we find a field representing an anonymous field, look in the
1784 // IndirectFieldDecl that follow for the designated initializer.
1785 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1786 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001787 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001788 // In verify mode, don't modify the original.
1789 if (VerifyOnly)
1790 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001791 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1792 D = DIE->getDesignator(DesigIdx);
1793 break;
1794 }
1795 }
David Blaikie581deb32012-06-06 20:45:41 +00001796 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001797 break;
1798 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 break;
1800
1801 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001802 }
1803
Douglas Gregor4c678342009-01-28 21:54:33 +00001804 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001805 if (VerifyOnly) {
1806 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001807 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001808 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001809
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001810 // There was no normal field in the struct with the designated
1811 // name. Perform another lookup for this name, which may find
1812 // something that we can't designate (e.g., a member function),
1813 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001814 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001815 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001816 FieldDecl *ReplacementField = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00001817 if (Lookup.empty()) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001818 // Name lookup didn't find anything. Determine whether this
1819 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001820 FieldInitializerValidatorCCC Validator(RT->getDecl());
Richard Smith2d670972013-08-17 00:46:16 +00001821 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1822 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1823 Sema::LookupMemberName, /*Scope=*/ 0, /*SS=*/ 0, Validator,
1824 RT->getDecl())) {
1825 SemaRef.diagnoseTypo(
1826 Corrected,
1827 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1828 << FieldName << CurrentObjectType);
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001829 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
Benjamin Kramera41ee492011-09-25 02:41:26 +00001830 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001831 } else {
1832 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1833 << FieldName << CurrentObjectType;
1834 ++Index;
1835 return true;
1836 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001837 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001838
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001839 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001840 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001841 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001842 << FieldName;
David Blaikie3bc93e32012-12-19 00:45:41 +00001843 SemaRef.Diag(Lookup.front()->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001844 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001845 ++Index;
1846 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001847 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001848
Francois Picheta0e27f02010-12-22 03:46:10 +00001849 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001850 // The replacement field comes from typo correction; find it
1851 // in the list of fields.
1852 FieldIndex = 0;
1853 Field = RT->getDecl()->field_begin();
1854 for (; Field != FieldEnd; ++Field) {
1855 if (Field->isUnnamedBitfield())
1856 continue;
1857
David Blaikie581deb32012-06-06 20:45:41 +00001858 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001859 Field->getIdentifier() == ReplacementField->getIdentifier())
1860 break;
1861
1862 ++FieldIndex;
1863 }
1864 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001865 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001866
1867 // All of the fields of a union are located at the same place in
1868 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001869 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001870 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001871 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001872 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001873 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001874
Douglas Gregor54001c12011-06-29 21:51:31 +00001875 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001876 bool InvalidUse;
1877 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001878 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001879 else
David Blaikie581deb32012-06-06 20:45:41 +00001880 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001881 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001882 ++Index;
1883 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001884 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001885
Sebastian Redl14b0c192011-09-24 17:48:00 +00001886 if (!VerifyOnly) {
1887 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001888 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Sebastian Redl14b0c192011-09-24 17:48:00 +00001890 // Make sure that our non-designated initializer list has space
1891 // for a subobject corresponding to this field.
1892 if (FieldIndex >= StructuredList->getNumInits())
1893 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1894 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001895
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001896 // This designator names a flexible array member.
1897 if (Field->getType()->isIncompleteArrayType()) {
1898 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001899 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001900 // We can't designate an object within the flexible array
1901 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001902 if (!VerifyOnly) {
1903 DesignatedInitExpr::Designator *NextD
1904 = DIE->getDesignator(DesigIdx + 1);
Erik Verbruggen65d78312012-12-25 14:51:39 +00001905 SemaRef.Diag(NextD->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001906 diag::err_designator_into_flexible_array_member)
Erik Verbruggen65d78312012-12-25 14:51:39 +00001907 << SourceRange(NextD->getLocStart(),
1908 DIE->getLocEnd());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001909 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001910 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001911 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001912 Invalid = true;
1913 }
1914
Chris Lattner9046c222010-10-10 17:49:49 +00001915 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1916 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001917 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001918 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001919 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001920 diag::err_flexible_array_init_needs_braces)
1921 << DIE->getInit()->getSourceRange();
1922 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001923 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001924 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001925 Invalid = true;
1926 }
1927
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001928 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001929 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001930 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001931 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001932
1933 if (Invalid) {
1934 ++Index;
1935 return true;
1936 }
1937
1938 // Initialize the array.
1939 bool prevHadError = hadError;
1940 unsigned newStructuredIndex = FieldIndex;
1941 unsigned OldIndex = Index;
1942 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001943
1944 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001945 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001946 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001947 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001948
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001949 IList->setInit(OldIndex, DIE);
1950 if (hadError && !prevHadError) {
1951 ++Field;
1952 ++FieldIndex;
1953 if (NextField)
1954 *NextField = Field;
1955 StructuredIndex = FieldIndex;
1956 return true;
1957 }
1958 } else {
1959 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001960 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001961 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001962
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001963 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001964 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001965 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1966 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001967 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001968 true, false))
1969 return true;
1970 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001971
1972 // Find the position of the next field to be initialized in this
1973 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001974 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001975 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001976
1977 // If this the first designator, our caller will continue checking
1978 // the rest of this struct/class/union subobject.
1979 if (IsFirstDesignator) {
1980 if (NextField)
1981 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001982 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001983 return false;
1984 }
1985
Douglas Gregor34e79462009-01-28 23:36:17 +00001986 if (!FinishSubobjectInit)
1987 return false;
1988
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001989 // We've already initialized something in the union; we're done.
1990 if (RT->getDecl()->isUnion())
1991 return hadError;
1992
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001993 // Check the remaining fields within this class/struct/union subobject.
1994 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001995
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001996 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001997 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001998 return hadError && !prevHadError;
1999 }
2000
2001 // C99 6.7.8p6:
2002 //
2003 // If a designator has the form
2004 //
2005 // [ constant-expression ]
2006 //
2007 // then the current object (defined below) shall have array
2008 // type and the expression shall be an integer constant
2009 // expression. If the array is of unknown size, any
2010 // nonnegative value is valid.
2011 //
2012 // Additionally, cope with the GNU extension that permits
2013 // designators of the form
2014 //
2015 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00002016 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002017 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002018 if (!VerifyOnly)
2019 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2020 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002021 ++Index;
2022 return true;
2023 }
2024
2025 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00002026 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2027 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002028 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002029 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00002030 DesignatedEndIndex = DesignatedStartIndex;
2031 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002032 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00002033
Mike Stump1eb44332009-09-09 15:08:12 +00002034 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002035 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002036 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002037 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002038 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00002039
Chris Lattnere0fd8322011-02-19 22:28:58 +00002040 // Codegen can't handle evaluating array range designators that have side
2041 // effects, because we replicate the AST value for each initialized element.
2042 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2043 // elements with something that has a side effect, so codegen can emit an
2044 // "error unsupported" error instead of miscompiling the app.
2045 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00002046 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00002047 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002048 }
2049
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002050 if (isa<ConstantArrayType>(AT)) {
2051 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002052 DesignatedStartIndex
2053 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002054 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00002055 DesignatedEndIndex
2056 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002057 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2058 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00002059 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002060 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00002061 diag::err_array_designator_too_large)
2062 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2063 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002064 ++Index;
2065 return true;
2066 }
Douglas Gregor34e79462009-01-28 23:36:17 +00002067 } else {
2068 // Make sure the bit-widths and signedness match.
2069 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002070 DesignatedEndIndex
2071 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00002072 else if (DesignatedStartIndex.getBitWidth() <
2073 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002074 DesignatedStartIndex
2075 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00002076 DesignatedStartIndex.setIsUnsigned(true);
2077 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Eli Friedman188ddb12013-06-11 21:48:11 +00002080 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2081 // We're modifying a string literal init; we have to decompose the string
2082 // so we can modify the individual characters.
2083 ASTContext &Context = SemaRef.Context;
2084 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2085
2086 // Compute the character type
2087 QualType CharTy = AT->getElementType();
2088
2089 // Compute the type of the integer literals.
2090 QualType PromotedCharTy = CharTy;
2091 if (CharTy->isPromotableIntegerType())
2092 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2093 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2094
2095 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2096 // Get the length of the string.
2097 uint64_t StrLen = SL->getLength();
2098 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2099 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2100 StructuredList->resizeInits(Context, StrLen);
2101
2102 // Build a literal for each character in the string, and put them into
2103 // the init list.
2104 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2105 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2106 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002107 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002108 if (CharTy != PromotedCharTy)
2109 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2110 Init, 0, VK_RValue);
2111 StructuredList->updateInit(Context, i, Init);
2112 }
2113 } else {
2114 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2115 std::string Str;
2116 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2117
2118 // Get the length of the string.
2119 uint64_t StrLen = Str.size();
2120 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2121 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2122 StructuredList->resizeInits(Context, StrLen);
2123
2124 // Build a literal for each character in the string, and put them into
2125 // the init list.
2126 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2127 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2128 Expr *Init = new (Context) IntegerLiteral(
Eli Friedman81359b02013-06-11 22:26:34 +00002129 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
Eli Friedman188ddb12013-06-11 21:48:11 +00002130 if (CharTy != PromotedCharTy)
2131 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2132 Init, 0, VK_RValue);
2133 StructuredList->updateInit(Context, i, Init);
2134 }
2135 }
2136 }
2137
Douglas Gregor4c678342009-01-28 21:54:33 +00002138 // Make sure that our non-designated initializer list has space
2139 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00002140 if (!VerifyOnly &&
2141 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00002142 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00002143 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00002144
Douglas Gregor34e79462009-01-28 23:36:17 +00002145 // Repeatedly perform subobject initializations in the range
2146 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002147
Douglas Gregor34e79462009-01-28 23:36:17 +00002148 // Move to the next designator
2149 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2150 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002152 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00002153 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002154
Douglas Gregor34e79462009-01-28 23:36:17 +00002155 while (DesignatedStartIndex <= DesignatedEndIndex) {
2156 // Recurse to check later designated subobjects.
2157 QualType ElementType = AT->getElementType();
2158 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002159
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002160 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002161 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2162 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002163 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002164 (DesignatedStartIndex == DesignatedEndIndex),
2165 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002166 return true;
2167
2168 // Move to the next index in the array that we'll be initializing.
2169 ++DesignatedStartIndex;
2170 ElementIndex = DesignatedStartIndex.getZExtValue();
2171 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002172
2173 // If this the first designator, our caller will continue checking
2174 // the rest of this array subobject.
2175 if (IsFirstDesignator) {
2176 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002177 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002178 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002179 return false;
2180 }
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Douglas Gregor34e79462009-01-28 23:36:17 +00002182 if (!FinishSubobjectInit)
2183 return false;
2184
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002185 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002186 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002188 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002189 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002190 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002191}
2192
Douglas Gregor4c678342009-01-28 21:54:33 +00002193// Get the structured initializer list for a subobject of type
2194// @p CurrentObjectType.
2195InitListExpr *
2196InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2197 QualType CurrentObjectType,
2198 InitListExpr *StructuredList,
2199 unsigned StructuredIndex,
2200 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002201 if (VerifyOnly)
2202 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002203 Expr *ExistingInit = 0;
2204 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002205 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002206 else if (StructuredIndex < StructuredList->getNumInits())
2207 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002208
Douglas Gregor4c678342009-01-28 21:54:33 +00002209 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2210 return Result;
2211
2212 if (ExistingInit) {
2213 // We are creating an initializer list that initializes the
2214 // subobjects of the current object, but there was already an
2215 // initialization that completely initialized the current
2216 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002217 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002218 // struct X { int a, b; };
2219 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002220 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002221 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2222 // designated initializer re-initializes the whole
2223 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002224 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002225 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002226 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002227 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002228 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002229 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002230 << ExistingInit->getSourceRange();
2231 }
2232
Mike Stump1eb44332009-09-09 15:08:12 +00002233 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002234 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002235 InitRange.getBegin(), None,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002236 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002237
Eli Friedman5c89c392012-02-23 02:25:10 +00002238 QualType ResultType = CurrentObjectType;
2239 if (!ResultType->isArrayType())
2240 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2241 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002242
Douglas Gregorfa219202009-03-20 23:58:33 +00002243 // Pre-allocate storage for the structured initializer list.
2244 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002245 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002246 bool GotNumInits = false;
2247 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002248 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002249 GotNumInits = true;
2250 } else if (Index < IList->getNumInits()) {
2251 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002252 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002253 GotNumInits = true;
2254 }
Douglas Gregor08457732009-03-21 18:13:52 +00002255 }
2256
Mike Stump1eb44332009-09-09 15:08:12 +00002257 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002258 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2259 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2260 NumElements = CAType->getSize().getZExtValue();
2261 // Simple heuristic so that we don't allocate a very large
2262 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002263 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002264 NumElements = 0;
2265 }
John McCall183700f2009-09-21 23:43:11 +00002266 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002267 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002268 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002269 RecordDecl *RDecl = RType->getDecl();
2270 if (RDecl->isUnion())
2271 NumElements = 1;
2272 else
Mike Stump1eb44332009-09-09 15:08:12 +00002273 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002274 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002275 }
2276
Ted Kremenek709210f2010-04-13 23:39:13 +00002277 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002278
Douglas Gregor4c678342009-01-28 21:54:33 +00002279 // Link this new initializer list into the structured initializer
2280 // lists.
2281 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002282 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002283 else {
2284 Result->setSyntacticForm(IList);
2285 SyntacticToSemantic[IList] = Result;
2286 }
2287
2288 return Result;
2289}
2290
2291/// Update the initializer at index @p StructuredIndex within the
2292/// structured initializer list to the value @p expr.
2293void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2294 unsigned &StructuredIndex,
2295 Expr *expr) {
2296 // No structured initializer list to update
2297 if (!StructuredList)
2298 return;
2299
Ted Kremenek709210f2010-04-13 23:39:13 +00002300 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2301 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002302 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002303 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002304 diag::warn_initializer_overrides)
2305 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002306 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002307 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002308 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002309 << PrevInit->getSourceRange();
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregor4c678342009-01-28 21:54:33 +00002312 ++StructuredIndex;
2313}
2314
Douglas Gregor05c13a32009-01-22 00:58:24 +00002315/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002316/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002317/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002318/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002319/// failure. Returns the index expression, possibly with an implicit cast
2320/// added, on success. If everything went okay, Value will receive the
2321/// value of the constant expression.
2322static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002323CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002324 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002325
2326 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002327 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2328 if (Result.isInvalid())
2329 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002330
Chris Lattner3bf68932009-04-25 21:59:05 +00002331 if (Value.isSigned() && Value.isNegative())
2332 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002333 << Value.toString(10) << Index->getSourceRange();
2334
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002335 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002336 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002337}
2338
John McCall60d7b3a2010-08-24 06:29:42 +00002339ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002340 SourceLocation Loc,
2341 bool GNUSyntax,
2342 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002343 typedef DesignatedInitExpr::Designator ASTDesignator;
2344
2345 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002346 SmallVector<ASTDesignator, 32> Designators;
2347 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002348
2349 // Build designators and check array designator expressions.
2350 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2351 const Designator &D = Desig.getDesignator(Idx);
2352 switch (D.getKind()) {
2353 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002354 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002355 D.getFieldLoc()));
2356 break;
2357
2358 case Designator::ArrayDesignator: {
2359 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2360 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002361 if (!Index->isTypeDependent() && !Index->isValueDependent())
2362 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2363 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002364 Invalid = true;
2365 else {
2366 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002367 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002368 D.getRBracketLoc()));
2369 InitExpressions.push_back(Index);
2370 }
2371 break;
2372 }
2373
2374 case Designator::ArrayRangeDesignator: {
2375 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2376 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2377 llvm::APSInt StartValue;
2378 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002379 bool StartDependent = StartIndex->isTypeDependent() ||
2380 StartIndex->isValueDependent();
2381 bool EndDependent = EndIndex->isTypeDependent() ||
2382 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002383 if (!StartDependent)
2384 StartIndex =
2385 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2386 if (!EndDependent)
2387 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2388
2389 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002390 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002391 else {
2392 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002393 if (StartDependent || EndDependent) {
2394 // Nothing to compute.
2395 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002396 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002397 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002398 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002399
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002400 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002401 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002402 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002403 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2404 Invalid = true;
2405 } else {
2406 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002407 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002408 D.getEllipsisLoc(),
2409 D.getRBracketLoc()));
2410 InitExpressions.push_back(StartIndex);
2411 InitExpressions.push_back(EndIndex);
2412 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002413 }
2414 break;
2415 }
2416 }
2417 }
2418
2419 if (Invalid || Init.isInvalid())
2420 return ExprError();
2421
2422 // Clear out the expressions within the designation.
2423 Desig.ClearExprs(*this);
2424
2425 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002426 = DesignatedInitExpr::Create(Context,
2427 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002428 InitExpressions, Loc, GNUSyntax,
2429 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002430
David Blaikie4e4d0842012-03-11 07:00:24 +00002431 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002432 Diag(DIE->getLocStart(), diag::ext_designated_init)
2433 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002434
Douglas Gregor05c13a32009-01-22 00:58:24 +00002435 return Owned(DIE);
2436}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002437
Douglas Gregor20093b42009-12-09 23:02:17 +00002438//===----------------------------------------------------------------------===//
2439// Initialization entity
2440//===----------------------------------------------------------------------===//
2441
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002442InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002443 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002444 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002445{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002446 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2447 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002448 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002449 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002450 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002451 Type = VT->getElementType();
2452 } else {
2453 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2454 assert(CT && "Unexpected type");
2455 Kind = EK_ComplexElement;
2456 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002457 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002458}
2459
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002460InitializedEntity
2461InitializedEntity::InitializeBase(ASTContext &Context,
2462 const CXXBaseSpecifier *Base,
2463 bool IsInheritedVirtualBase) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002464 InitializedEntity Result;
2465 Result.Kind = EK_Base;
Richard Smitha4bb99c2013-06-12 21:51:50 +00002466 Result.Parent = 0;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002467 Result.Base = reinterpret_cast<uintptr_t>(Base);
2468 if (IsInheritedVirtualBase)
2469 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470
Douglas Gregord6542d82009-12-22 15:35:07 +00002471 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002472 return Result;
2473}
2474
Douglas Gregor99a2e602009-12-16 01:38:02 +00002475DeclarationName InitializedEntity::getName() const {
2476 switch (getKind()) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002477 case EK_Parameter:
2478 case EK_Parameter_CF_Audited: {
John McCallf85e1932011-06-15 23:02:42 +00002479 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2480 return (D ? D->getDeclName() : DeclarationName());
2481 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002482
2483 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002484 case EK_Member:
2485 return VariableOrMember->getDeclName();
2486
Douglas Gregor47736542012-02-15 16:57:26 +00002487 case EK_LambdaCapture:
2488 return Capture.Var->getDeclName();
2489
Douglas Gregor99a2e602009-12-16 01:38:02 +00002490 case EK_Result:
2491 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002492 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002493 case EK_Temporary:
2494 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002495 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002496 case EK_ArrayElement:
2497 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002498 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002499 case EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00002500 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002501 case EK_RelatedResult:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002502 return DeclarationName();
2503 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002504
David Blaikie7530c032012-01-17 06:56:22 +00002505 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002506}
2507
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002508DeclaratorDecl *InitializedEntity::getDecl() const {
2509 switch (getKind()) {
2510 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002511 case EK_Member:
2512 return VariableOrMember;
2513
John McCallf85e1932011-06-15 23:02:42 +00002514 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002515 case EK_Parameter_CF_Audited:
John McCallf85e1932011-06-15 23:02:42 +00002516 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2517
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002518 case EK_Result:
2519 case EK_Exception:
2520 case EK_New:
2521 case EK_Temporary:
2522 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002523 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002524 case EK_ArrayElement:
2525 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002526 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002527 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002528 case EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00002529 case EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002530 case EK_RelatedResult:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002531 return 0;
2532 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002533
David Blaikie7530c032012-01-17 06:56:22 +00002534 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002535}
2536
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002537bool InitializedEntity::allowsNRVO() const {
2538 switch (getKind()) {
2539 case EK_Result:
2540 case EK_Exception:
2541 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002542
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002543 case EK_Variable:
2544 case EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002545 case EK_Parameter_CF_Audited:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002546 case EK_Member:
2547 case EK_New:
2548 case EK_Temporary:
Jordan Rose2624b812013-05-06 16:48:12 +00002549 case EK_CompoundLiteralInit:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002550 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002551 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002552 case EK_ArrayElement:
2553 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002554 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002555 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002556 case EK_LambdaCapture:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002557 case EK_RelatedResult:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002558 break;
2559 }
2560
2561 return false;
2562}
2563
Richard Smith211c8dd2013-06-05 00:46:14 +00002564unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
Richard Smitha4bb99c2013-06-12 21:51:50 +00002565 assert(getParent() != this);
Richard Smith211c8dd2013-06-05 00:46:14 +00002566 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2567 for (unsigned I = 0; I != Depth; ++I)
2568 OS << "`-";
2569
2570 switch (getKind()) {
2571 case EK_Variable: OS << "Variable"; break;
2572 case EK_Parameter: OS << "Parameter"; break;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002573 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2574 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002575 case EK_Result: OS << "Result"; break;
2576 case EK_Exception: OS << "Exception"; break;
2577 case EK_Member: OS << "Member"; break;
2578 case EK_New: OS << "New"; break;
2579 case EK_Temporary: OS << "Temporary"; break;
2580 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00002581 case EK_RelatedResult: OS << "RelatedResult"; break;
Richard Smith211c8dd2013-06-05 00:46:14 +00002582 case EK_Base: OS << "Base"; break;
2583 case EK_Delegating: OS << "Delegating"; break;
2584 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2585 case EK_VectorElement: OS << "VectorElement " << Index; break;
2586 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2587 case EK_BlockElement: OS << "Block"; break;
2588 case EK_LambdaCapture:
2589 OS << "LambdaCapture ";
2590 getCapturedVar()->printName(OS);
2591 break;
2592 }
2593
2594 if (Decl *D = getDecl()) {
2595 OS << " ";
2596 cast<NamedDecl>(D)->printQualifiedName(OS);
2597 }
2598
2599 OS << " '" << getType().getAsString() << "'\n";
2600
2601 return Depth + 1;
2602}
2603
2604void InitializedEntity::dump() const {
2605 dumpImpl(llvm::errs());
2606}
2607
Douglas Gregor20093b42009-12-09 23:02:17 +00002608//===----------------------------------------------------------------------===//
2609// Initialization sequence
2610//===----------------------------------------------------------------------===//
2611
2612void InitializationSequence::Step::Destroy() {
2613 switch (Kind) {
2614 case SK_ResolveAddressOfOverloadedFunction:
2615 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002616 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002617 case SK_CastDerivedToBaseLValue:
2618 case SK_BindReference:
2619 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002620 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002621 case SK_UserConversion:
2622 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002623 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002624 case SK_QualificationConversionLValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00002625 case SK_LValueToRValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002626 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002627 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002628 case SK_UnwrapInitList:
2629 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002630 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002631 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002632 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002633 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002634 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002635 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002636 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002637 case SK_PassByIndirectCopyRestore:
2638 case SK_PassByIndirectRestore:
2639 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002640 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00002641 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00002642 case SK_OCLZeroEvent:
Douglas Gregor20093b42009-12-09 23:02:17 +00002643 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002644
Douglas Gregor20093b42009-12-09 23:02:17 +00002645 case SK_ConversionSequence:
2646 delete ICS;
2647 }
2648}
2649
Douglas Gregorb70cf442010-03-26 20:14:36 +00002650bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002651 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002652}
2653
2654bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002655 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002656 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002657
Douglas Gregorb70cf442010-03-26 20:14:36 +00002658 switch (getFailureKind()) {
2659 case FK_TooManyInitsForReference:
2660 case FK_ArrayNeedsInitList:
2661 case FK_ArrayNeedsInitListOrStringLiteral:
Hans Wennborg0ff50742013-05-15 11:03:04 +00002662 case FK_ArrayNeedsInitListOrWideStringLiteral:
2663 case FK_NarrowStringIntoWideCharArray:
2664 case FK_WideStringIntoCharArray:
2665 case FK_IncompatWideStringIntoWideChar:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002666 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2667 case FK_NonConstLValueReferenceBindingToTemporary:
2668 case FK_NonConstLValueReferenceBindingToUnrelated:
2669 case FK_RValueReferenceBindingToLValue:
2670 case FK_ReferenceInitDropsQualifiers:
2671 case FK_ReferenceInitFailed:
2672 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002673 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002674 case FK_TooManyInitsForScalar:
2675 case FK_ReferenceBindingToInitList:
2676 case FK_InitListBadDestinationType:
2677 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002678 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002679 case FK_ArrayTypeMismatch:
2680 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002681 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002682 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002683 case FK_PlaceholderType:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002684 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002685 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002686
Douglas Gregorb70cf442010-03-26 20:14:36 +00002687 case FK_ReferenceInitOverloadFailed:
2688 case FK_UserConversionOverloadFailed:
2689 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002690 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002691 return FailedOverloadResult == OR_Ambiguous;
2692 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002693
David Blaikie7530c032012-01-17 06:56:22 +00002694 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002695}
2696
Douglas Gregord6e44a32010-04-16 22:09:46 +00002697bool InitializationSequence::isConstructorInitialization() const {
2698 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2699}
2700
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002701void
2702InitializationSequence
2703::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2704 DeclAccessPair Found,
2705 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002706 Step S;
2707 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2708 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002709 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002710 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002711 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002712 Steps.push_back(S);
2713}
2714
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002716 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002717 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002718 switch (VK) {
2719 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2720 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2721 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002722 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002723 S.Type = BaseType;
2724 Steps.push_back(S);
2725}
2726
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002727void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 bool BindingTemporary) {
2729 Step S;
2730 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2731 S.Type = T;
2732 Steps.push_back(S);
2733}
2734
Douglas Gregor523d46a2010-04-18 07:40:54 +00002735void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2736 Step S;
2737 S.Kind = SK_ExtraneousCopyToTemporary;
2738 S.Type = T;
2739 Steps.push_back(S);
2740}
2741
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002742void
2743InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2744 DeclAccessPair FoundDecl,
2745 QualType T,
2746 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002747 Step S;
2748 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002749 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002750 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002751 S.Function.Function = Function;
2752 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002753 Steps.push_back(S);
2754}
2755
2756void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002757 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002758 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002759 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002760 switch (VK) {
2761 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002762 S.Kind = SK_QualificationConversionRValue;
2763 break;
John McCall5baba9d2010-08-25 10:28:54 +00002764 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002765 S.Kind = SK_QualificationConversionXValue;
2766 break;
John McCall5baba9d2010-08-25 10:28:54 +00002767 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002768 S.Kind = SK_QualificationConversionLValue;
2769 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002770 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002771 S.Type = Ty;
2772 Steps.push_back(S);
2773}
2774
Jordan Rose1fd1e282013-04-11 00:58:58 +00002775void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2776 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2777
2778 Step S;
2779 S.Kind = SK_LValueToRValue;
2780 S.Type = Ty;
2781 Steps.push_back(S);
2782}
2783
Douglas Gregor20093b42009-12-09 23:02:17 +00002784void InitializationSequence::AddConversionSequenceStep(
2785 const ImplicitConversionSequence &ICS,
2786 QualType T) {
2787 Step S;
2788 S.Kind = SK_ConversionSequence;
2789 S.Type = T;
2790 S.ICS = new ImplicitConversionSequence(ICS);
2791 Steps.push_back(S);
2792}
2793
Douglas Gregord87b61f2009-12-10 17:56:55 +00002794void InitializationSequence::AddListInitializationStep(QualType T) {
2795 Step S;
2796 S.Kind = SK_ListInitialization;
2797 S.Type = T;
2798 Steps.push_back(S);
2799}
2800
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002801void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002802InitializationSequence
2803::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2804 AccessSpecifier Access,
2805 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002806 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002807 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002808 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002809 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2810 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002811 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002812 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002813 S.Function.Function = Constructor;
2814 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002815 Steps.push_back(S);
2816}
2817
Douglas Gregor71d17402009-12-15 00:01:57 +00002818void InitializationSequence::AddZeroInitializationStep(QualType T) {
2819 Step S;
2820 S.Kind = SK_ZeroInitialization;
2821 S.Type = T;
2822 Steps.push_back(S);
2823}
2824
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002825void InitializationSequence::AddCAssignmentStep(QualType T) {
2826 Step S;
2827 S.Kind = SK_CAssignment;
2828 S.Type = T;
2829 Steps.push_back(S);
2830}
2831
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002832void InitializationSequence::AddStringInitStep(QualType T) {
2833 Step S;
2834 S.Kind = SK_StringInit;
2835 S.Type = T;
2836 Steps.push_back(S);
2837}
2838
Douglas Gregor569c3162010-08-07 11:51:51 +00002839void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2840 Step S;
2841 S.Kind = SK_ObjCObjectConversion;
2842 S.Type = T;
2843 Steps.push_back(S);
2844}
2845
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002846void InitializationSequence::AddArrayInitStep(QualType T) {
2847 Step S;
2848 S.Kind = SK_ArrayInit;
2849 S.Type = T;
2850 Steps.push_back(S);
2851}
2852
Richard Smith0f163e92012-02-15 22:38:09 +00002853void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2854 Step S;
2855 S.Kind = SK_ParenthesizedArrayInit;
2856 S.Type = T;
2857 Steps.push_back(S);
2858}
2859
John McCallf85e1932011-06-15 23:02:42 +00002860void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2861 bool shouldCopy) {
2862 Step s;
2863 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2864 : SK_PassByIndirectRestore);
2865 s.Type = type;
2866 Steps.push_back(s);
2867}
2868
2869void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2870 Step S;
2871 S.Kind = SK_ProduceObjCObject;
2872 S.Type = T;
2873 Steps.push_back(S);
2874}
2875
Sebastian Redl2b916b82012-01-17 22:49:42 +00002876void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2877 Step S;
2878 S.Kind = SK_StdInitializerList;
2879 S.Type = T;
2880 Steps.push_back(S);
2881}
2882
Guy Benyei21f18c42013-02-07 10:55:47 +00002883void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2884 Step S;
2885 S.Kind = SK_OCLSamplerInit;
2886 S.Type = T;
2887 Steps.push_back(S);
2888}
2889
Guy Benyeie6b9d802013-01-20 12:31:11 +00002890void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2891 Step S;
2892 S.Kind = SK_OCLZeroEvent;
2893 S.Type = T;
2894 Steps.push_back(S);
2895}
2896
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002897void InitializationSequence::RewrapReferenceInitList(QualType T,
2898 InitListExpr *Syntactic) {
2899 assert(Syntactic->getNumInits() == 1 &&
2900 "Can only rewrap trivial init lists.");
2901 Step S;
2902 S.Kind = SK_UnwrapInitList;
2903 S.Type = Syntactic->getInit(0)->getType();
2904 Steps.insert(Steps.begin(), S);
2905
2906 S.Kind = SK_RewrapInitList;
2907 S.Type = T;
2908 S.WrappingSyntacticList = Syntactic;
2909 Steps.push_back(S);
2910}
2911
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002912void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002913 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002914 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002915 this->Failure = Failure;
2916 this->FailedOverloadResult = Result;
2917}
2918
2919//===----------------------------------------------------------------------===//
2920// Attempt initialization
2921//===----------------------------------------------------------------------===//
2922
John McCallf85e1932011-06-15 23:02:42 +00002923static void MaybeProduceObjCObject(Sema &S,
2924 InitializationSequence &Sequence,
2925 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002926 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002927
2928 /// When initializing a parameter, produce the value if it's marked
2929 /// __attribute__((ns_consumed)).
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00002930 if (Entity.isParameterKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002931 if (!Entity.isParameterConsumed())
2932 return;
2933
2934 assert(Entity.getType()->isObjCRetainableType() &&
2935 "consuming an object of unretainable type?");
2936 Sequence.AddProduceObjCObjectStep(Entity.getType());
2937
2938 /// When initializing a return value, if the return type is a
2939 /// retainable type, then returns need to immediately retain the
2940 /// object. If an autorelease is required, it will be done at the
2941 /// last instant.
2942 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2943 if (!Entity.getType()->isObjCRetainableType())
2944 return;
2945
2946 Sequence.AddProduceObjCObjectStep(Entity.getType());
2947 }
2948}
2949
Richard Smith7c3e6152013-06-12 22:31:48 +00002950static void TryListInitialization(Sema &S,
2951 const InitializedEntity &Entity,
2952 const InitializationKind &Kind,
2953 InitListExpr *InitList,
2954 InitializationSequence &Sequence);
2955
Richard Smithf4bb8d02012-07-05 08:39:21 +00002956/// \brief When initializing from init list via constructor, handle
2957/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002958///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002959/// \return true if we have handled initialization of an object of type
2960/// std::initializer_list<T>, false otherwise.
2961static bool TryInitializerListConstruction(Sema &S,
2962 InitListExpr *List,
2963 QualType DestType,
2964 InitializationSequence &Sequence) {
2965 QualType E;
2966 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002967 return false;
2968
Richard Smith7c3e6152013-06-12 22:31:48 +00002969 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2970 Sequence.setIncompleteTypeFailure(E);
2971 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002972 }
Richard Smith7c3e6152013-06-12 22:31:48 +00002973
2974 // Try initializing a temporary array from the init list.
2975 QualType ArrayType = S.Context.getConstantArrayType(
2976 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2977 List->getNumInits()),
2978 clang::ArrayType::Normal, 0);
2979 InitializedEntity HiddenArray =
2980 InitializedEntity::InitializeTemporary(ArrayType);
2981 InitializationKind Kind =
2982 InitializationKind::CreateDirectList(List->getExprLoc());
2983 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
2984 if (Sequence)
2985 Sequence.AddStdInitializerListConstructionStep(DestType);
Richard Smithf4bb8d02012-07-05 08:39:21 +00002986 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002987}
2988
Sebastian Redl96715b22012-02-04 21:27:39 +00002989static OverloadingResult
2990ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002991 MultiExprArg Args,
Sebastian Redl96715b22012-02-04 21:27:39 +00002992 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002993 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002994 OverloadCandidateSet::iterator &Best,
2995 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002996 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002997 CandidateSet.clear();
2998
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002999 for (ArrayRef<NamedDecl *>::iterator
3000 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003001 NamedDecl *D = *Con;
3002 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3003 bool SuppressUserConversions = false;
3004
3005 // Find the constructor (which may be a template).
3006 CXXConstructorDecl *Constructor = 0;
3007 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3008 if (ConstructorTmpl)
3009 Constructor = cast<CXXConstructorDecl>(
3010 ConstructorTmpl->getTemplatedDecl());
3011 else {
3012 Constructor = cast<CXXConstructorDecl>(D);
3013
3014 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003015 // suppress user-defined conversions on the arguments. We do the same for
3016 // move constructors.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003017 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003018 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00003019 SuppressUserConversions = true;
3020 }
3021
3022 if (!Constructor->isInvalidDecl() &&
3023 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003024 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00003025 if (ConstructorTmpl)
3026 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003027 /*ExplicitArgs*/ 0, Args,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003028 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00003029 else {
3030 // C++ [over.match.copy]p1:
3031 // - When initializing a temporary to be bound to the first parameter
3032 // of a constructor that takes a reference to possibly cv-qualified
3033 // T as its first argument, called with a single argument in the
3034 // context of direct-initialization, explicit conversion functions
3035 // are also considered.
3036 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003037 Args.size() == 1 &&
Douglas Gregored878af2012-02-24 23:56:31 +00003038 Constructor->isCopyOrMoveConstructor();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003039 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00003040 SuppressUserConversions,
3041 /*PartialOverloading=*/false,
3042 /*AllowExplicit=*/AllowExplicitConv);
3043 }
Sebastian Redl96715b22012-02-04 21:27:39 +00003044 }
3045 }
3046
3047 // Perform overload resolution and return the result.
3048 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3049}
3050
Sebastian Redl10f04a62011-12-22 14:44:04 +00003051/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3052/// enumerates the constructors of the initialized entity and performs overload
3053/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00003054/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00003055/// class type.
3056static void TryConstructorInitialization(Sema &S,
3057 const InitializedEntity &Entity,
3058 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003059 MultiExprArg Args, QualType DestType,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003060 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00003061 bool InitListSyntax = false) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003062 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
Sebastian Redl08ae3692012-02-04 21:27:33 +00003063 "InitListSyntax must come with a single initializer list argument.");
3064
Sebastian Redl10f04a62011-12-22 14:44:04 +00003065 // The type we're constructing needs to be complete.
3066 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003067 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00003068 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003069 }
3070
3071 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3072 assert(DestRecordType && "Constructor initialization requires record type");
3073 CXXRecordDecl *DestRecordDecl
3074 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3075
Sebastian Redl96715b22012-02-04 21:27:39 +00003076 // Build the candidate set directly in the initialization sequence
3077 // structure, so that it will persist if we fail.
3078 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3079
3080 // Determine whether we are allowed to call explicit constructors or
3081 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003082 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003083 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00003084
Sebastian Redl10f04a62011-12-22 14:44:04 +00003085 // - Otherwise, if T is a class type, constructors are considered. The
3086 // applicable constructors are enumerated, and the best one is chosen
3087 // through overload resolution.
David Blaikie3bc93e32012-12-19 00:45:41 +00003088 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003089 // The container holding the constructors can under certain conditions
3090 // be changed while iterating (e.g. because of deserialization).
3091 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003092 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Sebastian Redl10f04a62011-12-22 14:44:04 +00003093
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003094 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00003095 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003096 bool AsInitializerList = false;
3097
3098 // C++11 [over.match.list]p1:
3099 // When objects of non-aggregate type T are list-initialized, overload
3100 // resolution selects the constructor in two phases:
3101 // - Initially, the candidate functions are the initializer-list
3102 // constructors of the class T and the argument list consists of the
3103 // initializer list as a single argument.
3104 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003105 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003106 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003107
3108 // If the initializer list has no elements and T has a default constructor,
3109 // the first phase is omitted.
Richard Smithe5411b72012-12-01 02:35:44 +00003110 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003111 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003112 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003113 CopyInitialization, AllowExplicit,
3114 /*OnlyListConstructor=*/true,
3115 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003116
3117 // Time to unwrap the init list.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003118 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003119 }
3120
3121 // C++11 [over.match.list]p1:
3122 // - If no viable initializer-list constructor is found, overload resolution
3123 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00003124 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003125 // elements of the initializer list.
3126 if (Result == OR_No_Viable_Function) {
3127 AsInitializerList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003128 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003129 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003130 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00003131 /*OnlyListConstructors=*/false,
3132 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003133 }
3134 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00003135 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003136 InitializationSequence::FK_ListConstructorOverloadFailed :
3137 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003138 Result);
3139 return;
3140 }
3141
Richard Smithf4bb8d02012-07-05 08:39:21 +00003142 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00003143 // If a program calls for the default initialization of an object
3144 // of a const-qualified type T, T shall be a class type with a
3145 // user-provided default constructor.
3146 if (Kind.getKind() == InitializationKind::IK_Default &&
3147 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00003148 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003149 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3150 return;
3151 }
3152
Sebastian Redl70e24fc2012-04-01 19:54:59 +00003153 // C++11 [over.match.list]p1:
3154 // In copy-list-initialization, if an explicit constructor is chosen, the
3155 // initializer is ill-formed.
3156 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3157 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3158 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3159 return;
3160 }
3161
Sebastian Redl10f04a62011-12-22 14:44:04 +00003162 // Add the constructor initialization step. Any cv-qualification conversion is
3163 // subsumed by the initialization.
3164 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003165 Sequence.AddConstructorInitializationStep(CtorDecl,
3166 Best->FoundDecl.getAccess(),
3167 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00003168 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00003169}
3170
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003171static bool
3172ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3173 Expr *Initializer,
3174 QualType &SourceType,
3175 QualType &UnqualifiedSourceType,
3176 QualType UnqualifiedTargetType,
3177 InitializationSequence &Sequence) {
3178 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3179 S.Context.OverloadTy) {
3180 DeclAccessPair Found;
3181 bool HadMultipleCandidates = false;
3182 if (FunctionDecl *Fn
3183 = S.ResolveAddressOfOverloadedFunction(Initializer,
3184 UnqualifiedTargetType,
3185 false, Found,
3186 &HadMultipleCandidates)) {
3187 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3188 HadMultipleCandidates);
3189 SourceType = Fn->getType();
3190 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3191 } else if (!UnqualifiedTargetType->isRecordType()) {
3192 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3193 return true;
3194 }
3195 }
3196 return false;
3197}
3198
3199static void TryReferenceInitializationCore(Sema &S,
3200 const InitializedEntity &Entity,
3201 const InitializationKind &Kind,
3202 Expr *Initializer,
3203 QualType cv1T1, QualType T1,
3204 Qualifiers T1Quals,
3205 QualType cv2T2, QualType T2,
3206 Qualifiers T2Quals,
3207 InitializationSequence &Sequence);
3208
Richard Smithf4bb8d02012-07-05 08:39:21 +00003209static void TryValueInitialization(Sema &S,
3210 const InitializedEntity &Entity,
3211 const InitializationKind &Kind,
3212 InitializationSequence &Sequence,
3213 InitListExpr *InitList = 0);
3214
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003215/// \brief Attempt list initialization of a reference.
3216static void TryReferenceListInitialization(Sema &S,
3217 const InitializedEntity &Entity,
3218 const InitializationKind &Kind,
3219 InitListExpr *InitList,
Richard Smithb6e38082013-06-08 00:02:08 +00003220 InitializationSequence &Sequence) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003221 // First, catch C++03 where this isn't possible.
Richard Smith80ad52f2013-01-02 11:42:31 +00003222 if (!S.getLangOpts().CPlusPlus11) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003223 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3224 return;
3225 }
3226
3227 QualType DestType = Entity.getType();
3228 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3229 Qualifiers T1Quals;
3230 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3231
3232 // Reference initialization via an initializer list works thus:
3233 // If the initializer list consists of a single element that is
3234 // reference-related to the referenced type, bind directly to that element
3235 // (possibly creating temporaries).
3236 // Otherwise, initialize a temporary with the initializer list and
3237 // bind to that.
3238 if (InitList->getNumInits() == 1) {
3239 Expr *Initializer = InitList->getInit(0);
3240 QualType cv2T2 = Initializer->getType();
3241 Qualifiers T2Quals;
3242 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3243
3244 // If this fails, creating a temporary wouldn't work either.
3245 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3246 T1, Sequence))
3247 return;
3248
3249 SourceLocation DeclLoc = Initializer->getLocStart();
3250 bool dummy1, dummy2, dummy3;
3251 Sema::ReferenceCompareResult RefRelationship
3252 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3253 dummy2, dummy3);
3254 if (RefRelationship >= Sema::Ref_Related) {
3255 // Try to bind the reference here.
3256 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3257 T1Quals, cv2T2, T2, T2Quals, Sequence);
3258 if (Sequence)
3259 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3260 return;
3261 }
Richard Smith02d65ee2013-01-15 07:58:29 +00003262
3263 // Update the initializer if we've resolved an overloaded function.
3264 if (Sequence.step_begin() != Sequence.step_end())
3265 Sequence.RewrapReferenceInitList(cv1T1, InitList);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003266 }
3267
3268 // Not reference-related. Create a temporary and bind to that.
3269 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3270
3271 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3272 if (Sequence) {
3273 if (DestType->isRValueReferenceType() ||
3274 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3275 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3276 else
3277 Sequence.SetFailed(
3278 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3279 }
3280}
3281
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003282/// \brief Attempt list initialization (C++0x [dcl.init.list])
3283static void TryListInitialization(Sema &S,
3284 const InitializedEntity &Entity,
3285 const InitializationKind &Kind,
3286 InitListExpr *InitList,
3287 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003288 QualType DestType = Entity.getType();
3289
Sebastian Redl14b0c192011-09-24 17:48:00 +00003290 // C++ doesn't allow scalar initialization with more than one argument.
3291 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003292 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003293 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3294 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3295 return;
3296 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003297 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003298 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003299 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003300 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003301 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003302 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003303 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003304 return;
3305 }
3306
Richard Smithf4bb8d02012-07-05 08:39:21 +00003307 // C++11 [dcl.init.list]p3:
3308 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003309 if (!DestType->isAggregateType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003310 if (S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003311 // - Otherwise, if the initializer list has no elements and T is a
3312 // class type with a default constructor, the object is
3313 // value-initialized.
3314 if (InitList->getNumInits() == 0) {
3315 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
Richard Smithe5411b72012-12-01 02:35:44 +00003316 if (RD->hasDefaultConstructor()) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003317 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3318 return;
3319 }
3320 }
3321
3322 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3323 // an initializer_list object constructed [...]
3324 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3325 return;
3326
3327 // - Otherwise, if T is a class type, constructors are considered.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003328 Expr *InitListAsExpr = InitList;
3329 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003330 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003331 } else
3332 Sequence.SetFailed(
3333 InitializationSequence::FK_InitListBadDestinationType);
3334 return;
3335 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003336 }
3337
Sebastian Redl14b0c192011-09-24 17:48:00 +00003338 InitListChecker CheckInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00003339 DestType, /*VerifyOnly=*/true);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003340 if (CheckInitList.HadError()) {
3341 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3342 return;
3343 }
3344
3345 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003346 Sequence.AddListInitializationStep(DestType);
3347}
Douglas Gregor20093b42009-12-09 23:02:17 +00003348
3349/// \brief Try a reference initialization that involves calling a conversion
3350/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003351static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3352 const InitializedEntity &Entity,
3353 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003354 Expr *Initializer,
3355 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003356 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003357 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003358 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3359 QualType T1 = cv1T1.getUnqualifiedType();
3360 QualType cv2T2 = Initializer->getType();
3361 QualType T2 = cv2T2.getUnqualifiedType();
3362
3363 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003364 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003365 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003367 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003368 ObjCConversion,
3369 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003371 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003372 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003373 (void)ObjCLifetimeConversion;
3374
Douglas Gregor20093b42009-12-09 23:02:17 +00003375 // Build the candidate set directly in the initialization sequence
3376 // structure, so that it will persist if we fail.
3377 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3378 CandidateSet.clear();
3379
3380 // Determine whether we are allowed to call explicit constructors or
3381 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003382 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003383 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3384
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003386 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3387 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003388 // The type we're converting to is a class type. Enumerate its constructors
3389 // to see if there is a suitable conversion.
3390 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003391
David Blaikie3bc93e32012-12-19 00:45:41 +00003392 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003393 // The container holding the constructors can under certain conditions
3394 // be changed while iterating (e.g. because of deserialization).
3395 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00003396 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00003397 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003398 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3399 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003400 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3401
Douglas Gregor20093b42009-12-09 23:02:17 +00003402 // Find the constructor (which may be a template).
3403 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003404 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003405 if (ConstructorTmpl)
3406 Constructor = cast<CXXConstructorDecl>(
3407 ConstructorTmpl->getTemplatedDecl());
3408 else
John McCall9aa472c2010-03-19 07:35:19 +00003409 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregor20093b42009-12-09 23:02:17 +00003411 if (!Constructor->isInvalidDecl() &&
3412 Constructor->isConvertingConstructor(AllowExplicit)) {
3413 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003414 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003415 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003416 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003417 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003418 else
John McCall9aa472c2010-03-19 07:35:19 +00003419 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003420 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003421 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003422 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003424 }
John McCall572fc622010-08-17 07:23:57 +00003425 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3426 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003428 const RecordType *T2RecordType = 0;
3429 if ((T2RecordType = T2->getAs<RecordType>()) &&
3430 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003431 // The type we're converting from is a class type, enumerate its conversion
3432 // functions.
3433 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3434
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003435 std::pair<CXXRecordDecl::conversion_iterator,
3436 CXXRecordDecl::conversion_iterator>
3437 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3438 for (CXXRecordDecl::conversion_iterator
3439 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003440 NamedDecl *D = *I;
3441 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3442 if (isa<UsingShadowDecl>(D))
3443 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444
Douglas Gregor20093b42009-12-09 23:02:17 +00003445 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3446 CXXConversionDecl *Conv;
3447 if (ConvTemplate)
3448 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3449 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003450 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003451
Douglas Gregor20093b42009-12-09 23:02:17 +00003452 // If the conversion function doesn't return a reference type,
3453 // it can't be considered for this conversion unless we're allowed to
3454 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455 // FIXME: Do we need to make sure that we only consider conversion
3456 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003457 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003458 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3460 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003461 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003462 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003463 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003464 else
John McCall9aa472c2010-03-19 07:35:19 +00003465 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003466 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003467 }
3468 }
3469 }
John McCall572fc622010-08-17 07:23:57 +00003470 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3471 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003472
Douglas Gregor20093b42009-12-09 23:02:17 +00003473 SourceLocation DeclLoc = Initializer->getLocStart();
3474
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003475 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003476 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003477 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003478 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003480
Douglas Gregor20093b42009-12-09 23:02:17 +00003481 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00003482 // This is the overload that will be used for this initialization step if we
3483 // use this initialization. Mark it as referenced.
3484 Function->setReferenced();
Chandler Carruth25ca4212011-02-25 19:41:05 +00003485
Eli Friedman03981012009-12-11 02:42:07 +00003486 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003487 if (isa<CXXConversionDecl>(Function))
3488 T2 = Function->getResultType();
3489 else
3490 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003491
3492 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003493 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003494 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003495 T2.getNonLValueExprType(S.Context),
3496 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003497
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003498 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003499 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003500 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003501 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003502 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003503 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003504 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003505
Douglas Gregor20093b42009-12-09 23:02:17 +00003506 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003507 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003508 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003509 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003510 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003511 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003512 NewDerivedToBase, NewObjCConversion,
3513 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003514 if (NewRefRelationship == Sema::Ref_Incompatible) {
3515 // If the type we've converted to is not reference-related to the
3516 // type we're looking for, then there is another conversion step
3517 // we need to perform to produce a temporary of the right type
3518 // that we'll be binding to.
3519 ImplicitConversionSequence ICS;
3520 ICS.setStandard();
3521 ICS.Standard = Best->FinalConversion;
3522 T2 = ICS.Standard.getToType(2);
3523 Sequence.AddConversionSequenceStep(ICS, T2);
3524 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003525 Sequence.AddDerivedToBaseCastStep(
3526 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003527 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003528 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003529 else if (NewObjCConversion)
3530 Sequence.AddObjCObjectConversionStep(
3531 S.Context.getQualifiedType(T1,
3532 T2.getNonReferenceType().getQualifiers()));
3533
Douglas Gregor20093b42009-12-09 23:02:17 +00003534 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003535 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536
Douglas Gregor20093b42009-12-09 23:02:17 +00003537 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3538 return OR_Success;
3539}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003540
Richard Smith83da2e72011-10-19 16:55:56 +00003541static void CheckCXX98CompatAccessibleCopy(Sema &S,
3542 const InitializedEntity &Entity,
3543 Expr *CurInitExpr);
3544
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003545/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3546static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003547 const InitializedEntity &Entity,
3548 const InitializationKind &Kind,
3549 Expr *Initializer,
3550 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003551 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003552 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003553 Qualifiers T1Quals;
3554 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003555 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003556 Qualifiers T2Quals;
3557 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003558
Douglas Gregor20093b42009-12-09 23:02:17 +00003559 // If the initializer is the address of an overloaded function, try
3560 // to resolve the overloaded function. If all goes well, T2 is the
3561 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003562 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3563 T1, Sequence))
3564 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003565
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003566 // Delegate everything else to a subfunction.
3567 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3568 T1Quals, cv2T2, T2, T2Quals, Sequence);
3569}
3570
Jordan Rose1fd1e282013-04-11 00:58:58 +00003571/// Converts the target of reference initialization so that it has the
3572/// appropriate qualifiers and value kind.
3573///
3574/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3575/// \code
3576/// int x;
3577/// const int &r = x;
3578/// \endcode
3579///
3580/// In this case the reference is binding to a bitfield lvalue, which isn't
3581/// valid. Perform a load to create a lifetime-extended temporary instead.
3582/// \code
3583/// const int &r = someStruct.bitfield;
3584/// \endcode
3585static ExprValueKind
3586convertQualifiersAndValueKindIfNecessary(Sema &S,
3587 InitializationSequence &Sequence,
3588 Expr *Initializer,
3589 QualType cv1T1,
3590 Qualifiers T1Quals,
3591 Qualifiers T2Quals,
3592 bool IsLValueRef) {
John McCall993f43f2013-05-06 21:39:12 +00003593 bool IsNonAddressableType = Initializer->refersToBitField() ||
Jordan Rose1fd1e282013-04-11 00:58:58 +00003594 Initializer->refersToVectorElement();
3595
3596 if (IsNonAddressableType) {
3597 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3598 // lvalue reference to a non-volatile const type, or the reference shall be
3599 // an rvalue reference.
3600 //
3601 // If not, we can't make a temporary and bind to that. Give up and allow the
3602 // error to be diagnosed later.
3603 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3604 assert(Initializer->isGLValue());
3605 return Initializer->getValueKind();
3606 }
3607
3608 // Force a load so we can materialize a temporary.
3609 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3610 return VK_RValue;
3611 }
3612
3613 if (T1Quals != T2Quals) {
3614 Sequence.AddQualificationConversionStep(cv1T1,
3615 Initializer->getValueKind());
3616 }
3617
3618 return Initializer->getValueKind();
3619}
3620
3621
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003622/// \brief Reference initialization without resolving overloaded functions.
3623static void TryReferenceInitializationCore(Sema &S,
3624 const InitializedEntity &Entity,
3625 const InitializationKind &Kind,
3626 Expr *Initializer,
3627 QualType cv1T1, QualType T1,
3628 Qualifiers T1Quals,
3629 QualType cv2T2, QualType T2,
3630 Qualifiers T2Quals,
3631 InitializationSequence &Sequence) {
3632 QualType DestType = Entity.getType();
3633 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003634 // Compute some basic properties of the types and the initializer.
3635 bool isLValueRef = DestType->isLValueReferenceType();
3636 bool isRValueRef = !isLValueRef;
3637 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003638 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003639 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003640 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003641 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003642 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003643 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003644
Douglas Gregor20093b42009-12-09 23:02:17 +00003645 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003646 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003647 // "cv2 T2" as follows:
3648 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003649 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003650 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003651 // Note the analogous bullet points for rvlaue refs to functions. Because
3652 // there are no function rvalues in C++, rvalue refs to functions are treated
3653 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003654 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003655 bool T1Function = T1->isFunctionType();
3656 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003657 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003658 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003659 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003660 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003661 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003662 // reference-compatible with "cv2 T2," or
3663 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003665 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003666 // can occur. However, we do pay attention to whether it is a bit-field
3667 // to decide whether we're actually binding to a temporary created from
3668 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003669 if (DerivedToBase)
3670 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003672 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003673 else if (ObjCConversion)
3674 Sequence.AddObjCObjectConversionStep(
3675 S.Context.getQualifiedType(T1, T2Quals));
3676
Jordan Rose1fd1e282013-04-11 00:58:58 +00003677 ExprValueKind ValueKind =
3678 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3679 cv1T1, T1Quals, T2Quals,
3680 isLValueRef);
3681 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
Douglas Gregor20093b42009-12-09 23:02:17 +00003682 return;
3683 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684
3685 // - has a class type (i.e., T2 is a class type), where T1 is not
3686 // reference-related to T2, and can be implicitly converted to an
3687 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3688 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003689 // applicable conversion functions (13.3.1.6) and choosing the best
3690 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003691 // If we have an rvalue ref to function type here, the rhs must be
3692 // an rvalue.
3693 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3694 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003696 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003697 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003698 Sequence);
3699 if (ConvOvlResult == OR_Success)
3700 return;
John McCall1d318332010-01-12 00:44:57 +00003701 if (ConvOvlResult != OR_No_Viable_Function) {
3702 Sequence.SetOverloadFailure(
3703 InitializationSequence::FK_ReferenceInitOverloadFailed,
3704 ConvOvlResult);
3705 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003706 }
3707 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003708
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003711 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003712 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003713 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3714 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3715 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 Sequence.SetOverloadFailure(
3717 InitializationSequence::FK_ReferenceInitOverloadFailed,
3718 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003719 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003720 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003721 ? (RefRelationship == Sema::Ref_Related
3722 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3723 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3724 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003725
Douglas Gregor20093b42009-12-09 23:02:17 +00003726 return;
3727 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003728
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003729 // - If the initializer expression
3730 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3731 // "cv1 T1" is reference-compatible with "cv2 T2"
3732 // Note: functions are handled below.
3733 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003734 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003735 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003736 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003737 (InitCategory.isXValue() ||
3738 (InitCategory.isPRValue() && T2->isRecordType()) ||
3739 (InitCategory.isPRValue() && T2->isArrayType()))) {
3740 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3741 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003742 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3743 // compiler the freedom to perform a copy here or bind to the
3744 // object, while C++0x requires that we bind directly to the
3745 // object. Hence, we always bind to the object without making an
3746 // extra copy. However, in C++03 requires that we check for the
3747 // presence of a suitable copy constructor:
3748 //
3749 // The constructor that would be used to make the copy shall
3750 // be callable whether or not the copy is actually done.
Richard Smith80ad52f2013-01-02 11:42:31 +00003751 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003752 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith80ad52f2013-01-02 11:42:31 +00003753 else if (S.getLangOpts().CPlusPlus11)
Richard Smith83da2e72011-10-19 16:55:56 +00003754 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003755 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003757 if (DerivedToBase)
3758 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3759 ValueKind);
3760 else if (ObjCConversion)
3761 Sequence.AddObjCObjectConversionStep(
3762 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003763
Jordan Rose1fd1e282013-04-11 00:58:58 +00003764 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3765 Initializer, cv1T1,
3766 T1Quals, T2Quals,
3767 isLValueRef);
3768
3769 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003771 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
3773 // - has a class type (i.e., T2 is a class type), where T1 is not
3774 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003775 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3776 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003777 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003778 if (RefRelationship == Sema::Ref_Incompatible) {
3779 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3780 Kind, Initializer,
3781 /*AllowRValues=*/true,
3782 Sequence);
3783 if (ConvOvlResult)
3784 Sequence.SetOverloadFailure(
3785 InitializationSequence::FK_ReferenceInitOverloadFailed,
3786 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787
Douglas Gregor20093b42009-12-09 23:02:17 +00003788 return;
3789 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003790
Douglas Gregordefa32e2013-03-26 23:59:23 +00003791 if ((RefRelationship == Sema::Ref_Compatible ||
3792 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3793 isRValueRef && InitCategory.isLValue()) {
3794 Sequence.SetFailed(
3795 InitializationSequence::FK_RValueReferenceBindingToLValue);
3796 return;
3797 }
3798
Douglas Gregor20093b42009-12-09 23:02:17 +00003799 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3800 return;
3801 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003802
3803 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003804 // from the initializer expression using the rules for a non-reference
Richard Smith4e47ecb2013-06-13 00:57:57 +00003805 // copy-initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003806 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003807
John McCall369371c2010-06-04 02:29:22 +00003808 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3809
Richard Smith4e47ecb2013-06-13 00:57:57 +00003810 // FIXME: Why do we use an implicit conversion here rather than trying
3811 // copy-initialization?
John McCallf85e1932011-06-15 23:02:42 +00003812 ImplicitConversionSequence ICS
3813 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
Richard Smith4e47ecb2013-06-13 00:57:57 +00003814 /*SuppressUserConversions=*/false,
3815 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003816 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003817 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3818 /*AllowObjCWritebackConversion=*/false);
3819
3820 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003821 // FIXME: Use the conversion function set stored in ICS to turn
3822 // this into an overloading ambiguity diagnostic. However, we need
3823 // to keep that set as an OverloadCandidateSet rather than as some
3824 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003825 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3826 Sequence.SetOverloadFailure(
3827 InitializationSequence::FK_ReferenceInitOverloadFailed,
3828 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003829 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3830 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003831 else
3832 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003833 return;
John McCallf85e1932011-06-15 23:02:42 +00003834 } else {
3835 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003836 }
3837
3838 // [...] If T1 is reference-related to T2, cv1 must be the
3839 // same cv-qualification as, or greater cv-qualification
3840 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003841 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3842 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003844 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003845 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3846 return;
3847 }
3848
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003850 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003851 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003852 InitCategory.isLValue()) {
3853 Sequence.SetFailed(
3854 InitializationSequence::FK_RValueReferenceBindingToLValue);
3855 return;
3856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
Douglas Gregor20093b42009-12-09 23:02:17 +00003858 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3859 return;
3860}
3861
3862/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863/// (C++ [dcl.init.string], C99 6.7.8).
3864static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003865 const InitializedEntity &Entity,
3866 const InitializationKind &Kind,
3867 Expr *Initializer,
3868 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003869 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003870}
3871
Douglas Gregor71d17402009-12-15 00:01:57 +00003872/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003874 const InitializedEntity &Entity,
3875 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003876 InitializationSequence &Sequence,
3877 InitListExpr *InitList) {
3878 assert((!InitList || InitList->getNumInits() == 0) &&
3879 "Shouldn't use value-init for non-empty init lists");
3880
Richard Smith1d0c9a82012-02-14 21:14:13 +00003881 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003882 //
3883 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003884 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003885
Douglas Gregor71d17402009-12-15 00:01:57 +00003886 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003887 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003888
Douglas Gregor71d17402009-12-15 00:01:57 +00003889 if (const RecordType *RT = T->getAs<RecordType>()) {
3890 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003891 bool NeedZeroInitialization = true;
Richard Smith80ad52f2013-01-02 11:42:31 +00003892 if (!S.getLangOpts().CPlusPlus11) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003893 // C++98:
3894 // -- if T is a class type (clause 9) with a user-declared constructor
3895 // (12.1), then the default constructor for T is called (and the
3896 // initialization is ill-formed if T has no accessible default
3897 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003898 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003899 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003900 } else {
3901 // C++11:
3902 // -- if T is a class type (clause 9) with either no default constructor
3903 // (12.1 [class.ctor]) or a default constructor that is user-provided
3904 // or deleted, then the object is default-initialized;
3905 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3906 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003907 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003908 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003909
Richard Smith1d0c9a82012-02-14 21:14:13 +00003910 // -- if T is a (possibly cv-qualified) non-union class type without a
3911 // user-provided or deleted default constructor, then the object is
3912 // zero-initialized and, if T has a non-trivial default constructor,
3913 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003914 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3915 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003916 if (NeedZeroInitialization)
3917 Sequence.AddZeroInitializationStep(Entity.getType());
3918
Richard Smithd5bc8672012-12-08 02:01:17 +00003919 // C++03:
3920 // -- if T is a non-union class type without a user-declared constructor,
3921 // then every non-static data member and base class component of T is
3922 // value-initialized;
3923 // [...] A program that calls for [...] value-initialization of an
3924 // entity of reference type is ill-formed.
3925 //
3926 // C++11 doesn't need this handling, because value-initialization does not
3927 // occur recursively there, and the implicit default constructor is
3928 // defined as deleted in the problematic cases.
Richard Smith80ad52f2013-01-02 11:42:31 +00003929 if (!S.getLangOpts().CPlusPlus11 &&
Richard Smithd5bc8672012-12-08 02:01:17 +00003930 ClassDecl->hasUninitializedReferenceMember()) {
3931 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3932 return;
3933 }
3934
Richard Smithf4bb8d02012-07-05 08:39:21 +00003935 // If this is list-value-initialization, pass the empty init list on when
3936 // building the constructor call. This affects the semantics of a few
3937 // things (such as whether an explicit default constructor can be called).
3938 Expr *InitListAsExpr = InitList;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003939 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
Richard Smithf4bb8d02012-07-05 08:39:21 +00003940 bool InitListSyntax = InitList;
3941
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003942 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3943 InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003944 }
3945 }
3946
Douglas Gregord6542d82009-12-22 15:35:07 +00003947 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003948}
3949
Douglas Gregor99a2e602009-12-16 01:38:02 +00003950/// \brief Attempt default initialization (C++ [dcl.init]p6).
3951static void TryDefaultInitialization(Sema &S,
3952 const InitializedEntity &Entity,
3953 const InitializationKind &Kind,
3954 InitializationSequence &Sequence) {
3955 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956
Douglas Gregor99a2e602009-12-16 01:38:02 +00003957 // C++ [dcl.init]p6:
3958 // To default-initialize an object of type T means:
3959 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003960 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3961
Douglas Gregor99a2e602009-12-16 01:38:02 +00003962 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3963 // constructor for T is called (and the initialization is ill-formed if
3964 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003965 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003966 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003967 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003968 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003969
Douglas Gregor99a2e602009-12-16 01:38:02 +00003970 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003971
Douglas Gregor99a2e602009-12-16 01:38:02 +00003972 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003974 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003975 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003976 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003977 return;
3978 }
3979
3980 // If the destination type has a lifetime property, zero-initialize it.
3981 if (DestType.getQualifiers().hasObjCLifetime()) {
3982 Sequence.AddZeroInitializationStep(Entity.getType());
3983 return;
3984 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003985}
3986
Douglas Gregor20093b42009-12-09 23:02:17 +00003987/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3988/// which enumerates all conversion functions and performs overload resolution
3989/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003990static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003991 const InitializedEntity &Entity,
3992 const InitializationKind &Kind,
3993 Expr *Initializer,
3994 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003995 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003996 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3997 QualType SourceType = Initializer->getType();
3998 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3999 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004000
Douglas Gregor4a520a22009-12-14 17:27:33 +00004001 // Build the candidate set directly in the initialization sequence
4002 // structure, so that it will persist if we fail.
4003 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4004 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005
Douglas Gregor4a520a22009-12-14 17:27:33 +00004006 // Determine whether we are allowed to call explicit constructors or
4007 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00004008 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009
Douglas Gregor4a520a22009-12-14 17:27:33 +00004010 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4011 // The type we're converting to is a class type. Enumerate its constructors
4012 // to see if there is a suitable conversion.
4013 CXXRecordDecl *DestRecordDecl
4014 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004015
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004016 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004018 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004019 // The container holding the constructors can under certain conditions
4020 // be changed while iterating. To be safe we copy the lookup results
4021 // to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004022 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004023 for (SmallVectorImpl<NamedDecl *>::iterator
David Blaikie3d5cf5e2012-10-18 16:57:32 +00004024 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004025 Con != ConEnd; ++Con) {
4026 NamedDecl *D = *Con;
4027 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004028
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004029 // Find the constructor (which may be a template).
4030 CXXConstructorDecl *Constructor = 0;
4031 FunctionTemplateDecl *ConstructorTmpl
4032 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004033 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004034 Constructor = cast<CXXConstructorDecl>(
4035 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00004036 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004037 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004039 if (!Constructor->isInvalidDecl() &&
4040 Constructor->isConvertingConstructor(AllowExplicit)) {
4041 if (ConstructorTmpl)
4042 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4043 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004044 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004045 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004046 else
4047 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004048 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00004049 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004050 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004051 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00004052 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004053 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004054
4055 SourceLocation DeclLoc = Initializer->getLocStart();
4056
Douglas Gregor4a520a22009-12-14 17:27:33 +00004057 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4058 // The type we're converting from is a class type, enumerate its conversion
4059 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004060
Eli Friedman33c2da92009-12-20 22:12:03 +00004061 // We can only enumerate the conversion functions for a complete type; if
4062 // the type isn't complete, simply skip this step.
4063 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4064 CXXRecordDecl *SourceRecordDecl
4065 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004067 std::pair<CXXRecordDecl::conversion_iterator,
4068 CXXRecordDecl::conversion_iterator>
4069 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4070 for (CXXRecordDecl::conversion_iterator
4071 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00004072 NamedDecl *D = *I;
4073 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4074 if (isa<UsingShadowDecl>(D))
4075 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004076
Eli Friedman33c2da92009-12-20 22:12:03 +00004077 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4078 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00004079 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00004080 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00004081 else
John McCall32daa422010-03-31 01:36:47 +00004082 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004083
Eli Friedman33c2da92009-12-20 22:12:03 +00004084 if (AllowExplicit || !Conv->isExplicit()) {
4085 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00004086 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00004087 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00004088 CandidateSet);
4089 else
John McCall9aa472c2010-03-19 07:35:19 +00004090 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00004091 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00004092 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004093 }
4094 }
4095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
4097 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004098 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00004099 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004100 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00004101 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004102 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00004103 Result);
4104 return;
4105 }
John McCall1d318332010-01-12 00:44:57 +00004106
Douglas Gregor4a520a22009-12-14 17:27:33 +00004107 FunctionDecl *Function = Best->Function;
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00004108 Function->setReferenced();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004109 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
Douglas Gregor4a520a22009-12-14 17:27:33 +00004111 if (isa<CXXConstructorDecl>(Function)) {
4112 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004113 // subsumed by the initialization. Per DR5, the created temporary is of the
4114 // cv-unqualified type of the destination.
4115 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4116 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004117 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00004118 return;
4119 }
4120
4121 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004122 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004123 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00004124 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004125 // the resulting temporary object (possible to create an object of
4126 // a base class type). That copy is not a separate conversion, so
4127 // we just make a note of the actual destination type (possibly a
4128 // base class of the type returned by the conversion function) and
4129 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004130 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4131 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004132 return;
4133 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00004134
Abramo Bagnara22c107b2011-11-19 11:44:21 +00004135 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4136 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004137
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004138 // If the conversion following the call to the conversion function
4139 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00004140 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4141 Best->FinalConversion.Third) {
4142 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00004143 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00004144 ICS.Standard = Best->FinalConversion;
4145 Sequence.AddConversionSequenceStep(ICS, DestType);
4146 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004147}
4148
Richard Smith87c29322013-06-20 02:18:31 +00004149/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4150/// a function with a pointer return type contains a 'return false;' statement.
4151/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4152/// code using that header.
4153///
4154/// Work around this by treating 'return false;' as zero-initializing the result
4155/// if it's used in a pointer-returning function in a system header.
4156static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4157 const InitializedEntity &Entity,
4158 const Expr *Init) {
4159 return S.getLangOpts().CPlusPlus11 &&
4160 Entity.getKind() == InitializedEntity::EK_Result &&
4161 Entity.getType()->isPointerType() &&
4162 isa<CXXBoolLiteralExpr>(Init) &&
4163 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4164 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4165}
4166
John McCallf85e1932011-06-15 23:02:42 +00004167/// The non-zero enum values here are indexes into diagnostic alternatives.
4168enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4169
4170/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00004171static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004172 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00004173 // Skip parens.
4174 e = e->IgnoreParens();
4175
4176 // Skip address-of nodes.
4177 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4178 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004179 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4180 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004181
4182 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00004183 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4184 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00004185 case CK_Dependent:
4186 case CK_BitCast:
4187 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00004188 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004189 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004190
4191 case CK_ArrayToPointerDecay:
4192 return IIK_nonscalar;
4193
4194 case CK_NullToPointer:
4195 return IIK_okay;
4196
4197 default:
4198 break;
4199 }
4200
4201 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00004202 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004203 // set isWeakAccess to true, to mean that there will be an implicit
4204 // load which requires a cleanup.
4205 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4206 isWeakAccess = true;
4207
John McCallc03fa492011-06-27 23:59:58 +00004208 if (!isAddressOf) return IIK_nonlocal;
4209
John McCallf4b88a42012-03-10 09:33:50 +00004210 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4211 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00004212
4213 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00004214
4215 // If we have a conditional operator, check both sides.
4216 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004217 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4218 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00004219 return iik;
4220
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004221 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00004222
4223 // These are never scalar.
4224 } else if (isa<ArraySubscriptExpr>(e)) {
4225 return IIK_nonscalar;
4226
4227 // Otherwise, it needs to be a null pointer constant.
4228 } else {
4229 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4230 ? IIK_okay : IIK_nonlocal);
4231 }
4232
4233 return IIK_nonlocal;
4234}
4235
4236/// Check whether the given expression is a valid operand for an
4237/// indirect copy/restore.
4238static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4239 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00004240 bool isWeakAccess = false;
4241 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4242 // If isWeakAccess to true, there will be an implicit
4243 // load which requires a cleanup.
4244 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4245 S.ExprNeedsCleanups = true;
4246
John McCallf85e1932011-06-15 23:02:42 +00004247 if (iik == IIK_okay) return;
4248
4249 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4250 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4251 << src->getSourceRange();
4252}
4253
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004254/// \brief Determine whether we have compatible array types for the
4255/// purposes of GNU by-copy array initialization.
4256static bool hasCompatibleArrayTypes(ASTContext &Context,
4257 const ArrayType *Dest,
4258 const ArrayType *Source) {
4259 // If the source and destination array types are equivalent, we're
4260 // done.
4261 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4262 return true;
4263
4264 // Make sure that the element types are the same.
4265 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4266 return false;
4267
4268 // The only mismatch we allow is when the destination is an
4269 // incomplete array type and the source is a constant array type.
4270 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4271}
4272
John McCallf85e1932011-06-15 23:02:42 +00004273static bool tryObjCWritebackConversion(Sema &S,
4274 InitializationSequence &Sequence,
4275 const InitializedEntity &Entity,
4276 Expr *Initializer) {
4277 bool ArrayDecay = false;
4278 QualType ArgType = Initializer->getType();
4279 QualType ArgPointee;
4280 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4281 ArrayDecay = true;
4282 ArgPointee = ArgArrayType->getElementType();
4283 ArgType = S.Context.getPointerType(ArgPointee);
4284 }
4285
4286 // Handle write-back conversion.
4287 QualType ConvertedArgType;
4288 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4289 ConvertedArgType))
4290 return false;
4291
4292 // We should copy unless we're passing to an argument explicitly
4293 // marked 'out'.
4294 bool ShouldCopy = true;
4295 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4296 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4297
4298 // Do we need an lvalue conversion?
4299 if (ArrayDecay || Initializer->isGLValue()) {
4300 ImplicitConversionSequence ICS;
4301 ICS.setStandard();
4302 ICS.Standard.setAsIdentityConversion();
4303
4304 QualType ResultType;
4305 if (ArrayDecay) {
4306 ICS.Standard.First = ICK_Array_To_Pointer;
4307 ResultType = S.Context.getPointerType(ArgPointee);
4308 } else {
4309 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4310 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4311 }
4312
4313 Sequence.AddConversionSequenceStep(ICS, ResultType);
4314 }
4315
4316 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4317 return true;
4318}
4319
Guy Benyei21f18c42013-02-07 10:55:47 +00004320static bool TryOCLSamplerInitialization(Sema &S,
4321 InitializationSequence &Sequence,
4322 QualType DestType,
4323 Expr *Initializer) {
4324 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4325 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4326 return false;
4327
4328 Sequence.AddOCLSamplerInitStep(DestType);
4329 return true;
4330}
4331
Guy Benyeie6b9d802013-01-20 12:31:11 +00004332//
4333// OpenCL 1.2 spec, s6.12.10
4334//
4335// The event argument can also be used to associate the
4336// async_work_group_copy with a previous async copy allowing
4337// an event to be shared by multiple async copies; otherwise
4338// event should be zero.
4339//
4340static bool TryOCLZeroEventInitialization(Sema &S,
4341 InitializationSequence &Sequence,
4342 QualType DestType,
4343 Expr *Initializer) {
4344 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4345 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4346 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4347 return false;
4348
4349 Sequence.AddOCLZeroEventStep(DestType);
4350 return true;
4351}
4352
Douglas Gregor20093b42009-12-09 23:02:17 +00004353InitializationSequence::InitializationSequence(Sema &S,
4354 const InitializedEntity &Entity,
4355 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004356 MultiExprArg Args)
John McCall5769d612010-02-08 23:07:23 +00004357 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004358 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004359
John McCall76da55d2013-04-16 07:28:30 +00004360 // Eliminate non-overload placeholder types in the arguments. We
4361 // need to do this before checking whether types are dependent
4362 // because lowering a pseudo-object expression might well give us
4363 // something of dependent type.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004364 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall76da55d2013-04-16 07:28:30 +00004365 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4366 // FIXME: should we be doing this here?
4367 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4368 if (result.isInvalid()) {
4369 SetFailed(FK_PlaceholderType);
4370 return;
4371 }
4372 Args[I] = result.take();
4373 }
4374
Douglas Gregor20093b42009-12-09 23:02:17 +00004375 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004376 // The semantics of initializers are as follows. The destination type is
4377 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004378 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004379 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004380 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004381 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004382
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004383 if (DestType->isDependentType() ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004384 Expr::hasAnyTypeDependentArguments(Args)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004385 SequenceKind = DependentSequence;
4386 return;
4387 }
4388
Sebastian Redl7491c492011-06-05 13:59:11 +00004389 // Almost everything is a normal sequence.
4390 setSequenceKind(NormalSequence);
4391
Douglas Gregor20093b42009-12-09 23:02:17 +00004392 QualType SourceType;
4393 Expr *Initializer = 0;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004394 if (Args.size() == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004395 Initializer = Args[0];
4396 if (!isa<InitListExpr>(Initializer))
4397 SourceType = Initializer->getType();
4398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004399
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004400 // - If the initializer is a (non-parenthesized) braced-init-list, the
4401 // object is list-initialized (8.5.4).
4402 if (Kind.getKind() != InitializationKind::IK_Direct) {
4403 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4404 TryListInitialization(S, Entity, Kind, InitList, *this);
4405 return;
4406 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004408
Douglas Gregor20093b42009-12-09 23:02:17 +00004409 // - If the destination type is a reference type, see 8.5.3.
4410 if (DestType->isReferenceType()) {
4411 // C++0x [dcl.init.ref]p1:
4412 // A variable declared to be a T& or T&&, that is, "reference to type T"
4413 // (8.3.2), shall be initialized by an object, or function, of type T or
4414 // by an object that can be converted into a T.
4415 // (Therefore, multiple arguments are not permitted.)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004416 if (Args.size() != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004417 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004418 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004419 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004420 return;
4421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
Douglas Gregor20093b42009-12-09 23:02:17 +00004423 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004424 if (Kind.getKind() == InitializationKind::IK_Value ||
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004425 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004426 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004427 return;
4428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004429
Douglas Gregor99a2e602009-12-16 01:38:02 +00004430 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004431 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004432 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004433 return;
4434 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004435
John McCallce6c9b72011-02-21 07:22:22 +00004436 // - If the destination type is an array of characters, an array of
4437 // char16_t, an array of char32_t, or an array of wchar_t, and the
4438 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004440 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004441 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004442 if (Initializer && isa<VariableArrayType>(DestAT)) {
4443 SetFailed(FK_VariableLengthArrayHasInitializer);
4444 return;
4445 }
4446
Hans Wennborg0ff50742013-05-15 11:03:04 +00004447 if (Initializer) {
4448 switch (IsStringInit(Initializer, DestAT, Context)) {
4449 case SIF_None:
4450 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4451 return;
4452 case SIF_NarrowStringIntoWideChar:
4453 SetFailed(FK_NarrowStringIntoWideCharArray);
4454 return;
4455 case SIF_WideStringIntoChar:
4456 SetFailed(FK_WideStringIntoCharArray);
4457 return;
4458 case SIF_IncompatWideStringIntoWideChar:
4459 SetFailed(FK_IncompatWideStringIntoWideChar);
4460 return;
4461 case SIF_Other:
4462 break;
4463 }
John McCallce6c9b72011-02-21 07:22:22 +00004464 }
4465
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004466 // Note: as an GNU C extension, we allow initialization of an
4467 // array from a compound literal that creates an array of the same
4468 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004469 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004470 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4471 Initializer->getType()->isArrayType()) {
4472 const ArrayType *SourceAT
4473 = Context.getAsArrayType(Initializer->getType());
4474 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004475 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004476 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004477 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004478 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004479 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004480 }
Richard Smith0f163e92012-02-15 22:38:09 +00004481 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004482 // Note: as a GNU C++ extension, we allow list-initialization of a
4483 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004484 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004485 Entity.getKind() == InitializedEntity::EK_Member &&
4486 Initializer && isa<InitListExpr>(Initializer)) {
4487 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4488 *this);
4489 AddParenthesizedArrayInitStep(DestType);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004490 } else if (DestAT->getElementType()->isCharType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004491 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Hans Wennborg0ff50742013-05-15 11:03:04 +00004492 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4493 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004494 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004495 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496
Douglas Gregor20093b42009-12-09 23:02:17 +00004497 return;
4498 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004499
John McCallf85e1932011-06-15 23:02:42 +00004500 // Determine whether we should consider writeback conversions for
4501 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004502 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004503 Entity.isParameterKind();
John McCallf85e1932011-06-15 23:02:42 +00004504
4505 // We're at the end of the line for C: it's either a write-back conversion
4506 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004507 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004508 // If allowed, check whether this is an Objective-C writeback conversion.
4509 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004510 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004511 return;
4512 }
Guy Benyei21f18c42013-02-07 10:55:47 +00004513
4514 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4515 return;
Guy Benyeie6b9d802013-01-20 12:31:11 +00004516
4517 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4518 return;
4519
John McCallf85e1932011-06-15 23:02:42 +00004520 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004521 AddCAssignmentStep(DestType);
4522 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004523 return;
4524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525
David Blaikie4e4d0842012-03-11 07:00:24 +00004526 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004527
Douglas Gregor20093b42009-12-09 23:02:17 +00004528 // - If the destination type is a (possibly cv-qualified) class type:
4529 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004530 // - If the initialization is direct-initialization, or if it is
4531 // copy-initialization where the cv-unqualified version of the
4532 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004533 // class of the destination, constructors are considered. [...]
4534 if (Kind.getKind() == InitializationKind::IK_Direct ||
4535 (Kind.getKind() == InitializationKind::IK_Copy &&
4536 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4537 S.IsDerivedFrom(SourceType, DestType))))
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004538 TryConstructorInitialization(S, Entity, Kind, Args,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004539 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004541 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004542 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004543 // used) to a derived class thereof are enumerated as described in
4544 // 13.3.1.4, and the best one is chosen through overload resolution
4545 // (13.3).
4546 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004547 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004548 return;
4549 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004550
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004551 if (Args.size() > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004552 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004553 return;
4554 }
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004555 assert(Args.size() == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004556
4557 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004558 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004559 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004560 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4561 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004562 return;
4563 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004564
Douglas Gregor20093b42009-12-09 23:02:17 +00004565 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004566 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004567 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004569 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004570
4571 ImplicitConversionSequence ICS
4572 = S.TryImplicitConversion(Initializer, Entity.getType(),
4573 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004574 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004575 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004576 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4577 allowObjCWritebackConversion);
4578
4579 if (ICS.isStandard() &&
4580 ICS.Standard.Second == ICK_Writeback_Conversion) {
4581 // Objective-C ARC writeback conversion.
4582
4583 // We should copy unless we're passing to an argument explicitly
4584 // marked 'out'.
4585 bool ShouldCopy = true;
4586 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4587 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4588
4589 // If there was an lvalue adjustment, add it as a separate conversion.
4590 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4591 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4592 ImplicitConversionSequence LvalueICS;
4593 LvalueICS.setStandard();
4594 LvalueICS.Standard.setAsIdentityConversion();
4595 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4596 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004597 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004598 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004599
4600 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004601 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004602 DeclAccessPair dap;
Richard Smith87c29322013-06-20 02:18:31 +00004603 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4604 AddZeroInitializationStep(Entity.getType());
4605 } else if (Initializer->getType() == Context.OverloadTy &&
4606 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4607 false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004608 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004609 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004610 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004611 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004612 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004613
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004614 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004615 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004616}
4617
4618InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004619 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004620 StepEnd = Steps.end();
4621 Step != StepEnd; ++Step)
4622 Step->Destroy();
4623}
4624
4625//===----------------------------------------------------------------------===//
4626// Perform initialization
4627//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004628static Sema::AssignmentAction
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004629getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004630 switch(Entity.getKind()) {
4631 case InitializedEntity::EK_Variable:
4632 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004633 case InitializedEntity::EK_Exception:
4634 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004635 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004636 return Sema::AA_Initializing;
4637
4638 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004639 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004640 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4641 return Sema::AA_Sending;
4642
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004643 return Sema::AA_Passing;
4644
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00004645 case InitializedEntity::EK_Parameter_CF_Audited:
4646 if (Entity.getDecl() &&
4647 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4648 return Sema::AA_Sending;
4649
4650 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4651
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004652 case InitializedEntity::EK_Result:
4653 return Sema::AA_Returning;
4654
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004655 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf5200d62013-07-11 19:13:34 +00004656 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004657 // FIXME: Can we tell apart casting vs. converting?
4658 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004660 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004661 case InitializedEntity::EK_ArrayElement:
4662 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004663 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004664 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004665 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004666 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004667 return Sema::AA_Initializing;
4668 }
4669
David Blaikie7530c032012-01-17 06:56:22 +00004670 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004671}
4672
Richard Smith774d8b42013-01-08 00:08:23 +00004673/// \brief Whether we should bind a created object as a temporary when
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004674/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004675static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004676 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004677 case InitializedEntity::EK_ArrayElement:
4678 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004679 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004680 case InitializedEntity::EK_New:
4681 case InitializedEntity::EK_Variable:
4682 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004683 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004684 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004685 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004686 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004687 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004688 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00004689 case InitializedEntity::EK_CompoundLiteralInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004690 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004691
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004692 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004693 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004694 case InitializedEntity::EK_Temporary:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004695 case InitializedEntity::EK_RelatedResult:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004696 return true;
4697 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004698
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004699 llvm_unreachable("missed an InitializedEntity kind?");
4700}
4701
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004702/// \brief Whether the given entity, when initialized with an object
4703/// created for that initialization, requires destruction.
4704static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4705 switch (Entity.getKind()) {
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004706 case InitializedEntity::EK_Result:
4707 case InitializedEntity::EK_New:
4708 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004709 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004710 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004711 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004712 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004713 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004714 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004715
Richard Smith774d8b42013-01-08 00:08:23 +00004716 case InitializedEntity::EK_Member:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004717 case InitializedEntity::EK_Variable:
4718 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004719 case InitializedEntity::EK_Parameter_CF_Audited:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004720 case InitializedEntity::EK_Temporary:
4721 case InitializedEntity::EK_ArrayElement:
4722 case InitializedEntity::EK_Exception:
Jordan Rose2624b812013-05-06 16:48:12 +00004723 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004724 case InitializedEntity::EK_RelatedResult:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004725 return true;
4726 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004727
4728 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004729}
4730
Richard Smith83da2e72011-10-19 16:55:56 +00004731/// \brief Look for copy and move constructors and constructor templates, for
4732/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4733static void LookupCopyAndMoveConstructors(Sema &S,
4734 OverloadCandidateSet &CandidateSet,
4735 CXXRecordDecl *Class,
4736 Expr *CurInitExpr) {
David Blaikie3bc93e32012-12-19 00:45:41 +00004737 DeclContext::lookup_result R = S.LookupConstructors(Class);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004738 // The container holding the constructors can under certain conditions
4739 // be changed while iterating (e.g. because of deserialization).
4740 // To be safe we copy the lookup results to a new container.
David Blaikie3bc93e32012-12-19 00:45:41 +00004741 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
Craig Topper09d19ef2013-07-04 03:08:24 +00004742 for (SmallVectorImpl<NamedDecl *>::iterator
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004743 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4744 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004745 CXXConstructorDecl *Constructor = 0;
4746
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004747 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004748 // Handle copy/moveconstructors, only.
4749 if (!Constructor || Constructor->isInvalidDecl() ||
4750 !Constructor->isCopyOrMoveConstructor() ||
4751 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4752 continue;
4753
4754 DeclAccessPair FoundDecl
4755 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4756 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004757 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004758 continue;
4759 }
4760
4761 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004762 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004763 if (ConstructorTmpl->isInvalidDecl())
4764 continue;
4765
4766 Constructor = cast<CXXConstructorDecl>(
4767 ConstructorTmpl->getTemplatedDecl());
4768 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4769 continue;
4770
4771 // FIXME: Do we need to limit this to copy-constructor-like
4772 // candidates?
4773 DeclAccessPair FoundDecl
4774 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4775 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004776 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004777 }
4778}
4779
4780/// \brief Get the location at which initialization diagnostics should appear.
4781static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4782 Expr *Initializer) {
4783 switch (Entity.getKind()) {
4784 case InitializedEntity::EK_Result:
4785 return Entity.getReturnLoc();
4786
4787 case InitializedEntity::EK_Exception:
4788 return Entity.getThrowLoc();
4789
4790 case InitializedEntity::EK_Variable:
4791 return Entity.getDecl()->getLocation();
4792
Douglas Gregor47736542012-02-15 16:57:26 +00004793 case InitializedEntity::EK_LambdaCapture:
4794 return Entity.getCaptureLoc();
4795
Richard Smith83da2e72011-10-19 16:55:56 +00004796 case InitializedEntity::EK_ArrayElement:
4797 case InitializedEntity::EK_Member:
4798 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00004799 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith83da2e72011-10-19 16:55:56 +00004800 case InitializedEntity::EK_Temporary:
4801 case InitializedEntity::EK_New:
4802 case InitializedEntity::EK_Base:
4803 case InitializedEntity::EK_Delegating:
4804 case InitializedEntity::EK_VectorElement:
4805 case InitializedEntity::EK_ComplexElement:
4806 case InitializedEntity::EK_BlockElement:
Jordan Rose2624b812013-05-06 16:48:12 +00004807 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00004808 case InitializedEntity::EK_RelatedResult:
Richard Smith83da2e72011-10-19 16:55:56 +00004809 return Initializer->getLocStart();
4810 }
4811 llvm_unreachable("missed an InitializedEntity kind?");
4812}
4813
Douglas Gregor523d46a2010-04-18 07:40:54 +00004814/// \brief Make a (potentially elidable) temporary copy of the object
4815/// provided by the given initializer by calling the appropriate copy
4816/// constructor.
4817///
4818/// \param S The Sema object used for type-checking.
4819///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004820/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004821/// the type of the initializer expression or a superclass thereof.
4822///
James Dennett1dfbd922012-06-14 21:40:34 +00004823/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004824///
4825/// \param CurInit The initializer expression.
4826///
4827/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4828/// is permitted in C++03 (but not C++0x) when binding a reference to
4829/// an rvalue.
4830///
4831/// \returns An expression that copies the initializer expression into
4832/// a temporary object, or an error expression if a copy could not be
4833/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004834static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004835 QualType T,
4836 const InitializedEntity &Entity,
4837 ExprResult CurInit,
4838 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004839 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004840 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004841 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004842 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004843 Class = cast<CXXRecordDecl>(Record->getDecl());
4844 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004845 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004846
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004847 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004848 // When certain criteria are met, an implementation is allowed to
4849 // omit the copy/move construction of a class object, even if the
4850 // copy/move constructor and/or destructor for the object have
4851 // side effects. [...]
4852 // - when a temporary class object that has not been bound to a
4853 // reference (12.2) would be copied/moved to a class object
4854 // with the same cv-unqualified type, the copy/move operation
4855 // can be omitted by constructing the temporary object
4856 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004858 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004859 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004860 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004861 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004862 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004863 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004864
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004866 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004867 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004868
Douglas Gregorcc15f012011-01-21 19:38:21 +00004869 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004870 // Only consider constructors and constructor templates. Per
4871 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4872 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004873 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004874 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004876 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4877
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004878 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004879 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004880 case OR_Success:
4881 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004882
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004883 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004884 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4885 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4886 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004887 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004888 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004889 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004890 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004891 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004892 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004893
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004894 case OR_Ambiguous:
4895 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004896 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004897 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004898 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004899 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004900
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004901 case OR_Deleted:
4902 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004903 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004904 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004905 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004906 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004907 }
4908
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004909 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004910 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004911 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004912
Anders Carlsson9a68a672010-04-21 18:47:17 +00004913 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004914 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004915
4916 if (IsExtraneousCopy) {
4917 // If this is a totally extraneous copy for C++03 reference
4918 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004919 // expression. We don't generate an (elided) copy operation here
4920 // because doing so would require us to pass down a flag to avoid
4921 // infinite recursion, where each step adds another extraneous,
4922 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004923
Douglas Gregor2559a702010-04-18 07:57:34 +00004924 // Instantiate the default arguments of any extra parameters in
4925 // the selected copy constructor, as if we were going to create a
4926 // proper call to the copy constructor.
4927 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4928 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4929 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004930 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004931 break;
4932
4933 // Build the default argument expression; we don't actually care
4934 // if this succeeds or not, because this routine will complain
4935 // if there was a problem.
4936 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4937 }
4938
Douglas Gregor523d46a2010-04-18 07:40:54 +00004939 return S.Owned(CurInitExpr);
4940 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004941
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004942 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004943 // constructor call (we might have derived-to-base conversions, or
4944 // the copy constructor may have default arguments).
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004945 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004946 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004947
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004948 // Actually perform the constructor call.
4949 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004950 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004951 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00004952 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00004953 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004954 CXXConstructExpr::CK_Complete,
4955 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004956
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004957 // If we're supposed to bind temporaries, do so.
4958 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4959 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004960 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004961}
Douglas Gregor20093b42009-12-09 23:02:17 +00004962
Richard Smith83da2e72011-10-19 16:55:56 +00004963/// \brief Check whether elidable copy construction for binding a reference to
4964/// a temporary would have succeeded if we were building in C++98 mode, for
4965/// -Wc++98-compat.
4966static void CheckCXX98CompatAccessibleCopy(Sema &S,
4967 const InitializedEntity &Entity,
4968 Expr *CurInitExpr) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004969 assert(S.getLangOpts().CPlusPlus11);
Richard Smith83da2e72011-10-19 16:55:56 +00004970
4971 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4972 if (!Record)
4973 return;
4974
4975 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4976 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4977 == DiagnosticsEngine::Ignored)
4978 return;
4979
4980 // Find constructors which would have been considered.
4981 OverloadCandidateSet CandidateSet(Loc);
4982 LookupCopyAndMoveConstructors(
4983 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4984
4985 // Perform overload resolution.
4986 OverloadCandidateSet::iterator Best;
4987 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4988
4989 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4990 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4991 << CurInitExpr->getSourceRange();
4992
4993 switch (OR) {
4994 case OR_Success:
4995 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004996 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004997 // FIXME: Check default arguments as far as that's possible.
4998 break;
4999
5000 case OR_No_Viable_Function:
5001 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005002 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005003 break;
5004
5005 case OR_Ambiguous:
5006 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00005007 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00005008 break;
5009
5010 case OR_Deleted:
5011 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005012 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00005013 break;
5014 }
5015}
5016
Douglas Gregora41a8c52010-04-22 00:20:18 +00005017void InitializationSequence::PrintInitLocationNote(Sema &S,
5018 const InitializedEntity &Entity) {
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005019 if (Entity.isParameterKind() && Entity.getDecl()) {
Douglas Gregora41a8c52010-04-22 00:20:18 +00005020 if (Entity.getDecl()->getLocation().isInvalid())
5021 return;
5022
5023 if (Entity.getDecl()->getDeclName())
5024 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5025 << Entity.getDecl()->getDeclName();
5026 else
5027 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5028 }
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005029 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5030 Entity.getMethodDecl())
5031 S.Diag(Entity.getMethodDecl()->getLocation(),
5032 diag::note_method_return_type_change)
5033 << Entity.getMethodDecl()->getDeclName();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005034}
5035
Sebastian Redl3b802322011-07-14 19:07:55 +00005036static bool isReferenceBinding(const InitializationSequence::Step &s) {
5037 return s.Kind == InitializationSequence::SK_BindReference ||
5038 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5039}
5040
Jordan Rose2624b812013-05-06 16:48:12 +00005041/// Returns true if the parameters describe a constructor initialization of
5042/// an explicit temporary object, e.g. "Point(x, y)".
5043static bool isExplicitTemporary(const InitializedEntity &Entity,
5044 const InitializationKind &Kind,
5045 unsigned NumArgs) {
5046 switch (Entity.getKind()) {
5047 case InitializedEntity::EK_Temporary:
5048 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005049 case InitializedEntity::EK_RelatedResult:
Jordan Rose2624b812013-05-06 16:48:12 +00005050 break;
5051 default:
5052 return false;
5053 }
5054
5055 switch (Kind.getKind()) {
5056 case InitializationKind::IK_DirectList:
5057 return true;
5058 // FIXME: Hack to work around cast weirdness.
5059 case InitializationKind::IK_Direct:
5060 case InitializationKind::IK_Value:
5061 return NumArgs != 1;
5062 default:
5063 return false;
5064 }
5065}
5066
Sebastian Redl10f04a62011-12-22 14:44:04 +00005067static ExprResult
5068PerformConstructorInitialization(Sema &S,
5069 const InitializedEntity &Entity,
5070 const InitializationKind &Kind,
5071 MultiExprArg Args,
5072 const InitializationSequence::Step& Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005073 bool &ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005074 bool IsListInitialization,
5075 SourceLocation LBraceLoc,
5076 SourceLocation RBraceLoc) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005077 unsigned NumArgs = Args.size();
5078 CXXConstructorDecl *Constructor
5079 = cast<CXXConstructorDecl>(Step.Function.Function);
5080 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5081
5082 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005083 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005084 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5085 ? Kind.getEqualLoc()
5086 : Kind.getLocation();
5087
5088 if (Kind.getKind() == InitializationKind::IK_Default) {
5089 // Force even a trivial, implicit default constructor to be
5090 // semantically checked. We do this explicitly because we don't build
5091 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00005092 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00005093 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00005094 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005095 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5096 }
5097
5098 ExprResult CurInit = S.Owned((Expr *)0);
5099
Douglas Gregored878af2012-02-24 23:56:31 +00005100 // C++ [over.match.copy]p1:
5101 // - When initializing a temporary to be bound to the first parameter
5102 // of a constructor that takes a reference to possibly cv-qualified
5103 // T as its first argument, called with a single argument in the
5104 // context of direct-initialization, explicit conversion functions
5105 // are also considered.
5106 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5107 Args.size() == 1 &&
5108 Constructor->isCopyOrMoveConstructor();
5109
Sebastian Redl10f04a62011-12-22 14:44:04 +00005110 // Determine the arguments required to actually perform the constructor
5111 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005112 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00005113 Loc, ConstructorArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00005114 AllowExplicitConv,
5115 IsListInitialization))
Sebastian Redl10f04a62011-12-22 14:44:04 +00005116 return ExprError();
5117
5118
Jordan Rose2624b812013-05-06 16:48:12 +00005119 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00005120 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00005121 S.MarkFunctionReferenced(Loc, Constructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005122 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5123 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005124
5125 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5126 if (!TSInfo)
5127 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Enea Zaffanella1245a542013-09-07 05:49:53 +00005128 SourceRange ParenOrBraceRange =
5129 (Kind.getKind() == InitializationKind::IK_DirectList)
5130 ? SourceRange(LBraceLoc, RBraceLoc)
5131 : Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005132
Richard Smithc83c2302012-12-19 01:39:02 +00005133 CurInit = S.Owned(
5134 new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5135 TSInfo, ConstructorArgs,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005136 ParenOrBraceRange,
Richard Smithc83c2302012-12-19 01:39:02 +00005137 HadMultipleCandidates,
Enea Zaffanella14dcaa92013-09-07 11:22:02 +00005138 IsListInitialization,
Richard Smithc83c2302012-12-19 01:39:02 +00005139 ConstructorInitRequiresZeroInit));
Sebastian Redl10f04a62011-12-22 14:44:04 +00005140 } else {
5141 CXXConstructExpr::ConstructionKind ConstructKind =
5142 CXXConstructExpr::CK_Complete;
5143
5144 if (Entity.getKind() == InitializedEntity::EK_Base) {
5145 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5146 CXXConstructExpr::CK_VirtualBase :
5147 CXXConstructExpr::CK_NonVirtualBase;
5148 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5149 ConstructKind = CXXConstructExpr::CK_Delegating;
5150 }
5151
5152 // Only get the parenthesis range if it is a direct construction.
5153 SourceRange parenRange =
5154 Kind.getKind() == InitializationKind::IK_Direct ?
5155 Kind.getParenRange() : SourceRange();
5156
5157 // If the entity allows NRVO, mark the construction as elidable
5158 // unconditionally.
5159 if (Entity.allowsNRVO())
5160 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5161 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005162 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005163 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005164 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005165 ConstructorInitRequiresZeroInit,
5166 ConstructKind,
5167 parenRange);
5168 else
5169 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5170 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005171 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005172 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005173 IsListInitialization,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005174 ConstructorInitRequiresZeroInit,
5175 ConstructKind,
5176 parenRange);
5177 }
5178 if (CurInit.isInvalid())
5179 return ExprError();
5180
5181 // Only check access if all of that succeeded.
5182 S.CheckConstructorAccess(Loc, Constructor, Entity,
5183 Step.Function.FoundDecl.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005184 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5185 return ExprError();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005186
5187 if (shouldBindAsTemporary(Entity))
Richard Smith7c3e6152013-06-12 22:31:48 +00005188 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005189
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005190 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00005191}
5192
Richard Smith36d02af2012-06-04 22:27:30 +00005193/// Determine whether the specified InitializedEntity definitely has a lifetime
5194/// longer than the current full-expression. Conservatively returns false if
5195/// it's unclear.
5196static bool
5197InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5198 const InitializedEntity *Top = &Entity;
5199 while (Top->getParent())
5200 Top = Top->getParent();
5201
5202 switch (Top->getKind()) {
5203 case InitializedEntity::EK_Variable:
5204 case InitializedEntity::EK_Result:
5205 case InitializedEntity::EK_Exception:
5206 case InitializedEntity::EK_Member:
5207 case InitializedEntity::EK_New:
5208 case InitializedEntity::EK_Base:
5209 case InitializedEntity::EK_Delegating:
5210 return true;
5211
5212 case InitializedEntity::EK_ArrayElement:
5213 case InitializedEntity::EK_VectorElement:
5214 case InitializedEntity::EK_BlockElement:
5215 case InitializedEntity::EK_ComplexElement:
5216 // Could not determine what the full initialization is. Assume it might not
5217 // outlive the full-expression.
5218 return false;
5219
5220 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005221 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith36d02af2012-06-04 22:27:30 +00005222 case InitializedEntity::EK_Temporary:
5223 case InitializedEntity::EK_LambdaCapture:
Jordan Rose2624b812013-05-06 16:48:12 +00005224 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005225 case InitializedEntity::EK_RelatedResult:
Richard Smith36d02af2012-06-04 22:27:30 +00005226 // The entity being initialized might not outlive the full-expression.
5227 return false;
5228 }
5229
5230 llvm_unreachable("unknown entity kind");
5231}
5232
Richard Smith211c8dd2013-06-05 00:46:14 +00005233/// Determine the declaration which an initialized entity ultimately refers to,
5234/// for the purpose of lifetime-extending a temporary bound to a reference in
5235/// the initialization of \p Entity.
5236static const ValueDecl *
5237getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5238 const ValueDecl *FallbackDecl = 0) {
5239 // C++11 [class.temporary]p5:
5240 switch (Entity.getKind()) {
5241 case InitializedEntity::EK_Variable:
5242 // The temporary [...] persists for the lifetime of the reference
5243 return Entity.getDecl();
5244
5245 case InitializedEntity::EK_Member:
5246 // For subobjects, we look at the complete object.
5247 if (Entity.getParent())
5248 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5249 Entity.getDecl());
5250
5251 // except:
5252 // -- A temporary bound to a reference member in a constructor's
5253 // ctor-initializer persists until the constructor exits.
5254 return Entity.getDecl();
5255
5256 case InitializedEntity::EK_Parameter:
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005257 case InitializedEntity::EK_Parameter_CF_Audited:
Richard Smith211c8dd2013-06-05 00:46:14 +00005258 // -- A temporary bound to a reference parameter in a function call
5259 // persists until the completion of the full-expression containing
5260 // the call.
5261 case InitializedEntity::EK_Result:
5262 // -- The lifetime of a temporary bound to the returned value in a
5263 // function return statement is not extended; the temporary is
5264 // destroyed at the end of the full-expression in the return statement.
5265 case InitializedEntity::EK_New:
5266 // -- A temporary bound to a reference in a new-initializer persists
5267 // until the completion of the full-expression containing the
5268 // new-initializer.
5269 return 0;
5270
5271 case InitializedEntity::EK_Temporary:
5272 case InitializedEntity::EK_CompoundLiteralInit:
Fariborz Jahanianf92a5092013-07-11 16:48:06 +00005273 case InitializedEntity::EK_RelatedResult:
Richard Smith211c8dd2013-06-05 00:46:14 +00005274 // We don't yet know the storage duration of the surrounding temporary.
5275 // Assume it's got full-expression duration for now, it will patch up our
5276 // storage duration if that's not correct.
5277 return 0;
5278
5279 case InitializedEntity::EK_ArrayElement:
5280 // For subobjects, we look at the complete object.
5281 return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5282 FallbackDecl);
5283
5284 case InitializedEntity::EK_Base:
5285 case InitializedEntity::EK_Delegating:
5286 // We can reach this case for aggregate initialization in a constructor:
5287 // struct A { int &&r; };
5288 // struct B : A { B() : A{0} {} };
5289 // In this case, use the innermost field decl as the context.
5290 return FallbackDecl;
5291
5292 case InitializedEntity::EK_BlockElement:
5293 case InitializedEntity::EK_LambdaCapture:
5294 case InitializedEntity::EK_Exception:
5295 case InitializedEntity::EK_VectorElement:
5296 case InitializedEntity::EK_ComplexElement:
Richard Smithd6b69872013-06-15 00:30:29 +00005297 return 0;
Richard Smith211c8dd2013-06-05 00:46:14 +00005298 }
Benjamin Kramer6f773e82013-06-05 15:37:50 +00005299 llvm_unreachable("unknown entity kind");
Richard Smith211c8dd2013-06-05 00:46:14 +00005300}
5301
5302static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5303
5304/// Update a glvalue expression that is used as the initializer of a reference
5305/// to note that its lifetime is extended.
Richard Smithd6b69872013-06-15 00:30:29 +00005306/// \return \c true if any temporary had its lifetime extended.
5307static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005308 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5309 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5310 // This is just redundant braces around an initializer. Step over it.
5311 Init = ILE->getInit(0);
5312 }
5313 }
5314
Richard Smithd6b69872013-06-15 00:30:29 +00005315 // Walk past any constructs which we can lifetime-extend across.
5316 Expr *Old;
5317 do {
5318 Old = Init;
5319
5320 // Step over any subobject adjustments; we may have a materialized
5321 // temporary inside them.
5322 SmallVector<const Expr *, 2> CommaLHSs;
5323 SmallVector<SubobjectAdjustment, 2> Adjustments;
5324 Init = const_cast<Expr *>(
5325 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5326
5327 // Per current approach for DR1376, look through casts to reference type
5328 // when performing lifetime extension.
5329 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5330 if (CE->getSubExpr()->isGLValue())
5331 Init = CE->getSubExpr();
5332
5333 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5334 // It's unclear if binding a reference to that xvalue extends the array
5335 // temporary.
5336 } while (Init != Old);
5337
Richard Smith211c8dd2013-06-05 00:46:14 +00005338 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5339 // Update the storage duration of the materialized temporary.
5340 // FIXME: Rebuild the expression instead of mutating it.
5341 ME->setExtendingDecl(ExtendingD);
5342 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
Richard Smithd6b69872013-06-15 00:30:29 +00005343 return true;
Richard Smith211c8dd2013-06-05 00:46:14 +00005344 }
Richard Smithd6b69872013-06-15 00:30:29 +00005345
5346 return false;
Richard Smith211c8dd2013-06-05 00:46:14 +00005347}
5348
5349/// Update a prvalue expression that is going to be materialized as a
5350/// lifetime-extended temporary.
5351static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5352 // Dig out the expression which constructs the extended temporary.
5353 SmallVector<const Expr *, 2> CommaLHSs;
5354 SmallVector<SubobjectAdjustment, 2> Adjustments;
5355 Init = const_cast<Expr *>(
5356 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5357
Richard Smith8a07cd32013-06-12 20:42:33 +00005358 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5359 Init = BTE->getSubExpr();
5360
Richard Smith7c3e6152013-06-12 22:31:48 +00005361 if (CXXStdInitializerListExpr *ILE =
Richard Smithd6b69872013-06-15 00:30:29 +00005362 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5363 performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5364 return;
5365 }
Richard Smith7c3e6152013-06-12 22:31:48 +00005366
Richard Smith211c8dd2013-06-05 00:46:14 +00005367 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith7c3e6152013-06-12 22:31:48 +00005368 if (ILE->getType()->isArrayType()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005369 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5370 performLifetimeExtension(ILE->getInit(I), ExtendingD);
5371 return;
5372 }
5373
Richard Smith7c3e6152013-06-12 22:31:48 +00005374 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005375 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5376
5377 // If we lifetime-extend a braced initializer which is initializing an
5378 // aggregate, and that aggregate contains reference members which are
5379 // bound to temporaries, those temporaries are also lifetime-extended.
5380 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5381 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5382 performReferenceExtension(ILE->getInit(0), ExtendingD);
5383 else {
5384 unsigned Index = 0;
5385 for (RecordDecl::field_iterator I = RD->field_begin(),
5386 E = RD->field_end();
5387 I != E; ++I) {
Richard Smith3c3af142013-07-01 06:08:20 +00005388 if (Index >= ILE->getNumInits())
5389 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005390 if (I->isUnnamedBitfield())
5391 continue;
Richard Smith5771aab2013-06-27 22:54:33 +00005392 Expr *SubInit = ILE->getInit(Index);
Richard Smith211c8dd2013-06-05 00:46:14 +00005393 if (I->getType()->isReferenceType())
Richard Smith5771aab2013-06-27 22:54:33 +00005394 performReferenceExtension(SubInit, ExtendingD);
5395 else if (isa<InitListExpr>(SubInit) ||
5396 isa<CXXStdInitializerListExpr>(SubInit))
Richard Smith211c8dd2013-06-05 00:46:14 +00005397 // This may be either aggregate-initialization of a member or
5398 // initialization of a std::initializer_list object. Either way,
5399 // we should recursively lifetime-extend that initializer.
Richard Smith5771aab2013-06-27 22:54:33 +00005400 performLifetimeExtension(SubInit, ExtendingD);
Richard Smith211c8dd2013-06-05 00:46:14 +00005401 ++Index;
5402 }
5403 }
5404 }
5405 }
5406}
5407
Richard Smith7c3e6152013-06-12 22:31:48 +00005408static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5409 const Expr *Init, bool IsInitializerList,
5410 const ValueDecl *ExtendingDecl) {
5411 // Warn if a field lifetime-extends a temporary.
5412 if (isa<FieldDecl>(ExtendingDecl)) {
5413 if (IsInitializerList) {
5414 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5415 << /*at end of constructor*/true;
5416 return;
5417 }
5418
5419 bool IsSubobjectMember = false;
5420 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5421 Ent = Ent->getParent()) {
5422 if (Ent->getKind() != InitializedEntity::EK_Base) {
5423 IsSubobjectMember = true;
5424 break;
5425 }
5426 }
5427 S.Diag(Init->getExprLoc(),
5428 diag::warn_bind_ref_member_to_temporary)
5429 << ExtendingDecl << Init->getSourceRange()
5430 << IsSubobjectMember << IsInitializerList;
5431 if (IsSubobjectMember)
5432 S.Diag(ExtendingDecl->getLocation(),
5433 diag::note_ref_subobject_of_member_declared_here);
5434 else
5435 S.Diag(ExtendingDecl->getLocation(),
5436 diag::note_ref_or_ptr_member_declared_here)
5437 << /*is pointer*/false;
5438 }
5439}
5440
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005441ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00005442InitializationSequence::Perform(Sema &S,
5443 const InitializedEntity &Entity,
5444 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00005445 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00005446 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005447 if (Failed()) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00005448 Diagnose(S, Entity, Kind, Args);
John McCallf312b1e2010-08-26 23:41:50 +00005449 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005451
Sebastian Redl7491c492011-06-05 13:59:11 +00005452 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005453 // If the declaration is a non-dependent, incomplete array type
5454 // that has an initializer, then its type will be completed once
5455 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00005456 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00005457 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00005458 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005459 if (const IncompleteArrayType *ArrayT
5460 = S.Context.getAsIncompleteArrayType(DeclType)) {
5461 // FIXME: We don't currently have the ability to accurately
5462 // compute the length of an initializer list without
5463 // performing full type-checking of the initializer list
5464 // (since we have to determine where braces are implicitly
5465 // introduced and such). So, we fall back to making the array
5466 // type a dependently-sized array type with no specified
5467 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005468 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00005469 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00005470
Douglas Gregord87b61f2009-12-10 17:56:55 +00005471 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00005472 if (DeclaratorDecl *DD = Entity.getDecl()) {
5473 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5474 TypeLoc TL = TInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00005475 if (IncompleteArrayTypeLoc ArrayLoc =
5476 TL.getAs<IncompleteArrayTypeLoc>())
5477 Brackets = ArrayLoc.getBracketsRange();
Douglas Gregord6542d82009-12-22 15:35:07 +00005478 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00005479 }
5480
5481 *ResultType
5482 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5483 /*NumElts=*/0,
5484 ArrayT->getSizeModifier(),
5485 ArrayT->getIndexTypeCVRQualifiers(),
5486 Brackets);
5487 }
5488
5489 }
5490 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005491 if (Kind.getKind() == InitializationKind::IK_Direct &&
5492 !Kind.isExplicitCast()) {
5493 // Rebuild the ParenListExpr.
5494 SourceRange ParenRange = Kind.getParenRange();
5495 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005496 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00005497 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00005498 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00005499 Kind.isExplicitCast() ||
5500 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005501 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005502 }
5503
Sebastian Redl7491c492011-06-05 13:59:11 +00005504 // No steps means no initialization.
5505 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00005506 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005507
Richard Smith80ad52f2013-01-02 11:42:31 +00005508 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005509 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00005510 !Entity.isParameterKind()) {
Richard Smith03544fc2012-04-19 06:58:00 +00005511 // Produce a C++98 compatibility warning if we are initializing a reference
5512 // from an initializer list. For parameters, we produce a better warning
5513 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005514 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00005515 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5516 << Init->getSourceRange();
5517 }
5518
Richard Smith36d02af2012-06-04 22:27:30 +00005519 // Diagnose cases where we initialize a pointer to an array temporary, and the
5520 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005521 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00005522 Entity.getType()->isPointerType() &&
5523 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005524 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00005525 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5526 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5527 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5528 << Init->getSourceRange();
5529 }
5530
Douglas Gregord6542d82009-12-22 15:35:07 +00005531 QualType DestType = Entity.getType().getNonReferenceType();
5532 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00005533 // the same as Entity.getDecl()->getType() in cases involving type merging,
5534 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00005535 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00005536 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00005537 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005538
John McCall60d7b3a2010-08-24 06:29:42 +00005539 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005540
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005541 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00005542 // grab the only argument out the Args and place it into the "current"
5543 // initializer.
5544 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005545 case SK_ResolveAddressOfOverloadedFunction:
5546 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005547 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005548 case SK_CastDerivedToBaseLValue:
5549 case SK_BindReference:
5550 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00005551 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005552 case SK_UserConversion:
5553 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005554 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005555 case SK_QualificationConversionRValue:
Jordan Rose1fd1e282013-04-11 00:58:58 +00005556 case SK_LValueToRValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005557 case SK_ConversionSequence:
5558 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005559 case SK_UnwrapInitList:
5560 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005561 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005562 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005563 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00005564 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00005565 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00005566 case SK_PassByIndirectCopyRestore:
5567 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00005568 case SK_ProduceObjCObject:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005569 case SK_StdInitializerList:
Guy Benyei21f18c42013-02-07 10:55:47 +00005570 case SK_OCLSamplerInit:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005571 case SK_OCLZeroEvent: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005572 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005573 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00005574 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005575 break;
John McCallf6a16482010-12-04 03:47:34 +00005576 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005577
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005578 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00005579 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005580 case SK_ZeroInitialization:
5581 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00005582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005583
5584 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00005585 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00005586 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00005587 for (step_iterator Step = step_begin(), StepEnd = step_end();
5588 Step != StepEnd; ++Step) {
5589 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005590 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005591
John Wiegley429bb272011-04-08 18:41:53 +00005592 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005593
Douglas Gregor20093b42009-12-09 23:02:17 +00005594 switch (Step->Kind) {
5595 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005596 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00005597 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00005598 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +00005599 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5600 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005601 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00005602 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00005603 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005604 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005605
Douglas Gregor20093b42009-12-09 23:02:17 +00005606 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005607 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00005608 case SK_CastDerivedToBaseLValue: {
5609 // We have a derived-to-base cast that produces either an rvalue or an
5610 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005611
John McCallf871d0c2010-08-07 06:22:56 +00005612 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005613
Douglas Gregor20093b42009-12-09 23:02:17 +00005614 // Casts to inaccessible base classes are allowed with C-style casts.
5615 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5616 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00005617 CurInit.get()->getLocStart(),
5618 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005619 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00005620 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005621
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005622 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5623 QualType T = SourceType;
5624 if (const PointerType *Pointer = T->getAs<PointerType>())
5625 T = Pointer->getPointeeType();
5626 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00005627 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005628 cast<CXXRecordDecl>(RecordTy->getDecl()));
5629 }
5630
John McCall5baba9d2010-08-25 10:28:54 +00005631 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005632 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005633 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005634 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005635 VK_XValue :
5636 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00005637 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5638 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005639 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00005640 CurInit.get(),
5641 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00005642 break;
5643 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644
Douglas Gregor20093b42009-12-09 23:02:17 +00005645 case SK_BindReference:
John McCall993f43f2013-05-06 21:39:12 +00005646 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5647 if (CurInit.get()->refersToBitField()) {
5648 // We don't necessarily have an unambiguous source bit-field.
5649 FieldDecl *BitField = CurInit.get()->getSourceBitField();
Douglas Gregor20093b42009-12-09 23:02:17 +00005650 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005651 << Entity.getType().isVolatileQualified()
John McCall993f43f2013-05-06 21:39:12 +00005652 << (BitField ? BitField->getDeclName() : DeclarationName())
5653 << (BitField != NULL)
John Wiegley429bb272011-04-08 18:41:53 +00005654 << CurInit.get()->getSourceRange();
John McCall993f43f2013-05-06 21:39:12 +00005655 if (BitField)
5656 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5657
John McCallf312b1e2010-08-26 23:41:50 +00005658 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005659 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005660
John Wiegley429bb272011-04-08 18:41:53 +00005661 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005662 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005663 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5664 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005665 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005666 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005667 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005669
Douglas Gregor20093b42009-12-09 23:02:17 +00005670 // Reference binding does not have any corresponding ASTs.
5671
5672 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005673 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005674 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005675
Richard Smithd6b69872013-06-15 00:30:29 +00005676 // Even though we didn't materialize a temporary, the binding may still
5677 // extend the lifetime of a temporary. This happens if we bind a reference
5678 // to the result of a cast to reference type.
5679 if (const ValueDecl *ExtendingDecl =
5680 getDeclForTemporaryLifetimeExtension(Entity)) {
5681 if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5682 warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5683 ExtendingDecl);
5684 }
5685
Douglas Gregor20093b42009-12-09 23:02:17 +00005686 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005687
Richard Smith211c8dd2013-06-05 00:46:14 +00005688 case SK_BindReferenceToTemporary: {
Jordan Rose1fd1e282013-04-11 00:58:58 +00005689 // Make sure the "temporary" is actually an rvalue.
5690 assert(CurInit.get()->isRValue() && "not a temporary");
5691
Douglas Gregor20093b42009-12-09 23:02:17 +00005692 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005693 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005694 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005695
Richard Smith211c8dd2013-06-05 00:46:14 +00005696 // Maybe lifetime-extend the temporary's subobjects to match the
5697 // entity's lifetime.
5698 const ValueDecl *ExtendingDecl =
5699 getDeclForTemporaryLifetimeExtension(Entity);
Richard Smitha4bb99c2013-06-12 21:51:50 +00005700 if (ExtendingDecl) {
Richard Smith211c8dd2013-06-05 00:46:14 +00005701 performLifetimeExtension(CurInit.get(), ExtendingDecl);
Richard Smith7c3e6152013-06-12 22:31:48 +00005702 warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
Richard Smitha4bb99c2013-06-12 21:51:50 +00005703 }
5704
Douglas Gregor03e80032011-06-21 17:03:29 +00005705 // Materialize the temporary into memory.
Richard Smith8a07cd32013-06-12 20:42:33 +00005706 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
Richard Smith211c8dd2013-06-05 00:46:14 +00005707 Entity.getType().getNonReferenceType(), CurInit.get(),
5708 Entity.getType()->isLValueReferenceType(), ExtendingDecl);
Douglas Gregord7b23162011-06-22 16:12:01 +00005709
5710 // If we're binding to an Objective-C object that has lifetime, we
Richard Smith8a07cd32013-06-12 20:42:33 +00005711 // need cleanups. Likewise if we're extending this temporary to automatic
5712 // storage duration -- we need to register its cleanup during the
5713 // full-expression's cleanups.
5714 if ((S.getLangOpts().ObjCAutoRefCount &&
5715 MTE->getType()->isObjCLifetimeType()) ||
5716 (MTE->getStorageDuration() == SD_Automatic &&
5717 MTE->getType().isDestructedType()))
Douglas Gregord7b23162011-06-22 16:12:01 +00005718 S.ExprNeedsCleanups = true;
Richard Smith8a07cd32013-06-12 20:42:33 +00005719
5720 CurInit = S.Owned(MTE);
Douglas Gregor20093b42009-12-09 23:02:17 +00005721 break;
Richard Smith211c8dd2013-06-05 00:46:14 +00005722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005723
Douglas Gregor523d46a2010-04-18 07:40:54 +00005724 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005725 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005726 /*IsExtraneousCopy=*/true);
5727 break;
5728
Douglas Gregor20093b42009-12-09 23:02:17 +00005729 case SK_UserConversion: {
5730 // We have a user-defined conversion that invokes either a constructor
5731 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005732 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005733 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005734 FunctionDecl *Fn = Step->Function.Function;
5735 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005736 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005737 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005739 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005740 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005741 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005742 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005743
Douglas Gregor20093b42009-12-09 23:02:17 +00005744 // Determine the arguments required to actually perform the constructor
5745 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005746 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005747 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005748 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005749 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005750 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005752 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005753 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005754 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005755 HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00005756 /*ListInit*/ false,
John McCall7a1fad32010-08-24 07:32:53 +00005757 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005758 CXXConstructExpr::CK_Complete,
5759 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005760 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005761 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005762
Anders Carlsson9a68a672010-04-21 18:47:17 +00005763 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005764 FoundFn.getAccess());
Richard Smith82f145d2013-05-04 06:44:46 +00005765 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5766 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005767
John McCall2de56d12010-08-25 11:45:40 +00005768 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005769 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5770 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5771 S.IsDerivedFrom(SourceType, Class))
5772 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005773
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005774 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005775 } else {
5776 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005777 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005778 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005779 FoundFn);
Richard Smith82f145d2013-05-04 06:44:46 +00005780 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5781 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005782
5783 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005784 // derived-to-base conversion? I believe the answer is "no", because
5785 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005786 ExprResult CurInitExprRes =
5787 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5788 FoundFn, Conversion);
5789 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005790 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005791 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005792
Douglas Gregor20093b42009-12-09 23:02:17 +00005793 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005794 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5795 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005796 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005797 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005798
John McCall2de56d12010-08-25 11:45:40 +00005799 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005800
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005801 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005802 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005803
Sebastian Redl3b802322011-07-14 19:07:55 +00005804 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005805 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5806
5807 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005808 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005809 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005810 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005811 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005812 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005813 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005814 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
Richard Smith82f145d2013-05-04 06:44:46 +00005815 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5816 return ExprError();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005817 }
5818 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005819
John McCallf871d0c2010-08-07 06:22:56 +00005820 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005821 CurInit.get()->getType(),
5822 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005823 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005824 if (MaybeBindToTemp)
5825 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005826 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005827 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005828 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005829 break;
5830 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005831
Douglas Gregor20093b42009-12-09 23:02:17 +00005832 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005833 case SK_QualificationConversionXValue:
5834 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005835 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005836 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005837 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005838 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005839 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005840 VK_XValue :
5841 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005842 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005843 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005844 }
5845
Jordan Rose1fd1e282013-04-11 00:58:58 +00005846 case SK_LValueToRValue: {
5847 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5848 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5849 CK_LValueToRValue,
5850 CurInit.take(),
5851 /*BasePath=*/0,
5852 VK_RValue));
5853 break;
5854 }
5855
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005856 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005857 Sema::CheckedConversionKind CCK
5858 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5859 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005860 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005861 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005862 ExprResult CurInitExprRes =
5863 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005864 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005865 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005866 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005867 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005868 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005870
Douglas Gregord87b61f2009-12-10 17:56:55 +00005871 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005872 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Richard Smith7c3e6152013-06-12 22:31:48 +00005873 // If we're not initializing the top-level entity, we need to create an
5874 // InitializeTemporary entity for our target type.
5875 QualType Ty = Step->Type;
5876 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005877 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
Richard Smith802e2262013-02-02 01:13:06 +00005878 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5879 InitListChecker PerformInitList(S, InitEntity,
Richard Smith40cba902013-06-06 11:41:05 +00005880 InitList, Ty, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005881 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005882 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005883
Richard Smith7c3e6152013-06-12 22:31:48 +00005884 // Hack: We must update *ResultType if available in order to set the
5885 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5886 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5887 if (ResultType &&
5888 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005889 if ((*ResultType)->isRValueReferenceType())
5890 Ty = S.Context.getRValueReferenceType(Ty);
5891 else if ((*ResultType)->isLValueReferenceType())
5892 Ty = S.Context.getLValueReferenceType(Ty,
5893 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5894 *ResultType = Ty;
5895 }
5896
5897 InitListExpr *StructuredInitList =
5898 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005899 CurInit.release();
Richard Smith802e2262013-02-02 01:13:06 +00005900 CurInit = shouldBindAsTemporary(InitEntity)
5901 ? S.MaybeBindToTemporary(StructuredInitList)
5902 : S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005903 break;
5904 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005905
Sebastian Redl10f04a62011-12-22 14:44:04 +00005906 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005907 // When an initializer list is passed for a parameter of type "reference
5908 // to object", we don't get an EK_Temporary entity, but instead an
5909 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005910 // FIXME: This is a hack. What we really should do is create a user
5911 // conversion step for this case, but this makes it considerably more
5912 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005913 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5914 Entity.getType().getNonReferenceType());
5915 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005916 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005917 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005918 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5919 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005920 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005921 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5922 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005923 Kind, Arg, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005924 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005925 /*IsListInitialization*/ true,
5926 InitList->getLBraceLoc(),
5927 InitList->getRBraceLoc());
Sebastian Redl10f04a62011-12-22 14:44:04 +00005928 break;
5929 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005930
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005931 case SK_UnwrapInitList:
5932 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5933 break;
5934
5935 case SK_RewrapInitList: {
5936 Expr *E = CurInit.take();
5937 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5938 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005939 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005940 ILE->setSyntacticForm(Syntactic);
5941 ILE->setType(E->getType());
5942 ILE->setValueKind(E->getValueKind());
5943 CurInit = S.Owned(ILE);
5944 break;
5945 }
5946
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005947 case SK_ConstructorInitialization: {
5948 // When an initializer list is passed for a parameter of type "reference
5949 // to object", we don't get an EK_Temporary entity, but instead an
5950 // EK_Parameter entity with reference type.
5951 // FIXME: This is a hack. What we really should do is create a user
5952 // conversion step for this case, but this makes it considerably more
5953 // complicated. For now, this will do.
5954 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5955 Entity.getType().getNonReferenceType());
5956 bool UseTemporary = Entity.getType()->isReferenceType();
5957 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5958 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005959 Kind, Args, *Step,
Richard Smithc83c2302012-12-19 01:39:02 +00005960 ConstructorInitRequiresZeroInit,
Enea Zaffanella1245a542013-09-07 05:49:53 +00005961 /*IsListInitialization*/ false,
5962 /*LBraceLoc*/ SourceLocation(),
5963 /*RBraceLoc*/ SourceLocation());
Douglas Gregor51c56d62009-12-14 20:49:26 +00005964 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005965 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005966
Douglas Gregor71d17402009-12-15 00:01:57 +00005967 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005968 step_iterator NextStep = Step;
5969 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005970 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005971 (NextStep->Kind == SK_ConstructorInitialization ||
5972 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005973 // The need for zero-initialization is recorded directly into
5974 // the call to the object's constructor within the next step.
5975 ConstructorInitRequiresZeroInit = true;
5976 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005977 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005978 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005979 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5980 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005981 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005982 Kind.getRange().getBegin());
5983
5984 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5985 TSInfo->getType().getNonLValueExprType(S.Context),
5986 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005987 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005988 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005989 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005990 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005991 break;
5992 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005993
5994 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005995 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005996 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005997 Sema::AssignConvertType ConvTy =
Fariborz Jahanian01ad0482013-07-31 21:40:51 +00005998 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
5999 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
John Wiegley429bb272011-04-08 18:41:53 +00006000 if (Result.isInvalid())
6001 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006002 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00006003
6004 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006005 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00006006 if (ConvTy != Sema::Compatible &&
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006007 Entity.isParameterKind() &&
John Wiegley429bb272011-04-08 18:41:53 +00006008 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00006009 == Sema::Compatible)
6010 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00006011 if (CurInitExprRes.isInvalid())
6012 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006013 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00006014
Douglas Gregora41a8c52010-04-22 00:20:18 +00006015 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006016 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6017 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00006018 CurInit.get(),
Fariborz Jahanian3d672e42013-07-31 23:19:34 +00006019 getAssignmentAction(Entity, true),
Douglas Gregora41a8c52010-04-22 00:20:18 +00006020 &Complained)) {
6021 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00006022 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00006023 } else if (Complained)
6024 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006025 break;
6026 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006027
6028 case SK_StringInit: {
6029 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00006030 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00006031 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00006032 break;
6033 }
Douglas Gregor569c3162010-08-07 11:51:51 +00006034
6035 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00006036 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00006037 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00006038 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00006039 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006040
6041 case SK_ArrayInit:
6042 // Okay: we checked everything before creating this step. Note that
6043 // this is a GNU extension.
6044 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00006045 << Step->Type << CurInit.get()->getType()
6046 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006047
6048 // If the destination type is an incomplete array type, update the
6049 // type accordingly.
6050 if (ResultType) {
6051 if (const IncompleteArrayType *IncompleteDest
6052 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6053 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00006054 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006055 *ResultType = S.Context.getConstantArrayType(
6056 IncompleteDest->getElementType(),
6057 ConstantSource->getSize(),
6058 ArrayType::Normal, 0);
6059 }
6060 }
6061 }
John McCallf85e1932011-06-15 23:02:42 +00006062 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006063
Richard Smith0f163e92012-02-15 22:38:09 +00006064 case SK_ParenthesizedArrayInit:
6065 // Okay: we checked everything before creating this step. Note that
6066 // this is a GNU extension.
6067 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6068 << CurInit.get()->getSourceRange();
6069 break;
6070
John McCallf85e1932011-06-15 23:02:42 +00006071 case SK_PassByIndirectCopyRestore:
6072 case SK_PassByIndirectRestore:
6073 checkIndirectCopyRestoreSource(S, CurInit.get());
6074 CurInit = S.Owned(new (S.Context)
6075 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6076 Step->Kind == SK_PassByIndirectCopyRestore));
6077 break;
6078
6079 case SK_ProduceObjCObject:
6080 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00006081 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00006082 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006083 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006084
6085 case SK_StdInitializerList: {
Richard Smith7c3e6152013-06-12 22:31:48 +00006086 S.Diag(CurInit.get()->getExprLoc(),
6087 diag::warn_cxx98_compat_initializer_list_init)
6088 << CurInit.get()->getSourceRange();
Sebastian Redl28357452012-03-05 19:35:43 +00006089
Richard Smith7c3e6152013-06-12 22:31:48 +00006090 // Maybe lifetime-extend the array temporary's subobjects to match the
6091 // entity's lifetime.
6092 const ValueDecl *ExtendingDecl =
6093 getDeclForTemporaryLifetimeExtension(Entity);
6094 if (ExtendingDecl) {
6095 performLifetimeExtension(CurInit.get(), ExtendingDecl);
6096 warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
Sebastian Redl28357452012-03-05 19:35:43 +00006097 }
6098
Richard Smith7c3e6152013-06-12 22:31:48 +00006099 // Materialize the temporary into memory.
6100 MaterializeTemporaryExpr *MTE = new (S.Context)
6101 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6102 /*lvalue reference*/ false, ExtendingDecl);
6103
6104 // Wrap it in a construction of a std::initializer_list<T>.
6105 CurInit = S.Owned(
6106 new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6107
6108 // Bind the result, in case the library has given initializer_list a
6109 // non-trivial destructor.
6110 if (shouldBindAsTemporary(Entity))
6111 CurInit = S.MaybeBindToTemporary(CurInit.take());
Sebastian Redl2b916b82012-01-17 22:49:42 +00006112 break;
6113 }
Richard Smith7c3e6152013-06-12 22:31:48 +00006114
Guy Benyei21f18c42013-02-07 10:55:47 +00006115 case SK_OCLSamplerInit: {
6116 assert(Step->Type->isSamplerT() &&
6117 "Sampler initialization on non sampler type.");
6118
6119 QualType SourceType = CurInit.get()->getType();
Guy Benyei21f18c42013-02-07 10:55:47 +00006120
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006121 if (Entity.isParameterKind()) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006122 if (!SourceType->isSamplerT())
6123 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6124 << SourceType;
Fariborz Jahanian2651b7a2013-07-31 18:21:45 +00006125 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
Guy Benyei21f18c42013-02-07 10:55:47 +00006126 llvm_unreachable("Invalid EntityKind!");
6127 }
6128
6129 break;
6130 }
Guy Benyeie6b9d802013-01-20 12:31:11 +00006131 case SK_OCLZeroEvent: {
6132 assert(Step->Type->isEventT() &&
6133 "Event initialization on non event type.");
6134
6135 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6136 CK_ZeroToOCLEvent,
6137 CurInit.get()->getValueKind());
6138 break;
6139 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006140 }
6141 }
John McCall15d7d122010-11-11 03:21:53 +00006142
6143 // Diagnose non-fatal problems with the completed initialization.
6144 if (Entity.getKind() == InitializedEntity::EK_Member &&
6145 cast<FieldDecl>(Entity.getDecl())->isBitField())
6146 S.CheckBitFieldInitialization(Kind.getLocation(),
6147 cast<FieldDecl>(Entity.getDecl()),
6148 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006149
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006150 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00006151}
6152
Richard Smithd5bc8672012-12-08 02:01:17 +00006153/// Somewhere within T there is an uninitialized reference subobject.
6154/// Dig it out and diagnose it.
Benjamin Kramera574c892013-02-15 12:30:38 +00006155static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6156 QualType T) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006157 if (T->isReferenceType()) {
6158 S.Diag(Loc, diag::err_reference_without_init)
6159 << T.getNonReferenceType();
6160 return true;
6161 }
6162
6163 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6164 if (!RD || !RD->hasUninitializedReferenceMember())
6165 return false;
6166
6167 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6168 FE = RD->field_end(); FI != FE; ++FI) {
6169 if (FI->isUnnamedBitfield())
6170 continue;
6171
6172 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6173 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6174 return true;
6175 }
6176 }
6177
6178 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6179 BE = RD->bases_end();
6180 BI != BE; ++BI) {
6181 if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6182 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6183 return true;
6184 }
6185 }
6186
6187 return false;
6188}
6189
6190
Douglas Gregor20093b42009-12-09 23:02:17 +00006191//===----------------------------------------------------------------------===//
6192// Diagnose initialization failures
6193//===----------------------------------------------------------------------===//
John McCall7cca8212013-03-19 07:04:25 +00006194
6195/// Emit notes associated with an initialization that failed due to a
6196/// "simple" conversion failure.
6197static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6198 Expr *op) {
6199 QualType destType = entity.getType();
6200 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6201 op->getType()->isObjCObjectPointerType()) {
6202
6203 // Emit a possible note about the conversion failing because the
6204 // operand is a message send with a related result type.
6205 S.EmitRelatedResultTypeNote(op);
6206
6207 // Emit a possible note about a return failing because we're
6208 // expecting a related result type.
6209 if (entity.getKind() == InitializedEntity::EK_Result)
6210 S.EmitRelatedResultTypeNoteForReturn(destType);
6211 }
6212}
6213
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006214bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00006215 const InitializedEntity &Entity,
6216 const InitializationKind &Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006217 ArrayRef<Expr *> Args) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00006218 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00006219 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006220
Douglas Gregord6542d82009-12-22 15:35:07 +00006221 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00006222 switch (Failure) {
6223 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006224 // FIXME: Customize for the initialized entity?
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006225 if (Args.empty()) {
Richard Smithd5bc8672012-12-08 02:01:17 +00006226 // Dig out the reference subobject which is uninitialized and diagnose it.
6227 // If this is value-initialization, this could be nested some way within
6228 // the target type.
6229 assert(Kind.getKind() == InitializationKind::IK_Value ||
6230 DestType->isReferenceType());
6231 bool Diagnosed =
6232 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6233 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6234 (void)Diagnosed;
6235 } else // FIXME: diagnostic below could be better!
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006236 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006237 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00006238 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006239
Douglas Gregor20093b42009-12-09 23:02:17 +00006240 case FK_ArrayNeedsInitList:
Hans Wennborg0ff50742013-05-15 11:03:04 +00006241 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
Douglas Gregor20093b42009-12-09 23:02:17 +00006242 break;
Hans Wennborg0ff50742013-05-15 11:03:04 +00006243 case FK_ArrayNeedsInitListOrStringLiteral:
6244 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6245 break;
6246 case FK_ArrayNeedsInitListOrWideStringLiteral:
6247 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6248 break;
6249 case FK_NarrowStringIntoWideCharArray:
6250 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6251 break;
6252 case FK_WideStringIntoCharArray:
6253 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6254 break;
6255 case FK_IncompatWideStringIntoWideChar:
6256 S.Diag(Kind.getLocation(),
6257 diag::err_array_init_incompat_wide_string_into_wchar);
6258 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006259 case FK_ArrayTypeMismatch:
6260 case FK_NonConstantArrayInit:
6261 S.Diag(Kind.getLocation(),
6262 (Failure == FK_ArrayTypeMismatch
6263 ? diag::err_array_init_different_type
6264 : diag::err_array_init_non_constant_array))
6265 << DestType.getNonReferenceType()
6266 << Args[0]->getType()
6267 << Args[0]->getSourceRange();
6268 break;
6269
John McCall73076432012-01-05 00:13:19 +00006270 case FK_VariableLengthArrayHasInitializer:
6271 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6272 << Args[0]->getSourceRange();
6273 break;
6274
John McCall6bb80172010-03-30 21:47:33 +00006275 case FK_AddressOfOverloadFailed: {
6276 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006277 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00006278 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00006279 true,
6280 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00006281 break;
John McCall6bb80172010-03-30 21:47:33 +00006282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006283
Douglas Gregor20093b42009-12-09 23:02:17 +00006284 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00006285 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00006286 switch (FailedOverloadResult) {
6287 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006288 if (Failure == FK_UserConversionOverloadFailed)
6289 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6290 << Args[0]->getType() << DestType
6291 << Args[0]->getSourceRange();
6292 else
6293 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6294 << DestType << Args[0]->getType()
6295 << Args[0]->getSourceRange();
6296
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006297 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006298 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006299
Douglas Gregor20093b42009-12-09 23:02:17 +00006300 case OR_No_Viable_Function:
Larisse Voufo288f76a2013-06-27 03:36:30 +00006301 if (!S.RequireCompleteType(Kind.getLocation(),
Larisse Voufo7419d012013-06-27 01:50:25 +00006302 DestType.getNonReferenceType(),
6303 diag::err_typecheck_nonviable_condition_incomplete,
6304 Args[0]->getType(), Args[0]->getSourceRange()))
6305 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6306 << Args[0]->getType() << Args[0]->getSourceRange()
6307 << DestType.getNonReferenceType();
6308
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006309 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor20093b42009-12-09 23:02:17 +00006310 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006311
Douglas Gregor20093b42009-12-09 23:02:17 +00006312 case OR_Deleted: {
6313 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6314 << Args[0]->getType() << DestType.getNonReferenceType()
6315 << Args[0]->getSourceRange();
6316 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006317 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006318 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6319 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00006320 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00006321 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00006322 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006323 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00006324 }
6325 break;
6326 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006327
Douglas Gregor20093b42009-12-09 23:02:17 +00006328 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00006329 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00006330 }
6331 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006332
Douglas Gregor20093b42009-12-09 23:02:17 +00006333 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006334 if (isa<InitListExpr>(Args[0])) {
6335 S.Diag(Kind.getLocation(),
6336 diag::err_lvalue_reference_bind_to_initlist)
6337 << DestType.getNonReferenceType().isVolatileQualified()
6338 << DestType.getNonReferenceType()
6339 << Args[0]->getSourceRange();
6340 break;
6341 }
6342 // Intentional fallthrough
6343
Douglas Gregor20093b42009-12-09 23:02:17 +00006344 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00006346 Failure == FK_NonConstLValueReferenceBindingToTemporary
6347 ? diag::err_lvalue_reference_bind_to_temporary
6348 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00006349 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00006350 << DestType.getNonReferenceType()
6351 << Args[0]->getType()
6352 << Args[0]->getSourceRange();
6353 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006354
Douglas Gregor20093b42009-12-09 23:02:17 +00006355 case FK_RValueReferenceBindingToLValue:
6356 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00006357 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00006358 << Args[0]->getSourceRange();
6359 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006360
Douglas Gregor20093b42009-12-09 23:02:17 +00006361 case FK_ReferenceInitDropsQualifiers:
6362 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6363 << DestType.getNonReferenceType()
6364 << Args[0]->getType()
6365 << Args[0]->getSourceRange();
6366 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006367
Douglas Gregor20093b42009-12-09 23:02:17 +00006368 case FK_ReferenceInitFailed:
6369 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6370 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00006371 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00006372 << Args[0]->getType()
6373 << Args[0]->getSourceRange();
John McCall7cca8212013-03-19 07:04:25 +00006374 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00006375 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006376
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006377 case FK_ConversionFailed: {
6378 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006379 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006380 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00006381 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00006382 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006383 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00006384 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00006385 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6386 S.Diag(Kind.getLocation(), PDiag);
John McCall7cca8212013-03-19 07:04:25 +00006387 emitBadConversionNotes(S, Entity, Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00006388 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00006389 }
John Wiegley429bb272011-04-08 18:41:53 +00006390
6391 case FK_ConversionFromPropertyFailed:
6392 // No-op. This error has already been reported.
6393 break;
6394
Douglas Gregord87b61f2009-12-10 17:56:55 +00006395 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00006396 SourceRange R;
6397
6398 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00006399 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00006400 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006401 else
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006402 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00006403
Douglas Gregor19311e72010-09-08 21:40:08 +00006404 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6405 if (Kind.isCStyleOrFunctionalCast())
6406 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6407 << R;
6408 else
6409 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6410 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00006411 break;
6412 }
6413
6414 case FK_ReferenceBindingToInitList:
6415 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6416 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6417 break;
6418
6419 case FK_InitListBadDestinationType:
6420 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6421 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6422 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006423
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006424 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00006425 case FK_ConstructorOverloadFailed: {
6426 SourceRange ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006427 if (Args.size())
6428 ArgsRange = SourceRange(Args.front()->getLocStart(),
6429 Args.back()->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006430
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006431 if (Failure == FK_ListConstructorOverloadFailed) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006432 assert(Args.size() == 1 && "List construction from other than 1 argument.");
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006433 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006434 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Sebastian Redlcf15cef2011-12-22 18:58:38 +00006435 }
6436
Douglas Gregor51c56d62009-12-14 20:49:26 +00006437 // FIXME: Using "DestType" for the entity we're printing is probably
6438 // bad.
6439 switch (FailedOverloadResult) {
6440 case OR_Ambiguous:
6441 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6442 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006443 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006444 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006445
Douglas Gregor51c56d62009-12-14 20:49:26 +00006446 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006447 if (Kind.getKind() == InitializationKind::IK_Default &&
6448 (Entity.getKind() == InitializedEntity::EK_Base ||
6449 Entity.getKind() == InitializedEntity::EK_Member) &&
6450 isa<CXXConstructorDecl>(S.CurContext)) {
6451 // This is implicit default initialization of a member or
6452 // base within a constructor. If no viable function was
6453 // found, notify the user that she needs to explicitly
6454 // initialize this base/member.
6455 CXXConstructorDecl *Constructor
6456 = cast<CXXConstructorDecl>(S.CurContext);
6457 if (Entity.getKind() == InitializedEntity::EK_Base) {
6458 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006459 << (Constructor->getInheritedConstructor() ? 2 :
6460 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006461 << S.Context.getTypeDeclType(Constructor->getParent())
6462 << /*base=*/0
6463 << Entity.getType();
6464
6465 RecordDecl *BaseDecl
6466 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6467 ->getDecl();
6468 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6469 << S.Context.getTagDeclType(BaseDecl);
6470 } else {
6471 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006472 << (Constructor->getInheritedConstructor() ? 2 :
6473 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006474 << S.Context.getTypeDeclType(Constructor->getParent())
6475 << /*member=*/1
6476 << Entity.getName();
6477 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6478
6479 if (const RecordType *Record
6480 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006481 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006482 diag::note_previous_decl)
6483 << S.Context.getTagDeclType(Record->getDecl());
6484 }
6485 break;
6486 }
6487
Douglas Gregor51c56d62009-12-14 20:49:26 +00006488 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6489 << DestType << ArgsRange;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006490 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006491 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006492
Douglas Gregor51c56d62009-12-14 20:49:26 +00006493 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00006494 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006495 OverloadingResult Ovl
6496 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00006497 if (Ovl != OR_Deleted) {
6498 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6499 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006500 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00006501 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00006502 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00006503
6504 // If this is a defaulted or implicitly-declared function, then
6505 // it was implicitly deleted. Make it clear that the deletion was
6506 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00006507 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006508 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00006509 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00006510 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00006511 else
6512 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6513 << true << DestType << ArgsRange;
6514
6515 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00006516 break;
6517 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006518
Douglas Gregor51c56d62009-12-14 20:49:26 +00006519 case OR_Success:
6520 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00006521 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00006522 }
David Blaikie9fdefb32012-01-17 08:24:58 +00006523 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006524
Douglas Gregor99a2e602009-12-16 01:38:02 +00006525 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006526 if (Entity.getKind() == InitializedEntity::EK_Member &&
6527 isa<CXXConstructorDecl>(S.CurContext)) {
6528 // This is implicit default-initialization of a const member in
6529 // a constructor. Complain that it needs to be explicitly
6530 // initialized.
6531 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6532 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
Richard Smith07b0fdc2013-03-18 21:12:30 +00006533 << (Constructor->getInheritedConstructor() ? 2 :
6534 Constructor->isImplicit() ? 1 : 0)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006535 << S.Context.getTypeDeclType(Constructor->getParent())
6536 << /*const=*/1
6537 << Entity.getName();
6538 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6539 << Entity.getName();
6540 } else {
6541 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6542 << DestType << (bool)DestType->getAs<RecordType>();
6543 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00006544 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006545
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006546 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00006547 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006548 diag::err_init_incomplete_type);
6549 break;
6550
Sebastian Redl14b0c192011-09-24 17:48:00 +00006551 case FK_ListInitializationFailed: {
6552 // Run the init list checker again to emit diagnostics.
6553 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6554 QualType DestType = Entity.getType();
6555 InitListChecker DiagnoseInitList(S, Entity, InitList,
Richard Smith40cba902013-06-06 11:41:05 +00006556 DestType, /*VerifyOnly=*/false);
Sebastian Redl14b0c192011-09-24 17:48:00 +00006557 assert(DiagnoseInitList.HadError() &&
6558 "Inconsistent init list check result.");
6559 break;
6560 }
John McCall5acb0c92011-10-17 18:40:02 +00006561
6562 case FK_PlaceholderType: {
6563 // FIXME: Already diagnosed!
6564 break;
6565 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00006566
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006567 case FK_ExplicitConstructor: {
6568 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6569 << Args[0]->getSourceRange();
6570 OverloadCandidateSet::iterator Best;
6571 OverloadingResult Ovl
6572 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00006573 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006574 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6575 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6576 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6577 break;
6578 }
Douglas Gregor20093b42009-12-09 23:02:17 +00006579 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006580
Douglas Gregora41a8c52010-04-22 00:20:18 +00006581 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00006582 return true;
6583}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006584
Chris Lattner5f9e2722011-07-23 10:55:15 +00006585void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006586 switch (SequenceKind) {
6587 case FailedSequence: {
6588 OS << "Failed sequence: ";
6589 switch (Failure) {
6590 case FK_TooManyInitsForReference:
6591 OS << "too many initializers for reference";
6592 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006593
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006594 case FK_ArrayNeedsInitList:
6595 OS << "array requires initializer list";
6596 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006597
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006598 case FK_ArrayNeedsInitListOrStringLiteral:
6599 OS << "array requires initializer list or string literal";
6600 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006601
Hans Wennborg0ff50742013-05-15 11:03:04 +00006602 case FK_ArrayNeedsInitListOrWideStringLiteral:
6603 OS << "array requires initializer list or wide string literal";
6604 break;
6605
6606 case FK_NarrowStringIntoWideCharArray:
6607 OS << "narrow string into wide char array";
6608 break;
6609
6610 case FK_WideStringIntoCharArray:
6611 OS << "wide string into char array";
6612 break;
6613
6614 case FK_IncompatWideStringIntoWideChar:
6615 OS << "incompatible wide string into wide char array";
6616 break;
6617
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006618 case FK_ArrayTypeMismatch:
6619 OS << "array type mismatch";
6620 break;
6621
6622 case FK_NonConstantArrayInit:
6623 OS << "non-constant array initializer";
6624 break;
6625
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006626 case FK_AddressOfOverloadFailed:
6627 OS << "address of overloaded function failed";
6628 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006629
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006630 case FK_ReferenceInitOverloadFailed:
6631 OS << "overload resolution for reference initialization failed";
6632 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006633
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006634 case FK_NonConstLValueReferenceBindingToTemporary:
6635 OS << "non-const lvalue reference bound to temporary";
6636 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006637
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006638 case FK_NonConstLValueReferenceBindingToUnrelated:
6639 OS << "non-const lvalue reference bound to unrelated type";
6640 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006641
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006642 case FK_RValueReferenceBindingToLValue:
6643 OS << "rvalue reference bound to an lvalue";
6644 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006645
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006646 case FK_ReferenceInitDropsQualifiers:
6647 OS << "reference initialization drops qualifiers";
6648 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006649
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006650 case FK_ReferenceInitFailed:
6651 OS << "reference initialization failed";
6652 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006653
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006654 case FK_ConversionFailed:
6655 OS << "conversion failed";
6656 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006657
John Wiegley429bb272011-04-08 18:41:53 +00006658 case FK_ConversionFromPropertyFailed:
6659 OS << "conversion from property failed";
6660 break;
6661
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006662 case FK_TooManyInitsForScalar:
6663 OS << "too many initializers for scalar";
6664 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006665
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006666 case FK_ReferenceBindingToInitList:
6667 OS << "referencing binding to initializer list";
6668 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006669
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006670 case FK_InitListBadDestinationType:
6671 OS << "initializer list for non-aggregate, non-scalar type";
6672 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006673
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006674 case FK_UserConversionOverloadFailed:
6675 OS << "overloading failed for user-defined conversion";
6676 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006677
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006678 case FK_ConstructorOverloadFailed:
6679 OS << "constructor overloading failed";
6680 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006681
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006682 case FK_DefaultInitOfConst:
6683 OS << "default initialization of a const variable";
6684 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006685
Douglas Gregor72a43bb2010-05-20 22:12:02 +00006686 case FK_Incomplete:
6687 OS << "initialization of incomplete type";
6688 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006689
6690 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00006691 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00006692 break;
6693
John McCall73076432012-01-05 00:13:19 +00006694 case FK_VariableLengthArrayHasInitializer:
6695 OS << "variable length array has an initializer";
6696 break;
6697
John McCall5acb0c92011-10-17 18:40:02 +00006698 case FK_PlaceholderType:
6699 OS << "initializer expression isn't contextually valid";
6700 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00006701
6702 case FK_ListConstructorOverloadFailed:
6703 OS << "list constructor overloading failed";
6704 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006705
Sebastian Redl70e24fc2012-04-01 19:54:59 +00006706 case FK_ExplicitConstructor:
6707 OS << "list copy initialization chose explicit constructor";
6708 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006709 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006710 OS << '\n';
6711 return;
6712 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006713
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006714 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00006715 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006716 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006717
Sebastian Redl7491c492011-06-05 13:59:11 +00006718 case NormalSequence:
6719 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006720 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006721 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006722
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006723 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6724 if (S != step_begin()) {
6725 OS << " -> ";
6726 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006727
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006728 switch (S->Kind) {
6729 case SK_ResolveAddressOfOverloadedFunction:
6730 OS << "resolve address of overloaded function";
6731 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006732
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006733 case SK_CastDerivedToBaseRValue:
6734 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6735 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006736
Sebastian Redl906082e2010-07-20 04:20:21 +00006737 case SK_CastDerivedToBaseXValue:
6738 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6739 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006740
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006741 case SK_CastDerivedToBaseLValue:
6742 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6743 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006744
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006745 case SK_BindReference:
6746 OS << "bind reference to lvalue";
6747 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006748
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006749 case SK_BindReferenceToTemporary:
6750 OS << "bind reference to a temporary";
6751 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006752
Douglas Gregor523d46a2010-04-18 07:40:54 +00006753 case SK_ExtraneousCopyToTemporary:
6754 OS << "extraneous C++03 copy to temporary";
6755 break;
6756
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006757 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006758 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006759 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006760
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006761 case SK_QualificationConversionRValue:
6762 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006763 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006764
Sebastian Redl906082e2010-07-20 04:20:21 +00006765 case SK_QualificationConversionXValue:
6766 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006767 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006768
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006769 case SK_QualificationConversionLValue:
6770 OS << "qualification conversion (lvalue)";
6771 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006772
Jordan Rose1fd1e282013-04-11 00:58:58 +00006773 case SK_LValueToRValue:
6774 OS << "load (lvalue to rvalue)";
6775 break;
6776
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006777 case SK_ConversionSequence:
6778 OS << "implicit conversion sequence (";
6779 S->ICS->DebugPrint(); // FIXME: use OS
6780 OS << ")";
6781 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006782
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006783 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006784 OS << "list aggregate initialization";
6785 break;
6786
6787 case SK_ListConstructorCall:
6788 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006789 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006790
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006791 case SK_UnwrapInitList:
6792 OS << "unwrap reference initializer list";
6793 break;
6794
6795 case SK_RewrapInitList:
6796 OS << "rewrap reference initializer list";
6797 break;
6798
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006799 case SK_ConstructorInitialization:
6800 OS << "constructor initialization";
6801 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006802
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006803 case SK_ZeroInitialization:
6804 OS << "zero initialization";
6805 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006806
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006807 case SK_CAssignment:
6808 OS << "C assignment";
6809 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006810
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006811 case SK_StringInit:
6812 OS << "string initialization";
6813 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006814
6815 case SK_ObjCObjectConversion:
6816 OS << "Objective-C object conversion";
6817 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006818
6819 case SK_ArrayInit:
6820 OS << "array initialization";
6821 break;
John McCallf85e1932011-06-15 23:02:42 +00006822
Richard Smith0f163e92012-02-15 22:38:09 +00006823 case SK_ParenthesizedArrayInit:
6824 OS << "parenthesized array initialization";
6825 break;
6826
John McCallf85e1932011-06-15 23:02:42 +00006827 case SK_PassByIndirectCopyRestore:
6828 OS << "pass by indirect copy and restore";
6829 break;
6830
6831 case SK_PassByIndirectRestore:
6832 OS << "pass by indirect restore";
6833 break;
6834
6835 case SK_ProduceObjCObject:
6836 OS << "Objective-C object retension";
6837 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006838
6839 case SK_StdInitializerList:
6840 OS << "std::initializer_list from initializer list";
6841 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00006842
Guy Benyei21f18c42013-02-07 10:55:47 +00006843 case SK_OCLSamplerInit:
6844 OS << "OpenCL sampler_t from integer constant";
6845 break;
6846
Guy Benyeie6b9d802013-01-20 12:31:11 +00006847 case SK_OCLZeroEvent:
6848 OS << "OpenCL event_t from zero";
6849 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006850 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006851
6852 OS << " [" << S->Type.getAsString() << ']';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006853 }
Richard Smitha4dc51b2013-02-05 05:52:24 +00006854
6855 OS << '\n';
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006856}
6857
6858void InitializationSequence::dump() const {
6859 dump(llvm::errs());
6860}
6861
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006862static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6863 QualType EntityType,
6864 const Expr *PreInit,
6865 const Expr *PostInit) {
6866 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6867 return;
6868
6869 // A narrowing conversion can only appear as the final implicit conversion in
6870 // an initialization sequence.
6871 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6872 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6873 return;
6874
6875 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6876 const StandardConversionSequence *SCS = 0;
6877 switch (ICS.getKind()) {
6878 case ImplicitConversionSequence::StandardConversion:
6879 SCS = &ICS.Standard;
6880 break;
6881 case ImplicitConversionSequence::UserDefinedConversion:
6882 SCS = &ICS.UserDefined.After;
6883 break;
6884 case ImplicitConversionSequence::AmbiguousConversion:
6885 case ImplicitConversionSequence::EllipsisConversion:
6886 case ImplicitConversionSequence::BadConversion:
6887 return;
6888 }
6889
6890 // Determine the type prior to the narrowing conversion. If a conversion
6891 // operator was used, this may be different from both the type of the entity
6892 // and of the pre-initialization expression.
6893 QualType PreNarrowingType = PreInit->getType();
6894 if (Seq.step_begin() + 1 != Seq.step_end())
6895 PreNarrowingType = Seq.step_end()[-2].Type;
6896
6897 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6898 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006899 QualType ConstantType;
6900 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6901 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006902 case NK_Not_Narrowing:
6903 // No narrowing occurred.
6904 return;
6905
6906 case NK_Type_Narrowing:
6907 // This was a floating-to-integer conversion, which is always considered a
6908 // narrowing conversion even if the value is a constant and can be
6909 // represented exactly as an integer.
6910 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006911 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006912 diag::warn_init_list_type_narrowing
6913 : S.isSFINAEContext()?
6914 diag::err_init_list_type_narrowing_sfinae
6915 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006916 << PostInit->getSourceRange()
6917 << PreNarrowingType.getLocalUnqualifiedType()
6918 << EntityType.getLocalUnqualifiedType();
6919 break;
6920
6921 case NK_Constant_Narrowing:
6922 // A constant value was narrowed.
6923 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006924 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006925 diag::warn_init_list_constant_narrowing
6926 : S.isSFINAEContext()?
6927 diag::err_init_list_constant_narrowing_sfinae
6928 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006929 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006930 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006931 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006932 break;
6933
6934 case NK_Variable_Narrowing:
6935 // A variable's value may have been narrowed.
6936 S.Diag(PostInit->getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006937 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006938 diag::warn_init_list_variable_narrowing
6939 : S.isSFINAEContext()?
6940 diag::err_init_list_variable_narrowing_sfinae
6941 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006942 << PostInit->getSourceRange()
6943 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006944 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006945 break;
6946 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006947
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006948 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006949 llvm::raw_svector_ostream OS(StaticCast);
6950 OS << "static_cast<";
6951 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6952 // It's important to use the typedef's name if there is one so that the
6953 // fixit doesn't break code using types like int64_t.
6954 //
6955 // FIXME: This will break if the typedef requires qualification. But
6956 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006957 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006958 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006959 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006960 else {
6961 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6962 // with a broken cast.
6963 return;
6964 }
6965 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006966 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6967 << PostInit->getSourceRange()
6968 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006969 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006970 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006971}
6972
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006973//===----------------------------------------------------------------------===//
6974// Initialization helper functions
6975//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006976bool
6977Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6978 ExprResult Init) {
6979 if (Init.isInvalid())
6980 return false;
6981
6982 Expr *InitE = Init.get();
6983 assert(InitE && "No initialization expression");
6984
Douglas Gregor3c394c52012-07-31 22:15:04 +00006985 InitializationKind Kind
6986 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00006987 InitializationSequence Seq(*this, Entity, Kind, InitE);
Sebastian Redl383616c2011-06-05 12:23:28 +00006988 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006989}
6990
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006991ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006992Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6993 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006994 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006995 bool TopLevelOfInitList,
6996 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006997 if (Init.isInvalid())
6998 return ExprError();
6999
John McCall15d7d122010-11-11 03:21:53 +00007000 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007001 assert(InitE && "No initialization expression?");
7002
7003 if (EqualLoc.isInvalid())
7004 EqualLoc = InitE->getLocStart();
7005
7006 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00007007 EqualLoc,
7008 AllowExplicit);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007009 InitializationSequence Seq(*this, Entity, Kind, InitE);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007010 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00007011
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00007012 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00007013
7014 if (!Result.isInvalid() && TopLevelOfInitList)
7015 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
7016 InitE, Result.get());
7017
7018 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00007019}