blob: 6344aa44b190d92796f6fba4fd469a207f25fc32 [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
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.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
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
Benjamin Kramer65263b42012-08-04 17:00:46 +000095 llvm::APInt ConstVal(32, StrLength);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000100 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Eli Friedman8718a6a2009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000105 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
David Blaikie4e4d0842012-03-11 07:00:24 +0000108 if (S.getLangOpts().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
112 //
113 // unsigned char a[2] = "\pa";
114 if (SL->isPascal())
115 StrLength--;
116 }
117
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000120 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
123 } else {
124 // C99 6.7.8p14.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000126 S.Diag(Str->getLocStart(),
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
129 }
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Eli Friedman8718a6a2009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000136}
137
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregor9e80f722009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000156/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000169namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000173 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000174 bool AllowBraceElision;
Benjamin Kramera7894162012-02-23 14:48:40 +0000175 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000176 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000178 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000179 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000181 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
201 unsigned &Index,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000205 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000211 unsigned &Index,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000214 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000215 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000218 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000219 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000226 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000227 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000232 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000233 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000234 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
237 unsigned &Index,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000240 bool FinishSubobjectInit,
241 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000249 Expr *expr);
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000261 void CheckValueInitializable(const InitializedEntity &Entity);
262
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000263public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000264 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000267 bool HadError() { return hadError; }
268
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272};
Chris Lattner8b419b92009-02-24 22:48:58 +0000273} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000274
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000275void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276 assert(VerifyOnly &&
277 "CheckValueInitializable is only inteded for verification mode.");
278
279 SourceLocation Loc;
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
284 hadError = true;
285}
286
Douglas Gregord6d37de2009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 bool &RequiresSecondPass) {
Daniel Dunbar96a00142012-03-09 18:35:03 +0000291 SourceLocation Loc = ILE->getLocStart();
Douglas Gregord6d37de2009-12-22 00:05:34 +0000292 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
296 // FIXME: We probably don't need to handle references
297 // specially here, since value-initialization of references is
298 // handled in InitializationSequence.
299 if (Field->getType()->isReferenceType()) {
300 // C++ [dcl.init.aggr]p9:
301 // If an incomplete or empty initializer-list leaves a
302 // member of reference type uninitialized, the program is
303 // ill-formed.
304 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
305 << Field->getType()
306 << ILE->getSyntacticForm()->getSourceRange();
307 SemaRef.Diag(Field->getLocation(),
308 diag::note_uninit_reference_member);
309 hadError = true;
310 return;
311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000312
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
314 true);
315 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
316 if (!InitSeq) {
317 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
318 hadError = true;
319 return;
320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321
John McCall60d7b3a2010-08-24 06:29:42 +0000322 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000323 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000324 if (MemberInit.isInvalid()) {
325 hadError = true;
326 return;
327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 if (hadError) {
330 // Do nothing
331 } else if (Init < NumInits) {
332 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000333 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000334 // Value-initialization requires a constructor call, so
335 // extend the initializer list to include the constructor
336 // call and make a note that we'll need to take another pass
337 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000338 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000339 RequiresSecondPass = true;
340 }
341 } else if (InitListExpr *InnerILE
342 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343 FillInValueInitializations(MemberEntity, InnerILE,
344 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345}
346
Douglas Gregor4c678342009-01-28 21:54:33 +0000347/// Recursively replaces NULL values within the given initializer list
348/// with expressions that perform value-initialization of the
349/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
352 InitListExpr *ILE,
353 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000355 "Should not have void type");
Daniel Dunbar96a00142012-03-09 18:35:03 +0000356 SourceLocation Loc = ILE->getLocStart();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357 if (ILE->getSyntacticForm())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000358 Loc = ILE->getSyntacticForm()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Ted Kremenek6217b802009-07-29 21:53:49 +0000360 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361 if (RType->getDecl()->isUnion() &&
362 ILE->getInitializedFieldInUnion())
363 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
364 Entity, ILE, RequiresSecondPass);
365 else {
366 unsigned Init = 0;
367 for (RecordDecl::field_iterator
368 Field = RType->getDecl()->field_begin(),
369 FieldEnd = RType->getDecl()->field_end();
370 Field != FieldEnd; ++Field) {
371 if (Field->isUnnamedBitfield())
372 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000373
Douglas Gregord6d37de2009-12-22 00:05:34 +0000374 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000375 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000376
David Blaikie581deb32012-06-06 20:45:41 +0000377 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000378 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380
Douglas Gregord6d37de2009-12-22 00:05:34 +0000381 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000382
Douglas Gregord6d37de2009-12-22 00:05:34 +0000383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
386 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 }
388
389 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000391
392 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000394 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 unsigned NumInits = ILE->getNumInits();
396 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000397 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000398 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
400 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000402 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000403 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000404 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000408 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000409 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000410
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000411
Douglas Gregor87fd7032009-02-02 17:43:21 +0000412 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000413 if (hadError)
414 return;
415
Anders Carlssond3d824d2010-01-23 04:34:47 +0000416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
417 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 ElementEntity.setElementIndex(Init);
419
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000420 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
421 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000422 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
423 true);
424 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
425 if (!InitSeq) {
426 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000427 hadError = true;
428 return;
429 }
430
John McCall60d7b3a2010-08-24 06:29:42 +0000431 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000432 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000433 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000434 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000435 return;
436 }
437
438 if (hadError) {
439 // Do nothing
440 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000441 // For arrays, just set the expression used for value-initialization
442 // of the "holes" in the array.
443 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
444 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
445 else
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000447 } else {
448 // For arrays, just set the expression used for value-initialization
449 // of the rest of elements and exit.
450 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
451 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
452 return;
453 }
454
Sebastian Redl7491c492011-06-05 13:59:11 +0000455 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000456 // Value-initialization requires a constructor call, so
457 // extend the initializer list to include the constructor
458 // call and make a note that we'll need to take another pass
459 // through the initializer list.
460 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
461 RequiresSecondPass = true;
462 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000463 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000464 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000465 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000466 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000467 }
468}
469
Chris Lattner68355a52009-01-29 05:10:57 +0000470
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000472 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000473 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000474 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000475 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000476
Eli Friedmanb85f7072008-05-19 19:16:24 +0000477 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000479 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000481 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000482 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000483 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000484
Sebastian Redl14b0c192011-09-24 17:48:00 +0000485 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000486 bool RequiresSecondPass = false;
487 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000488 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490 RequiresSecondPass);
491 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000492}
493
494int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000495 // FIXME: use a proper constant
496 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000497 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000498 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
500 }
501 return maxElements;
502}
503
504int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000508 Field = structDecl->field_begin(),
509 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000511 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000512 ++InitializableMembers;
513 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000514 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000515 return std::min(InitializableMembers, 1);
516 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000517}
518
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000519void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000520 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 QualType T, unsigned &Index,
522 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000523 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000524 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Steve Naroff0cca7492008-05-01 22:18:59 +0000526 if (T->isArrayType())
527 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000528 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000529 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000530 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000531 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000532 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000533 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000534
Eli Friedman402256f2008-05-25 13:49:22 +0000535 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000536 if (!VerifyOnly)
537 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
538 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000539 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000540 hadError = true;
541 return;
542 }
543
Douglas Gregor4c678342009-01-28 21:54:33 +0000544 // Build a structured initializer list corresponding to this subobject.
545 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000546 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
547 StructuredIndex,
Daniel Dunbar96a00142012-03-09 18:35:03 +0000548 SourceRange(ParentIList->getInit(Index)->getLocStart(),
Douglas Gregored8a93d2009-03-01 17:12:46 +0000549 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000550 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000551
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000553 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000555 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000556 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000557 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000558
559 if (VerifyOnly) {
560 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
561 hadError = true;
562 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000563 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000564
Sebastian Redlc2235182011-10-16 18:19:28 +0000565 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000566 // Update the structured sub-object initializer so that it's ending
567 // range corresponds with the end of the last initializer it used.
568 if (EndIndex < ParentIList->getNumInits()) {
569 SourceLocation EndLoc
570 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
571 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573
Sebastian Redlc2235182011-10-16 18:19:28 +0000574 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000575 if (T->isArrayType() || T->isRecordType()) {
576 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000577 AllowBraceElision ? diag::warn_missing_braces :
578 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000579 << StructuredSubobjectInitList->getSourceRange()
580 << FixItHint::CreateInsertion(
581 StructuredSubobjectInitList->getLocStart(), "{")
582 << FixItHint::CreateInsertion(
583 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000585 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000586 if (!AllowBraceElision)
587 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000588 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000589 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000590}
591
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000592void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000593 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 unsigned &Index,
595 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000599 if (!VerifyOnly) {
600 SyntacticToSemantic[IList] = StructuredList;
601 StructuredList->setSyntacticForm(IList);
602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000604 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000605 if (!VerifyOnly) {
Eli Friedman5c89c392012-02-23 02:25:10 +0000606 QualType ExprTy = T;
607 if (!ExprTy->isArrayType())
608 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000609 IList->setType(ExprTy);
610 StructuredList->setType(ExprTy);
611 }
Eli Friedman638e1442008-05-25 13:22:35 +0000612 if (hadError)
613 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000614
Eli Friedman638e1442008-05-25 13:22:35 +0000615 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000616 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000617 if (VerifyOnly) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000618 if (SemaRef.getLangOpts().CPlusPlus ||
619 (SemaRef.getLangOpts().OpenCL &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000620 IList->getType()->isVectorType())) {
621 hadError = true;
622 }
623 return;
624 }
625
Eli Friedmane5408582009-05-29 20:20:05 +0000626 if (StructuredIndex == 1 &&
627 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000628 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
David Blaikie4e4d0842012-03-11 07:00:24 +0000629 if (SemaRef.getLangOpts().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000630 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000631 hadError = true;
632 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000633 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000634 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000635 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000636 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000637 // Don't complain for incomplete types, since we'll get an error
638 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000640 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000641 CurrentObjectType->isArrayType()? 0 :
642 CurrentObjectType->isVectorType()? 1 :
643 CurrentObjectType->isScalarType()? 2 :
644 CurrentObjectType->isUnionType()? 3 :
645 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000646
647 unsigned DK = diag::warn_excess_initializers;
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmane5408582009-05-29 20:20:05 +0000649 DK = diag::err_excess_initializers;
650 hadError = true;
651 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000652 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
Nate Begeman08634522009-07-07 21:53:06 +0000653 DK = diag::err_excess_initializers;
654 hadError = true;
655 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000656
Chris Lattner08202542009-02-24 22:50:46 +0000657 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000658 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000659 }
660 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000661
Sebastian Redl14b0c192011-09-24 17:48:00 +0000662 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
663 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000664 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000665 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000666 << FixItHint::CreateRemoval(IList->getLocStart())
667 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000668}
669
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000670void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000671 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000672 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000673 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000676 unsigned &StructuredIndex,
677 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000678 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
679 // Explicitly braced initializer for complex type can be real+imaginary
680 // parts.
681 CheckComplexType(Entity, IList, DeclType, Index,
682 StructuredList, StructuredIndex);
683 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000684 CheckScalarType(Entity, IList, DeclType, Index,
685 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000686 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000687 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000688 StructuredList, StructuredIndex);
Richard Smith20599392012-07-07 08:35:56 +0000689 } else if (DeclType->isRecordType()) {
690 assert(DeclType->isAggregateType() &&
691 "non-aggregate records should be handed in CheckSubElementType");
692 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
693 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
694 SubobjectIsDesignatorContext, Index,
695 StructuredList, StructuredIndex,
696 TopLevelObject);
697 } else if (DeclType->isArrayType()) {
698 llvm::APSInt Zero(
699 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
700 false);
701 CheckArrayType(Entity, IList, DeclType, Zero,
702 SubobjectIsDesignatorContext, Index,
703 StructuredList, StructuredIndex);
Steve Naroff61353522008-08-10 16:05:48 +0000704 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
705 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000706 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000710 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000711 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000712 CheckReferenceType(Entity, IList, DeclType, Index,
713 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000714 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000715 if (!VerifyOnly)
716 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
717 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000718 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000719 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000720 if (!VerifyOnly)
721 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
722 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000723 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000724 }
725}
726
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000727void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000728 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000729 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000730 unsigned &Index,
731 InitListExpr *StructuredList,
732 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000733 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000734 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
Richard Smith20599392012-07-07 08:35:56 +0000735 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
736 unsigned newIndex = 0;
737 unsigned newStructuredIndex = 0;
738 InitListExpr *newStructuredList
739 = getStructuredSubobjectInit(IList, Index, ElemType,
740 StructuredList, StructuredIndex,
741 SubInitList->getSourceRange());
742 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
743 newStructuredList, newStructuredIndex);
744 ++StructuredIndex;
745 ++Index;
746 return;
747 }
748 assert(SemaRef.getLangOpts().CPlusPlus &&
749 "non-aggregate records are only possible in C++");
750 // C++ initialization is handled later.
751 }
752
753 if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000754 return CheckScalarType(Entity, IList, ElemType, Index,
755 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000756 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000757 return CheckReferenceType(Entity, IList, ElemType, Index,
758 StructuredList, StructuredIndex);
759 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000760
John McCallfef8b342011-02-21 07:57:55 +0000761 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
762 // arrayType can be incomplete if we're initializing a flexible
763 // array member. There's nothing we can do with the completed
764 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765
John McCallfef8b342011-02-21 07:57:55 +0000766 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000767 if (!VerifyOnly) {
768 CheckStringInit(Str, ElemType, arrayType, SemaRef);
769 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
770 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000771 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000772 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000773 }
John McCallfef8b342011-02-21 07:57:55 +0000774
775 // Fall through for subaggregate initialization.
776
David Blaikie4e4d0842012-03-11 07:00:24 +0000777 } else if (SemaRef.getLangOpts().CPlusPlus) {
John McCallfef8b342011-02-21 07:57:55 +0000778 // C++ [dcl.init.aggr]p12:
779 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000780 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000781 // an initializer-list. If the initializer can initialize a
782 // member, the member is initialized. [...]
783
784 // FIXME: Better EqualLoc?
785 InitializationKind Kind =
786 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
787 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
788
789 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000790 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000791 ExprResult Result =
792 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
793 if (Result.isInvalid())
794 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000795
Sebastian Redl14b0c192011-09-24 17:48:00 +0000796 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000797 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000798 }
John McCallfef8b342011-02-21 07:57:55 +0000799 ++Index;
800 return;
801 }
802
803 // Fall through for subaggregate initialization
804 } else {
805 // C99 6.7.8p13:
806 //
807 // The initializer for a structure or union object that has
808 // automatic storage duration shall be either an initializer
809 // list as described below, or a single expression that has
810 // compatible structure or union type. In the latter case, the
811 // initial value of the object, including unnamed members, is
812 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000813 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000814 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000815 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
816 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000817 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000818 if (ExprRes.isInvalid())
819 hadError = true;
820 else {
821 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
822 if (ExprRes.isInvalid())
823 hadError = true;
824 }
825 UpdateStructuredListElement(StructuredList, StructuredIndex,
826 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000827 ++Index;
828 return;
829 }
John Wiegley429bb272011-04-08 18:41:53 +0000830 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000831 // Fall through for subaggregate initialization
832 }
833
834 // C++ [dcl.init.aggr]p12:
835 //
836 // [...] Otherwise, if the member is itself a non-empty
837 // subaggregate, brace elision is assumed and the initializer is
838 // considered for the initialization of the first member of
839 // the subaggregate.
David Blaikie4e4d0842012-03-11 07:00:24 +0000840 if (!SemaRef.getLangOpts().OpenCL &&
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000841 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000842 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
843 StructuredIndex);
844 ++StructuredIndex;
845 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000846 if (!VerifyOnly) {
847 // We cannot initialize this element, so let
848 // PerformCopyInitialization produce the appropriate diagnostic.
849 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
850 SemaRef.Owned(expr),
851 /*TopLevelOfInitList=*/true);
852 }
John McCallfef8b342011-02-21 07:57:55 +0000853 hadError = true;
854 ++Index;
855 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000856 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000857}
858
Eli Friedman0c706c22011-09-19 23:17:44 +0000859void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
860 InitListExpr *IList, QualType DeclType,
861 unsigned &Index,
862 InitListExpr *StructuredList,
863 unsigned &StructuredIndex) {
864 assert(Index == 0 && "Index in explicit init list must be zero");
865
866 // As an extension, clang supports complex initializers, which initialize
867 // a complex number component-wise. When an explicit initializer list for
868 // a complex number contains two two initializers, this extension kicks in:
869 // it exepcts the initializer list to contain two elements convertible to
870 // the element type of the complex type. The first element initializes
871 // the real part, and the second element intitializes the imaginary part.
872
873 if (IList->getNumInits() != 2)
874 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
875 StructuredIndex);
876
877 // This is an extension in C. (The builtin _Complex type does not exist
878 // in the C++ standard.)
David Blaikie4e4d0842012-03-11 07:00:24 +0000879 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000880 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
881 << IList->getSourceRange();
882
883 // Initialize the complex number.
884 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
885 InitializedEntity ElementEntity =
886 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
887
888 for (unsigned i = 0; i < 2; ++i) {
889 ElementEntity.setElementIndex(Index);
890 CheckSubElementType(ElementEntity, IList, elementType, Index,
891 StructuredList, StructuredIndex);
892 }
893}
894
895
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000896void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000897 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000898 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000899 InitListExpr *StructuredList,
900 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000901 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000902 if (!VerifyOnly)
903 SemaRef.Diag(IList->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +0000904 SemaRef.getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +0000905 diag::warn_cxx98_compat_empty_scalar_initializer :
906 diag::err_empty_scalar_initializer)
907 << IList->getSourceRange();
David Blaikie4e4d0842012-03-11 07:00:24 +0000908 hadError = !SemaRef.getLangOpts().CPlusPlus0x;
Douglas Gregor4c678342009-01-28 21:54:33 +0000909 ++Index;
910 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000911 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000912 }
John McCallb934c2d2010-11-11 00:46:36 +0000913
914 Expr *expr = IList->getInit(Index);
915 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000916 if (!VerifyOnly)
917 SemaRef.Diag(SubIList->getLocStart(),
918 diag::warn_many_braces_around_scalar_init)
919 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000920
921 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
922 StructuredIndex);
923 return;
924 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000925 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000926 SemaRef.Diag(expr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000927 diag::err_designator_for_scalar_init)
928 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000929 hadError = true;
930 ++Index;
931 ++StructuredIndex;
932 return;
933 }
934
Sebastian Redl14b0c192011-09-24 17:48:00 +0000935 if (VerifyOnly) {
936 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
937 hadError = true;
938 ++Index;
939 return;
940 }
941
John McCallb934c2d2010-11-11 00:46:36 +0000942 ExprResult Result =
943 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000944 SemaRef.Owned(expr),
945 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000946
947 Expr *ResultExpr = 0;
948
949 if (Result.isInvalid())
950 hadError = true; // types weren't compatible.
951 else {
952 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000953
John McCallb934c2d2010-11-11 00:46:36 +0000954 if (ResultExpr != expr) {
955 // The type was promoted, update initializer list.
956 IList->setInit(Index, ResultExpr);
957 }
958 }
959 if (hadError)
960 ++StructuredIndex;
961 else
962 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
963 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000964}
965
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000966void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
967 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000968 unsigned &Index,
969 InitListExpr *StructuredList,
970 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000971 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000972 // FIXME: It would be wonderful if we could point at the actual member. In
973 // general, it would be useful to pass location information down the stack,
974 // so that we know the location (or decl) of the "current object" being
975 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000976 if (!VerifyOnly)
977 SemaRef.Diag(IList->getLocStart(),
978 diag::err_init_reference_member_uninitialized)
979 << DeclType
980 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000981 hadError = true;
982 ++Index;
983 ++StructuredIndex;
984 return;
985 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000986
987 Expr *expr = IList->getInit(Index);
David Blaikie4e4d0842012-03-11 07:00:24 +0000988 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000989 if (!VerifyOnly)
990 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
991 << DeclType << IList->getSourceRange();
992 hadError = true;
993 ++Index;
994 ++StructuredIndex;
995 return;
996 }
997
998 if (VerifyOnly) {
999 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1000 hadError = true;
1001 ++Index;
1002 return;
1003 }
1004
1005 ExprResult Result =
1006 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1007 SemaRef.Owned(expr),
1008 /*TopLevelOfInitList=*/true);
1009
1010 if (Result.isInvalid())
1011 hadError = true;
1012
1013 expr = Result.takeAs<Expr>();
1014 IList->setInit(Index, expr);
1015
1016 if (hadError)
1017 ++StructuredIndex;
1018 else
1019 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1020 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001021}
1022
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001023void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001024 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001025 unsigned &Index,
1026 InitListExpr *StructuredList,
1027 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001028 const VectorType *VT = DeclType->getAs<VectorType>();
1029 unsigned maxElements = VT->getNumElements();
1030 unsigned numEltsInit = 0;
1031 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001032
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001033 if (Index >= IList->getNumInits()) {
1034 // Make sure the element type can be value-initialized.
1035 if (VerifyOnly)
1036 CheckValueInitializable(
1037 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1038 return;
1039 }
1040
David Blaikie4e4d0842012-03-11 07:00:24 +00001041 if (!SemaRef.getLangOpts().OpenCL) {
John McCall20e047a2010-10-30 00:11:39 +00001042 // If the initializing element is a vector, try to copy-initialize
1043 // instead of breaking it apart (which is doomed to failure anyway).
1044 Expr *Init = IList->getInit(Index);
1045 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001046 if (VerifyOnly) {
1047 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1048 hadError = true;
1049 ++Index;
1050 return;
1051 }
1052
John McCall20e047a2010-10-30 00:11:39 +00001053 ExprResult Result =
1054 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001055 SemaRef.Owned(Init),
1056 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001057
1058 Expr *ResultExpr = 0;
1059 if (Result.isInvalid())
1060 hadError = true; // types weren't compatible.
1061 else {
1062 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001063
John McCall20e047a2010-10-30 00:11:39 +00001064 if (ResultExpr != Init) {
1065 // The type was promoted, update initializer list.
1066 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001067 }
1068 }
John McCall20e047a2010-10-30 00:11:39 +00001069 if (hadError)
1070 ++StructuredIndex;
1071 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001072 UpdateStructuredListElement(StructuredList, StructuredIndex,
1073 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001074 ++Index;
1075 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
John McCall20e047a2010-10-30 00:11:39 +00001078 InitializedEntity ElementEntity =
1079 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
John McCall20e047a2010-10-30 00:11:39 +00001081 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1082 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001083 if (Index >= IList->getNumInits()) {
1084 if (VerifyOnly)
1085 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001086 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001087 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall20e047a2010-10-30 00:11:39 +00001089 ElementEntity.setElementIndex(Index);
1090 CheckSubElementType(ElementEntity, IList, elementType, Index,
1091 StructuredList, StructuredIndex);
1092 }
1093 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001094 }
John McCall20e047a2010-10-30 00:11:39 +00001095
1096 InitializedEntity ElementEntity =
1097 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098
John McCall20e047a2010-10-30 00:11:39 +00001099 // OpenCL initializers allows vectors to be constructed from vectors.
1100 for (unsigned i = 0; i < maxElements; ++i) {
1101 // Don't attempt to go past the end of the init list
1102 if (Index >= IList->getNumInits())
1103 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001104
John McCall20e047a2010-10-30 00:11:39 +00001105 ElementEntity.setElementIndex(Index);
1106
1107 QualType IType = IList->getInit(Index)->getType();
1108 if (!IType->isVectorType()) {
1109 CheckSubElementType(ElementEntity, IList, elementType, Index,
1110 StructuredList, StructuredIndex);
1111 ++numEltsInit;
1112 } else {
1113 QualType VecType;
1114 const VectorType *IVT = IType->getAs<VectorType>();
1115 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
John McCall20e047a2010-10-30 00:11:39 +00001117 if (IType->isExtVectorType())
1118 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1119 else
1120 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001121 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001122 CheckSubElementType(ElementEntity, IList, VecType, Index,
1123 StructuredList, StructuredIndex);
1124 numEltsInit += numIElts;
1125 }
1126 }
1127
1128 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001129 if (numEltsInit != maxElements) {
1130 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001131 SemaRef.Diag(IList->getLocStart(),
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001132 diag::err_vector_incorrect_num_initializers)
1133 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1134 hadError = true;
1135 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001136}
1137
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001138void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001139 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001140 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001141 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001142 unsigned &Index,
1143 InitListExpr *StructuredList,
1144 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001145 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1146
Steve Naroff0cca7492008-05-01 22:18:59 +00001147 // Check for the special-case of initializing an array with a string.
1148 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001149 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001150 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001151 // We place the string literal directly into the resulting
1152 // initializer list. This is the only place where the structure
1153 // of the structured initializer list doesn't match exactly,
1154 // because doing so would involve allocating one character
1155 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001156 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001157 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001158 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1159 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1160 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001161 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001162 return;
1163 }
1164 }
John McCallce6c9b72011-02-21 07:22:22 +00001165 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001166 // Check for VLAs; in standard C it would be possible to check this
1167 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1168 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001169 if (!VerifyOnly)
1170 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1171 diag::err_variable_object_no_init)
1172 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001173 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001174 ++Index;
1175 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001176 return;
1177 }
1178
Douglas Gregor05c13a32009-01-22 00:58:24 +00001179 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001180 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1181 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001182 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001183 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001184 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001185 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001186 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 maxElementsKnown = true;
1188 }
1189
John McCallce6c9b72011-02-21 07:22:22 +00001190 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001191 while (Index < IList->getNumInits()) {
1192 Expr *Init = IList->getInit(Index);
1193 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001194 // If we're not the subobject that matches up with the '{' for
1195 // the designator, we shouldn't be handling the
1196 // designator. Return immediately.
1197 if (!SubobjectIsDesignatorContext)
1198 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001199
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001200 // Handle this designated initializer. elementIndex will be
1201 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001202 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001203 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001204 StructuredList, StructuredIndex, true,
1205 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001206 hadError = true;
1207 continue;
1208 }
1209
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001210 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001211 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001212 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001213 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001214 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001215
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001216 // If the array is of incomplete type, keep track of the number of
1217 // elements in the initializer.
1218 if (!maxElementsKnown && elementIndex > maxElements)
1219 maxElements = elementIndex;
1220
Douglas Gregor05c13a32009-01-22 00:58:24 +00001221 continue;
1222 }
1223
1224 // If we know the maximum number of elements, and we've already
1225 // hit it, stop consuming elements in the initializer list.
1226 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001227 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001228
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001229 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001230 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001231 Entity);
1232 // Check this element.
1233 CheckSubElementType(ElementEntity, IList, elementType, Index,
1234 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001235 ++elementIndex;
1236
1237 // If the array is of incomplete type, keep track of the number of
1238 // elements in the initializer.
1239 if (!maxElementsKnown && elementIndex > maxElements)
1240 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001241 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001242 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001243 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001244 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001245 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001246 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001247 // Sizing an array implicitly to zero is not allowed by ISO C,
1248 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001249 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001250 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001251 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001252
Mike Stump1eb44332009-09-09 15:08:12 +00001253 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001254 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001255 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001256 if (!hadError && VerifyOnly) {
1257 // Check if there are any members of the array that get value-initialized.
1258 // If so, check if doing that is possible.
1259 // FIXME: This needs to detect holes left by designated initializers too.
1260 if (maxElementsKnown && elementIndex < maxElements)
1261 CheckValueInitializable(InitializedEntity::InitializeElement(
1262 SemaRef.Context, 0, Entity));
1263 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001264}
1265
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001266bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1267 Expr *InitExpr,
1268 FieldDecl *Field,
1269 bool TopLevelObject) {
1270 // Handle GNU flexible array initializers.
1271 unsigned FlexArrayDiag;
1272 if (isa<InitListExpr>(InitExpr) &&
1273 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1274 // Empty flexible array init always allowed as an extension
1275 FlexArrayDiag = diag::ext_flexible_array_init;
David Blaikie4e4d0842012-03-11 07:00:24 +00001276 } else if (SemaRef.getLangOpts().CPlusPlus) {
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001277 // Disallow flexible array init in C++; it is not required for gcc
1278 // compatibility, and it needs work to IRGen correctly in general.
1279 FlexArrayDiag = diag::err_flexible_array_init;
1280 } else if (!TopLevelObject) {
1281 // Disallow flexible array init on non-top-level object
1282 FlexArrayDiag = diag::err_flexible_array_init;
1283 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1284 // Disallow flexible array init on anything which is not a variable.
1285 FlexArrayDiag = diag::err_flexible_array_init;
1286 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1287 // Disallow flexible array init on local variables.
1288 FlexArrayDiag = diag::err_flexible_array_init;
1289 } else {
1290 // Allow other cases.
1291 FlexArrayDiag = diag::ext_flexible_array_init;
1292 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001293
1294 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001295 SemaRef.Diag(InitExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001296 FlexArrayDiag)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001297 << InitExpr->getLocStart();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001298 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1299 << Field;
1300 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001301
1302 return FlexArrayDiag != diag::ext_flexible_array_init;
1303}
1304
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001305void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001306 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001308 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001309 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001310 unsigned &Index,
1311 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001312 unsigned &StructuredIndex,
1313 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001314 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Eli Friedmanb85f7072008-05-19 19:16:24 +00001316 // If the record is invalid, some of it's members are invalid. To avoid
1317 // confusion, we forgo checking the intializer for the entire record.
1318 if (structDecl->isInvalidDecl()) {
Richard Smith72ab2772012-09-28 21:23:50 +00001319 // Assume it was supposed to consume a single initializer.
1320 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001321 hadError = true;
1322 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001323 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001324
1325 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001326 // Value-initialize the first named member of the union.
1327 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1328 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1329 Field != FieldEnd; ++Field) {
1330 if (Field->getDeclName()) {
1331 if (VerifyOnly)
1332 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001333 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001334 else
David Blaikie581deb32012-06-06 20:45:41 +00001335 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001336 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001337 }
1338 }
1339 return;
1340 }
1341
Douglas Gregor05c13a32009-01-22 00:58:24 +00001342 // If structDecl is a forward declaration, this loop won't do
1343 // anything except look at designated initializers; That's okay,
1344 // because an error should get printed out elsewhere. It might be
1345 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001346 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001347 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001348 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001349 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001350 while (Index < IList->getNumInits()) {
1351 Expr *Init = IList->getInit(Index);
1352
1353 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001354 // If we're not the subobject that matches up with the '{' for
1355 // the designator, we shouldn't be handling the
1356 // designator. Return immediately.
1357 if (!SubobjectIsDesignatorContext)
1358 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001359
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001360 // Handle this designated initializer. Field will be updated to
1361 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001362 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001363 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001364 StructuredList, StructuredIndex,
1365 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001366 hadError = true;
1367
Douglas Gregordfb5e592009-02-12 19:00:39 +00001368 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001369
1370 // Disable check for missing fields when designators are used.
1371 // This matches gcc behaviour.
1372 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001373 continue;
1374 }
1375
1376 if (Field == FieldEnd) {
1377 // We've run out of fields. We're done.
1378 break;
1379 }
1380
Douglas Gregordfb5e592009-02-12 19:00:39 +00001381 // We've already initialized a member of a union. We're done.
1382 if (InitializedSomething && DeclType->isUnionType())
1383 break;
1384
Douglas Gregor44b43212008-12-11 16:49:14 +00001385 // If we've hit the flexible array member at the end, we're done.
1386 if (Field->getType()->isIncompleteArrayType())
1387 break;
1388
Douglas Gregor0bb76892009-01-29 16:53:55 +00001389 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001390 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001391 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001392 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001393 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001394
Douglas Gregor54001c12011-06-29 21:51:31 +00001395 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001396 bool InvalidUse;
1397 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001398 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001399 else
David Blaikie581deb32012-06-06 20:45:41 +00001400 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001401 IList->getInit(Index)->getLocStart());
1402 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001403 ++Index;
1404 ++Field;
1405 hadError = true;
1406 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001407 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001408
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001409 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001410 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001411 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1412 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001413 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001414
Sebastian Redl14b0c192011-09-24 17:48:00 +00001415 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001416 // Initialize the first field within the union.
David Blaikie581deb32012-06-06 20:45:41 +00001417 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001418 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001419
1420 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001421 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001422
John McCall80639de2010-03-11 19:32:38 +00001423 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001424 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1425 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1426 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001427 // It is possible we have one or more unnamed bitfields remaining.
1428 // Find first (if any) named field and emit warning.
1429 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1430 it != end; ++it) {
1431 if (!it->isUnnamedBitfield()) {
1432 SemaRef.Diag(IList->getSourceRange().getEnd(),
1433 diag::warn_missing_field_initializers) << it->getName();
1434 break;
1435 }
1436 }
1437 }
1438
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001439 // Check that any remaining fields can be value-initialized.
1440 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1441 !Field->getType()->isIncompleteArrayType()) {
1442 // FIXME: Should check for holes left by designated initializers too.
1443 for (; Field != FieldEnd && !hadError; ++Field) {
1444 if (!Field->isUnnamedBitfield())
1445 CheckValueInitializable(
David Blaikie581deb32012-06-06 20:45:41 +00001446 InitializedEntity::InitializeMember(*Field, &Entity));
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001447 }
1448 }
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001451 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001452 return;
1453
David Blaikie581deb32012-06-06 20:45:41 +00001454 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001455 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001457 ++Index;
1458 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 }
1460
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001461 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001462 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001464 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001465 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001466 StructuredList, StructuredIndex);
1467 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001469 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001470}
Steve Naroff0cca7492008-05-01 22:18:59 +00001471
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001472/// \brief Expand a field designator that refers to a member of an
1473/// anonymous struct or union into a series of field designators that
1474/// refers to the field within the appropriate subobject.
1475///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001476static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001477 DesignatedInitExpr *DIE,
1478 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001479 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001480 typedef DesignatedInitExpr::Designator Designator;
1481
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001482 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001483 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001484 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1485 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1486 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001487 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001488 DIE->getDesignator(DesigIdx)->getDotLoc(),
1489 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1490 else
1491 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1492 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001493 assert(isa<FieldDecl>(*PI));
1494 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001495 }
1496
1497 // Expand the current designator into the set of replacement
1498 // designators, so we have a full subobject path down to where the
1499 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001500 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001501 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001502}
Mike Stump1eb44332009-09-09 15:08:12 +00001503
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001504/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001505/// corresponds to FieldName.
1506static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1507 IdentifierInfo *FieldName) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001508 if (!FieldName)
1509 return 0;
1510
Francois Picheta0e27f02010-12-22 03:46:10 +00001511 assert(AnonField->isAnonymousStructOrUnion());
1512 Decl *NextDecl = AnonField->getNextDeclInContext();
Aaron Ballman3e78b192012-02-09 22:16:56 +00001513 while (IndirectFieldDecl *IF =
1514 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
Argyrios Kyrtzidisb22b0a52012-09-10 22:04:26 +00001515 if (FieldName == IF->getAnonField()->getIdentifier())
Francois Picheta0e27f02010-12-22 03:46:10 +00001516 return IF;
1517 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001518 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001519 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001520}
1521
Sebastian Redl14b0c192011-09-24 17:48:00 +00001522static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1523 DesignatedInitExpr *DIE) {
1524 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1525 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1526 for (unsigned I = 0; I < NumIndexExprs; ++I)
1527 IndexExprs[I] = DIE->getSubExpr(I + 1);
1528 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001529 DIE->size(), IndexExprs,
1530 DIE->getEqualOrColonLoc(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001531 DIE->usesGNUSyntax(), DIE->getInit());
1532}
1533
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001534namespace {
1535
1536// Callback to only accept typo corrections that are for field members of
1537// the given struct or union.
1538class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1539 public:
1540 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1541 : Record(RD) {}
1542
1543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1544 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1545 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1546 }
1547
1548 private:
1549 RecordDecl *Record;
1550};
1551
1552}
1553
Douglas Gregor05c13a32009-01-22 00:58:24 +00001554/// @brief Check the well-formedness of a C99 designated initializer.
1555///
1556/// Determines whether the designated initializer @p DIE, which
1557/// resides at the given @p Index within the initializer list @p
1558/// IList, is well-formed for a current object of type @p DeclType
1559/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001560/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001561/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001562///
1563/// @param IList The initializer list in which this designated
1564/// initializer occurs.
1565///
Douglas Gregor71199712009-04-15 04:56:10 +00001566/// @param DIE The designated initializer expression.
1567///
1568/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001569///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001570/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001571/// into which the designation in @p DIE should refer.
1572///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001573/// @param NextField If non-NULL and the first designator in @p DIE is
1574/// a field, this will be set to the field declaration corresponding
1575/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001576///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001577/// @param NextElementIndex If non-NULL and the first designator in @p
1578/// DIE is an array designator or GNU array-range designator, this
1579/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001580///
1581/// @param Index Index into @p IList where the designated initializer
1582/// @p DIE occurs.
1583///
Douglas Gregor4c678342009-01-28 21:54:33 +00001584/// @param StructuredList The initializer list expression that
1585/// describes all of the subobject initializers in the order they'll
1586/// actually be initialized.
1587///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001588/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001589bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001590InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001591 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001592 DesignatedInitExpr *DIE,
1593 unsigned DesigIdx,
1594 QualType &CurrentObjectType,
1595 RecordDecl::field_iterator *NextField,
1596 llvm::APSInt *NextElementIndex,
1597 unsigned &Index,
1598 InitListExpr *StructuredList,
1599 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001600 bool FinishSubobjectInit,
1601 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001602 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001603 // Check the actual initialization for the designated object type.
1604 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001605
1606 // Temporarily remove the designator expression from the
1607 // initializer list that the child calls see, so that we don't try
1608 // to re-process the designator.
1609 unsigned OldIndex = Index;
1610 IList->setInit(OldIndex, DIE->getInit());
1611
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001612 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001613 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001614
1615 // Restore the designated initializer expression in the syntactic
1616 // form of the initializer list.
1617 if (IList->getInit(OldIndex) != DIE->getInit())
1618 DIE->setInit(IList->getInit(OldIndex));
1619 IList->setInit(OldIndex, DIE);
1620
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001621 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001622 }
1623
Douglas Gregor71199712009-04-15 04:56:10 +00001624 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001625 bool IsFirstDesignator = (DesigIdx == 0);
1626 if (!VerifyOnly) {
1627 assert((IsFirstDesignator || StructuredList) &&
1628 "Need a non-designated initializer list to start from");
1629
1630 // Determine the structural initializer list that corresponds to the
1631 // current subobject.
Benjamin Kramera7894162012-02-23 14:48:40 +00001632 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001633 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1634 StructuredList, StructuredIndex,
1635 SourceRange(D->getStartLocation(),
1636 DIE->getSourceRange().getEnd()));
1637 assert(StructuredList && "Expected a structured initializer list");
1638 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001639
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001640 if (D->isFieldDesignator()) {
1641 // C99 6.7.8p7:
1642 //
1643 // If a designator has the form
1644 //
1645 // . identifier
1646 //
1647 // then the current object (defined below) shall have
1648 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001649 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001650 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001651 if (!RT) {
1652 SourceLocation Loc = D->getDotLoc();
1653 if (Loc.isInvalid())
1654 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001655 if (!VerifyOnly)
1656 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
David Blaikie4e4d0842012-03-11 07:00:24 +00001657 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001658 ++Index;
1659 return true;
1660 }
1661
Douglas Gregor4c678342009-01-28 21:54:33 +00001662 // Note: we perform a linear search of the fields here, despite
1663 // the fact that we have a faster lookup method, because we always
1664 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001665 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001666 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001667 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001668 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001669 Field = RT->getDecl()->field_begin(),
1670 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001671 for (; Field != FieldEnd; ++Field) {
1672 if (Field->isUnnamedBitfield())
1673 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674
Francois Picheta0e27f02010-12-22 03:46:10 +00001675 // If we find a field representing an anonymous field, look in the
1676 // IndirectFieldDecl that follow for the designated initializer.
1677 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1678 if (IndirectFieldDecl *IF =
David Blaikie581deb32012-06-06 20:45:41 +00001679 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001680 // In verify mode, don't modify the original.
1681 if (VerifyOnly)
1682 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001683 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1684 D = DIE->getDesignator(DesigIdx);
1685 break;
1686 }
1687 }
David Blaikie581deb32012-06-06 20:45:41 +00001688 if (KnownField && KnownField == *Field)
Douglas Gregor022d13d2010-10-08 20:44:28 +00001689 break;
1690 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001691 break;
1692
1693 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001694 }
1695
Douglas Gregor4c678342009-01-28 21:54:33 +00001696 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001697 if (VerifyOnly) {
1698 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001699 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001700 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001701
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001702 // There was no normal field in the struct with the designated
1703 // name. Perform another lookup for this name, which may find
1704 // something that we can't designate (e.g., a member function),
1705 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001706 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001707 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001708 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001709 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001710 // Name lookup didn't find anything. Determine whether this
1711 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001712 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001713 TypoCorrection Corrected = SemaRef.CorrectTypo(
1714 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001715 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001716 RT->getDecl());
1717 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001718 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001719 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001720 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +00001721 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001722 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001724 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001725 << FieldName << CurrentObjectType << CorrectedQuotedStr
1726 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001727 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001728 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001729 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001730 } else {
1731 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1732 << FieldName << CurrentObjectType;
1733 ++Index;
1734 return true;
1735 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001737
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001738 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001739 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001740 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001741 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001742 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001743 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001744 ++Index;
1745 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001746 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001747
Francois Picheta0e27f02010-12-22 03:46:10 +00001748 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001749 // The replacement field comes from typo correction; find it
1750 // in the list of fields.
1751 FieldIndex = 0;
1752 Field = RT->getDecl()->field_begin();
1753 for (; Field != FieldEnd; ++Field) {
1754 if (Field->isUnnamedBitfield())
1755 continue;
1756
David Blaikie581deb32012-06-06 20:45:41 +00001757 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001758 Field->getIdentifier() == ReplacementField->getIdentifier())
1759 break;
1760
1761 ++FieldIndex;
1762 }
1763 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001764 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001765
1766 // All of the fields of a union are located at the same place in
1767 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001768 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001770 if (!VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001771 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001772 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001773
Douglas Gregor54001c12011-06-29 21:51:31 +00001774 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001775 bool InvalidUse;
1776 if (VerifyOnly)
David Blaikie581deb32012-06-06 20:45:41 +00001777 InvalidUse = !SemaRef.CanUseDecl(*Field);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001778 else
David Blaikie581deb32012-06-06 20:45:41 +00001779 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
Sebastian Redl14b0c192011-09-24 17:48:00 +00001780 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001781 ++Index;
1782 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001783 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001784
Sebastian Redl14b0c192011-09-24 17:48:00 +00001785 if (!VerifyOnly) {
1786 // Update the designator with the field declaration.
David Blaikie581deb32012-06-06 20:45:41 +00001787 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Sebastian Redl14b0c192011-09-24 17:48:00 +00001789 // Make sure that our non-designated initializer list has space
1790 // for a subobject corresponding to this field.
1791 if (FieldIndex >= StructuredList->getNumInits())
1792 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1793 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001794
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001795 // This designator names a flexible array member.
1796 if (Field->getType()->isIncompleteArrayType()) {
1797 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001798 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001799 // We can't designate an object within the flexible array
1800 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001801 if (!VerifyOnly) {
1802 DesignatedInitExpr::Designator *NextD
1803 = DIE->getDesignator(DesigIdx + 1);
1804 SemaRef.Diag(NextD->getStartLocation(),
1805 diag::err_designator_into_flexible_array_member)
1806 << SourceRange(NextD->getStartLocation(),
1807 DIE->getSourceRange().getEnd());
1808 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001809 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001810 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001811 Invalid = true;
1812 }
1813
Chris Lattner9046c222010-10-10 17:49:49 +00001814 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1815 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001816 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001817 if (!VerifyOnly) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00001818 SemaRef.Diag(DIE->getInit()->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001819 diag::err_flexible_array_init_needs_braces)
1820 << DIE->getInit()->getSourceRange();
1821 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
David Blaikie581deb32012-06-06 20:45:41 +00001822 << *Field;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001823 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001824 Invalid = true;
1825 }
1826
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001827 // Check GNU flexible array initializer.
David Blaikie581deb32012-06-06 20:45:41 +00001828 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001829 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001830 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001831
1832 if (Invalid) {
1833 ++Index;
1834 return true;
1835 }
1836
1837 // Initialize the array.
1838 bool prevHadError = hadError;
1839 unsigned newStructuredIndex = FieldIndex;
1840 unsigned OldIndex = Index;
1841 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001842
1843 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001844 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001845 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001846 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001847
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001848 IList->setInit(OldIndex, DIE);
1849 if (hadError && !prevHadError) {
1850 ++Field;
1851 ++FieldIndex;
1852 if (NextField)
1853 *NextField = Field;
1854 StructuredIndex = FieldIndex;
1855 return true;
1856 }
1857 } else {
1858 // Recurse to check later designated subobjects.
David Blaikie262bc182012-04-30 02:36:29 +00001859 QualType FieldType = Field->getType();
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001860 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001861
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001862 InitializedEntity MemberEntity =
David Blaikie581deb32012-06-06 20:45:41 +00001863 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1865 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001866 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001867 true, false))
1868 return true;
1869 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001870
1871 // Find the position of the next field to be initialized in this
1872 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001873 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001874 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001875
1876 // If this the first designator, our caller will continue checking
1877 // the rest of this struct/class/union subobject.
1878 if (IsFirstDesignator) {
1879 if (NextField)
1880 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001881 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001882 return false;
1883 }
1884
Douglas Gregor34e79462009-01-28 23:36:17 +00001885 if (!FinishSubobjectInit)
1886 return false;
1887
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001888 // We've already initialized something in the union; we're done.
1889 if (RT->getDecl()->isUnion())
1890 return hadError;
1891
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001892 // Check the remaining fields within this class/struct/union subobject.
1893 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001894
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001895 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001896 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001897 return hadError && !prevHadError;
1898 }
1899
1900 // C99 6.7.8p6:
1901 //
1902 // If a designator has the form
1903 //
1904 // [ constant-expression ]
1905 //
1906 // then the current object (defined below) shall have array
1907 // type and the expression shall be an integer constant
1908 // expression. If the array is of unknown size, any
1909 // nonnegative value is valid.
1910 //
1911 // Additionally, cope with the GNU extension that permits
1912 // designators of the form
1913 //
1914 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001915 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001916 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001917 if (!VerifyOnly)
1918 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1919 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001920 ++Index;
1921 return true;
1922 }
1923
1924 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001925 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1926 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001927 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001928 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001929 DesignatedEndIndex = DesignatedStartIndex;
1930 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001931 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001932
Mike Stump1eb44332009-09-09 15:08:12 +00001933 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001934 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001935 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001936 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001937 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001938
Chris Lattnere0fd8322011-02-19 22:28:58 +00001939 // Codegen can't handle evaluating array range designators that have side
1940 // effects, because we replicate the AST value for each initialized element.
1941 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1942 // elements with something that has a side effect, so codegen can emit an
1943 // "error unsupported" error instead of miscompiling the app.
1944 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001945 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001946 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001947 }
1948
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001949 if (isa<ConstantArrayType>(AT)) {
1950 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001951 DesignatedStartIndex
1952 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001953 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001954 DesignatedEndIndex
1955 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001956 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1957 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001958 if (!VerifyOnly)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001959 SemaRef.Diag(IndexExpr->getLocStart(),
Sebastian Redl14b0c192011-09-24 17:48:00 +00001960 diag::err_array_designator_too_large)
1961 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1962 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001963 ++Index;
1964 return true;
1965 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001966 } else {
1967 // Make sure the bit-widths and signedness match.
1968 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001969 DesignatedEndIndex
1970 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001971 else if (DesignatedStartIndex.getBitWidth() <
1972 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001973 DesignatedStartIndex
1974 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001975 DesignatedStartIndex.setIsUnsigned(true);
1976 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor4c678342009-01-28 21:54:33 +00001979 // Make sure that our non-designated initializer list has space
1980 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001981 if (!VerifyOnly &&
1982 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001983 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001984 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001985
Douglas Gregor34e79462009-01-28 23:36:17 +00001986 // Repeatedly perform subobject initializations in the range
1987 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001988
Douglas Gregor34e79462009-01-28 23:36:17 +00001989 // Move to the next designator
1990 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1991 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001992
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001993 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001994 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001995
Douglas Gregor34e79462009-01-28 23:36:17 +00001996 while (DesignatedStartIndex <= DesignatedEndIndex) {
1997 // Recurse to check later designated subobjects.
1998 QualType ElementType = AT->getElementType();
1999 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002000
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002001 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002002 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2003 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002004 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002005 (DesignatedStartIndex == DesignatedEndIndex),
2006 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002007 return true;
2008
2009 // Move to the next index in the array that we'll be initializing.
2010 ++DesignatedStartIndex;
2011 ElementIndex = DesignatedStartIndex.getZExtValue();
2012 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002013
2014 // If this the first designator, our caller will continue checking
2015 // the rest of this array subobject.
2016 if (IsFirstDesignator) {
2017 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002018 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002019 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002020 return false;
2021 }
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Douglas Gregor34e79462009-01-28 23:36:17 +00002023 if (!FinishSubobjectInit)
2024 return false;
2025
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002026 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002027 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002028 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002029 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002030 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002031 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002032}
2033
Douglas Gregor4c678342009-01-28 21:54:33 +00002034// Get the structured initializer list for a subobject of type
2035// @p CurrentObjectType.
2036InitListExpr *
2037InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2038 QualType CurrentObjectType,
2039 InitListExpr *StructuredList,
2040 unsigned StructuredIndex,
2041 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002042 if (VerifyOnly)
2043 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002044 Expr *ExistingInit = 0;
2045 if (!StructuredList)
Benjamin Kramera7894162012-02-23 14:48:40 +00002046 ExistingInit = SyntacticToSemantic.lookup(IList);
Douglas Gregor4c678342009-01-28 21:54:33 +00002047 else if (StructuredIndex < StructuredList->getNumInits())
2048 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Douglas Gregor4c678342009-01-28 21:54:33 +00002050 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2051 return Result;
2052
2053 if (ExistingInit) {
2054 // We are creating an initializer list that initializes the
2055 // subobjects of the current object, but there was already an
2056 // initialization that completely initialized the current
2057 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002058 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002059 // struct X { int a, b; };
2060 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002061 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002062 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2063 // designated initializer re-initializes the whole
2064 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002065 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002066 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002067 << InitRange;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002068 SemaRef.Diag(ExistingInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002069 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002070 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002071 << ExistingInit->getSourceRange();
2072 }
2073
Mike Stump1eb44332009-09-09 15:08:12 +00002074 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002075 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002076 InitRange.getBegin(), MultiExprArg(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00002077 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002078
Eli Friedman5c89c392012-02-23 02:25:10 +00002079 QualType ResultType = CurrentObjectType;
2080 if (!ResultType->isArrayType())
2081 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2082 Result->setType(ResultType);
Douglas Gregor4c678342009-01-28 21:54:33 +00002083
Douglas Gregorfa219202009-03-20 23:58:33 +00002084 // Pre-allocate storage for the structured initializer list.
2085 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002086 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002087 bool GotNumInits = false;
2088 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002089 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002090 GotNumInits = true;
2091 } else if (Index < IList->getNumInits()) {
2092 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002093 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002094 GotNumInits = true;
2095 }
Douglas Gregor08457732009-03-21 18:13:52 +00002096 }
2097
Mike Stump1eb44332009-09-09 15:08:12 +00002098 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002099 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2100 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2101 NumElements = CAType->getSize().getZExtValue();
2102 // Simple heuristic so that we don't allocate a very large
2103 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002104 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002105 NumElements = 0;
2106 }
John McCall183700f2009-09-21 23:43:11 +00002107 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002108 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002109 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002110 RecordDecl *RDecl = RType->getDecl();
2111 if (RDecl->isUnion())
2112 NumElements = 1;
2113 else
Mike Stump1eb44332009-09-09 15:08:12 +00002114 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002115 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002116 }
2117
Ted Kremenek709210f2010-04-13 23:39:13 +00002118 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002119
Douglas Gregor4c678342009-01-28 21:54:33 +00002120 // Link this new initializer list into the structured initializer
2121 // lists.
2122 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002123 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002124 else {
2125 Result->setSyntacticForm(IList);
2126 SyntacticToSemantic[IList] = Result;
2127 }
2128
2129 return Result;
2130}
2131
2132/// Update the initializer at index @p StructuredIndex within the
2133/// structured initializer list to the value @p expr.
2134void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2135 unsigned &StructuredIndex,
2136 Expr *expr) {
2137 // No structured initializer list to update
2138 if (!StructuredList)
2139 return;
2140
Ted Kremenek709210f2010-04-13 23:39:13 +00002141 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2142 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002143 // This initializer overwrites a previous initializer. Warn.
Daniel Dunbar96a00142012-03-09 18:35:03 +00002144 SemaRef.Diag(expr->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002145 diag::warn_initializer_overrides)
2146 << expr->getSourceRange();
Daniel Dunbar96a00142012-03-09 18:35:03 +00002147 SemaRef.Diag(PrevInit->getLocStart(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002148 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002149 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002150 << PrevInit->getSourceRange();
2151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Douglas Gregor4c678342009-01-28 21:54:33 +00002153 ++StructuredIndex;
2154}
2155
Douglas Gregor05c13a32009-01-22 00:58:24 +00002156/// Check that the given Index expression is a valid array designator
Richard Smith282e7e62012-02-04 09:53:13 +00002157/// value. This is essentially just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002158/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002159/// and produces a reasonable diagnostic if there is a
Richard Smith282e7e62012-02-04 09:53:13 +00002160/// failure. Returns the index expression, possibly with an implicit cast
2161/// added, on success. If everything went okay, Value will receive the
2162/// value of the constant expression.
2163static ExprResult
Chris Lattner3bf68932009-04-25 21:59:05 +00002164CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002165 SourceLocation Loc = Index->getLocStart();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002166
2167 // Make sure this is an integer constant expression.
Richard Smith282e7e62012-02-04 09:53:13 +00002168 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2169 if (Result.isInvalid())
2170 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002171
Chris Lattner3bf68932009-04-25 21:59:05 +00002172 if (Value.isSigned() && Value.isNegative())
2173 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002174 << Value.toString(10) << Index->getSourceRange();
2175
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002176 Value.setIsUnsigned(true);
Richard Smith282e7e62012-02-04 09:53:13 +00002177 return Result;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002178}
2179
John McCall60d7b3a2010-08-24 06:29:42 +00002180ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002181 SourceLocation Loc,
2182 bool GNUSyntax,
2183 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002184 typedef DesignatedInitExpr::Designator ASTDesignator;
2185
2186 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002187 SmallVector<ASTDesignator, 32> Designators;
2188 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002189
2190 // Build designators and check array designator expressions.
2191 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2192 const Designator &D = Desig.getDesignator(Idx);
2193 switch (D.getKind()) {
2194 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002195 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002196 D.getFieldLoc()));
2197 break;
2198
2199 case Designator::ArrayDesignator: {
2200 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2201 llvm::APSInt IndexValue;
Richard Smith282e7e62012-02-04 09:53:13 +00002202 if (!Index->isTypeDependent() && !Index->isValueDependent())
2203 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2204 if (!Index)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002205 Invalid = true;
2206 else {
2207 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002208 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002209 D.getRBracketLoc()));
2210 InitExpressions.push_back(Index);
2211 }
2212 break;
2213 }
2214
2215 case Designator::ArrayRangeDesignator: {
2216 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2217 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2218 llvm::APSInt StartValue;
2219 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002220 bool StartDependent = StartIndex->isTypeDependent() ||
2221 StartIndex->isValueDependent();
2222 bool EndDependent = EndIndex->isTypeDependent() ||
2223 EndIndex->isValueDependent();
Richard Smith282e7e62012-02-04 09:53:13 +00002224 if (!StartDependent)
2225 StartIndex =
2226 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2227 if (!EndDependent)
2228 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2229
2230 if (!StartIndex || !EndIndex)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002231 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002232 else {
2233 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002234 if (StartDependent || EndDependent) {
2235 // Nothing to compute.
2236 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002237 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002238 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002239 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002240
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002241 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002242 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002243 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002244 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2245 Invalid = true;
2246 } else {
2247 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002248 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002249 D.getEllipsisLoc(),
2250 D.getRBracketLoc()));
2251 InitExpressions.push_back(StartIndex);
2252 InitExpressions.push_back(EndIndex);
2253 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002254 }
2255 break;
2256 }
2257 }
2258 }
2259
2260 if (Invalid || Init.isInvalid())
2261 return ExprError();
2262
2263 // Clear out the expressions within the designation.
2264 Desig.ClearExprs(*this);
2265
2266 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002267 = DesignatedInitExpr::Create(Context,
2268 Designators.data(), Designators.size(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002269 InitExpressions, Loc, GNUSyntax,
2270 Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002271
David Blaikie4e4d0842012-03-11 07:00:24 +00002272 if (!getLangOpts().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002273 Diag(DIE->getLocStart(), diag::ext_designated_init)
2274 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002275
Douglas Gregor05c13a32009-01-22 00:58:24 +00002276 return Owned(DIE);
2277}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002278
Douglas Gregor20093b42009-12-09 23:02:17 +00002279//===----------------------------------------------------------------------===//
2280// Initialization entity
2281//===----------------------------------------------------------------------===//
2282
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002284 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002285 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002286{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002287 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2288 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002289 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002290 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002291 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002292 Type = VT->getElementType();
2293 } else {
2294 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2295 assert(CT && "Unexpected type");
2296 Kind = EK_ComplexElement;
2297 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002298 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002299}
2300
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002301InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002302 CXXBaseSpecifier *Base,
2303 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002304{
2305 InitializedEntity Result;
2306 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002307 Result.Base = reinterpret_cast<uintptr_t>(Base);
2308 if (IsInheritedVirtualBase)
2309 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002310
Douglas Gregord6542d82009-12-22 15:35:07 +00002311 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002312 return Result;
2313}
2314
Douglas Gregor99a2e602009-12-16 01:38:02 +00002315DeclarationName InitializedEntity::getName() const {
2316 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002317 case EK_Parameter: {
2318 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2319 return (D ? D->getDeclName() : DeclarationName());
2320 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002321
2322 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002323 case EK_Member:
2324 return VariableOrMember->getDeclName();
2325
Douglas Gregor47736542012-02-15 16:57:26 +00002326 case EK_LambdaCapture:
2327 return Capture.Var->getDeclName();
2328
Douglas Gregor99a2e602009-12-16 01:38:02 +00002329 case EK_Result:
2330 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002331 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002332 case EK_Temporary:
2333 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002334 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002335 case EK_ArrayElement:
2336 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002337 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002338 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002339 return DeclarationName();
2340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002341
David Blaikie7530c032012-01-17 06:56:22 +00002342 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002343}
2344
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002345DeclaratorDecl *InitializedEntity::getDecl() const {
2346 switch (getKind()) {
2347 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002348 case EK_Member:
2349 return VariableOrMember;
2350
John McCallf85e1932011-06-15 23:02:42 +00002351 case EK_Parameter:
2352 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2353
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002354 case EK_Result:
2355 case EK_Exception:
2356 case EK_New:
2357 case EK_Temporary:
2358 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002359 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002360 case EK_ArrayElement:
2361 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002362 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002363 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002364 case EK_LambdaCapture:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002365 return 0;
2366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002367
David Blaikie7530c032012-01-17 06:56:22 +00002368 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002369}
2370
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002371bool InitializedEntity::allowsNRVO() const {
2372 switch (getKind()) {
2373 case EK_Result:
2374 case EK_Exception:
2375 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002376
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002377 case EK_Variable:
2378 case EK_Parameter:
2379 case EK_Member:
2380 case EK_New:
2381 case EK_Temporary:
2382 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002383 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002384 case EK_ArrayElement:
2385 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002386 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002387 case EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00002388 case EK_LambdaCapture:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002389 break;
2390 }
2391
2392 return false;
2393}
2394
Douglas Gregor20093b42009-12-09 23:02:17 +00002395//===----------------------------------------------------------------------===//
2396// Initialization sequence
2397//===----------------------------------------------------------------------===//
2398
2399void InitializationSequence::Step::Destroy() {
2400 switch (Kind) {
2401 case SK_ResolveAddressOfOverloadedFunction:
2402 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002403 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002404 case SK_CastDerivedToBaseLValue:
2405 case SK_BindReference:
2406 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002407 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002408 case SK_UserConversion:
2409 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002410 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002412 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002413 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002414 case SK_UnwrapInitList:
2415 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002416 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002417 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002418 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002419 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002420 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002421 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00002422 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002423 case SK_PassByIndirectCopyRestore:
2424 case SK_PassByIndirectRestore:
2425 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002426 case SK_StdInitializerList:
Douglas Gregor20093b42009-12-09 23:02:17 +00002427 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002428
Douglas Gregor20093b42009-12-09 23:02:17 +00002429 case SK_ConversionSequence:
2430 delete ICS;
2431 }
2432}
2433
Douglas Gregorb70cf442010-03-26 20:14:36 +00002434bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002435 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002436}
2437
2438bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002439 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002440 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002441
Douglas Gregorb70cf442010-03-26 20:14:36 +00002442 switch (getFailureKind()) {
2443 case FK_TooManyInitsForReference:
2444 case FK_ArrayNeedsInitList:
2445 case FK_ArrayNeedsInitListOrStringLiteral:
2446 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2447 case FK_NonConstLValueReferenceBindingToTemporary:
2448 case FK_NonConstLValueReferenceBindingToUnrelated:
2449 case FK_RValueReferenceBindingToLValue:
2450 case FK_ReferenceInitDropsQualifiers:
2451 case FK_ReferenceInitFailed:
2452 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002453 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002454 case FK_TooManyInitsForScalar:
2455 case FK_ReferenceBindingToInitList:
2456 case FK_InitListBadDestinationType:
2457 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002458 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002459 case FK_ArrayTypeMismatch:
2460 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002461 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002462 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002463 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002464 case FK_InitListElementCopyFailure:
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002465 case FK_ExplicitConstructor:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002466 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002467
Douglas Gregorb70cf442010-03-26 20:14:36 +00002468 case FK_ReferenceInitOverloadFailed:
2469 case FK_UserConversionOverloadFailed:
2470 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002471 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002472 return FailedOverloadResult == OR_Ambiguous;
2473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474
David Blaikie7530c032012-01-17 06:56:22 +00002475 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002476}
2477
Douglas Gregord6e44a32010-04-16 22:09:46 +00002478bool InitializationSequence::isConstructorInitialization() const {
2479 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2480}
2481
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002482void
2483InitializationSequence
2484::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2485 DeclAccessPair Found,
2486 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002487 Step S;
2488 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2489 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002490 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002491 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002492 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002493 Steps.push_back(S);
2494}
2495
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002496void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002497 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002498 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002499 switch (VK) {
2500 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2501 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2502 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002503 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002504 S.Type = BaseType;
2505 Steps.push_back(S);
2506}
2507
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002508void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002509 bool BindingTemporary) {
2510 Step S;
2511 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2512 S.Type = T;
2513 Steps.push_back(S);
2514}
2515
Douglas Gregor523d46a2010-04-18 07:40:54 +00002516void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2517 Step S;
2518 S.Kind = SK_ExtraneousCopyToTemporary;
2519 S.Type = T;
2520 Steps.push_back(S);
2521}
2522
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002523void
2524InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2525 DeclAccessPair FoundDecl,
2526 QualType T,
2527 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002528 Step S;
2529 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002530 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002531 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002532 S.Function.Function = Function;
2533 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002534 Steps.push_back(S);
2535}
2536
2537void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002538 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002539 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002540 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002541 switch (VK) {
2542 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002543 S.Kind = SK_QualificationConversionRValue;
2544 break;
John McCall5baba9d2010-08-25 10:28:54 +00002545 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002546 S.Kind = SK_QualificationConversionXValue;
2547 break;
John McCall5baba9d2010-08-25 10:28:54 +00002548 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002549 S.Kind = SK_QualificationConversionLValue;
2550 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002551 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 S.Type = Ty;
2553 Steps.push_back(S);
2554}
2555
2556void InitializationSequence::AddConversionSequenceStep(
2557 const ImplicitConversionSequence &ICS,
2558 QualType T) {
2559 Step S;
2560 S.Kind = SK_ConversionSequence;
2561 S.Type = T;
2562 S.ICS = new ImplicitConversionSequence(ICS);
2563 Steps.push_back(S);
2564}
2565
Douglas Gregord87b61f2009-12-10 17:56:55 +00002566void InitializationSequence::AddListInitializationStep(QualType T) {
2567 Step S;
2568 S.Kind = SK_ListInitialization;
2569 S.Type = T;
2570 Steps.push_back(S);
2571}
2572
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002573void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002574InitializationSequence
2575::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2576 AccessSpecifier Access,
2577 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002578 bool HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002579 bool FromInitList, bool AsInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002580 Step S;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002581 S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2582 : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002583 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002584 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002585 S.Function.Function = Constructor;
2586 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002587 Steps.push_back(S);
2588}
2589
Douglas Gregor71d17402009-12-15 00:01:57 +00002590void InitializationSequence::AddZeroInitializationStep(QualType T) {
2591 Step S;
2592 S.Kind = SK_ZeroInitialization;
2593 S.Type = T;
2594 Steps.push_back(S);
2595}
2596
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002597void InitializationSequence::AddCAssignmentStep(QualType T) {
2598 Step S;
2599 S.Kind = SK_CAssignment;
2600 S.Type = T;
2601 Steps.push_back(S);
2602}
2603
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002604void InitializationSequence::AddStringInitStep(QualType T) {
2605 Step S;
2606 S.Kind = SK_StringInit;
2607 S.Type = T;
2608 Steps.push_back(S);
2609}
2610
Douglas Gregor569c3162010-08-07 11:51:51 +00002611void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2612 Step S;
2613 S.Kind = SK_ObjCObjectConversion;
2614 S.Type = T;
2615 Steps.push_back(S);
2616}
2617
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002618void InitializationSequence::AddArrayInitStep(QualType T) {
2619 Step S;
2620 S.Kind = SK_ArrayInit;
2621 S.Type = T;
2622 Steps.push_back(S);
2623}
2624
Richard Smith0f163e92012-02-15 22:38:09 +00002625void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2626 Step S;
2627 S.Kind = SK_ParenthesizedArrayInit;
2628 S.Type = T;
2629 Steps.push_back(S);
2630}
2631
John McCallf85e1932011-06-15 23:02:42 +00002632void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2633 bool shouldCopy) {
2634 Step s;
2635 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2636 : SK_PassByIndirectRestore);
2637 s.Type = type;
2638 Steps.push_back(s);
2639}
2640
2641void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2642 Step S;
2643 S.Kind = SK_ProduceObjCObject;
2644 S.Type = T;
2645 Steps.push_back(S);
2646}
2647
Sebastian Redl2b916b82012-01-17 22:49:42 +00002648void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2649 Step S;
2650 S.Kind = SK_StdInitializerList;
2651 S.Type = T;
2652 Steps.push_back(S);
2653}
2654
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002655void InitializationSequence::RewrapReferenceInitList(QualType T,
2656 InitListExpr *Syntactic) {
2657 assert(Syntactic->getNumInits() == 1 &&
2658 "Can only rewrap trivial init lists.");
2659 Step S;
2660 S.Kind = SK_UnwrapInitList;
2661 S.Type = Syntactic->getInit(0)->getType();
2662 Steps.insert(Steps.begin(), S);
2663
2664 S.Kind = SK_RewrapInitList;
2665 S.Type = T;
2666 S.WrappingSyntacticList = Syntactic;
2667 Steps.push_back(S);
2668}
2669
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002670void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002671 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002672 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002673 this->Failure = Failure;
2674 this->FailedOverloadResult = Result;
2675}
2676
2677//===----------------------------------------------------------------------===//
2678// Attempt initialization
2679//===----------------------------------------------------------------------===//
2680
John McCallf85e1932011-06-15 23:02:42 +00002681static void MaybeProduceObjCObject(Sema &S,
2682 InitializationSequence &Sequence,
2683 const InitializedEntity &Entity) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002684 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallf85e1932011-06-15 23:02:42 +00002685
2686 /// When initializing a parameter, produce the value if it's marked
2687 /// __attribute__((ns_consumed)).
2688 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2689 if (!Entity.isParameterConsumed())
2690 return;
2691
2692 assert(Entity.getType()->isObjCRetainableType() &&
2693 "consuming an object of unretainable type?");
2694 Sequence.AddProduceObjCObjectStep(Entity.getType());
2695
2696 /// When initializing a return value, if the return type is a
2697 /// retainable type, then returns need to immediately retain the
2698 /// object. If an autorelease is required, it will be done at the
2699 /// last instant.
2700 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2701 if (!Entity.getType()->isObjCRetainableType())
2702 return;
2703
2704 Sequence.AddProduceObjCObjectStep(Entity.getType());
2705 }
2706}
2707
Richard Smithf4bb8d02012-07-05 08:39:21 +00002708/// \brief When initializing from init list via constructor, handle
2709/// initialization of an object of type std::initializer_list<T>.
Sebastian Redl10f04a62011-12-22 14:44:04 +00002710///
Richard Smithf4bb8d02012-07-05 08:39:21 +00002711/// \return true if we have handled initialization of an object of type
2712/// std::initializer_list<T>, false otherwise.
2713static bool TryInitializerListConstruction(Sema &S,
2714 InitListExpr *List,
2715 QualType DestType,
2716 InitializationSequence &Sequence) {
2717 QualType E;
2718 if (!S.isStdInitializerList(DestType, &E))
Richard Smith1d0c9a82012-02-14 21:14:13 +00002719 return false;
2720
Richard Smithf4bb8d02012-07-05 08:39:21 +00002721 // Check that each individual element can be copy-constructed. But since we
2722 // have no place to store further information, we'll recalculate everything
2723 // later.
2724 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2725 S.Context.getConstantArrayType(E,
2726 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2727 List->getNumInits()),
2728 ArrayType::Normal, 0));
2729 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2730 0, HiddenArray);
2731 for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
2732 Element.setElementIndex(i);
2733 if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
2734 Sequence.SetFailed(
2735 InitializationSequence::FK_InitListElementCopyFailure);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002736 return true;
2737 }
2738 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00002739 Sequence.AddStdInitializerListConstructionStep(DestType);
2740 return true;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002741}
2742
Sebastian Redl96715b22012-02-04 21:27:39 +00002743static OverloadingResult
2744ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2745 Expr **Args, unsigned NumArgs,
2746 OverloadCandidateSet &CandidateSet,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002747 ArrayRef<NamedDecl *> Ctors,
Sebastian Redl96715b22012-02-04 21:27:39 +00002748 OverloadCandidateSet::iterator &Best,
2749 bool CopyInitializing, bool AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002750 bool OnlyListConstructors, bool InitListSyntax) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002751 CandidateSet.clear();
2752
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002753 for (ArrayRef<NamedDecl *>::iterator
2754 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002755 NamedDecl *D = *Con;
2756 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2757 bool SuppressUserConversions = false;
2758
2759 // Find the constructor (which may be a template).
2760 CXXConstructorDecl *Constructor = 0;
2761 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2762 if (ConstructorTmpl)
2763 Constructor = cast<CXXConstructorDecl>(
2764 ConstructorTmpl->getTemplatedDecl());
2765 else {
2766 Constructor = cast<CXXConstructorDecl>(D);
2767
2768 // If we're performing copy initialization using a copy constructor, we
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002769 // suppress user-defined conversions on the arguments. We do the same for
2770 // move constructors.
2771 if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
2772 Constructor->isCopyOrMoveConstructor())
Sebastian Redl96715b22012-02-04 21:27:39 +00002773 SuppressUserConversions = true;
2774 }
2775
2776 if (!Constructor->isInvalidDecl() &&
2777 (AllowExplicit || !Constructor->isExplicit()) &&
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002778 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
Sebastian Redl96715b22012-02-04 21:27:39 +00002779 if (ConstructorTmpl)
2780 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2781 /*ExplicitArgs*/ 0,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002782 llvm::makeArrayRef(Args, NumArgs),
2783 CandidateSet, SuppressUserConversions);
Douglas Gregored878af2012-02-24 23:56:31 +00002784 else {
2785 // C++ [over.match.copy]p1:
2786 // - When initializing a temporary to be bound to the first parameter
2787 // of a constructor that takes a reference to possibly cv-qualified
2788 // T as its first argument, called with a single argument in the
2789 // context of direct-initialization, explicit conversion functions
2790 // are also considered.
2791 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
2792 NumArgs == 1 &&
2793 Constructor->isCopyOrMoveConstructor();
Sebastian Redl96715b22012-02-04 21:27:39 +00002794 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002795 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregored878af2012-02-24 23:56:31 +00002796 SuppressUserConversions,
2797 /*PartialOverloading=*/false,
2798 /*AllowExplicit=*/AllowExplicitConv);
2799 }
Sebastian Redl96715b22012-02-04 21:27:39 +00002800 }
2801 }
2802
2803 // Perform overload resolution and return the result.
2804 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
2805}
2806
Sebastian Redl10f04a62011-12-22 14:44:04 +00002807/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2808/// enumerates the constructors of the initialized entity and performs overload
2809/// resolution to select the best.
Sebastian Redl08ae3692012-02-04 21:27:33 +00002810/// If InitListSyntax is true, this is list-initialization of a non-aggregate
Sebastian Redl10f04a62011-12-22 14:44:04 +00002811/// class type.
2812static void TryConstructorInitialization(Sema &S,
2813 const InitializedEntity &Entity,
2814 const InitializationKind &Kind,
2815 Expr **Args, unsigned NumArgs,
2816 QualType DestType,
2817 InitializationSequence &Sequence,
Sebastian Redl08ae3692012-02-04 21:27:33 +00002818 bool InitListSyntax = false) {
2819 assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
2820 "InitListSyntax must come with a single initializer list argument.");
2821
Sebastian Redl10f04a62011-12-22 14:44:04 +00002822 // The type we're constructing needs to be complete.
2823 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00002824 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redl96715b22012-02-04 21:27:39 +00002825 return;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002826 }
2827
2828 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2829 assert(DestRecordType && "Constructor initialization requires record type");
2830 CXXRecordDecl *DestRecordDecl
2831 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2832
Sebastian Redl96715b22012-02-04 21:27:39 +00002833 // Build the candidate set directly in the initialization sequence
2834 // structure, so that it will persist if we fail.
2835 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2836
2837 // Determine whether we are allowed to call explicit constructors or
2838 // explicit conversion operators.
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002839 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002840 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
Sebastian Redl08ae3692012-02-04 21:27:33 +00002841
Sebastian Redl10f04a62011-12-22 14:44:04 +00002842 // - Otherwise, if T is a class type, constructors are considered. The
2843 // applicable constructors are enumerated, and the best one is chosen
2844 // through overload resolution.
Sebastian Redl96715b22012-02-04 21:27:39 +00002845 DeclContext::lookup_iterator ConStart, ConEnd;
2846 llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002847 // The container holding the constructors can under certain conditions
2848 // be changed while iterating (e.g. because of deserialization).
2849 // To be safe we copy the lookup results to a new container.
2850 SmallVector<NamedDecl*, 16> Ctors(ConStart, ConEnd);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002851
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002852 OverloadingResult Result = OR_No_Viable_Function;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002853 OverloadCandidateSet::iterator Best;
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002854 bool AsInitializerList = false;
2855
2856 // C++11 [over.match.list]p1:
2857 // When objects of non-aggregate type T are list-initialized, overload
2858 // resolution selects the constructor in two phases:
2859 // - Initially, the candidate functions are the initializer-list
2860 // constructors of the class T and the argument list consists of the
2861 // initializer list as a single argument.
2862 if (InitListSyntax) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00002863 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002864 AsInitializerList = true;
Richard Smithf4bb8d02012-07-05 08:39:21 +00002865
2866 // If the initializer list has no elements and T has a default constructor,
2867 // the first phase is omitted.
2868 if (ILE->getNumInits() != 0 ||
2869 (!DestRecordDecl->hasDeclaredDefaultConstructor() &&
2870 !DestRecordDecl->needsImplicitDefaultConstructor()))
2871 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002872 CandidateSet, Ctors, Best,
Richard Smithf4bb8d02012-07-05 08:39:21 +00002873 CopyInitialization, AllowExplicit,
2874 /*OnlyListConstructor=*/true,
2875 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002876
2877 // Time to unwrap the init list.
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002878 Args = ILE->getInits();
2879 NumArgs = ILE->getNumInits();
2880 }
2881
2882 // C++11 [over.match.list]p1:
2883 // - If no viable initializer-list constructor is found, overload resolution
2884 // is performed again, where the candidate functions are all the
Richard Smithf4bb8d02012-07-05 08:39:21 +00002885 // constructors of the class T and the argument list consists of the
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002886 // elements of the initializer list.
2887 if (Result == OR_No_Viable_Function) {
2888 AsInitializerList = false;
2889 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00002890 CandidateSet, Ctors, Best,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002891 CopyInitialization, AllowExplicit,
Sebastian Redl51ad9cd2012-02-29 12:47:43 +00002892 /*OnlyListConstructors=*/false,
2893 InitListSyntax);
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002894 }
2895 if (Result) {
Sebastian Redl08ae3692012-02-04 21:27:33 +00002896 Sequence.SetOverloadFailure(InitListSyntax ?
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002897 InitializationSequence::FK_ListConstructorOverloadFailed :
2898 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002899 Result);
2900 return;
2901 }
2902
Richard Smithf4bb8d02012-07-05 08:39:21 +00002903 // C++11 [dcl.init]p6:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002904 // If a program calls for the default initialization of an object
2905 // of a const-qualified type T, T shall be a class type with a
2906 // user-provided default constructor.
2907 if (Kind.getKind() == InitializationKind::IK_Default &&
2908 Entity.getType().isConstQualified() &&
Aaron Ballman51217812012-07-31 22:40:31 +00002909 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00002910 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2911 return;
2912 }
2913
Sebastian Redl70e24fc2012-04-01 19:54:59 +00002914 // C++11 [over.match.list]p1:
2915 // In copy-list-initialization, if an explicit constructor is chosen, the
2916 // initializer is ill-formed.
2917 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
2918 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
2919 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
2920 return;
2921 }
2922
Sebastian Redl10f04a62011-12-22 14:44:04 +00002923 // Add the constructor initialization step. Any cv-qualification conversion is
2924 // subsumed by the initialization.
2925 bool HadMultipleCandidates = (CandidateSet.size() > 1);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002926 Sequence.AddConstructorInitializationStep(CtorDecl,
2927 Best->FoundDecl.getAccess(),
2928 DestType, HadMultipleCandidates,
Sebastian Redl6cd03db2012-02-04 21:27:47 +00002929 InitListSyntax, AsInitializerList);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002930}
2931
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002932static bool
2933ResolveOverloadedFunctionForReferenceBinding(Sema &S,
2934 Expr *Initializer,
2935 QualType &SourceType,
2936 QualType &UnqualifiedSourceType,
2937 QualType UnqualifiedTargetType,
2938 InitializationSequence &Sequence) {
2939 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
2940 S.Context.OverloadTy) {
2941 DeclAccessPair Found;
2942 bool HadMultipleCandidates = false;
2943 if (FunctionDecl *Fn
2944 = S.ResolveAddressOfOverloadedFunction(Initializer,
2945 UnqualifiedTargetType,
2946 false, Found,
2947 &HadMultipleCandidates)) {
2948 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
2949 HadMultipleCandidates);
2950 SourceType = Fn->getType();
2951 UnqualifiedSourceType = SourceType.getUnqualifiedType();
2952 } else if (!UnqualifiedTargetType->isRecordType()) {
2953 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2954 return true;
2955 }
2956 }
2957 return false;
2958}
2959
2960static void TryReferenceInitializationCore(Sema &S,
2961 const InitializedEntity &Entity,
2962 const InitializationKind &Kind,
2963 Expr *Initializer,
2964 QualType cv1T1, QualType T1,
2965 Qualifiers T1Quals,
2966 QualType cv2T2, QualType T2,
2967 Qualifiers T2Quals,
2968 InitializationSequence &Sequence);
2969
Richard Smithf4bb8d02012-07-05 08:39:21 +00002970static void TryValueInitialization(Sema &S,
2971 const InitializedEntity &Entity,
2972 const InitializationKind &Kind,
2973 InitializationSequence &Sequence,
2974 InitListExpr *InitList = 0);
2975
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002976static void TryListInitialization(Sema &S,
2977 const InitializedEntity &Entity,
2978 const InitializationKind &Kind,
2979 InitListExpr *InitList,
2980 InitializationSequence &Sequence);
2981
2982/// \brief Attempt list initialization of a reference.
2983static void TryReferenceListInitialization(Sema &S,
2984 const InitializedEntity &Entity,
2985 const InitializationKind &Kind,
2986 InitListExpr *InitList,
2987 InitializationSequence &Sequence)
2988{
2989 // First, catch C++03 where this isn't possible.
David Blaikie4e4d0842012-03-11 07:00:24 +00002990 if (!S.getLangOpts().CPlusPlus0x) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002991 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2992 return;
2993 }
2994
2995 QualType DestType = Entity.getType();
2996 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2997 Qualifiers T1Quals;
2998 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2999
3000 // Reference initialization via an initializer list works thus:
3001 // If the initializer list consists of a single element that is
3002 // reference-related to the referenced type, bind directly to that element
3003 // (possibly creating temporaries).
3004 // Otherwise, initialize a temporary with the initializer list and
3005 // bind to that.
3006 if (InitList->getNumInits() == 1) {
3007 Expr *Initializer = InitList->getInit(0);
3008 QualType cv2T2 = Initializer->getType();
3009 Qualifiers T2Quals;
3010 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3011
3012 // If this fails, creating a temporary wouldn't work either.
3013 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3014 T1, Sequence))
3015 return;
3016
3017 SourceLocation DeclLoc = Initializer->getLocStart();
3018 bool dummy1, dummy2, dummy3;
3019 Sema::ReferenceCompareResult RefRelationship
3020 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3021 dummy2, dummy3);
3022 if (RefRelationship >= Sema::Ref_Related) {
3023 // Try to bind the reference here.
3024 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3025 T1Quals, cv2T2, T2, T2Quals, Sequence);
3026 if (Sequence)
3027 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3028 return;
3029 }
3030 }
3031
3032 // Not reference-related. Create a temporary and bind to that.
3033 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3034
3035 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3036 if (Sequence) {
3037 if (DestType->isRValueReferenceType() ||
3038 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3039 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3040 else
3041 Sequence.SetFailed(
3042 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3043 }
3044}
3045
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003046/// \brief Attempt list initialization (C++0x [dcl.init.list])
3047static void TryListInitialization(Sema &S,
3048 const InitializedEntity &Entity,
3049 const InitializationKind &Kind,
3050 InitListExpr *InitList,
3051 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003052 QualType DestType = Entity.getType();
3053
Sebastian Redl14b0c192011-09-24 17:48:00 +00003054 // C++ doesn't allow scalar initialization with more than one argument.
3055 // But C99 complex numbers are scalars and it makes sense there.
David Blaikie4e4d0842012-03-11 07:00:24 +00003056 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00003057 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3058 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3059 return;
3060 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003061 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003062 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003063 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003064 }
Sebastian Redld2231c92012-02-19 12:27:43 +00003065 if (DestType->isRecordType()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003066 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
Douglas Gregor69a30b82012-04-10 20:43:46 +00003067 Sequence.setIncompleteTypeFailure(DestType);
Sebastian Redld2231c92012-02-19 12:27:43 +00003068 return;
3069 }
3070
Richard Smithf4bb8d02012-07-05 08:39:21 +00003071 // C++11 [dcl.init.list]p3:
3072 // - If T is an aggregate, aggregate initialization is performed.
Sebastian Redld2231c92012-02-19 12:27:43 +00003073 if (!DestType->isAggregateType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003074 if (S.getLangOpts().CPlusPlus0x) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003075 // - Otherwise, if the initializer list has no elements and T is a
3076 // class type with a default constructor, the object is
3077 // value-initialized.
3078 if (InitList->getNumInits() == 0) {
3079 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3080 if (RD->hasDeclaredDefaultConstructor() ||
3081 RD->needsImplicitDefaultConstructor()) {
3082 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3083 return;
3084 }
3085 }
3086
3087 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3088 // an initializer_list object constructed [...]
3089 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3090 return;
3091
3092 // - Otherwise, if T is a class type, constructors are considered.
Sebastian Redld2231c92012-02-19 12:27:43 +00003093 Expr *Arg = InitList;
Richard Smithf4bb8d02012-07-05 08:39:21 +00003094 TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,
3095 Sequence, /*InitListSyntax*/true);
Sebastian Redld2231c92012-02-19 12:27:43 +00003096 } else
3097 Sequence.SetFailed(
3098 InitializationSequence::FK_InitListBadDestinationType);
3099 return;
3100 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003101 }
3102
Sebastian Redl14b0c192011-09-24 17:48:00 +00003103 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003104 DestType, /*VerifyOnly=*/true,
Sebastian Redl168319c2012-02-12 16:37:24 +00003105 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003106 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003107 if (CheckInitList.HadError()) {
3108 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3109 return;
3110 }
3111
3112 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003113 Sequence.AddListInitializationStep(DestType);
3114}
Douglas Gregor20093b42009-12-09 23:02:17 +00003115
3116/// \brief Try a reference initialization that involves calling a conversion
3117/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003118static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3119 const InitializedEntity &Entity,
3120 const InitializationKind &Kind,
Douglas Gregored878af2012-02-24 23:56:31 +00003121 Expr *Initializer,
3122 bool AllowRValues,
Douglas Gregor20093b42009-12-09 23:02:17 +00003123 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003124 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003125 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3126 QualType T1 = cv1T1.getUnqualifiedType();
3127 QualType cv2T2 = Initializer->getType();
3128 QualType T2 = cv2T2.getUnqualifiedType();
3129
3130 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003131 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003132 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003133 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003134 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003135 ObjCConversion,
3136 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003137 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003138 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003139 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003140 (void)ObjCLifetimeConversion;
3141
Douglas Gregor20093b42009-12-09 23:02:17 +00003142 // Build the candidate set directly in the initialization sequence
3143 // structure, so that it will persist if we fail.
3144 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3145 CandidateSet.clear();
3146
3147 // Determine whether we are allowed to call explicit constructors or
3148 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003149 bool AllowExplicit = Kind.AllowExplicit();
Douglas Gregored878af2012-02-24 23:56:31 +00003150 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
3151
Douglas Gregor20093b42009-12-09 23:02:17 +00003152 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003153 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3154 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003155 // The type we're converting to is a class type. Enumerate its constructors
3156 // to see if there is a suitable conversion.
3157 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003158
Douglas Gregor20093b42009-12-09 23:02:17 +00003159 DeclContext::lookup_iterator Con, ConEnd;
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00003160 llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
3161 // The container holding the constructors can under certain conditions
3162 // be changed while iterating (e.g. because of deserialization).
3163 // To be safe we copy the lookup results to a new container.
3164 SmallVector<NamedDecl*, 16> Ctors(Con, ConEnd);
3165 for (SmallVector<NamedDecl*, 16>::iterator
3166 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3167 NamedDecl *D = *CI;
John McCall9aa472c2010-03-19 07:35:19 +00003168 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3169
Douglas Gregor20093b42009-12-09 23:02:17 +00003170 // Find the constructor (which may be a template).
3171 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003172 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003173 if (ConstructorTmpl)
3174 Constructor = cast<CXXConstructorDecl>(
3175 ConstructorTmpl->getTemplatedDecl());
3176 else
John McCall9aa472c2010-03-19 07:35:19 +00003177 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003178
Douglas Gregor20093b42009-12-09 23:02:17 +00003179 if (!Constructor->isInvalidDecl() &&
3180 Constructor->isConvertingConstructor(AllowExplicit)) {
3181 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003182 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003183 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003184 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003185 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003186 else
John McCall9aa472c2010-03-19 07:35:19 +00003187 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003188 Initializer, CandidateSet,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003189 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003190 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003191 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003192 }
John McCall572fc622010-08-17 07:23:57 +00003193 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3194 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003196 const RecordType *T2RecordType = 0;
3197 if ((T2RecordType = T2->getAs<RecordType>()) &&
3198 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003199 // The type we're converting from is a class type, enumerate its conversion
3200 // functions.
3201 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3202
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003203 std::pair<CXXRecordDecl::conversion_iterator,
3204 CXXRecordDecl::conversion_iterator>
3205 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3206 for (CXXRecordDecl::conversion_iterator
3207 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003208 NamedDecl *D = *I;
3209 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3210 if (isa<UsingShadowDecl>(D))
3211 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003212
Douglas Gregor20093b42009-12-09 23:02:17 +00003213 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3214 CXXConversionDecl *Conv;
3215 if (ConvTemplate)
3216 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3217 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003218 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219
Douglas Gregor20093b42009-12-09 23:02:17 +00003220 // If the conversion function doesn't return a reference type,
3221 // it can't be considered for this conversion unless we're allowed to
3222 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223 // FIXME: Do we need to make sure that we only consider conversion
3224 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003225 // break recursion.
Douglas Gregored878af2012-02-24 23:56:31 +00003226 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003227 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3228 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003229 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003230 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003231 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003232 else
John McCall9aa472c2010-03-19 07:35:19 +00003233 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003234 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003235 }
3236 }
3237 }
John McCall572fc622010-08-17 07:23:57 +00003238 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3239 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003240
Douglas Gregor20093b42009-12-09 23:02:17 +00003241 SourceLocation DeclLoc = Initializer->getLocStart();
3242
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003244 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003246 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003247 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003248
Douglas Gregor20093b42009-12-09 23:02:17 +00003249 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003250
Chandler Carruth25ca4212011-02-25 19:41:05 +00003251 // This is the overload that will actually be used for the initialization, so
3252 // mark it as used.
Eli Friedman5f2987c2012-02-02 03:46:19 +00003253 S.MarkFunctionReferenced(DeclLoc, Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003254
Eli Friedman03981012009-12-11 02:42:07 +00003255 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003256 if (isa<CXXConversionDecl>(Function))
3257 T2 = Function->getResultType();
3258 else
3259 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003260
3261 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003262 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003263 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003264 T2.getNonLValueExprType(S.Context),
3265 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003266
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003267 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003268 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003269 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003270 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003271 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003272 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003273 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003274
Douglas Gregor20093b42009-12-09 23:02:17 +00003275 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003276 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003277 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003278 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003280 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003281 NewDerivedToBase, NewObjCConversion,
3282 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003283 if (NewRefRelationship == Sema::Ref_Incompatible) {
3284 // If the type we've converted to is not reference-related to the
3285 // type we're looking for, then there is another conversion step
3286 // we need to perform to produce a temporary of the right type
3287 // that we'll be binding to.
3288 ImplicitConversionSequence ICS;
3289 ICS.setStandard();
3290 ICS.Standard = Best->FinalConversion;
3291 T2 = ICS.Standard.getToType(2);
3292 Sequence.AddConversionSequenceStep(ICS, T2);
3293 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003294 Sequence.AddDerivedToBaseCastStep(
3295 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003296 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003297 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003298 else if (NewObjCConversion)
3299 Sequence.AddObjCObjectConversionStep(
3300 S.Context.getQualifiedType(T1,
3301 T2.getNonReferenceType().getQualifiers()));
3302
Douglas Gregor20093b42009-12-09 23:02:17 +00003303 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003304 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305
Douglas Gregor20093b42009-12-09 23:02:17 +00003306 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3307 return OR_Success;
3308}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003309
Richard Smith83da2e72011-10-19 16:55:56 +00003310static void CheckCXX98CompatAccessibleCopy(Sema &S,
3311 const InitializedEntity &Entity,
3312 Expr *CurInitExpr);
3313
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3315static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003316 const InitializedEntity &Entity,
3317 const InitializationKind &Kind,
3318 Expr *Initializer,
3319 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003320 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003321 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003322 Qualifiers T1Quals;
3323 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003324 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003325 Qualifiers T2Quals;
3326 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003327
Douglas Gregor20093b42009-12-09 23:02:17 +00003328 // If the initializer is the address of an overloaded function, try
3329 // to resolve the overloaded function. If all goes well, T2 is the
3330 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003331 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3332 T1, Sequence))
3333 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003334
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003335 // Delegate everything else to a subfunction.
3336 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3337 T1Quals, cv2T2, T2, T2Quals, Sequence);
3338}
3339
3340/// \brief Reference initialization without resolving overloaded functions.
3341static void TryReferenceInitializationCore(Sema &S,
3342 const InitializedEntity &Entity,
3343 const InitializationKind &Kind,
3344 Expr *Initializer,
3345 QualType cv1T1, QualType T1,
3346 Qualifiers T1Quals,
3347 QualType cv2T2, QualType T2,
3348 Qualifiers T2Quals,
3349 InitializationSequence &Sequence) {
3350 QualType DestType = Entity.getType();
3351 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003352 // Compute some basic properties of the types and the initializer.
3353 bool isLValueRef = DestType->isLValueReferenceType();
3354 bool isRValueRef = !isLValueRef;
3355 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003356 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003357 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003358 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003359 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003360 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003361 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003362
Douglas Gregor20093b42009-12-09 23:02:17 +00003363 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003365 // "cv2 T2" as follows:
3366 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003367 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003368 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003369 // Note the analogous bullet points for rvlaue refs to functions. Because
3370 // there are no function rvalues in C++, rvalue refs to functions are treated
3371 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003372 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003373 bool T1Function = T1->isFunctionType();
3374 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003376 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003378 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003380 // reference-compatible with "cv2 T2," or
3381 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003384 // can occur. However, we do pay attention to whether it is a bit-field
3385 // to decide whether we're actually binding to a temporary created from
3386 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003387 if (DerivedToBase)
3388 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003389 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003390 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003391 else if (ObjCConversion)
3392 Sequence.AddObjCObjectConversionStep(
3393 S.Context.getQualifiedType(T1, T2Quals));
3394
Chandler Carruth5535c382010-01-12 20:32:25 +00003395 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003396 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003397 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003398 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003399 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003400 return;
3401 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003402
3403 // - has a class type (i.e., T2 is a class type), where T1 is not
3404 // reference-related to T2, and can be implicitly converted to an
3405 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3406 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003407 // applicable conversion functions (13.3.1.6) and choosing the best
3408 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003409 // If we have an rvalue ref to function type here, the rhs must be
3410 // an rvalue.
3411 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3412 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003414 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003415 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003416 Sequence);
3417 if (ConvOvlResult == OR_Success)
3418 return;
John McCall1d318332010-01-12 00:44:57 +00003419 if (ConvOvlResult != OR_No_Viable_Function) {
3420 Sequence.SetOverloadFailure(
3421 InitializationSequence::FK_ReferenceInitOverloadFailed,
3422 ConvOvlResult);
3423 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003424 }
3425 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003426
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003428 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003429 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003430 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003431 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3432 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3433 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003434 Sequence.SetOverloadFailure(
3435 InitializationSequence::FK_ReferenceInitOverloadFailed,
3436 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003437 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003438 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003439 ? (RefRelationship == Sema::Ref_Related
3440 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3441 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3442 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003443
Douglas Gregor20093b42009-12-09 23:02:17 +00003444 return;
3445 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003446
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003447 // - If the initializer expression
3448 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3449 // "cv1 T1" is reference-compatible with "cv2 T2"
3450 // Note: functions are handled below.
3451 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003452 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003453 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003454 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003455 (InitCategory.isXValue() ||
3456 (InitCategory.isPRValue() && T2->isRecordType()) ||
3457 (InitCategory.isPRValue() && T2->isArrayType()))) {
3458 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3459 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003460 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3461 // compiler the freedom to perform a copy here or bind to the
3462 // object, while C++0x requires that we bind directly to the
3463 // object. Hence, we always bind to the object without making an
3464 // extra copy. However, in C++03 requires that we check for the
3465 // presence of a suitable copy constructor:
3466 //
3467 // The constructor that would be used to make the copy shall
3468 // be callable whether or not the copy is actually done.
David Blaikie4e4d0842012-03-11 07:00:24 +00003469 if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003470 Sequence.AddExtraneousCopyToTemporary(cv2T2);
David Blaikie4e4d0842012-03-11 07:00:24 +00003471 else if (S.getLangOpts().CPlusPlus0x)
Richard Smith83da2e72011-10-19 16:55:56 +00003472 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003474
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003475 if (DerivedToBase)
3476 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3477 ValueKind);
3478 else if (ObjCConversion)
3479 Sequence.AddObjCObjectConversionStep(
3480 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003481
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003482 if (T1Quals != T2Quals)
3483 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003485 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488
3489 // - has a class type (i.e., T2 is a class type), where T1 is not
3490 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003491 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3492 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003493 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003494 if (RefRelationship == Sema::Ref_Incompatible) {
3495 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3496 Kind, Initializer,
3497 /*AllowRValues=*/true,
3498 Sequence);
3499 if (ConvOvlResult)
3500 Sequence.SetOverloadFailure(
3501 InitializationSequence::FK_ReferenceInitOverloadFailed,
3502 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003503
Douglas Gregor20093b42009-12-09 23:02:17 +00003504 return;
3505 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003506
Douglas Gregor20093b42009-12-09 23:02:17 +00003507 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3508 return;
3509 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003510
3511 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003512 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003513 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003514 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003515
Douglas Gregor20093b42009-12-09 23:02:17 +00003516 // Determine whether we are allowed to call explicit constructors or
3517 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003518 bool AllowExplicit = Kind.AllowExplicit();
John McCall369371c2010-06-04 02:29:22 +00003519
3520 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3521
John McCallf85e1932011-06-15 23:02:42 +00003522 ImplicitConversionSequence ICS
3523 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003524 /*SuppressUserConversions*/ false,
3525 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003526 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003527 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3528 /*AllowObjCWritebackConversion=*/false);
3529
3530 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003531 // FIXME: Use the conversion function set stored in ICS to turn
3532 // this into an overloading ambiguity diagnostic. However, we need
3533 // to keep that set as an OverloadCandidateSet rather than as some
3534 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003535 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3536 Sequence.SetOverloadFailure(
3537 InitializationSequence::FK_ReferenceInitOverloadFailed,
3538 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003539 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3540 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003541 else
3542 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003543 return;
John McCallf85e1932011-06-15 23:02:42 +00003544 } else {
3545 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003546 }
3547
3548 // [...] If T1 is reference-related to T2, cv1 must be the
3549 // same cv-qualification as, or greater cv-qualification
3550 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003551 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3552 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003553 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003554 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003555 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3556 return;
3557 }
3558
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003559 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003560 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003561 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003562 InitCategory.isLValue()) {
3563 Sequence.SetFailed(
3564 InitializationSequence::FK_RValueReferenceBindingToLValue);
3565 return;
3566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567
Douglas Gregor20093b42009-12-09 23:02:17 +00003568 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3569 return;
3570}
3571
3572/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003573/// (C++ [dcl.init.string], C99 6.7.8).
3574static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003575 const InitializedEntity &Entity,
3576 const InitializationKind &Kind,
3577 Expr *Initializer,
3578 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003579 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003580}
3581
Douglas Gregor71d17402009-12-15 00:01:57 +00003582/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003583static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003584 const InitializedEntity &Entity,
3585 const InitializationKind &Kind,
Richard Smithf4bb8d02012-07-05 08:39:21 +00003586 InitializationSequence &Sequence,
3587 InitListExpr *InitList) {
3588 assert((!InitList || InitList->getNumInits() == 0) &&
3589 "Shouldn't use value-init for non-empty init lists");
3590
Richard Smith1d0c9a82012-02-14 21:14:13 +00003591 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
Douglas Gregor71d17402009-12-15 00:01:57 +00003592 //
3593 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003594 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003595
Douglas Gregor71d17402009-12-15 00:01:57 +00003596 // -- if T is an array type, then each element is value-initialized;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003597 T = S.Context.getBaseElementType(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003598
Douglas Gregor71d17402009-12-15 00:01:57 +00003599 if (const RecordType *RT = T->getAs<RecordType>()) {
3600 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003601 bool NeedZeroInitialization = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00003602 if (!S.getLangOpts().CPlusPlus0x) {
Richard Smithf4bb8d02012-07-05 08:39:21 +00003603 // C++98:
3604 // -- if T is a class type (clause 9) with a user-declared constructor
3605 // (12.1), then the default constructor for T is called (and the
3606 // initialization is ill-formed if T has no accessible default
3607 // constructor);
Richard Smith1d0c9a82012-02-14 21:14:13 +00003608 if (ClassDecl->hasUserDeclaredConstructor())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003609 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003610 } else {
3611 // C++11:
3612 // -- if T is a class type (clause 9) with either no default constructor
3613 // (12.1 [class.ctor]) or a default constructor that is user-provided
3614 // or deleted, then the object is default-initialized;
3615 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3616 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
Richard Smithf4bb8d02012-07-05 08:39:21 +00003617 NeedZeroInitialization = false;
Richard Smith1d0c9a82012-02-14 21:14:13 +00003618 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003619
Richard Smith1d0c9a82012-02-14 21:14:13 +00003620 // -- if T is a (possibly cv-qualified) non-union class type without a
3621 // user-provided or deleted default constructor, then the object is
3622 // zero-initialized and, if T has a non-trivial default constructor,
3623 // default-initialized;
Richard Smith6678a052012-10-18 00:44:17 +00003624 // The 'non-union' here was removed by DR1502. The 'non-trivial default
3625 // constructor' part was removed by DR1507.
Richard Smithf4bb8d02012-07-05 08:39:21 +00003626 if (NeedZeroInitialization)
3627 Sequence.AddZeroInitializationStep(Entity.getType());
3628
3629 // If this is list-value-initialization, pass the empty init list on when
3630 // building the constructor call. This affects the semantics of a few
3631 // things (such as whether an explicit default constructor can be called).
3632 Expr *InitListAsExpr = InitList;
3633 Expr **Args = InitList ? &InitListAsExpr : 0;
3634 unsigned NumArgs = InitList ? 1 : 0;
3635 bool InitListSyntax = InitList;
3636
3637 return TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, T,
3638 Sequence, InitListSyntax);
Douglas Gregor71d17402009-12-15 00:01:57 +00003639 }
3640 }
3641
Douglas Gregord6542d82009-12-22 15:35:07 +00003642 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003643}
3644
Douglas Gregor99a2e602009-12-16 01:38:02 +00003645/// \brief Attempt default initialization (C++ [dcl.init]p6).
3646static void TryDefaultInitialization(Sema &S,
3647 const InitializedEntity &Entity,
3648 const InitializationKind &Kind,
3649 InitializationSequence &Sequence) {
3650 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003651
Douglas Gregor99a2e602009-12-16 01:38:02 +00003652 // C++ [dcl.init]p6:
3653 // To default-initialize an object of type T means:
3654 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003655 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3656
Douglas Gregor99a2e602009-12-16 01:38:02 +00003657 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3658 // constructor for T is called (and the initialization is ill-formed if
3659 // T has no accessible default constructor);
David Blaikie4e4d0842012-03-11 07:00:24 +00003660 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003661 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3662 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003663 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregor99a2e602009-12-16 01:38:02 +00003665 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003666
Douglas Gregor99a2e602009-12-16 01:38:02 +00003667 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003668 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003669 // default constructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00003670 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003671 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003672 return;
3673 }
3674
3675 // If the destination type has a lifetime property, zero-initialize it.
3676 if (DestType.getQualifiers().hasObjCLifetime()) {
3677 Sequence.AddZeroInitializationStep(Entity.getType());
3678 return;
3679 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003680}
3681
Douglas Gregor20093b42009-12-09 23:02:17 +00003682/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3683/// which enumerates all conversion functions and performs overload resolution
3684/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003685static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003686 const InitializedEntity &Entity,
3687 const InitializationKind &Kind,
3688 Expr *Initializer,
3689 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003690 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003691 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3692 QualType SourceType = Initializer->getType();
3693 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3694 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003695
Douglas Gregor4a520a22009-12-14 17:27:33 +00003696 // Build the candidate set directly in the initialization sequence
3697 // structure, so that it will persist if we fail.
3698 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3699 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003700
Douglas Gregor4a520a22009-12-14 17:27:33 +00003701 // Determine whether we are allowed to call explicit constructors or
3702 // explicit conversion operators.
Sebastian Redl168319c2012-02-12 16:37:24 +00003703 bool AllowExplicit = Kind.AllowExplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704
Douglas Gregor4a520a22009-12-14 17:27:33 +00003705 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3706 // The type we're converting to is a class type. Enumerate its constructors
3707 // to see if there is a suitable conversion.
3708 CXXRecordDecl *DestRecordDecl
3709 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003711 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003712 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
David Blaikie3d5cf5e2012-10-18 16:57:32 +00003713 DeclContext::lookup_iterator ConOrig, ConEndOrig;
3714 llvm::tie(ConOrig, ConEndOrig) = S.LookupConstructors(DestRecordDecl);
3715 // The container holding the constructors can under certain conditions
3716 // be changed while iterating. To be safe we copy the lookup results
3717 // to a new container.
3718 SmallVector<NamedDecl*, 8> CopyOfCon(ConOrig, ConEndOrig);
3719 for (SmallVector<NamedDecl*, 8>::iterator
3720 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003721 Con != ConEnd; ++Con) {
3722 NamedDecl *D = *Con;
3723 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003724
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003725 // Find the constructor (which may be a template).
3726 CXXConstructorDecl *Constructor = 0;
3727 FunctionTemplateDecl *ConstructorTmpl
3728 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003729 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003730 Constructor = cast<CXXConstructorDecl>(
3731 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003732 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003733 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003734
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003735 if (!Constructor->isInvalidDecl() &&
3736 Constructor->isConvertingConstructor(AllowExplicit)) {
3737 if (ConstructorTmpl)
3738 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3739 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003740 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003741 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003742 else
3743 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003744 Initializer, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003745 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003747 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003748 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003749 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003750
3751 SourceLocation DeclLoc = Initializer->getLocStart();
3752
Douglas Gregor4a520a22009-12-14 17:27:33 +00003753 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3754 // The type we're converting from is a class type, enumerate its conversion
3755 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003756
Eli Friedman33c2da92009-12-20 22:12:03 +00003757 // We can only enumerate the conversion functions for a complete type; if
3758 // the type isn't complete, simply skip this step.
3759 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3760 CXXRecordDecl *SourceRecordDecl
3761 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003762
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003763 std::pair<CXXRecordDecl::conversion_iterator,
3764 CXXRecordDecl::conversion_iterator>
3765 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
3766 for (CXXRecordDecl::conversion_iterator
3767 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Eli Friedman33c2da92009-12-20 22:12:03 +00003768 NamedDecl *D = *I;
3769 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3770 if (isa<UsingShadowDecl>(D))
3771 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
Eli Friedman33c2da92009-12-20 22:12:03 +00003773 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3774 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003775 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003776 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003777 else
John McCall32daa422010-03-31 01:36:47 +00003778 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779
Eli Friedman33c2da92009-12-20 22:12:03 +00003780 if (AllowExplicit || !Conv->isExplicit()) {
3781 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003782 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003783 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003784 CandidateSet);
3785 else
John McCall9aa472c2010-03-19 07:35:19 +00003786 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003787 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003788 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003789 }
3790 }
3791 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003792
3793 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003794 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003795 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003796 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003797 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003799 Result);
3800 return;
3801 }
John McCall1d318332010-01-12 00:44:57 +00003802
Douglas Gregor4a520a22009-12-14 17:27:33 +00003803 FunctionDecl *Function = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00003804 S.MarkFunctionReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003805 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806
Douglas Gregor4a520a22009-12-14 17:27:33 +00003807 if (isa<CXXConstructorDecl>(Function)) {
3808 // Add the user-defined conversion step. Any cv-qualification conversion is
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003809 // subsumed by the initialization. Per DR5, the created temporary is of the
3810 // cv-unqualified type of the destination.
3811 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3812 DestType.getUnqualifiedType(),
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003813 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003814 return;
3815 }
3816
3817 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003818 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003819 if (ConvType->getAs<RecordType>()) {
Richard Smithf2e4dfc2012-02-11 19:22:50 +00003820 // If we're converting to a class type, there may be an copy of
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003821 // the resulting temporary object (possible to create an object of
3822 // a base class type). That copy is not a separate conversion, so
3823 // we just make a note of the actual destination type (possibly a
3824 // base class of the type returned by the conversion function) and
3825 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003826 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3827 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003828 return;
3829 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003830
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003831 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3832 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003833
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003834 // If the conversion following the call to the conversion function
3835 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003836 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3837 Best->FinalConversion.Third) {
3838 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003839 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003840 ICS.Standard = Best->FinalConversion;
3841 Sequence.AddConversionSequenceStep(ICS, DestType);
3842 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003843}
3844
John McCallf85e1932011-06-15 23:02:42 +00003845/// The non-zero enum values here are indexes into diagnostic alternatives.
3846enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3847
3848/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003849static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003850 bool isAddressOf, bool &isWeakAccess) {
John McCallf85e1932011-06-15 23:02:42 +00003851 // Skip parens.
3852 e = e->IgnoreParens();
3853
3854 // Skip address-of nodes.
3855 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3856 if (op->getOpcode() == UO_AddrOf)
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003857 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
3858 isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00003859
3860 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003861 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3862 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003863 case CK_Dependent:
3864 case CK_BitCast:
3865 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003866 case CK_NoOp:
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003867 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00003868
3869 case CK_ArrayToPointerDecay:
3870 return IIK_nonscalar;
3871
3872 case CK_NullToPointer:
3873 return IIK_okay;
3874
3875 default:
3876 break;
3877 }
3878
3879 // If we have a declaration reference, it had better be a local variable.
John McCallf4b88a42012-03-10 09:33:50 +00003880 } else if (isa<DeclRefExpr>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003881 // set isWeakAccess to true, to mean that there will be an implicit
3882 // load which requires a cleanup.
3883 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
3884 isWeakAccess = true;
3885
John McCallc03fa492011-06-27 23:59:58 +00003886 if (!isAddressOf) return IIK_nonlocal;
3887
John McCallf4b88a42012-03-10 09:33:50 +00003888 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3889 if (!var) return IIK_nonlocal;
John McCallc03fa492011-06-27 23:59:58 +00003890
3891 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003892
3893 // If we have a conditional operator, check both sides.
3894 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003895 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
3896 isWeakAccess))
John McCallf85e1932011-06-15 23:02:42 +00003897 return iik;
3898
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003899 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
John McCallf85e1932011-06-15 23:02:42 +00003900
3901 // These are never scalar.
3902 } else if (isa<ArraySubscriptExpr>(e)) {
3903 return IIK_nonscalar;
3904
3905 // Otherwise, it needs to be a null pointer constant.
3906 } else {
3907 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3908 ? IIK_okay : IIK_nonlocal);
3909 }
3910
3911 return IIK_nonlocal;
3912}
3913
3914/// Check whether the given expression is a valid operand for an
3915/// indirect copy/restore.
3916static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3917 assert(src->isRValue());
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00003918 bool isWeakAccess = false;
3919 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
3920 // If isWeakAccess to true, there will be an implicit
3921 // load which requires a cleanup.
3922 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
3923 S.ExprNeedsCleanups = true;
3924
John McCallf85e1932011-06-15 23:02:42 +00003925 if (iik == IIK_okay) return;
3926
3927 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3928 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3929 << src->getSourceRange();
3930}
3931
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003932/// \brief Determine whether we have compatible array types for the
3933/// purposes of GNU by-copy array initialization.
3934static bool hasCompatibleArrayTypes(ASTContext &Context,
3935 const ArrayType *Dest,
3936 const ArrayType *Source) {
3937 // If the source and destination array types are equivalent, we're
3938 // done.
3939 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3940 return true;
3941
3942 // Make sure that the element types are the same.
3943 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3944 return false;
3945
3946 // The only mismatch we allow is when the destination is an
3947 // incomplete array type and the source is a constant array type.
3948 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3949}
3950
John McCallf85e1932011-06-15 23:02:42 +00003951static bool tryObjCWritebackConversion(Sema &S,
3952 InitializationSequence &Sequence,
3953 const InitializedEntity &Entity,
3954 Expr *Initializer) {
3955 bool ArrayDecay = false;
3956 QualType ArgType = Initializer->getType();
3957 QualType ArgPointee;
3958 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3959 ArrayDecay = true;
3960 ArgPointee = ArgArrayType->getElementType();
3961 ArgType = S.Context.getPointerType(ArgPointee);
3962 }
3963
3964 // Handle write-back conversion.
3965 QualType ConvertedArgType;
3966 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3967 ConvertedArgType))
3968 return false;
3969
3970 // We should copy unless we're passing to an argument explicitly
3971 // marked 'out'.
3972 bool ShouldCopy = true;
3973 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3974 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3975
3976 // Do we need an lvalue conversion?
3977 if (ArrayDecay || Initializer->isGLValue()) {
3978 ImplicitConversionSequence ICS;
3979 ICS.setStandard();
3980 ICS.Standard.setAsIdentityConversion();
3981
3982 QualType ResultType;
3983 if (ArrayDecay) {
3984 ICS.Standard.First = ICK_Array_To_Pointer;
3985 ResultType = S.Context.getPointerType(ArgPointee);
3986 } else {
3987 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3988 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3989 }
3990
3991 Sequence.AddConversionSequenceStep(ICS, ResultType);
3992 }
3993
3994 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3995 return true;
3996}
3997
Douglas Gregor20093b42009-12-09 23:02:17 +00003998InitializationSequence::InitializationSequence(Sema &S,
3999 const InitializedEntity &Entity,
4000 const InitializationKind &Kind,
4001 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00004002 unsigned NumArgs)
4003 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004004 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004005
Douglas Gregor20093b42009-12-09 23:02:17 +00004006 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004007 // The semantics of initializers are as follows. The destination type is
4008 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004009 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004010 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004011 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004012 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004013
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004014 if (DestType->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +00004015 Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004016 SequenceKind = DependentSequence;
4017 return;
4018 }
4019
Sebastian Redl7491c492011-06-05 13:59:11 +00004020 // Almost everything is a normal sequence.
4021 setSequenceKind(NormalSequence);
4022
John McCall241d5582010-12-07 22:54:16 +00004023 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00004024 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00004025 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00004026 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4027 if (result.isInvalid()) {
4028 SetFailed(FK_PlaceholderType);
4029 return;
John McCall5acb0c92011-10-17 18:40:02 +00004030 }
John McCall32509f12011-11-15 01:35:18 +00004031 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00004032 }
John McCall241d5582010-12-07 22:54:16 +00004033
John McCall5acb0c92011-10-17 18:40:02 +00004034
Douglas Gregor20093b42009-12-09 23:02:17 +00004035 QualType SourceType;
4036 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004037 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004038 Initializer = Args[0];
4039 if (!isa<InitListExpr>(Initializer))
4040 SourceType = Initializer->getType();
4041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004042
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00004043 // - If the initializer is a (non-parenthesized) braced-init-list, the
4044 // object is list-initialized (8.5.4).
4045 if (Kind.getKind() != InitializationKind::IK_Direct) {
4046 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4047 TryListInitialization(S, Entity, Kind, InitList, *this);
4048 return;
4049 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004050 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004051
Douglas Gregor20093b42009-12-09 23:02:17 +00004052 // - If the destination type is a reference type, see 8.5.3.
4053 if (DestType->isReferenceType()) {
4054 // C++0x [dcl.init.ref]p1:
4055 // A variable declared to be a T& or T&&, that is, "reference to type T"
4056 // (8.3.2), shall be initialized by an object, or function, of type T or
4057 // by an object that can be converted into a T.
4058 // (Therefore, multiple arguments are not permitted.)
4059 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004060 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004061 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004062 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004063 return;
4064 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004065
Douglas Gregor20093b42009-12-09 23:02:17 +00004066 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004067 if (Kind.getKind() == InitializationKind::IK_Value ||
4068 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004069 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004070 return;
4071 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072
Douglas Gregor99a2e602009-12-16 01:38:02 +00004073 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004074 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004075 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004076 return;
4077 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004078
John McCallce6c9b72011-02-21 07:22:22 +00004079 // - If the destination type is an array of characters, an array of
4080 // char16_t, an array of char32_t, or an array of wchar_t, and the
4081 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004082 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004083 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004084 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004085 if (Initializer && isa<VariableArrayType>(DestAT)) {
4086 SetFailed(FK_VariableLengthArrayHasInitializer);
4087 return;
4088 }
4089
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004090 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004091 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004092 return;
4093 }
4094
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004095 // Note: as an GNU C extension, we allow initialization of an
4096 // array from a compound literal that creates an array of the same
4097 // type, so long as the initializer has no side effects.
David Blaikie4e4d0842012-03-11 07:00:24 +00004098 if (!S.getLangOpts().CPlusPlus && Initializer &&
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004099 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4100 Initializer->getType()->isArrayType()) {
4101 const ArrayType *SourceAT
4102 = Context.getAsArrayType(Initializer->getType());
4103 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004104 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004105 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004106 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004107 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004108 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004109 }
Richard Smith0f163e92012-02-15 22:38:09 +00004110 }
Richard Smithf4bb8d02012-07-05 08:39:21 +00004111 // Note: as a GNU C++ extension, we allow list-initialization of a
4112 // class member of array type from a parenthesized initializer list.
David Blaikie4e4d0842012-03-11 07:00:24 +00004113 else if (S.getLangOpts().CPlusPlus &&
Richard Smith0f163e92012-02-15 22:38:09 +00004114 Entity.getKind() == InitializedEntity::EK_Member &&
4115 Initializer && isa<InitListExpr>(Initializer)) {
4116 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4117 *this);
4118 AddParenthesizedArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004119 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004120 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004121 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004122 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004123
Douglas Gregor20093b42009-12-09 23:02:17 +00004124 return;
4125 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004126
John McCallf85e1932011-06-15 23:02:42 +00004127 // Determine whether we should consider writeback conversions for
4128 // Objective-C ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00004129 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004130 Entity.getKind() == InitializedEntity::EK_Parameter;
4131
4132 // We're at the end of the line for C: it's either a write-back conversion
4133 // or it's a C assignment. There's no need to check anything else.
David Blaikie4e4d0842012-03-11 07:00:24 +00004134 if (!S.getLangOpts().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004135 // If allowed, check whether this is an Objective-C writeback conversion.
4136 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004137 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004138 return;
4139 }
4140
4141 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004142 AddCAssignmentStep(DestType);
4143 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004144 return;
4145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004146
David Blaikie4e4d0842012-03-11 07:00:24 +00004147 assert(S.getLangOpts().CPlusPlus);
John McCallf85e1932011-06-15 23:02:42 +00004148
Douglas Gregor20093b42009-12-09 23:02:17 +00004149 // - If the destination type is a (possibly cv-qualified) class type:
4150 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004151 // - If the initialization is direct-initialization, or if it is
4152 // copy-initialization where the cv-unqualified version of the
4153 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004154 // class of the destination, constructors are considered. [...]
4155 if (Kind.getKind() == InitializationKind::IK_Direct ||
4156 (Kind.getKind() == InitializationKind::IK_Copy &&
4157 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4158 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004160 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004161 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004162 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004164 // used) to a derived class thereof are enumerated as described in
4165 // 13.3.1.4, and the best one is chosen through overload resolution
4166 // (13.3).
4167 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004168 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004169 return;
4170 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004171
Douglas Gregor99a2e602009-12-16 01:38:02 +00004172 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004173 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004174 return;
4175 }
4176 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004177
4178 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004179 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004180 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004181 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4182 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004183 return;
4184 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185
Douglas Gregor20093b42009-12-09 23:02:17 +00004186 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004187 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004188 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004189 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004190 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004191
4192 ImplicitConversionSequence ICS
4193 = S.TryImplicitConversion(Initializer, Entity.getType(),
4194 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004195 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004196 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004197 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4198 allowObjCWritebackConversion);
4199
4200 if (ICS.isStandard() &&
4201 ICS.Standard.Second == ICK_Writeback_Conversion) {
4202 // Objective-C ARC writeback conversion.
4203
4204 // We should copy unless we're passing to an argument explicitly
4205 // marked 'out'.
4206 bool ShouldCopy = true;
4207 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4208 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4209
4210 // If there was an lvalue adjustment, add it as a separate conversion.
4211 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4212 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4213 ImplicitConversionSequence LvalueICS;
4214 LvalueICS.setStandard();
4215 LvalueICS.Standard.setAsIdentityConversion();
4216 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4217 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004218 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004219 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004220
4221 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004222 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004223 DeclAccessPair dap;
4224 if (Initializer->getType() == Context.OverloadTy &&
4225 !S.ResolveAddressOfOverloadedFunction(Initializer
4226 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004227 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004228 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004229 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004230 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004231 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004232
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004233 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004234 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004235}
4236
4237InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004238 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004239 StepEnd = Steps.end();
4240 Step != StepEnd; ++Step)
4241 Step->Destroy();
4242}
4243
4244//===----------------------------------------------------------------------===//
4245// Perform initialization
4246//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004247static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004248getAssignmentAction(const InitializedEntity &Entity) {
4249 switch(Entity.getKind()) {
4250 case InitializedEntity::EK_Variable:
4251 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004252 case InitializedEntity::EK_Exception:
4253 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004254 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004255 return Sema::AA_Initializing;
4256
4257 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004259 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4260 return Sema::AA_Sending;
4261
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004262 return Sema::AA_Passing;
4263
4264 case InitializedEntity::EK_Result:
4265 return Sema::AA_Returning;
4266
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004267 case InitializedEntity::EK_Temporary:
4268 // FIXME: Can we tell apart casting vs. converting?
4269 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004271 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004272 case InitializedEntity::EK_ArrayElement:
4273 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004274 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004275 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004276 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004277 return Sema::AA_Initializing;
4278 }
4279
David Blaikie7530c032012-01-17 06:56:22 +00004280 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004281}
4282
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004283/// \brief Whether we should binding a created object as a temporary when
4284/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004285static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004286 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004287 case InitializedEntity::EK_ArrayElement:
4288 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004289 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004290 case InitializedEntity::EK_New:
4291 case InitializedEntity::EK_Variable:
4292 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004293 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004294 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004295 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004296 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004297 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004298 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004299 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004301 case InitializedEntity::EK_Parameter:
4302 case InitializedEntity::EK_Temporary:
4303 return true;
4304 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004305
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004306 llvm_unreachable("missed an InitializedEntity kind?");
4307}
4308
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004309/// \brief Whether the given entity, when initialized with an object
4310/// created for that initialization, requires destruction.
4311static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4312 switch (Entity.getKind()) {
4313 case InitializedEntity::EK_Member:
4314 case InitializedEntity::EK_Result:
4315 case InitializedEntity::EK_New:
4316 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004317 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004318 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004319 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004320 case InitializedEntity::EK_BlockElement:
Douglas Gregor47736542012-02-15 16:57:26 +00004321 case InitializedEntity::EK_LambdaCapture:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004322 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004324 case InitializedEntity::EK_Variable:
4325 case InitializedEntity::EK_Parameter:
4326 case InitializedEntity::EK_Temporary:
4327 case InitializedEntity::EK_ArrayElement:
4328 case InitializedEntity::EK_Exception:
4329 return true;
4330 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004331
4332 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004333}
4334
Richard Smith83da2e72011-10-19 16:55:56 +00004335/// \brief Look for copy and move constructors and constructor templates, for
4336/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4337static void LookupCopyAndMoveConstructors(Sema &S,
4338 OverloadCandidateSet &CandidateSet,
4339 CXXRecordDecl *Class,
4340 Expr *CurInitExpr) {
4341 DeclContext::lookup_iterator Con, ConEnd;
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004342 llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4343 // The container holding the constructors can under certain conditions
4344 // be changed while iterating (e.g. because of deserialization).
4345 // To be safe we copy the lookup results to a new container.
4346 SmallVector<NamedDecl*, 16> Ctors(Con, ConEnd);
4347 for (SmallVector<NamedDecl*, 16>::iterator
4348 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4349 NamedDecl *D = *CI;
Richard Smith83da2e72011-10-19 16:55:56 +00004350 CXXConstructorDecl *Constructor = 0;
4351
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004352 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
Richard Smith83da2e72011-10-19 16:55:56 +00004353 // Handle copy/moveconstructors, only.
4354 if (!Constructor || Constructor->isInvalidDecl() ||
4355 !Constructor->isCopyOrMoveConstructor() ||
4356 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4357 continue;
4358
4359 DeclAccessPair FoundDecl
4360 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4361 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004362 CurInitExpr, CandidateSet);
Richard Smith83da2e72011-10-19 16:55:56 +00004363 continue;
4364 }
4365
4366 // Handle constructor templates.
Argyrios Kyrtzidis8682b932012-11-13 05:07:23 +00004367 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
Richard Smith83da2e72011-10-19 16:55:56 +00004368 if (ConstructorTmpl->isInvalidDecl())
4369 continue;
4370
4371 Constructor = cast<CXXConstructorDecl>(
4372 ConstructorTmpl->getTemplatedDecl());
4373 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4374 continue;
4375
4376 // FIXME: Do we need to limit this to copy-constructor-like
4377 // candidates?
4378 DeclAccessPair FoundDecl
4379 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4380 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00004381 CurInitExpr, CandidateSet, true);
Richard Smith83da2e72011-10-19 16:55:56 +00004382 }
4383}
4384
4385/// \brief Get the location at which initialization diagnostics should appear.
4386static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4387 Expr *Initializer) {
4388 switch (Entity.getKind()) {
4389 case InitializedEntity::EK_Result:
4390 return Entity.getReturnLoc();
4391
4392 case InitializedEntity::EK_Exception:
4393 return Entity.getThrowLoc();
4394
4395 case InitializedEntity::EK_Variable:
4396 return Entity.getDecl()->getLocation();
4397
Douglas Gregor47736542012-02-15 16:57:26 +00004398 case InitializedEntity::EK_LambdaCapture:
4399 return Entity.getCaptureLoc();
4400
Richard Smith83da2e72011-10-19 16:55:56 +00004401 case InitializedEntity::EK_ArrayElement:
4402 case InitializedEntity::EK_Member:
4403 case InitializedEntity::EK_Parameter:
4404 case InitializedEntity::EK_Temporary:
4405 case InitializedEntity::EK_New:
4406 case InitializedEntity::EK_Base:
4407 case InitializedEntity::EK_Delegating:
4408 case InitializedEntity::EK_VectorElement:
4409 case InitializedEntity::EK_ComplexElement:
4410 case InitializedEntity::EK_BlockElement:
4411 return Initializer->getLocStart();
4412 }
4413 llvm_unreachable("missed an InitializedEntity kind?");
4414}
4415
Douglas Gregor523d46a2010-04-18 07:40:54 +00004416/// \brief Make a (potentially elidable) temporary copy of the object
4417/// provided by the given initializer by calling the appropriate copy
4418/// constructor.
4419///
4420/// \param S The Sema object used for type-checking.
4421///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004422/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004423/// the type of the initializer expression or a superclass thereof.
4424///
James Dennett1dfbd922012-06-14 21:40:34 +00004425/// \param Entity The entity being initialized.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004426///
4427/// \param CurInit The initializer expression.
4428///
4429/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4430/// is permitted in C++03 (but not C++0x) when binding a reference to
4431/// an rvalue.
4432///
4433/// \returns An expression that copies the initializer expression into
4434/// a temporary object, or an error expression if a copy could not be
4435/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004436static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004437 QualType T,
4438 const InitializedEntity &Entity,
4439 ExprResult CurInit,
4440 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004441 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004442 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004443 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004444 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004445 Class = cast<CXXRecordDecl>(Record->getDecl());
4446 if (!Class)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004447 return CurInit;
Douglas Gregor2f599792010-04-02 18:24:57 +00004448
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004449 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004450 // When certain criteria are met, an implementation is allowed to
4451 // omit the copy/move construction of a class object, even if the
4452 // copy/move constructor and/or destructor for the object have
4453 // side effects. [...]
4454 // - when a temporary class object that has not been bound to a
4455 // reference (12.2) would be copied/moved to a class object
4456 // with the same cv-unqualified type, the copy/move operation
4457 // can be omitted by constructing the temporary object
4458 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004459 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004460 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004461 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004462 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004463 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004464 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004465 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004466
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004467 // Make sure that the type we are copying is complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004468 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004469 return CurInit;
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004470
Douglas Gregorcc15f012011-01-21 19:38:21 +00004471 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004472 // Only consider constructors and constructor templates. Per
4473 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4474 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004475 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004476 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004477
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004478 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4479
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004480 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004481 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004482 case OR_Success:
4483 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004485 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004486 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4487 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4488 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004489 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004490 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004491 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004492 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004493 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004494 return CurInit;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004496 case OR_Ambiguous:
4497 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004498 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004499 << CurInitExpr->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00004500 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
John McCallf312b1e2010-08-26 23:41:50 +00004501 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004502
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004503 case OR_Deleted:
4504 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004505 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004506 << CurInitExpr->getSourceRange();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004507 S.NoteDeletedFunction(Best->Function);
John McCallf312b1e2010-08-26 23:41:50 +00004508 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004509 }
4510
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004511 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004512 SmallVector<Expr*, 8> ConstructorArgs;
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004513 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004514
Anders Carlsson9a68a672010-04-21 18:47:17 +00004515 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004516 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004517
4518 if (IsExtraneousCopy) {
4519 // If this is a totally extraneous copy for C++03 reference
4520 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004521 // expression. We don't generate an (elided) copy operation here
4522 // because doing so would require us to pass down a flag to avoid
4523 // infinite recursion, where each step adds another extraneous,
4524 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004525
Douglas Gregor2559a702010-04-18 07:57:34 +00004526 // Instantiate the default arguments of any extra parameters in
4527 // the selected copy constructor, as if we were going to create a
4528 // proper call to the copy constructor.
4529 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4530 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4531 if (S.RequireCompleteType(Loc, Parm->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004532 diag::err_call_incomplete_argument))
Douglas Gregor2559a702010-04-18 07:57:34 +00004533 break;
4534
4535 // Build the default argument expression; we don't actually care
4536 // if this succeeds or not, because this routine will complain
4537 // if there was a problem.
4538 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4539 }
4540
Douglas Gregor523d46a2010-04-18 07:40:54 +00004541 return S.Owned(CurInitExpr);
4542 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004543
Eli Friedman5f2987c2012-02-02 03:46:19 +00004544 S.MarkFunctionReferenced(Loc, Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00004545
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004546 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004547 // constructor call (we might have derived-to-base conversions, or
4548 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004549 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004550 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004551 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004552
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004553 // Actually perform the constructor call.
4554 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004555 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004556 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004557 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004558 CXXConstructExpr::CK_Complete,
4559 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004560
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004561 // If we're supposed to bind temporaries, do so.
4562 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4563 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004564 return CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004565}
Douglas Gregor20093b42009-12-09 23:02:17 +00004566
Richard Smith83da2e72011-10-19 16:55:56 +00004567/// \brief Check whether elidable copy construction for binding a reference to
4568/// a temporary would have succeeded if we were building in C++98 mode, for
4569/// -Wc++98-compat.
4570static void CheckCXX98CompatAccessibleCopy(Sema &S,
4571 const InitializedEntity &Entity,
4572 Expr *CurInitExpr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004573 assert(S.getLangOpts().CPlusPlus0x);
Richard Smith83da2e72011-10-19 16:55:56 +00004574
4575 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4576 if (!Record)
4577 return;
4578
4579 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4580 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4581 == DiagnosticsEngine::Ignored)
4582 return;
4583
4584 // Find constructors which would have been considered.
4585 OverloadCandidateSet CandidateSet(Loc);
4586 LookupCopyAndMoveConstructors(
4587 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4588
4589 // Perform overload resolution.
4590 OverloadCandidateSet::iterator Best;
4591 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4592
4593 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4594 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4595 << CurInitExpr->getSourceRange();
4596
4597 switch (OR) {
4598 case OR_Success:
4599 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
John McCallb9abd8722012-04-07 03:04:20 +00004600 Entity, Best->FoundDecl.getAccess(), Diag);
Richard Smith83da2e72011-10-19 16:55:56 +00004601 // FIXME: Check default arguments as far as that's possible.
4602 break;
4603
4604 case OR_No_Viable_Function:
4605 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004606 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004607 break;
4608
4609 case OR_Ambiguous:
4610 S.Diag(Loc, Diag);
Ahmed Charles13a140c2012-02-25 11:00:22 +00004611 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
Richard Smith83da2e72011-10-19 16:55:56 +00004612 break;
4613
4614 case OR_Deleted:
4615 S.Diag(Loc, Diag);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004616 S.NoteDeletedFunction(Best->Function);
Richard Smith83da2e72011-10-19 16:55:56 +00004617 break;
4618 }
4619}
4620
Douglas Gregora41a8c52010-04-22 00:20:18 +00004621void InitializationSequence::PrintInitLocationNote(Sema &S,
4622 const InitializedEntity &Entity) {
4623 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4624 if (Entity.getDecl()->getLocation().isInvalid())
4625 return;
4626
4627 if (Entity.getDecl()->getDeclName())
4628 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4629 << Entity.getDecl()->getDeclName();
4630 else
4631 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4632 }
4633}
4634
Sebastian Redl3b802322011-07-14 19:07:55 +00004635static bool isReferenceBinding(const InitializationSequence::Step &s) {
4636 return s.Kind == InitializationSequence::SK_BindReference ||
4637 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4638}
4639
Sebastian Redl10f04a62011-12-22 14:44:04 +00004640static ExprResult
4641PerformConstructorInitialization(Sema &S,
4642 const InitializedEntity &Entity,
4643 const InitializationKind &Kind,
4644 MultiExprArg Args,
4645 const InitializationSequence::Step& Step,
4646 bool &ConstructorInitRequiresZeroInit) {
4647 unsigned NumArgs = Args.size();
4648 CXXConstructorDecl *Constructor
4649 = cast<CXXConstructorDecl>(Step.Function.Function);
4650 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4651
4652 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00004653 SmallVector<Expr*, 8> ConstructorArgs;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004654 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4655 ? Kind.getEqualLoc()
4656 : Kind.getLocation();
4657
4658 if (Kind.getKind() == InitializationKind::IK_Default) {
4659 // Force even a trivial, implicit default constructor to be
4660 // semantically checked. We do this explicitly because we don't build
4661 // the definition for completely trivial constructors.
Matt Beaumont-Gay28e47022012-02-24 08:37:56 +00004662 assert(Constructor->getParent() && "No parent class for constructor.");
Sebastian Redl10f04a62011-12-22 14:44:04 +00004663 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Douglas Gregor5d86f612012-02-24 07:48:37 +00004664 Constructor->isTrivial() && !Constructor->isUsed(false))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004665 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4666 }
4667
4668 ExprResult CurInit = S.Owned((Expr *)0);
4669
Douglas Gregored878af2012-02-24 23:56:31 +00004670 // C++ [over.match.copy]p1:
4671 // - When initializing a temporary to be bound to the first parameter
4672 // of a constructor that takes a reference to possibly cv-qualified
4673 // T as its first argument, called with a single argument in the
4674 // context of direct-initialization, explicit conversion functions
4675 // are also considered.
4676 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
4677 Args.size() == 1 &&
4678 Constructor->isCopyOrMoveConstructor();
4679
Sebastian Redl10f04a62011-12-22 14:44:04 +00004680 // Determine the arguments required to actually perform the constructor
4681 // call.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004682 if (S.CompleteConstructorCall(Constructor, Args,
Douglas Gregored878af2012-02-24 23:56:31 +00004683 Loc, ConstructorArgs,
4684 AllowExplicitConv))
Sebastian Redl10f04a62011-12-22 14:44:04 +00004685 return ExprError();
4686
4687
4688 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Sebastian Redl188158d2012-03-08 21:05:45 +00004689 (Kind.getKind() == InitializationKind::IK_DirectList ||
4690 (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4691 (Kind.getKind() == InitializationKind::IK_Direct ||
4692 Kind.getKind() == InitializationKind::IK_Value)))) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00004693 // An explicitly-constructed temporary, e.g., X(1, 2).
Eli Friedman5f2987c2012-02-02 03:46:19 +00004694 S.MarkFunctionReferenced(Loc, Constructor);
Sebastian Redl10f04a62011-12-22 14:44:04 +00004695 S.DiagnoseUseOfDecl(Constructor, Loc);
4696
4697 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4698 if (!TSInfo)
4699 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
Sebastian Redl188158d2012-03-08 21:05:45 +00004700 SourceRange ParenRange;
4701 if (Kind.getKind() != InitializationKind::IK_DirectList)
4702 ParenRange = Kind.getParenRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00004703
4704 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4705 Constructor,
4706 TSInfo,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004707 ConstructorArgs,
Sebastian Redl188158d2012-03-08 21:05:45 +00004708 ParenRange,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004709 HadMultipleCandidates,
4710 ConstructorInitRequiresZeroInit));
4711 } else {
4712 CXXConstructExpr::ConstructionKind ConstructKind =
4713 CXXConstructExpr::CK_Complete;
4714
4715 if (Entity.getKind() == InitializedEntity::EK_Base) {
4716 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4717 CXXConstructExpr::CK_VirtualBase :
4718 CXXConstructExpr::CK_NonVirtualBase;
4719 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4720 ConstructKind = CXXConstructExpr::CK_Delegating;
4721 }
4722
4723 // Only get the parenthesis range if it is a direct construction.
4724 SourceRange parenRange =
4725 Kind.getKind() == InitializationKind::IK_Direct ?
4726 Kind.getParenRange() : SourceRange();
4727
4728 // If the entity allows NRVO, mark the construction as elidable
4729 // unconditionally.
4730 if (Entity.allowsNRVO())
4731 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4732 Constructor, /*Elidable=*/true,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004733 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004734 HadMultipleCandidates,
4735 ConstructorInitRequiresZeroInit,
4736 ConstructKind,
4737 parenRange);
4738 else
4739 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4740 Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004741 ConstructorArgs,
Sebastian Redl10f04a62011-12-22 14:44:04 +00004742 HadMultipleCandidates,
4743 ConstructorInitRequiresZeroInit,
4744 ConstructKind,
4745 parenRange);
4746 }
4747 if (CurInit.isInvalid())
4748 return ExprError();
4749
4750 // Only check access if all of that succeeded.
4751 S.CheckConstructorAccess(Loc, Constructor, Entity,
4752 Step.Function.FoundDecl.getAccess());
4753 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4754
4755 if (shouldBindAsTemporary(Entity))
4756 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4757
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004758 return CurInit;
Sebastian Redl10f04a62011-12-22 14:44:04 +00004759}
4760
Richard Smith36d02af2012-06-04 22:27:30 +00004761/// Determine whether the specified InitializedEntity definitely has a lifetime
4762/// longer than the current full-expression. Conservatively returns false if
4763/// it's unclear.
4764static bool
4765InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
4766 const InitializedEntity *Top = &Entity;
4767 while (Top->getParent())
4768 Top = Top->getParent();
4769
4770 switch (Top->getKind()) {
4771 case InitializedEntity::EK_Variable:
4772 case InitializedEntity::EK_Result:
4773 case InitializedEntity::EK_Exception:
4774 case InitializedEntity::EK_Member:
4775 case InitializedEntity::EK_New:
4776 case InitializedEntity::EK_Base:
4777 case InitializedEntity::EK_Delegating:
4778 return true;
4779
4780 case InitializedEntity::EK_ArrayElement:
4781 case InitializedEntity::EK_VectorElement:
4782 case InitializedEntity::EK_BlockElement:
4783 case InitializedEntity::EK_ComplexElement:
4784 // Could not determine what the full initialization is. Assume it might not
4785 // outlive the full-expression.
4786 return false;
4787
4788 case InitializedEntity::EK_Parameter:
4789 case InitializedEntity::EK_Temporary:
4790 case InitializedEntity::EK_LambdaCapture:
4791 // The entity being initialized might not outlive the full-expression.
4792 return false;
4793 }
4794
4795 llvm_unreachable("unknown entity kind");
4796}
4797
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004798ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004799InitializationSequence::Perform(Sema &S,
4800 const InitializedEntity &Entity,
4801 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004802 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004803 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004804 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004805 unsigned NumArgs = Args.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00004806 Diagnose(S, Entity, Kind, Args.data(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004807 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004808 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004809
Sebastian Redl7491c492011-06-05 13:59:11 +00004810 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004811 // If the declaration is a non-dependent, incomplete array type
4812 // that has an initializer, then its type will be completed once
4813 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004814 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004815 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004816 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004817 if (const IncompleteArrayType *ArrayT
4818 = S.Context.getAsIncompleteArrayType(DeclType)) {
4819 // FIXME: We don't currently have the ability to accurately
4820 // compute the length of an initializer list without
4821 // performing full type-checking of the initializer list
4822 // (since we have to determine where braces are implicitly
4823 // introduced and such). So, we fall back to making the array
4824 // type a dependently-sized array type with no specified
4825 // bound.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004826 if (isa<InitListExpr>((Expr *)Args[0])) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004827 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004828
Douglas Gregord87b61f2009-12-10 17:56:55 +00004829 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004830 if (DeclaratorDecl *DD = Entity.getDecl()) {
4831 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4832 TypeLoc TL = TInfo->getTypeLoc();
4833 if (IncompleteArrayTypeLoc *ArrayLoc
4834 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4835 Brackets = ArrayLoc->getBracketsRange();
4836 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004837 }
4838
4839 *ResultType
4840 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4841 /*NumElts=*/0,
4842 ArrayT->getSizeModifier(),
4843 ArrayT->getIndexTypeCVRQualifiers(),
4844 Brackets);
4845 }
4846
4847 }
4848 }
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004849 if (Kind.getKind() == InitializationKind::IK_Direct &&
4850 !Kind.isExplicitCast()) {
4851 // Rebuild the ParenListExpr.
4852 SourceRange ParenRange = Kind.getParenRange();
4853 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004854 Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00004855 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004856 assert(Kind.getKind() == InitializationKind::IK_Copy ||
Douglas Gregora9b55a42012-04-04 04:06:51 +00004857 Kind.isExplicitCast() ||
4858 Kind.getKind() == InitializationKind::IK_DirectList);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004859 return ExprResult(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004860 }
4861
Sebastian Redl7491c492011-06-05 13:59:11 +00004862 // No steps means no initialization.
4863 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004864 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865
Richard Smith03544fc2012-04-19 06:58:00 +00004866 if (S.getLangOpts().CPlusPlus0x && Entity.getType()->isReferenceType() &&
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004867 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
Richard Smith03544fc2012-04-19 06:58:00 +00004868 Entity.getKind() != InitializedEntity::EK_Parameter) {
4869 // Produce a C++98 compatibility warning if we are initializing a reference
4870 // from an initializer list. For parameters, we produce a better warning
4871 // elsewhere.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004872 Expr *Init = Args[0];
Richard Smith03544fc2012-04-19 06:58:00 +00004873 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
4874 << Init->getSourceRange();
4875 }
4876
Richard Smith36d02af2012-06-04 22:27:30 +00004877 // Diagnose cases where we initialize a pointer to an array temporary, and the
4878 // pointer obviously outlives the temporary.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004879 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
Richard Smith36d02af2012-06-04 22:27:30 +00004880 Entity.getType()->isPointerType() &&
4881 InitializedEntityOutlivesFullExpression(Entity)) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004882 Expr *Init = Args[0];
Richard Smith36d02af2012-06-04 22:27:30 +00004883 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
4884 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
4885 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
4886 << Init->getSourceRange();
4887 }
4888
Douglas Gregord6542d82009-12-22 15:35:07 +00004889 QualType DestType = Entity.getType().getNonReferenceType();
4890 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004891 // the same as Entity.getDecl()->getType() in cases involving type merging,
4892 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004893 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004894 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004895 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004896
John McCall60d7b3a2010-08-24 06:29:42 +00004897 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004898
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004899 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004900 // grab the only argument out the Args and place it into the "current"
4901 // initializer.
4902 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004903 case SK_ResolveAddressOfOverloadedFunction:
4904 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004905 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004906 case SK_CastDerivedToBaseLValue:
4907 case SK_BindReference:
4908 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004909 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004910 case SK_UserConversion:
4911 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004912 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004913 case SK_QualificationConversionRValue:
4914 case SK_ConversionSequence:
4915 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004916 case SK_UnwrapInitList:
4917 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004918 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004919 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004920 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004921 case SK_ArrayInit:
Richard Smith0f163e92012-02-15 22:38:09 +00004922 case SK_ParenthesizedArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00004923 case SK_PassByIndirectCopyRestore:
4924 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00004925 case SK_ProduceObjCObject:
4926 case SK_StdInitializerList: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004927 assert(Args.size() == 1);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004928 CurInit = Args[0];
John Wiegley429bb272011-04-08 18:41:53 +00004929 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004930 break;
John McCallf6a16482010-12-04 03:47:34 +00004931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004932
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004933 case SK_ConstructorInitialization:
Richard Smithf4bb8d02012-07-05 08:39:21 +00004934 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004935 case SK_ZeroInitialization:
4936 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004937 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004938
4939 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004940 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004941 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004942 for (step_iterator Step = step_begin(), StepEnd = step_end();
4943 Step != StepEnd; ++Step) {
4944 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004945 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004946
John Wiegley429bb272011-04-08 18:41:53 +00004947 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004948
Douglas Gregor20093b42009-12-09 23:02:17 +00004949 switch (Step->Kind) {
4950 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004951 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004952 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004953 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004954 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004955 CurInit = S.FixOverloadedFunctionReference(CurInit,
John McCall6bb80172010-03-30 21:47:33 +00004956 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004957 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004958 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004959
Douglas Gregor20093b42009-12-09 23:02:17 +00004960 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004961 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004962 case SK_CastDerivedToBaseLValue: {
4963 // We have a derived-to-base cast that produces either an rvalue or an
4964 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004965
John McCallf871d0c2010-08-07 06:22:56 +00004966 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004967
Douglas Gregor20093b42009-12-09 23:02:17 +00004968 // Casts to inaccessible base classes are allowed with C-style casts.
4969 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4970 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004971 CurInit.get()->getLocStart(),
4972 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004973 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004974 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004975
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004976 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4977 QualType T = SourceType;
4978 if (const PointerType *Pointer = T->getAs<PointerType>())
4979 T = Pointer->getPointeeType();
4980 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004981 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004982 cast<CXXRecordDecl>(RecordTy->getDecl()));
4983 }
4984
John McCall5baba9d2010-08-25 10:28:54 +00004985 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004986 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004987 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004988 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004989 VK_XValue :
4990 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004991 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4992 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004993 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004994 CurInit.get(),
4995 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004996 break;
4997 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004998
Douglas Gregor20093b42009-12-09 23:02:17 +00004999 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00005000 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005001 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
5002 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00005003 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005004 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00005005 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00005006 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00005007 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005008 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00005009
John Wiegley429bb272011-04-08 18:41:53 +00005010 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00005011 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00005012 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5013 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00005014 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005015 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005016 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00005017 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005018
Douglas Gregor20093b42009-12-09 23:02:17 +00005019 // Reference binding does not have any corresponding ASTs.
5020
5021 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005022 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005023 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00005024
Douglas Gregor20093b42009-12-09 23:02:17 +00005025 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00005026
Douglas Gregor20093b42009-12-09 23:02:17 +00005027 case SK_BindReferenceToTemporary:
5028 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00005029 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00005030 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00005031
Douglas Gregor03e80032011-06-21 17:03:29 +00005032 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00005033 CurInit = new (S.Context) MaterializeTemporaryExpr(
5034 Entity.getType().getNonReferenceType(),
5035 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00005036 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00005037
5038 // If we're binding to an Objective-C object that has lifetime, we
5039 // need cleanups.
David Blaikie4e4d0842012-03-11 07:00:24 +00005040 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregord7b23162011-06-22 16:12:01 +00005041 CurInit.get()->getType()->isObjCLifetimeType())
5042 S.ExprNeedsCleanups = true;
5043
Douglas Gregor20093b42009-12-09 23:02:17 +00005044 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005045
Douglas Gregor523d46a2010-04-18 07:40:54 +00005046 case SK_ExtraneousCopyToTemporary:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005047 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
Douglas Gregor523d46a2010-04-18 07:40:54 +00005048 /*IsExtraneousCopy=*/true);
5049 break;
5050
Douglas Gregor20093b42009-12-09 23:02:17 +00005051 case SK_UserConversion: {
5052 // We have a user-defined conversion that invokes either a constructor
5053 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00005054 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005055 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00005056 FunctionDecl *Fn = Step->Function.Function;
5057 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005058 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005059 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00005060 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00005061 // Build a call to the selected constructor.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00005062 SmallVector<Expr*, 8> ConstructorArgs;
John Wiegley429bb272011-04-08 18:41:53 +00005063 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00005064 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00005065
Douglas Gregor20093b42009-12-09 23:02:17 +00005066 // Determine the arguments required to actually perform the constructor
5067 // call.
John Wiegley429bb272011-04-08 18:41:53 +00005068 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00005069 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00005070 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00005071 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00005072 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005073
Richard Smithf2e4dfc2012-02-11 19:22:50 +00005074 // Build an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005075 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005076 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005077 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00005078 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005079 CXXConstructExpr::CK_Complete,
5080 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005081 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005082 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005083
Anders Carlsson9a68a672010-04-21 18:47:17 +00005084 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005085 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00005086 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005087
John McCall2de56d12010-08-25 11:45:40 +00005088 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005089 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5090 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5091 S.IsDerivedFrom(SourceType, Class))
5092 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005093
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005094 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005095 } else {
5096 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005097 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005098 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005099 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00005100 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101
5102 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005103 // derived-to-base conversion? I believe the answer is "no", because
5104 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005105 ExprResult CurInitExprRes =
5106 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5107 FoundFn, Conversion);
5108 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005109 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005110 CurInit = CurInitExprRes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005111
Douglas Gregor20093b42009-12-09 23:02:17 +00005112 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005113 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5114 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005115 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005116 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005117
John McCall2de56d12010-08-25 11:45:40 +00005118 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005119
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005120 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005121 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
Sebastian Redl3b802322011-07-14 19:07:55 +00005123 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005124 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5125
5126 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005127 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005128 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005130 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005131 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005132 S.PDiag(diag::err_access_dtor_temp) << T);
Eli Friedman5f2987c2012-02-02 03:46:19 +00005133 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
John Wiegley429bb272011-04-08 18:41:53 +00005134 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005135 }
5136 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005137
John McCallf871d0c2010-08-07 06:22:56 +00005138 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005139 CurInit.get()->getType(),
5140 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005141 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005142 if (MaybeBindToTemp)
5143 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005144 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005145 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005146 CurInit, /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005147 break;
5148 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005149
Douglas Gregor20093b42009-12-09 23:02:17 +00005150 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005151 case SK_QualificationConversionXValue:
5152 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005153 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005154 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005155 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005156 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005157 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005158 VK_XValue :
5159 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005160 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005161 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005162 }
5163
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005164 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005165 Sema::CheckedConversionKind CCK
5166 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5167 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005168 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005169 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005170 ExprResult CurInitExprRes =
5171 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005172 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005173 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005174 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005175 CurInit = CurInitExprRes;
Douglas Gregor20093b42009-12-09 23:02:17 +00005176 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005177 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005178
Douglas Gregord87b61f2009-12-10 17:56:55 +00005179 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005180 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005181 // Hack: We must pass *ResultType if available in order to set the type
5182 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5183 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5184 // temporary, not a reference, so we should pass Ty.
5185 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5186 // Since this step is never used for a reference directly, we explicitly
5187 // unwrap references here and rewrap them afterwards.
5188 // We also need to create a InitializeTemporary entity for this.
5189 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
Sebastian Redlcbf82092012-03-07 16:10:45 +00005190 bool IsTemporary = Entity.getType()->isReferenceType();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005191 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5192 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5193 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005194 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00005195 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005196 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005197 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005198
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005199 if (ResultType) {
5200 if ((*ResultType)->isRValueReferenceType())
5201 Ty = S.Context.getRValueReferenceType(Ty);
5202 else if ((*ResultType)->isLValueReferenceType())
5203 Ty = S.Context.getLValueReferenceType(Ty,
5204 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5205 *ResultType = Ty;
5206 }
5207
5208 InitListExpr *StructuredInitList =
5209 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005210 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005211 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005212 break;
5213 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005214
Sebastian Redl10f04a62011-12-22 14:44:04 +00005215 case SK_ListConstructorCall: {
Sebastian Redl168319c2012-02-12 16:37:24 +00005216 // When an initializer list is passed for a parameter of type "reference
5217 // to object", we don't get an EK_Temporary entity, but instead an
5218 // EK_Parameter entity with reference type.
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005219 // FIXME: This is a hack. What we really should do is create a user
5220 // conversion step for this case, but this makes it considerably more
5221 // complicated. For now, this will do.
Sebastian Redl168319c2012-02-12 16:37:24 +00005222 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5223 Entity.getType().getNonReferenceType());
5224 bool UseTemporary = Entity.getType()->isReferenceType();
Richard Smithf4bb8d02012-07-05 08:39:21 +00005225 assert(Args.size() == 1 && "expected a single argument for list init");
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005226 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
Richard Smith03544fc2012-04-19 06:58:00 +00005227 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5228 << InitList->getSourceRange();
Sebastian Redl10f04a62011-12-22 14:44:04 +00005229 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
Sebastian Redl168319c2012-02-12 16:37:24 +00005230 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5231 Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005232 Kind, Arg, *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005233 ConstructorInitRequiresZeroInit);
5234 break;
5235 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005236
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005237 case SK_UnwrapInitList:
5238 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5239 break;
5240
5241 case SK_RewrapInitList: {
5242 Expr *E = CurInit.take();
5243 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5244 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005245 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005246 ILE->setSyntacticForm(Syntactic);
5247 ILE->setType(E->getType());
5248 ILE->setValueKind(E->getValueKind());
5249 CurInit = S.Owned(ILE);
5250 break;
5251 }
5252
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005253 case SK_ConstructorInitialization: {
5254 // When an initializer list is passed for a parameter of type "reference
5255 // to object", we don't get an EK_Temporary entity, but instead an
5256 // EK_Parameter entity with reference type.
5257 // FIXME: This is a hack. What we really should do is create a user
5258 // conversion step for this case, but this makes it considerably more
5259 // complicated. For now, this will do.
5260 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5261 Entity.getType().getNonReferenceType());
5262 bool UseTemporary = Entity.getType()->isReferenceType();
5263 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5264 : Entity,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005265 Kind, Args, *Step,
Sebastian Redl10f04a62011-12-22 14:44:04 +00005266 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005267 break;
Sebastian Redlbac5cf42012-02-19 12:27:56 +00005268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005269
Douglas Gregor71d17402009-12-15 00:01:57 +00005270 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005271 step_iterator NextStep = Step;
5272 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005273 if (NextStep != StepEnd &&
Richard Smithf4bb8d02012-07-05 08:39:21 +00005274 (NextStep->Kind == SK_ConstructorInitialization ||
5275 NextStep->Kind == SK_ListConstructorCall)) {
Douglas Gregor16006c92009-12-16 18:50:27 +00005276 // The need for zero-initialization is recorded directly into
5277 // the call to the object's constructor within the next step.
5278 ConstructorInitRequiresZeroInit = true;
5279 } else if (Kind.getKind() == InitializationKind::IK_Value &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005280 S.getLangOpts().CPlusPlus &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005281 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005282 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5283 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005284 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005285 Kind.getRange().getBegin());
5286
5287 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5288 TSInfo->getType().getNonLValueExprType(S.Context),
5289 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005290 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005291 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005292 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005293 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005294 break;
5295 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005296
5297 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005298 QualType SourceType = CurInit.get()->getType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005299 ExprResult Result = CurInit;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005300 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005301 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5302 if (Result.isInvalid())
5303 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005304 CurInit = Result;
Douglas Gregoraa037312009-12-22 07:24:36 +00005305
5306 // If this is a call, allow conversion to a transparent union.
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005307 ExprResult CurInitExprRes = CurInit;
Douglas Gregoraa037312009-12-22 07:24:36 +00005308 if (ConvTy != Sema::Compatible &&
5309 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005310 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005311 == Sema::Compatible)
5312 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005313 if (CurInitExprRes.isInvalid())
5314 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005315 CurInit = CurInitExprRes;
Douglas Gregoraa037312009-12-22 07:24:36 +00005316
Douglas Gregora41a8c52010-04-22 00:20:18 +00005317 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005318 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5319 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005320 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005321 getAssignmentAction(Entity),
5322 &Complained)) {
5323 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005324 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005325 } else if (Complained)
5326 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005327 break;
5328 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005329
5330 case SK_StringInit: {
5331 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005332 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005333 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005334 break;
5335 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005336
5337 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005338 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005339 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005340 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005341 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005342
5343 case SK_ArrayInit:
5344 // Okay: we checked everything before creating this step. Note that
5345 // this is a GNU extension.
5346 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005347 << Step->Type << CurInit.get()->getType()
5348 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005349
5350 // If the destination type is an incomplete array type, update the
5351 // type accordingly.
5352 if (ResultType) {
5353 if (const IncompleteArrayType *IncompleteDest
5354 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5355 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005356 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005357 *ResultType = S.Context.getConstantArrayType(
5358 IncompleteDest->getElementType(),
5359 ConstantSource->getSize(),
5360 ArrayType::Normal, 0);
5361 }
5362 }
5363 }
John McCallf85e1932011-06-15 23:02:42 +00005364 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005365
Richard Smith0f163e92012-02-15 22:38:09 +00005366 case SK_ParenthesizedArrayInit:
5367 // Okay: we checked everything before creating this step. Note that
5368 // this is a GNU extension.
5369 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
5370 << CurInit.get()->getSourceRange();
5371 break;
5372
John McCallf85e1932011-06-15 23:02:42 +00005373 case SK_PassByIndirectCopyRestore:
5374 case SK_PassByIndirectRestore:
5375 checkIndirectCopyRestoreSource(S, CurInit.get());
5376 CurInit = S.Owned(new (S.Context)
5377 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5378 Step->Kind == SK_PassByIndirectCopyRestore));
5379 break;
5380
5381 case SK_ProduceObjCObject:
5382 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005383 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005384 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005385 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005386
5387 case SK_StdInitializerList: {
5388 QualType Dest = Step->Type;
5389 QualType E;
5390 bool Success = S.isStdInitializerList(Dest, &E);
5391 (void)Success;
5392 assert(Success && "Destination type changed?");
Sebastian Redl28357452012-03-05 19:35:43 +00005393
5394 // If the element type has a destructor, check it.
5395 if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
5396 if (!RD->hasIrrelevantDestructor()) {
5397 if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
5398 S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
5399 S.CheckDestructorAccess(Kind.getLocation(), Destructor,
5400 S.PDiag(diag::err_access_dtor_temp) << E);
5401 S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
5402 }
5403 }
5404 }
5405
Sebastian Redl2b916b82012-01-17 22:49:42 +00005406 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
Richard Smith03544fc2012-04-19 06:58:00 +00005407 S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
5408 << ILE->getSourceRange();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005409 unsigned NumInits = ILE->getNumInits();
5410 SmallVector<Expr*, 16> Converted(NumInits);
5411 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5412 S.Context.getConstantArrayType(E,
5413 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5414 NumInits),
5415 ArrayType::Normal, 0));
5416 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5417 0, HiddenArray);
5418 for (unsigned i = 0; i < NumInits; ++i) {
5419 Element.setElementIndex(i);
5420 ExprResult Init = S.Owned(ILE->getInit(i));
5421 ExprResult Res = S.PerformCopyInitialization(Element,
5422 Init.get()->getExprLoc(),
5423 Init);
5424 assert(!Res.isInvalid() && "Result changed since try phase.");
5425 Converted[i] = Res.take();
5426 }
5427 InitListExpr *Semantic = new (S.Context)
5428 InitListExpr(S.Context, ILE->getLBraceLoc(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005429 Converted, ILE->getRBraceLoc());
Sebastian Redl2b916b82012-01-17 22:49:42 +00005430 Semantic->setSyntacticForm(ILE);
5431 Semantic->setType(Dest);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00005432 Semantic->setInitializesStdInitializerList();
Sebastian Redl2b916b82012-01-17 22:49:42 +00005433 CurInit = S.Owned(Semantic);
5434 break;
5435 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005436 }
5437 }
John McCall15d7d122010-11-11 03:21:53 +00005438
5439 // Diagnose non-fatal problems with the completed initialization.
5440 if (Entity.getKind() == InitializedEntity::EK_Member &&
5441 cast<FieldDecl>(Entity.getDecl())->isBitField())
5442 S.CheckBitFieldInitialization(Kind.getLocation(),
5443 cast<FieldDecl>(Entity.getDecl()),
5444 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005445
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005446 return CurInit;
Douglas Gregor20093b42009-12-09 23:02:17 +00005447}
5448
5449//===----------------------------------------------------------------------===//
5450// Diagnose initialization failures
5451//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005452bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005453 const InitializedEntity &Entity,
5454 const InitializationKind &Kind,
5455 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005456 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005457 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005458
Douglas Gregord6542d82009-12-22 15:35:07 +00005459 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005460 switch (Failure) {
5461 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005462 // FIXME: Customize for the initialized entity?
5463 if (NumArgs == 0)
5464 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5465 << DestType.getNonReferenceType();
5466 else // FIXME: diagnostic below could be better!
5467 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5468 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005469 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005470
Douglas Gregor20093b42009-12-09 23:02:17 +00005471 case FK_ArrayNeedsInitList:
5472 case FK_ArrayNeedsInitListOrStringLiteral:
5473 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5474 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5475 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005476
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005477 case FK_ArrayTypeMismatch:
5478 case FK_NonConstantArrayInit:
5479 S.Diag(Kind.getLocation(),
5480 (Failure == FK_ArrayTypeMismatch
5481 ? diag::err_array_init_different_type
5482 : diag::err_array_init_non_constant_array))
5483 << DestType.getNonReferenceType()
5484 << Args[0]->getType()
5485 << Args[0]->getSourceRange();
5486 break;
5487
John McCall73076432012-01-05 00:13:19 +00005488 case FK_VariableLengthArrayHasInitializer:
5489 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5490 << Args[0]->getSourceRange();
5491 break;
5492
John McCall6bb80172010-03-30 21:47:33 +00005493 case FK_AddressOfOverloadFailed: {
5494 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005495 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005496 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005497 true,
5498 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005499 break;
John McCall6bb80172010-03-30 21:47:33 +00005500 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005501
Douglas Gregor20093b42009-12-09 23:02:17 +00005502 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005503 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005504 switch (FailedOverloadResult) {
5505 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005506 if (Failure == FK_UserConversionOverloadFailed)
5507 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5508 << Args[0]->getType() << DestType
5509 << Args[0]->getSourceRange();
5510 else
5511 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5512 << DestType << Args[0]->getType()
5513 << Args[0]->getSourceRange();
5514
Ahmed Charles13a140c2012-02-25 11:00:22 +00005515 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5516 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005517 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005518
Douglas Gregor20093b42009-12-09 23:02:17 +00005519 case OR_No_Viable_Function:
5520 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5521 << Args[0]->getType() << DestType.getNonReferenceType()
5522 << Args[0]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005523 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5524 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor20093b42009-12-09 23:02:17 +00005525 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005526
Douglas Gregor20093b42009-12-09 23:02:17 +00005527 case OR_Deleted: {
5528 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5529 << Args[0]->getType() << DestType.getNonReferenceType()
5530 << Args[0]->getSourceRange();
5531 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005532 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005533 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5534 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005535 if (Ovl == OR_Deleted) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005536 S.NoteDeletedFunction(Best->Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00005537 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005538 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005539 }
5540 break;
5541 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005542
Douglas Gregor20093b42009-12-09 23:02:17 +00005543 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005544 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005545 }
5546 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005547
Douglas Gregor20093b42009-12-09 23:02:17 +00005548 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005549 if (isa<InitListExpr>(Args[0])) {
5550 S.Diag(Kind.getLocation(),
5551 diag::err_lvalue_reference_bind_to_initlist)
5552 << DestType.getNonReferenceType().isVolatileQualified()
5553 << DestType.getNonReferenceType()
5554 << Args[0]->getSourceRange();
5555 break;
5556 }
5557 // Intentional fallthrough
5558
Douglas Gregor20093b42009-12-09 23:02:17 +00005559 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005560 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005561 Failure == FK_NonConstLValueReferenceBindingToTemporary
5562 ? diag::err_lvalue_reference_bind_to_temporary
5563 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005564 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005565 << DestType.getNonReferenceType()
5566 << Args[0]->getType()
5567 << Args[0]->getSourceRange();
5568 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005569
Douglas Gregor20093b42009-12-09 23:02:17 +00005570 case FK_RValueReferenceBindingToLValue:
5571 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005572 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005573 << Args[0]->getSourceRange();
5574 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005575
Douglas Gregor20093b42009-12-09 23:02:17 +00005576 case FK_ReferenceInitDropsQualifiers:
5577 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5578 << DestType.getNonReferenceType()
5579 << Args[0]->getType()
5580 << Args[0]->getSourceRange();
5581 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005582
Douglas Gregor20093b42009-12-09 23:02:17 +00005583 case FK_ReferenceInitFailed:
5584 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5585 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005586 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005587 << Args[0]->getType()
5588 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005589 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5590 Args[0]->getType()->isObjCObjectPointerType())
5591 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005592 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005593
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005594 case FK_ConversionFailed: {
5595 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005596 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005597 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005598 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005599 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005600 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005601 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005602 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5603 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005604 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5605 Args[0]->getType()->isObjCObjectPointerType())
5606 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005607 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005608 }
John Wiegley429bb272011-04-08 18:41:53 +00005609
5610 case FK_ConversionFromPropertyFailed:
5611 // No-op. This error has already been reported.
5612 break;
5613
Douglas Gregord87b61f2009-12-10 17:56:55 +00005614 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005615 SourceRange R;
5616
5617 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005618 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005619 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005620 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005621 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005622
Douglas Gregor19311e72010-09-08 21:40:08 +00005623 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5624 if (Kind.isCStyleOrFunctionalCast())
5625 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5626 << R;
5627 else
5628 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5629 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005630 break;
5631 }
5632
5633 case FK_ReferenceBindingToInitList:
5634 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5635 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5636 break;
5637
5638 case FK_InitListBadDestinationType:
5639 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5640 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5641 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005642
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005643 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005644 case FK_ConstructorOverloadFailed: {
5645 SourceRange ArgsRange;
5646 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005647 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005648 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005649
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005650 if (Failure == FK_ListConstructorOverloadFailed) {
5651 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5652 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5653 Args = InitList->getInits();
5654 NumArgs = InitList->getNumInits();
5655 }
5656
Douglas Gregor51c56d62009-12-14 20:49:26 +00005657 // FIXME: Using "DestType" for the entity we're printing is probably
5658 // bad.
5659 switch (FailedOverloadResult) {
5660 case OR_Ambiguous:
5661 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5662 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005663 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005664 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005665 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005666
Douglas Gregor51c56d62009-12-14 20:49:26 +00005667 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005668 if (Kind.getKind() == InitializationKind::IK_Default &&
5669 (Entity.getKind() == InitializedEntity::EK_Base ||
5670 Entity.getKind() == InitializedEntity::EK_Member) &&
5671 isa<CXXConstructorDecl>(S.CurContext)) {
5672 // This is implicit default initialization of a member or
5673 // base within a constructor. If no viable function was
5674 // found, notify the user that she needs to explicitly
5675 // initialize this base/member.
5676 CXXConstructorDecl *Constructor
5677 = cast<CXXConstructorDecl>(S.CurContext);
5678 if (Entity.getKind() == InitializedEntity::EK_Base) {
5679 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5680 << Constructor->isImplicit()
5681 << S.Context.getTypeDeclType(Constructor->getParent())
5682 << /*base=*/0
5683 << Entity.getType();
5684
5685 RecordDecl *BaseDecl
5686 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5687 ->getDecl();
5688 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5689 << S.Context.getTagDeclType(BaseDecl);
5690 } else {
5691 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5692 << Constructor->isImplicit()
5693 << S.Context.getTypeDeclType(Constructor->getParent())
5694 << /*member=*/1
5695 << Entity.getName();
5696 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5697
5698 if (const RecordType *Record
5699 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005700 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005701 diag::note_previous_decl)
5702 << S.Context.getTagDeclType(Record->getDecl());
5703 }
5704 break;
5705 }
5706
Douglas Gregor51c56d62009-12-14 20:49:26 +00005707 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5708 << DestType << ArgsRange;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005709 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
5710 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor51c56d62009-12-14 20:49:26 +00005711 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005712
Douglas Gregor51c56d62009-12-14 20:49:26 +00005713 case OR_Deleted: {
Douglas Gregor51c56d62009-12-14 20:49:26 +00005714 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005715 OverloadingResult Ovl
5716 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregore4e68d42012-02-15 19:33:52 +00005717 if (Ovl != OR_Deleted) {
5718 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5719 << true << DestType << ArgsRange;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005720 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregore4e68d42012-02-15 19:33:52 +00005721 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00005722 }
Douglas Gregore4e68d42012-02-15 19:33:52 +00005723
5724 // If this is a defaulted or implicitly-declared function, then
5725 // it was implicitly deleted. Make it clear that the deletion was
5726 // implicit.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005727 if (S.isImplicitlyDeleted(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00005728 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
Richard Smith6c4c36c2012-03-30 20:53:28 +00005729 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
Douglas Gregore4e68d42012-02-15 19:33:52 +00005730 << DestType << ArgsRange;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005731 else
5732 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5733 << true << DestType << ArgsRange;
5734
5735 S.NoteDeletedFunction(Best->Function);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005736 break;
5737 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005738
Douglas Gregor51c56d62009-12-14 20:49:26 +00005739 case OR_Success:
5740 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00005741 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005742 }
David Blaikie9fdefb32012-01-17 08:24:58 +00005743 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005744
Douglas Gregor99a2e602009-12-16 01:38:02 +00005745 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005746 if (Entity.getKind() == InitializedEntity::EK_Member &&
5747 isa<CXXConstructorDecl>(S.CurContext)) {
5748 // This is implicit default-initialization of a const member in
5749 // a constructor. Complain that it needs to be explicitly
5750 // initialized.
5751 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5752 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5753 << Constructor->isImplicit()
5754 << S.Context.getTypeDeclType(Constructor->getParent())
5755 << /*const=*/1
5756 << Entity.getName();
5757 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5758 << Entity.getName();
5759 } else {
5760 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5761 << DestType << (bool)DestType->getAs<RecordType>();
5762 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005763 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005764
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005765 case FK_Incomplete:
Douglas Gregor69a30b82012-04-10 20:43:46 +00005766 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005767 diag::err_init_incomplete_type);
5768 break;
5769
Sebastian Redl14b0c192011-09-24 17:48:00 +00005770 case FK_ListInitializationFailed: {
5771 // Run the init list checker again to emit diagnostics.
5772 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5773 QualType DestType = Entity.getType();
5774 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005775 DestType, /*VerifyOnly=*/false,
Sebastian Redl168319c2012-02-12 16:37:24 +00005776 Kind.getKind() != InitializationKind::IK_DirectList ||
David Blaikie4e4d0842012-03-11 07:00:24 +00005777 !S.getLangOpts().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005778 assert(DiagnoseInitList.HadError() &&
5779 "Inconsistent init list check result.");
5780 break;
5781 }
John McCall5acb0c92011-10-17 18:40:02 +00005782
5783 case FK_PlaceholderType: {
5784 // FIXME: Already diagnosed!
5785 break;
5786 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00005787
5788 case FK_InitListElementCopyFailure: {
5789 // Try to perform all copies again.
5790 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5791 unsigned NumInits = InitList->getNumInits();
5792 QualType DestType = Entity.getType();
5793 QualType E;
5794 bool Success = S.isStdInitializerList(DestType, &E);
5795 (void)Success;
5796 assert(Success && "Where did the std::initializer_list go?");
5797 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5798 S.Context.getConstantArrayType(E,
5799 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5800 NumInits),
5801 ArrayType::Normal, 0));
5802 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5803 0, HiddenArray);
5804 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5805 // where the init list type is wrong, e.g.
5806 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5807 // FIXME: Emit a note if we hit the limit?
5808 int ErrorCount = 0;
5809 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5810 Element.setElementIndex(i);
5811 ExprResult Init = S.Owned(InitList->getInit(i));
5812 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5813 .isInvalid())
5814 ++ErrorCount;
5815 }
5816 break;
5817 }
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005818
5819 case FK_ExplicitConstructor: {
5820 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
5821 << Args[0]->getSourceRange();
5822 OverloadCandidateSet::iterator Best;
5823 OverloadingResult Ovl
5824 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Matt Beaumont-Gaye7d0bbf2012-04-02 19:05:35 +00005825 (void)Ovl;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005826 assert(Ovl == OR_Success && "Inconsistent overload resolution");
5827 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
5828 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
5829 break;
5830 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005831 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005832
Douglas Gregora41a8c52010-04-22 00:20:18 +00005833 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005834 return true;
5835}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005836
Chris Lattner5f9e2722011-07-23 10:55:15 +00005837void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005838 switch (SequenceKind) {
5839 case FailedSequence: {
5840 OS << "Failed sequence: ";
5841 switch (Failure) {
5842 case FK_TooManyInitsForReference:
5843 OS << "too many initializers for reference";
5844 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005845
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005846 case FK_ArrayNeedsInitList:
5847 OS << "array requires initializer list";
5848 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005849
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005850 case FK_ArrayNeedsInitListOrStringLiteral:
5851 OS << "array requires initializer list or string literal";
5852 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005853
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005854 case FK_ArrayTypeMismatch:
5855 OS << "array type mismatch";
5856 break;
5857
5858 case FK_NonConstantArrayInit:
5859 OS << "non-constant array initializer";
5860 break;
5861
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005862 case FK_AddressOfOverloadFailed:
5863 OS << "address of overloaded function failed";
5864 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005865
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005866 case FK_ReferenceInitOverloadFailed:
5867 OS << "overload resolution for reference initialization failed";
5868 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005869
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005870 case FK_NonConstLValueReferenceBindingToTemporary:
5871 OS << "non-const lvalue reference bound to temporary";
5872 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005873
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005874 case FK_NonConstLValueReferenceBindingToUnrelated:
5875 OS << "non-const lvalue reference bound to unrelated type";
5876 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005877
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005878 case FK_RValueReferenceBindingToLValue:
5879 OS << "rvalue reference bound to an lvalue";
5880 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005881
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005882 case FK_ReferenceInitDropsQualifiers:
5883 OS << "reference initialization drops qualifiers";
5884 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005885
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005886 case FK_ReferenceInitFailed:
5887 OS << "reference initialization failed";
5888 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005889
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005890 case FK_ConversionFailed:
5891 OS << "conversion failed";
5892 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005893
John Wiegley429bb272011-04-08 18:41:53 +00005894 case FK_ConversionFromPropertyFailed:
5895 OS << "conversion from property failed";
5896 break;
5897
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005898 case FK_TooManyInitsForScalar:
5899 OS << "too many initializers for scalar";
5900 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005901
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005902 case FK_ReferenceBindingToInitList:
5903 OS << "referencing binding to initializer list";
5904 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005905
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005906 case FK_InitListBadDestinationType:
5907 OS << "initializer list for non-aggregate, non-scalar type";
5908 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005909
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005910 case FK_UserConversionOverloadFailed:
5911 OS << "overloading failed for user-defined conversion";
5912 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005913
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005914 case FK_ConstructorOverloadFailed:
5915 OS << "constructor overloading failed";
5916 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005917
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005918 case FK_DefaultInitOfConst:
5919 OS << "default initialization of a const variable";
5920 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005921
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005922 case FK_Incomplete:
5923 OS << "initialization of incomplete type";
5924 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005925
5926 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005927 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005928 break;
5929
John McCall73076432012-01-05 00:13:19 +00005930 case FK_VariableLengthArrayHasInitializer:
5931 OS << "variable length array has an initializer";
5932 break;
5933
John McCall5acb0c92011-10-17 18:40:02 +00005934 case FK_PlaceholderType:
5935 OS << "initializer expression isn't contextually valid";
5936 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005937
5938 case FK_ListConstructorOverloadFailed:
5939 OS << "list constructor overloading failed";
5940 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005941
5942 case FK_InitListElementCopyFailure:
5943 OS << "copy construction of initializer list element failed";
5944 break;
Sebastian Redl70e24fc2012-04-01 19:54:59 +00005945
5946 case FK_ExplicitConstructor:
5947 OS << "list copy initialization chose explicit constructor";
5948 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005949 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005950 OS << '\n';
5951 return;
5952 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005953
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005954 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005955 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005956 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005957
Sebastian Redl7491c492011-06-05 13:59:11 +00005958 case NormalSequence:
5959 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005960 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005961 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005962
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005963 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5964 if (S != step_begin()) {
5965 OS << " -> ";
5966 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005967
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005968 switch (S->Kind) {
5969 case SK_ResolveAddressOfOverloadedFunction:
5970 OS << "resolve address of overloaded function";
5971 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005972
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005973 case SK_CastDerivedToBaseRValue:
5974 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5975 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005976
Sebastian Redl906082e2010-07-20 04:20:21 +00005977 case SK_CastDerivedToBaseXValue:
5978 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5979 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005980
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005981 case SK_CastDerivedToBaseLValue:
5982 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5983 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005984
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005985 case SK_BindReference:
5986 OS << "bind reference to lvalue";
5987 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005988
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005989 case SK_BindReferenceToTemporary:
5990 OS << "bind reference to a temporary";
5991 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005992
Douglas Gregor523d46a2010-04-18 07:40:54 +00005993 case SK_ExtraneousCopyToTemporary:
5994 OS << "extraneous C++03 copy to temporary";
5995 break;
5996
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005997 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005998 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005999 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006000
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006001 case SK_QualificationConversionRValue:
6002 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006003 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006004
Sebastian Redl906082e2010-07-20 04:20:21 +00006005 case SK_QualificationConversionXValue:
6006 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006007 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00006008
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006009 case SK_QualificationConversionLValue:
6010 OS << "qualification conversion (lvalue)";
6011 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006012
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006013 case SK_ConversionSequence:
6014 OS << "implicit conversion sequence (";
6015 S->ICS->DebugPrint(); // FIXME: use OS
6016 OS << ")";
6017 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006018
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006019 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00006020 OS << "list aggregate initialization";
6021 break;
6022
6023 case SK_ListConstructorCall:
6024 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006025 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006026
Sebastian Redl13dc8f92011-11-27 16:50:07 +00006027 case SK_UnwrapInitList:
6028 OS << "unwrap reference initializer list";
6029 break;
6030
6031 case SK_RewrapInitList:
6032 OS << "rewrap reference initializer list";
6033 break;
6034
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006035 case SK_ConstructorInitialization:
6036 OS << "constructor initialization";
6037 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006038
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006039 case SK_ZeroInitialization:
6040 OS << "zero initialization";
6041 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006042
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006043 case SK_CAssignment:
6044 OS << "C assignment";
6045 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006046
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006047 case SK_StringInit:
6048 OS << "string initialization";
6049 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00006050
6051 case SK_ObjCObjectConversion:
6052 OS << "Objective-C object conversion";
6053 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00006054
6055 case SK_ArrayInit:
6056 OS << "array initialization";
6057 break;
John McCallf85e1932011-06-15 23:02:42 +00006058
Richard Smith0f163e92012-02-15 22:38:09 +00006059 case SK_ParenthesizedArrayInit:
6060 OS << "parenthesized array initialization";
6061 break;
6062
John McCallf85e1932011-06-15 23:02:42 +00006063 case SK_PassByIndirectCopyRestore:
6064 OS << "pass by indirect copy and restore";
6065 break;
6066
6067 case SK_PassByIndirectRestore:
6068 OS << "pass by indirect restore";
6069 break;
6070
6071 case SK_ProduceObjCObject:
6072 OS << "Objective-C object retension";
6073 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00006074
6075 case SK_StdInitializerList:
6076 OS << "std::initializer_list from initializer list";
6077 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00006078 }
6079 }
6080}
6081
6082void InitializationSequence::dump() const {
6083 dump(llvm::errs());
6084}
6085
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006086static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
6087 QualType EntityType,
6088 const Expr *PreInit,
6089 const Expr *PostInit) {
6090 if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
6091 return;
6092
6093 // A narrowing conversion can only appear as the final implicit conversion in
6094 // an initialization sequence.
6095 const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
6096 if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
6097 return;
6098
6099 const ImplicitConversionSequence &ICS = *LastStep.ICS;
6100 const StandardConversionSequence *SCS = 0;
6101 switch (ICS.getKind()) {
6102 case ImplicitConversionSequence::StandardConversion:
6103 SCS = &ICS.Standard;
6104 break;
6105 case ImplicitConversionSequence::UserDefinedConversion:
6106 SCS = &ICS.UserDefined.After;
6107 break;
6108 case ImplicitConversionSequence::AmbiguousConversion:
6109 case ImplicitConversionSequence::EllipsisConversion:
6110 case ImplicitConversionSequence::BadConversion:
6111 return;
6112 }
6113
6114 // Determine the type prior to the narrowing conversion. If a conversion
6115 // operator was used, this may be different from both the type of the entity
6116 // and of the pre-initialization expression.
6117 QualType PreNarrowingType = PreInit->getType();
6118 if (Seq.step_begin() + 1 != Seq.step_end())
6119 PreNarrowingType = Seq.step_end()[-2].Type;
6120
6121 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6122 APValue ConstantValue;
Richard Smithf6028062012-03-23 23:55:39 +00006123 QualType ConstantType;
6124 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6125 ConstantType)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006126 case NK_Not_Narrowing:
6127 // No narrowing occurred.
6128 return;
6129
6130 case NK_Type_Narrowing:
6131 // This was a floating-to-integer conversion, which is always considered a
6132 // narrowing conversion even if the value is a constant and can be
6133 // represented exactly as an integer.
6134 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006135 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006136 diag::warn_init_list_type_narrowing
6137 : S.isSFINAEContext()?
6138 diag::err_init_list_type_narrowing_sfinae
6139 : diag::err_init_list_type_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006140 << PostInit->getSourceRange()
6141 << PreNarrowingType.getLocalUnqualifiedType()
6142 << EntityType.getLocalUnqualifiedType();
6143 break;
6144
6145 case NK_Constant_Narrowing:
6146 // A constant value was narrowed.
6147 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006148 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006149 diag::warn_init_list_constant_narrowing
6150 : S.isSFINAEContext()?
6151 diag::err_init_list_constant_narrowing_sfinae
6152 : diag::err_init_list_constant_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006153 << PostInit->getSourceRange()
Richard Smithf6028062012-03-23 23:55:39 +00006154 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006155 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006156 break;
6157
6158 case NK_Variable_Narrowing:
6159 // A variable's value may have been narrowed.
6160 S.Diag(PostInit->getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006161 S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?
Douglas Gregorf3c82c52012-01-23 15:29:33 +00006162 diag::warn_init_list_variable_narrowing
6163 : S.isSFINAEContext()?
6164 diag::err_init_list_variable_narrowing_sfinae
6165 : diag::err_init_list_variable_narrowing)
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006166 << PostInit->getSourceRange()
6167 << PreNarrowingType.getLocalUnqualifiedType()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00006168 << EntityType.getLocalUnqualifiedType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006169 break;
6170 }
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006171
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00006172 SmallString<128> StaticCast;
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006173 llvm::raw_svector_ostream OS(StaticCast);
6174 OS << "static_cast<";
6175 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6176 // It's important to use the typedef's name if there is one so that the
6177 // fixit doesn't break code using types like int64_t.
6178 //
6179 // FIXME: This will break if the typedef requires qualification. But
6180 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00006181 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006182 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
David Blaikie4e4d0842012-03-11 07:00:24 +00006183 OS << BT->getName(S.getLangOpts());
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006184 else {
6185 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
6186 // with a broken cast.
6187 return;
6188 }
6189 OS << ">(";
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006190 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6191 << PostInit->getSourceRange()
6192 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006193 << FixItHint::CreateInsertion(
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006194 S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006195}
6196
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006197//===----------------------------------------------------------------------===//
6198// Initialization helper functions
6199//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00006200bool
6201Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6202 ExprResult Init) {
6203 if (Init.isInvalid())
6204 return false;
6205
6206 Expr *InitE = Init.get();
6207 assert(InitE && "No initialization expression");
6208
Douglas Gregor3c394c52012-07-31 22:15:04 +00006209 InitializationKind Kind
6210 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
Sean Hunt2be7e902011-05-12 22:46:29 +00006211 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00006212 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00006213}
6214
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006215ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006216Sema::PerformCopyInitialization(const InitializedEntity &Entity,
6217 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006218 ExprResult Init,
Douglas Gregored878af2012-02-24 23:56:31 +00006219 bool TopLevelOfInitList,
6220 bool AllowExplicit) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006221 if (Init.isInvalid())
6222 return ExprError();
6223
John McCall15d7d122010-11-11 03:21:53 +00006224 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006225 assert(InitE && "No initialization expression?");
6226
6227 if (EqualLoc.isInvalid())
6228 EqualLoc = InitE->getLocStart();
6229
6230 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
Douglas Gregored878af2012-02-24 23:56:31 +00006231 EqualLoc,
6232 AllowExplicit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006233 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6234 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006235
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006236 ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
6237
6238 if (!Result.isInvalid() && TopLevelOfInitList)
6239 DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
6240 InitE, Result.get());
6241
6242 return Result;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006243}