blob: 0f4ba7c0288433588b356b2721ff02e7fde6fe8e [file] [log] [blame]
Steve Narofff8ecff22008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner0cb78032009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Anders Carlsson26d05642010-01-23 18:35:41 +000069static Sema::OwningExprResult
70CheckSingleInitializer(const InitializedEntity *Entity,
71 Sema::OwningExprResult Init, QualType DeclType, Sema &S){
72 Expr *InitExpr = Init.takeAs<Expr>();
73
Chris Lattner0cb78032009-02-24 22:27:37 +000074 // Get the type before calling CheckSingleAssignmentConstraints(), since
75 // it can promote the expression.
Anders Carlsson26d05642010-01-23 18:35:41 +000076 QualType InitType = InitExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +000077
Chris Lattner94d2f682009-02-24 22:46:58 +000078 if (S.getLangOptions().CPlusPlus) {
Anders Carlsson3cc795a2010-01-23 19:22:30 +000079 if (Entity) {
80 assert(Entity->getType() == DeclType);
81
82 // C++ [dcl.init.aggr]p2:
83 // Each member is copy-initialized from the corresponding
84 // initializer-clause
85 Sema::OwningExprResult Result =
86 S.PerformCopyInitialization(*Entity, InitExpr->getLocStart(),
87 S.Owned(InitExpr));
88
89 return move(Result);
90 } else {
91 // FIXME: I dislike this error message. A lot.
92 if (S.PerformImplicitConversion(InitExpr, DeclType,
93 Sema::AA_Initializing,
94 /*DirectInit=*/false)) {
95 ImplicitConversionSequence ICS;
96 OverloadCandidateSet CandidateSet;
97 if (S.IsUserDefinedConversion(InitExpr, DeclType, ICS.UserDefined,
98 CandidateSet,
99 true, false, false) != OR_Ambiguous) {
100 S.Diag(InitExpr->getSourceRange().getBegin(),
101 diag::err_typecheck_convert_incompatible)
102 << DeclType << InitExpr->getType()
103 << Sema::AA_Initializing
104 << InitExpr->getSourceRange();
105 return S.ExprError();
106 }
Anders Carlsson26d05642010-01-23 18:35:41 +0000107 S.Diag(InitExpr->getSourceRange().getBegin(),
Anders Carlsson3cc795a2010-01-23 19:22:30 +0000108 diag::err_typecheck_convert_ambiguous)
109 << DeclType << InitExpr->getType() << InitExpr->getSourceRange();
110 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
111 &InitExpr, 1);
112
Anders Carlsson26d05642010-01-23 18:35:41 +0000113 return S.ExprError();
114 }
Anders Carlsson26d05642010-01-23 18:35:41 +0000115
Anders Carlsson3cc795a2010-01-23 19:22:30 +0000116 Init.release();
117 return S.Owned(InitExpr);
118 }
Chris Lattner0cb78032009-02-24 22:27:37 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Chris Lattner94d2f682009-02-24 22:46:58 +0000121 Sema::AssignConvertType ConvTy =
Anders Carlsson26d05642010-01-23 18:35:41 +0000122 S.CheckSingleAssignmentConstraints(DeclType, InitExpr);
123 if (S.DiagnoseAssignmentResult(ConvTy, InitExpr->getLocStart(), DeclType,
124 InitType, InitExpr, Sema::AA_Initializing))
125 return S.ExprError();
126
127 Init.release();
128 return S.Owned(InitExpr);
Chris Lattner0cb78032009-02-24 22:27:37 +0000129}
130
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000131static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
132 // Get the length of the string as parsed.
133 uint64_t StrLength =
134 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
135
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000137 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000138 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000139 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000140 // being initialized to a string literal.
141 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000142 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000143 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000144 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
145 ConstVal,
146 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000147 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000148 }
Mike Stump11289f42009-09-09 15:08:12 +0000149
Eli Friedman893abe42009-05-29 18:22:49 +0000150 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000151
Eli Friedman893abe42009-05-29 18:22:49 +0000152 // C99 6.7.8p14. We have an array of character type with known size. However,
153 // the size may be smaller or larger than the string we are initializing.
154 // FIXME: Avoid truncation for 64-bit length strings.
155 if (StrLength-1 > CAT->getSize().getZExtValue())
156 S.Diag(Str->getSourceRange().getBegin(),
157 diag::warn_initializer_string_for_char_array_too_long)
158 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Eli Friedman893abe42009-05-29 18:22:49 +0000160 // Set the type to the actual size that we are initializing. If we have
161 // something like:
162 // char x[1] = "foo";
163 // then this will set the string literal's type to char[1].
164 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000165}
166
Chris Lattner0cb78032009-02-24 22:27:37 +0000167//===----------------------------------------------------------------------===//
168// Semantic checking for initializer lists.
169//===----------------------------------------------------------------------===//
170
Douglas Gregorcde232f2009-01-29 01:05:33 +0000171/// @brief Semantic checking for initializer lists.
172///
173/// The InitListChecker class contains a set of routines that each
174/// handle the initialization of a certain kind of entity, e.g.,
175/// arrays, vectors, struct/union types, scalars, etc. The
176/// InitListChecker itself performs a recursive walk of the subobject
177/// structure of the type to be initialized, while stepping through
178/// the initializer list one element at a time. The IList and Index
179/// parameters to each of the Check* routines contain the active
180/// (syntactic) initializer list and the index into that initializer
181/// list that represents the current initializer. Each routine is
182/// responsible for moving that Index forward as it consumes elements.
183///
184/// Each Check* routine also has a StructuredList/StructuredIndex
185/// arguments, which contains the current the "structured" (semantic)
186/// initializer list and the index into that initializer list where we
187/// are copying initializers as we map them over to the semantic
188/// list. Once we have completed our recursive walk of the subobject
189/// structure, we will have constructed a full semantic initializer
190/// list.
191///
192/// C99 designators cause changes in the initializer list traversal,
193/// because they make the initialization "jump" into a specific
194/// subobject and then continue the initialization from that
195/// point. CheckDesignatedInitializer() recursively steps into the
196/// designated subobject and manages backing out the recursion to
197/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000198namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000199class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000200 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000201 bool hadError;
202 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
203 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000204
205 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000209 void CheckExplicitInitList(const InitializedEntity *Entity,
210 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000211 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000212 unsigned &StructuredIndex,
213 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000214 void CheckListElementTypes(const InitializedEntity *Entity,
215 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000216 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000217 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000218 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000219 unsigned &StructuredIndex,
220 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000221 void CheckSubElementType(const InitializedEntity *Entity,
222 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000223 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000224 InitListExpr *StructuredList,
225 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000226 void CheckScalarType(const InitializedEntity *Entity,
227 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000228 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000231 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000232 unsigned &Index,
233 InitListExpr *StructuredList,
234 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000235 void CheckVectorType(const InitializedEntity *Entity,
236 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000239 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
240 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000242 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000243 unsigned &StructuredIndex,
244 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000245 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
246 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000247 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000248 InitListExpr *StructuredList,
249 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000250 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000251 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000252 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000253 RecordDecl::field_iterator *NextField,
254 llvm::APSInt *NextElementIndex,
255 unsigned &Index,
256 InitListExpr *StructuredList,
257 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000258 bool FinishSubobjectInit,
259 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000260 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
261 QualType CurrentObjectType,
262 InitListExpr *StructuredList,
263 unsigned StructuredIndex,
264 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000265 void UpdateStructuredListElement(InitListExpr *StructuredList,
266 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000267 Expr *expr);
268 int numArrayElements(QualType DeclType);
269 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000270
Douglas Gregor2bb07652009-12-22 00:05:34 +0000271 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
272 const InitializedEntity &ParentEntity,
273 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000274 void FillInValueInitializations(const InitializedEntity &Entity,
275 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000276public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000277 InitListChecker(Sema &S, const InitializedEntity &Entity,
278 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000279 bool HadError() { return hadError; }
280
281 // @brief Retrieves the fully-structured initializer list used for
282 // semantic analysis and code generation.
283 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
284};
Chris Lattner9ececce2009-02-24 22:48:58 +0000285} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000286
Douglas Gregor2bb07652009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
289 InitListExpr *ILE,
290 bool &RequiresSecondPass) {
291 SourceLocation Loc = ILE->getSourceRange().getBegin();
292 unsigned NumInits = ILE->getNumInits();
293 InitializedEntity MemberEntity
294 = 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 }
312
313 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 }
321
322 Sema::OwningExprResult MemberInit
323 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
324 Sema::MultiExprArg(SemaRef, 0, 0));
325 if (MemberInit.isInvalid()) {
326 hadError = true;
327 return;
328 }
329
330 if (hadError) {
331 // Do nothing
332 } else if (Init < NumInits) {
333 ILE->setInit(Init, MemberInit.takeAs<Expr>());
334 } else if (InitSeq.getKind()
335 == InitializationSequence::ConstructorInitialization) {
336 // Value-initialization requires a constructor call, so
337 // extend the initializer list to include the constructor
338 // call and make a note that we'll need to take another pass
339 // through the initializer list.
340 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
341 RequiresSecondPass = true;
342 }
343 } else if (InitListExpr *InnerILE
344 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
345 FillInValueInitializations(MemberEntity, InnerILE,
346 RequiresSecondPass);
347}
348
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000349/// Recursively replaces NULL values within the given initializer list
350/// with expressions that perform value-initialization of the
351/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000352void
353InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
354 InitListExpr *ILE,
355 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000356 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000357 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000358 SourceLocation Loc = ILE->getSourceRange().getBegin();
359 if (ILE->getSyntacticForm())
360 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000361
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000362 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000363 if (RType->getDecl()->isUnion() &&
364 ILE->getInitializedFieldInUnion())
365 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
366 Entity, ILE, RequiresSecondPass);
367 else {
368 unsigned Init = 0;
369 for (RecordDecl::field_iterator
370 Field = RType->getDecl()->field_begin(),
371 FieldEnd = RType->getDecl()->field_end();
372 Field != FieldEnd; ++Field) {
373 if (Field->isUnnamedBitfield())
374 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000375
Douglas Gregor2bb07652009-12-22 00:05:34 +0000376 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000377 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000378
379 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
380 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000382
Douglas Gregor2bb07652009-12-22 00:05:34 +0000383 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000384
Douglas Gregor2bb07652009-12-22 00:05:34 +0000385 // Only look at the first initialization of a union.
386 if (RType->getDecl()->isUnion())
387 break;
388 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000389 }
390
391 return;
Mike Stump11289f42009-09-09 15:08:12 +0000392 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000393
394 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Douglas Gregor723796a2009-12-16 06:35:08 +0000396 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000397 unsigned NumInits = ILE->getNumInits();
398 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000399 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000400 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000401 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
402 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
404 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000405 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000406 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000407 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000408 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
409 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000410 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000411 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000412
Douglas Gregor723796a2009-12-16 06:35:08 +0000413
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000414 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000415 if (hadError)
416 return;
417
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000418 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
419 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 ElementEntity.setElementIndex(Init);
421
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000422 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000423 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
424 true);
425 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
426 if (!InitSeq) {
427 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000428 hadError = true;
429 return;
430 }
431
Douglas Gregor723796a2009-12-16 06:35:08 +0000432 Sema::OwningExprResult ElementInit
433 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
434 Sema::MultiExprArg(SemaRef, 0, 0));
435 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000436 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000437 return;
438 }
439
440 if (hadError) {
441 // Do nothing
442 } else if (Init < NumInits) {
443 ILE->setInit(Init, ElementInit.takeAs<Expr>());
444 } else if (InitSeq.getKind()
445 == InitializationSequence::ConstructorInitialization) {
446 // Value-initialization requires a constructor call, so
447 // extend the initializer list to include the constructor
448 // call and make a note that we'll need to take another pass
449 // through the initializer list.
450 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
451 RequiresSecondPass = true;
452 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000453 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000454 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
455 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000456 }
457}
458
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000459
Douglas Gregor723796a2009-12-16 06:35:08 +0000460InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
461 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000462 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000463 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000464
Eli Friedman23a9e312008-05-19 19:16:24 +0000465 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000466 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000467 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000468 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000469 CheckExplicitInitList(&Entity, IL, T, newIndex,
470 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000471 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000472
Douglas Gregor723796a2009-12-16 06:35:08 +0000473 if (!hadError) {
474 bool RequiresSecondPass = false;
475 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000476 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000477 FillInValueInitializations(Entity, FullyStructuredList,
478 RequiresSecondPass);
479 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000480}
481
482int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000483 // FIXME: use a proper constant
484 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000485 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000486 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000487 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
488 }
489 return maxElements;
490}
491
492int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000493 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000494 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000495 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000496 Field = structDecl->field_begin(),
497 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000498 Field != FieldEnd; ++Field) {
499 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
500 ++InitializableMembers;
501 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000502 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000503 return std::min(InitializableMembers, 1);
504 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000505}
506
Mike Stump11289f42009-09-09 15:08:12 +0000507void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000508 QualType T, unsigned &Index,
509 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000510 unsigned &StructuredIndex,
511 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000512 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000513
Steve Narofff8ecff22008-05-01 22:18:59 +0000514 if (T->isArrayType())
515 maxElements = numArrayElements(T);
516 else if (T->isStructureType() || T->isUnionType())
517 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000518 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000519 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000520 else
521 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000522
Eli Friedmane0f832b2008-05-25 13:49:22 +0000523 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000524 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000525 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000526 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000527 hadError = true;
528 return;
529 }
530
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000531 // Build a structured initializer list corresponding to this subobject.
532 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000533 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
534 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000535 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
536 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000537 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000538
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000539 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000540 unsigned StartIndex = Index;
Anders Carlssond0849252010-01-23 19:55:29 +0000541 CheckListElementTypes(0, ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000542 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000543 StructuredSubobjectInitIndex,
544 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000545 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000546 StructuredSubobjectInitList->setType(T);
547
Douglas Gregor5741efb2009-03-01 17:12:46 +0000548 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000549 // range corresponds with the end of the last initializer it used.
550 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000551 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000552 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
553 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
554 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000555}
556
Anders Carlssond0849252010-01-23 19:55:29 +0000557void InitListChecker::CheckExplicitInitList(const InitializedEntity *Entity,
558 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000559 unsigned &Index,
560 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000561 unsigned &StructuredIndex,
562 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000563 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000564 SyntacticToSemantic[IList] = StructuredList;
565 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000566 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
567 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000568 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000569 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000570 if (hadError)
571 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000572
Eli Friedman85f54972008-05-25 13:22:35 +0000573 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000574 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000575 if (StructuredIndex == 1 &&
576 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000577 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000578 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000579 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000580 hadError = true;
581 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000582 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000583 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000584 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000585 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000586 // Don't complain for incomplete types, since we'll get an error
587 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000588 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000589 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000590 CurrentObjectType->isArrayType()? 0 :
591 CurrentObjectType->isVectorType()? 1 :
592 CurrentObjectType->isScalarType()? 2 :
593 CurrentObjectType->isUnionType()? 3 :
594 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000595
596 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000597 if (SemaRef.getLangOptions().CPlusPlus) {
598 DK = diag::err_excess_initializers;
599 hadError = true;
600 }
Nate Begeman425038c2009-07-07 21:53:06 +0000601 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
602 DK = diag::err_excess_initializers;
603 hadError = true;
604 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000605
Chris Lattnerb0912a52009-02-24 22:50:46 +0000606 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000607 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000608 }
609 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000610
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000611 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000612 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000613 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000614 << CodeModificationHint::CreateRemoval(IList->getLocStart())
615 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000616}
617
Anders Carlssond0849252010-01-23 19:55:29 +0000618void InitListChecker::CheckListElementTypes(const InitializedEntity *Entity,
619 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000620 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000621 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000622 unsigned &Index,
623 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000624 unsigned &StructuredIndex,
625 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000626 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000627 CheckScalarType(Entity, IList, DeclType, Index,
628 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000629 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000630 CheckVectorType(Entity, IList, DeclType, Index,
631 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000632 } else if (DeclType->isAggregateType()) {
633 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000634 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000635 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000636 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000637 StructuredList, StructuredIndex,
638 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000639 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000640 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000641 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000642 false);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
644 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000645 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000646 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000647 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
648 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000650 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000651 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000652 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000653 } else if (DeclType->isRecordType()) {
654 // C++ [dcl.init]p14:
655 // [...] If the class is an aggregate (8.5.1), and the initializer
656 // is a brace-enclosed list, see 8.5.1.
657 //
658 // Note: 8.5.1 is handled below; here, we diagnose the case where
659 // we have an initializer list and a destination type that is not
660 // an aggregate.
661 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000662 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000663 << DeclType << IList->getSourceRange();
664 hadError = true;
665 } else if (DeclType->isReferenceType()) {
666 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000667 } else {
668 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000669 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000670 assert(0 && "Unsupported initializer type");
671 }
672}
673
Anders Carlssond0849252010-01-23 19:55:29 +0000674void InitListChecker::CheckSubElementType(const InitializedEntity *Entity,
675 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000676 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000677 unsigned &Index,
678 InitListExpr *StructuredList,
679 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000680 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000681 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
682 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000683 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000684 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000685 = getStructuredSubobjectInit(IList, Index, ElemType,
686 StructuredList, StructuredIndex,
687 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000688 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000689 newStructuredList, newStructuredIndex);
690 ++StructuredIndex;
691 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000692 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
693 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000694 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000695 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000696 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000697 CheckScalarType(Entity, IList, ElemType, Index,
698 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000699 } else if (ElemType->isReferenceType()) {
700 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000701 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000702 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 // C++ [dcl.init.aggr]p12:
704 // All implicit type conversions (clause 4) are considered when
705 // initializing the aggregate member with an ini- tializer from
706 // an initializer-list. If the initializer can initialize a
707 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000708 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000709 = SemaRef.TryCopyInitialization(expr, ElemType,
710 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000711 /*ForceRValue=*/false,
712 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000713
John McCall0d1da222010-01-12 00:44:57 +0000714 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000715 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000716 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000717 hadError = true;
718 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
719 ++Index;
720 return;
721 }
722
723 // Fall through for subaggregate initialization
724 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000725 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000726 //
727 // The initializer for a structure or union object that has
728 // automatic storage duration shall be either an initializer
729 // list as described below, or a single expression that has
730 // compatible structure or union type. In the latter case, the
731 // initial value of the object, including unnamed members, is
732 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000733 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000734 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000735 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
736 ++Index;
737 return;
738 }
739
740 // Fall through for subaggregate initialization
741 }
742
743 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000744 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000745 // [...] Otherwise, if the member is itself a non-empty
746 // subaggregate, brace elision is assumed and the initializer is
747 // considered for the initialization of the first member of
748 // the subaggregate.
749 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000750 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000751 StructuredIndex);
752 ++StructuredIndex;
753 } else {
754 // We cannot initialize this element, so let
755 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000756 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000757 hadError = true;
758 ++Index;
759 ++StructuredIndex;
760 }
761 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000762}
763
Anders Carlssond0849252010-01-23 19:55:29 +0000764void InitListChecker::CheckScalarType(const InitializedEntity *Entity,
765 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000766 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000767 InitListExpr *StructuredList,
768 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000769 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000770 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000771 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000772 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000773 diag::err_many_braces_around_scalar_init)
774 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000775 hadError = true;
776 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000777 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000778 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000779 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000780 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000781 diag::err_designator_for_scalar_init)
782 << DeclType << expr->getSourceRange();
783 hadError = true;
784 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000785 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000786 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000787 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000788
Anders Carlsson26d05642010-01-23 18:35:41 +0000789 Sema::OwningExprResult Result =
Anders Carlssond0849252010-01-23 19:55:29 +0000790 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlsson26d05642010-01-23 18:35:41 +0000791
792 Expr *ResultExpr;
793
794 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000795 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000796 else {
797 ResultExpr = Result.takeAs<Expr>();
798
799 if (ResultExpr != expr) {
800 // The type was promoted, update initializer list.
801 IList->setInit(Index, ResultExpr);
802 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000803 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000804 if (hadError)
805 ++StructuredIndex;
806 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000807 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000808 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000809 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000810 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000811 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000812 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000813 ++Index;
814 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000815 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000816 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000817}
818
Douglas Gregord14247a2009-01-30 22:09:00 +0000819void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
820 unsigned &Index,
821 InitListExpr *StructuredList,
822 unsigned &StructuredIndex) {
823 if (Index < IList->getNumInits()) {
824 Expr *expr = IList->getInit(Index);
825 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000826 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000827 << DeclType << IList->getSourceRange();
828 hadError = true;
829 ++Index;
830 ++StructuredIndex;
831 return;
Mike Stump11289f42009-09-09 15:08:12 +0000832 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000833
834 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000835 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000836 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000837 /*SuppressUserConversions=*/false,
838 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000839 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000840 hadError = true;
841 else if (savExpr != expr) {
842 // The type was promoted, update initializer list.
843 IList->setInit(Index, expr);
844 }
845 if (hadError)
846 ++StructuredIndex;
847 else
848 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
849 ++Index;
850 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000851 // FIXME: It would be wonderful if we could point at the actual member. In
852 // general, it would be useful to pass location information down the stack,
853 // so that we know the location (or decl) of the "current object" being
854 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000855 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000856 diag::err_init_reference_member_uninitialized)
857 << DeclType
858 << IList->getSourceRange();
859 hadError = true;
860 ++Index;
861 ++StructuredIndex;
862 return;
863 }
864}
865
Anders Carlssond0849252010-01-23 19:55:29 +0000866void InitListChecker::CheckVectorType(const InitializedEntity *Entity,
867 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000868 unsigned &Index,
869 InitListExpr *StructuredList,
870 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000871 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000872 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000873 unsigned maxElements = VT->getNumElements();
874 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000875 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000876
Nate Begeman5ec4b312009-08-10 23:49:36 +0000877 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlssond0849252010-01-23 19:55:29 +0000878 // FIXME: Once we know Entity is never null we can remove this check,
879 // as well as the else block.
880 if (Entity) {
881 InitializedEntity ElementEntity =
882 InitializedEntity::InitializeElement(SemaRef.Context, 0, *Entity);
883
884 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
885 // Don't attempt to go past the end of the init list
886 if (Index >= IList->getNumInits())
887 break;
888
889 ElementEntity.setElementIndex(Index);
890 CheckSubElementType(&ElementEntity, IList, elementType, Index,
891 StructuredList, StructuredIndex);
892 }
893 } else {
894 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
895 // Don't attempt to go past the end of the init list
896 if (Index >= IList->getNumInits())
897 break;
898
899 CheckSubElementType(0, IList, elementType, Index,
900 StructuredList, StructuredIndex);
901 }
902 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000903 } else {
904 // OpenCL initializers allows vectors to be constructed from vectors.
905 for (unsigned i = 0; i < maxElements; ++i) {
906 // Don't attempt to go past the end of the init list
907 if (Index >= IList->getNumInits())
908 break;
909 QualType IType = IList->getInit(Index)->getType();
910 if (!IType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000911 CheckSubElementType(0, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000912 StructuredList, StructuredIndex);
913 ++numEltsInit;
914 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000915 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000916 unsigned numIElts = IVT->getNumElements();
917 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
918 numIElts);
Anders Carlssond0849252010-01-23 19:55:29 +0000919 CheckSubElementType(0, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000920 StructuredList, StructuredIndex);
921 numEltsInit += numIElts;
922 }
923 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Nate Begeman5ec4b312009-08-10 23:49:36 +0000926 // OpenCL & AltiVec require all elements to be initialized.
927 if (numEltsInit != maxElements)
928 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
929 SemaRef.Diag(IList->getSourceRange().getBegin(),
930 diag::err_vector_incorrect_num_initializers)
931 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000932 }
933}
934
Mike Stump11289f42009-09-09 15:08:12 +0000935void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000936 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000937 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000938 unsigned &Index,
939 InitListExpr *StructuredList,
940 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000941 // Check for the special-case of initializing an array with a string.
942 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000943 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
944 SemaRef.Context)) {
945 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000946 // We place the string literal directly into the resulting
947 // initializer list. This is the only place where the structure
948 // of the structured initializer list doesn't match exactly,
949 // because doing so would involve allocating one character
950 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000951 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000952 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000953 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000954 return;
955 }
956 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000957 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000958 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000959 // Check for VLAs; in standard C it would be possible to check this
960 // earlier, but I don't know where clang accepts VLAs (gcc accepts
961 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000962 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000963 diag::err_variable_object_no_init)
964 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000965 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000966 ++Index;
967 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000968 return;
969 }
970
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000971 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000972 llvm::APSInt maxElements(elementIndex.getBitWidth(),
973 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000974 bool maxElementsKnown = false;
975 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000976 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000977 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000978 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000979 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000980 maxElementsKnown = true;
981 }
982
Chris Lattnerb0912a52009-02-24 22:50:46 +0000983 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000984 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000985 while (Index < IList->getNumInits()) {
986 Expr *Init = IList->getInit(Index);
987 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000988 // If we're not the subobject that matches up with the '{' for
989 // the designator, we shouldn't be handling the
990 // designator. Return immediately.
991 if (!SubobjectIsDesignatorContext)
992 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000993
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000994 // Handle this designated initializer. elementIndex will be
995 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +0000996 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000997 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000998 StructuredList, StructuredIndex, true,
999 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001000 hadError = true;
1001 continue;
1002 }
1003
Douglas Gregor033d1252009-01-23 16:54:12 +00001004 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1005 maxElements.extend(elementIndex.getBitWidth());
1006 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1007 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001008 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001009
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001010 // If the array is of incomplete type, keep track of the number of
1011 // elements in the initializer.
1012 if (!maxElementsKnown && elementIndex > maxElements)
1013 maxElements = elementIndex;
1014
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001015 continue;
1016 }
1017
1018 // If we know the maximum number of elements, and we've already
1019 // hit it, stop consuming elements in the initializer list.
1020 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001021 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001022
1023 // Check this element.
Anders Carlssond0849252010-01-23 19:55:29 +00001024 CheckSubElementType(0, IList, elementType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001025 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001026 ++elementIndex;
1027
1028 // If the array is of incomplete type, keep track of the number of
1029 // elements in the initializer.
1030 if (!maxElementsKnown && elementIndex > maxElements)
1031 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001032 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001033 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001034 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001035 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001036 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001037 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001038 // Sizing an array implicitly to zero is not allowed by ISO C,
1039 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001040 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001041 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001042 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001043
Mike Stump11289f42009-09-09 15:08:12 +00001044 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001045 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001046 }
1047}
1048
Mike Stump11289f42009-09-09 15:08:12 +00001049void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1050 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001051 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001052 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001053 unsigned &Index,
1054 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001055 unsigned &StructuredIndex,
1056 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001057 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001058
Eli Friedman23a9e312008-05-19 19:16:24 +00001059 // If the record is invalid, some of it's members are invalid. To avoid
1060 // confusion, we forgo checking the intializer for the entire record.
1061 if (structDecl->isInvalidDecl()) {
1062 hadError = true;
1063 return;
Mike Stump11289f42009-09-09 15:08:12 +00001064 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001065
1066 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1067 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001068 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001069 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001070 Field != FieldEnd; ++Field) {
1071 if (Field->getDeclName()) {
1072 StructuredList->setInitializedFieldInUnion(*Field);
1073 break;
1074 }
1075 }
1076 return;
1077 }
1078
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001079 // If structDecl is a forward declaration, this loop won't do
1080 // anything except look at designated initializers; That's okay,
1081 // because an error should get printed out elsewhere. It might be
1082 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001083 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001084 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001085 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001086 while (Index < IList->getNumInits()) {
1087 Expr *Init = IList->getInit(Index);
1088
1089 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001090 // If we're not the subobject that matches up with the '{' for
1091 // the designator, we shouldn't be handling the
1092 // designator. Return immediately.
1093 if (!SubobjectIsDesignatorContext)
1094 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001095
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001096 // Handle this designated initializer. Field will be updated to
1097 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001098 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001099 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001100 StructuredList, StructuredIndex,
1101 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001102 hadError = true;
1103
Douglas Gregora9add4e2009-02-12 19:00:39 +00001104 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001105 continue;
1106 }
1107
1108 if (Field == FieldEnd) {
1109 // We've run out of fields. We're done.
1110 break;
1111 }
1112
Douglas Gregora9add4e2009-02-12 19:00:39 +00001113 // We've already initialized a member of a union. We're done.
1114 if (InitializedSomething && DeclType->isUnionType())
1115 break;
1116
Douglas Gregor91f84212008-12-11 16:49:14 +00001117 // If we've hit the flexible array member at the end, we're done.
1118 if (Field->getType()->isIncompleteArrayType())
1119 break;
1120
Douglas Gregor51695702009-01-29 16:53:55 +00001121 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001122 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001123 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001124 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001125 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001126
Anders Carlssond0849252010-01-23 19:55:29 +00001127 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001128 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001129 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001130
1131 if (DeclType->isUnionType()) {
1132 // Initialize the first field within the union.
1133 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001134 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001135
1136 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001137 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001138
Mike Stump11289f42009-09-09 15:08:12 +00001139 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001140 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001141 return;
1142
1143 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001144 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001145 (!isa<InitListExpr>(IList->getInit(Index)) ||
1146 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001147 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001148 diag::err_flexible_array_init_nonempty)
1149 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001150 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001151 << *Field;
1152 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001153 ++Index;
1154 return;
1155 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001156 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001157 diag::ext_flexible_array_init)
1158 << IList->getInit(Index)->getSourceRange().getBegin();
1159 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1160 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001161 }
1162
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001163 if (isa<InitListExpr>(IList->getInit(Index)))
Anders Carlssond0849252010-01-23 19:55:29 +00001164 CheckSubElementType(0, IList, Field->getType(), Index, StructuredList,
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001165 StructuredIndex);
1166 else
1167 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1168 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001169}
Steve Narofff8ecff22008-05-01 22:18:59 +00001170
Douglas Gregord5846a12009-04-15 06:41:24 +00001171/// \brief Expand a field designator that refers to a member of an
1172/// anonymous struct or union into a series of field designators that
1173/// refers to the field within the appropriate subobject.
1174///
1175/// Field/FieldIndex will be updated to point to the (new)
1176/// currently-designated field.
1177static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001178 DesignatedInitExpr *DIE,
1179 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001180 FieldDecl *Field,
1181 RecordDecl::field_iterator &FieldIter,
1182 unsigned &FieldIndex) {
1183 typedef DesignatedInitExpr::Designator Designator;
1184
1185 // Build the path from the current object to the member of the
1186 // anonymous struct/union (backwards).
1187 llvm::SmallVector<FieldDecl *, 4> Path;
1188 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001189
Douglas Gregord5846a12009-04-15 06:41:24 +00001190 // Build the replacement designators.
1191 llvm::SmallVector<Designator, 4> Replacements;
1192 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1193 FI = Path.rbegin(), FIEnd = Path.rend();
1194 FI != FIEnd; ++FI) {
1195 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001196 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001197 DIE->getDesignator(DesigIdx)->getDotLoc(),
1198 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1199 else
1200 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1201 SourceLocation()));
1202 Replacements.back().setField(*FI);
1203 }
1204
1205 // Expand the current designator into the set of replacement
1206 // designators, so we have a full subobject path down to where the
1207 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001208 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001209 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001210
Douglas Gregord5846a12009-04-15 06:41:24 +00001211 // Update FieldIter/FieldIndex;
1212 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001213 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001214 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001215 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001216 FieldIter != FEnd; ++FieldIter) {
1217 if (FieldIter->isUnnamedBitfield())
1218 continue;
1219
1220 if (*FieldIter == Path.back())
1221 return;
1222
1223 ++FieldIndex;
1224 }
1225
1226 assert(false && "Unable to find anonymous struct/union field");
1227}
1228
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001229/// @brief Check the well-formedness of a C99 designated initializer.
1230///
1231/// Determines whether the designated initializer @p DIE, which
1232/// resides at the given @p Index within the initializer list @p
1233/// IList, is well-formed for a current object of type @p DeclType
1234/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001235/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001236/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001237///
1238/// @param IList The initializer list in which this designated
1239/// initializer occurs.
1240///
Douglas Gregora5324162009-04-15 04:56:10 +00001241/// @param DIE The designated initializer expression.
1242///
1243/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001244///
1245/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1246/// into which the designation in @p DIE should refer.
1247///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001248/// @param NextField If non-NULL and the first designator in @p DIE is
1249/// a field, this will be set to the field declaration corresponding
1250/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001251///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001252/// @param NextElementIndex If non-NULL and the first designator in @p
1253/// DIE is an array designator or GNU array-range designator, this
1254/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001255///
1256/// @param Index Index into @p IList where the designated initializer
1257/// @p DIE occurs.
1258///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001259/// @param StructuredList The initializer list expression that
1260/// describes all of the subobject initializers in the order they'll
1261/// actually be initialized.
1262///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001263/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001264bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001265InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001266 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001267 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001268 QualType &CurrentObjectType,
1269 RecordDecl::field_iterator *NextField,
1270 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001271 unsigned &Index,
1272 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001273 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001274 bool FinishSubobjectInit,
1275 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001276 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001277 // Check the actual initialization for the designated object type.
1278 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001279
1280 // Temporarily remove the designator expression from the
1281 // initializer list that the child calls see, so that we don't try
1282 // to re-process the designator.
1283 unsigned OldIndex = Index;
1284 IList->setInit(OldIndex, DIE->getInit());
1285
Anders Carlssond0849252010-01-23 19:55:29 +00001286 CheckSubElementType(0, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001287 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001288
1289 // Restore the designated initializer expression in the syntactic
1290 // form of the initializer list.
1291 if (IList->getInit(OldIndex) != DIE->getInit())
1292 DIE->setInit(IList->getInit(OldIndex));
1293 IList->setInit(OldIndex, DIE);
1294
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001295 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001296 }
1297
Douglas Gregora5324162009-04-15 04:56:10 +00001298 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001299 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001300 "Need a non-designated initializer list to start from");
1301
Douglas Gregora5324162009-04-15 04:56:10 +00001302 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001303 // Determine the structural initializer list that corresponds to the
1304 // current subobject.
1305 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001306 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001307 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001308 SourceRange(D->getStartLocation(),
1309 DIE->getSourceRange().getEnd()));
1310 assert(StructuredList && "Expected a structured initializer list");
1311
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001312 if (D->isFieldDesignator()) {
1313 // C99 6.7.8p7:
1314 //
1315 // If a designator has the form
1316 //
1317 // . identifier
1318 //
1319 // then the current object (defined below) shall have
1320 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001321 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001322 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001323 if (!RT) {
1324 SourceLocation Loc = D->getDotLoc();
1325 if (Loc.isInvalid())
1326 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001327 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1328 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001329 ++Index;
1330 return true;
1331 }
1332
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001333 // Note: we perform a linear search of the fields here, despite
1334 // the fact that we have a faster lookup method, because we always
1335 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001336 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001337 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001338 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001339 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001340 Field = RT->getDecl()->field_begin(),
1341 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001342 for (; Field != FieldEnd; ++Field) {
1343 if (Field->isUnnamedBitfield())
1344 continue;
1345
Douglas Gregord5846a12009-04-15 06:41:24 +00001346 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001347 break;
1348
1349 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001350 }
1351
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001352 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001353 // There was no normal field in the struct with the designated
1354 // name. Perform another lookup for this name, which may find
1355 // something that we can't designate (e.g., a member function),
1356 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001357 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001358 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001359 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001360 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001361 // Name lookup didn't find anything. Determine whether this
1362 // was a typo for another field name.
1363 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1364 Sema::LookupMemberName);
1365 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1366 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1367 ReplacementField->getDeclContext()->getLookupContext()
1368 ->Equals(RT->getDecl())) {
1369 SemaRef.Diag(D->getFieldLoc(),
1370 diag::err_field_designator_unknown_suggest)
1371 << FieldName << CurrentObjectType << R.getLookupName()
1372 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1373 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001374 SemaRef.Diag(ReplacementField->getLocation(),
1375 diag::note_previous_decl)
1376 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001377 } else {
1378 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1379 << FieldName << CurrentObjectType;
1380 ++Index;
1381 return true;
1382 }
1383 } else if (!KnownField) {
1384 // Determine whether we found a field at all.
1385 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1386 }
1387
1388 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001389 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001390 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001391 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001392 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001393 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001394 ++Index;
1395 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001396 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001397
1398 if (!KnownField &&
1399 cast<RecordDecl>((ReplacementField)->getDeclContext())
1400 ->isAnonymousStructOrUnion()) {
1401 // Handle an field designator that refers to a member of an
1402 // anonymous struct or union.
1403 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1404 ReplacementField,
1405 Field, FieldIndex);
1406 D = DIE->getDesignator(DesigIdx);
1407 } else if (!KnownField) {
1408 // The replacement field comes from typo correction; find it
1409 // in the list of fields.
1410 FieldIndex = 0;
1411 Field = RT->getDecl()->field_begin();
1412 for (; Field != FieldEnd; ++Field) {
1413 if (Field->isUnnamedBitfield())
1414 continue;
1415
1416 if (ReplacementField == *Field ||
1417 Field->getIdentifier() == ReplacementField->getIdentifier())
1418 break;
1419
1420 ++FieldIndex;
1421 }
1422 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001423 } else if (!KnownField &&
1424 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001425 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001426 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1427 Field, FieldIndex);
1428 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001429 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001430
1431 // All of the fields of a union are located at the same place in
1432 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001433 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001434 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001435 StructuredList->setInitializedFieldInUnion(*Field);
1436 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001437
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001438 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001439 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001440
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001441 // Make sure that our non-designated initializer list has space
1442 // for a subobject corresponding to this field.
1443 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001444 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001445
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001446 // This designator names a flexible array member.
1447 if (Field->getType()->isIncompleteArrayType()) {
1448 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001449 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001450 // We can't designate an object within the flexible array
1451 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001452 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001453 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001454 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001455 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001456 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001457 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001458 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001459 << *Field;
1460 Invalid = true;
1461 }
1462
1463 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1464 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001465 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001466 diag::err_flexible_array_init_needs_braces)
1467 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001468 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001469 << *Field;
1470 Invalid = true;
1471 }
1472
1473 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001474 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001475 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001477 diag::err_flexible_array_init_nonempty)
1478 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001479 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 << *Field;
1481 Invalid = true;
1482 }
1483
1484 if (Invalid) {
1485 ++Index;
1486 return true;
1487 }
1488
1489 // Initialize the array.
1490 bool prevHadError = hadError;
1491 unsigned newStructuredIndex = FieldIndex;
1492 unsigned OldIndex = Index;
1493 IList->setInit(Index, DIE->getInit());
Anders Carlssond0849252010-01-23 19:55:29 +00001494 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001495 StructuredList, newStructuredIndex);
1496 IList->setInit(OldIndex, DIE);
1497 if (hadError && !prevHadError) {
1498 ++Field;
1499 ++FieldIndex;
1500 if (NextField)
1501 *NextField = Field;
1502 StructuredIndex = FieldIndex;
1503 return true;
1504 }
1505 } else {
1506 // Recurse to check later designated subobjects.
1507 QualType FieldType = (*Field)->getType();
1508 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001509 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1510 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001511 true, false))
1512 return true;
1513 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001514
1515 // Find the position of the next field to be initialized in this
1516 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001517 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001518 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001519
1520 // If this the first designator, our caller will continue checking
1521 // the rest of this struct/class/union subobject.
1522 if (IsFirstDesignator) {
1523 if (NextField)
1524 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001525 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001526 return false;
1527 }
1528
Douglas Gregor17bd0942009-01-28 23:36:17 +00001529 if (!FinishSubobjectInit)
1530 return false;
1531
Douglas Gregord5846a12009-04-15 06:41:24 +00001532 // We've already initialized something in the union; we're done.
1533 if (RT->getDecl()->isUnion())
1534 return hadError;
1535
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001536 // Check the remaining fields within this class/struct/union subobject.
1537 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001538 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1539 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001540 return hadError && !prevHadError;
1541 }
1542
1543 // C99 6.7.8p6:
1544 //
1545 // If a designator has the form
1546 //
1547 // [ constant-expression ]
1548 //
1549 // then the current object (defined below) shall have array
1550 // type and the expression shall be an integer constant
1551 // expression. If the array is of unknown size, any
1552 // nonnegative value is valid.
1553 //
1554 // Additionally, cope with the GNU extension that permits
1555 // designators of the form
1556 //
1557 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001558 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001559 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001560 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001561 << CurrentObjectType;
1562 ++Index;
1563 return true;
1564 }
1565
1566 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001567 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1568 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001569 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001570 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001571 DesignatedEndIndex = DesignatedStartIndex;
1572 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001573 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001574
Mike Stump11289f42009-09-09 15:08:12 +00001575
1576 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001577 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001578 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001579 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001580 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001581
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001582 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001583 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001584 }
1585
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001586 if (isa<ConstantArrayType>(AT)) {
1587 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001588 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1589 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1590 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1591 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1592 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001593 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001594 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001595 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001596 << IndexExpr->getSourceRange();
1597 ++Index;
1598 return true;
1599 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001600 } else {
1601 // Make sure the bit-widths and signedness match.
1602 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1603 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001604 else if (DesignatedStartIndex.getBitWidth() <
1605 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001606 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1607 DesignatedStartIndex.setIsUnsigned(true);
1608 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 // Make sure that our non-designated initializer list has space
1612 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001613 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001614 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001615 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001616
Douglas Gregor17bd0942009-01-28 23:36:17 +00001617 // Repeatedly perform subobject initializations in the range
1618 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001619
Douglas Gregor17bd0942009-01-28 23:36:17 +00001620 // Move to the next designator
1621 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1622 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001623 while (DesignatedStartIndex <= DesignatedEndIndex) {
1624 // Recurse to check later designated subobjects.
1625 QualType ElementType = AT->getElementType();
1626 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001627 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1628 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001629 (DesignatedStartIndex == DesignatedEndIndex),
1630 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001631 return true;
1632
1633 // Move to the next index in the array that we'll be initializing.
1634 ++DesignatedStartIndex;
1635 ElementIndex = DesignatedStartIndex.getZExtValue();
1636 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001637
1638 // If this the first designator, our caller will continue checking
1639 // the rest of this array subobject.
1640 if (IsFirstDesignator) {
1641 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001642 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001643 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001644 return false;
1645 }
Mike Stump11289f42009-09-09 15:08:12 +00001646
Douglas Gregor17bd0942009-01-28 23:36:17 +00001647 if (!FinishSubobjectInit)
1648 return false;
1649
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001650 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001651 bool prevHadError = hadError;
Douglas Gregoraef040a2009-02-09 19:45:19 +00001652 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001653 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001654 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001655}
1656
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001657// Get the structured initializer list for a subobject of type
1658// @p CurrentObjectType.
1659InitListExpr *
1660InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1661 QualType CurrentObjectType,
1662 InitListExpr *StructuredList,
1663 unsigned StructuredIndex,
1664 SourceRange InitRange) {
1665 Expr *ExistingInit = 0;
1666 if (!StructuredList)
1667 ExistingInit = SyntacticToSemantic[IList];
1668 else if (StructuredIndex < StructuredList->getNumInits())
1669 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001670
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001671 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1672 return Result;
1673
1674 if (ExistingInit) {
1675 // We are creating an initializer list that initializes the
1676 // subobjects of the current object, but there was already an
1677 // initialization that completely initialized the current
1678 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001679 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001680 // struct X { int a, b; };
1681 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001682 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001683 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1684 // designated initializer re-initializes the whole
1685 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001686 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001687 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001688 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001689 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001690 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001691 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001692 << ExistingInit->getSourceRange();
1693 }
1694
Mike Stump11289f42009-09-09 15:08:12 +00001695 InitListExpr *Result
1696 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001697 InitRange.getEnd());
1698
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001699 Result->setType(CurrentObjectType);
1700
Douglas Gregor6d00c992009-03-20 23:58:33 +00001701 // Pre-allocate storage for the structured initializer list.
1702 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001703 unsigned NumInits = 0;
1704 if (!StructuredList)
1705 NumInits = IList->getNumInits();
1706 else if (Index < IList->getNumInits()) {
1707 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1708 NumInits = SubList->getNumInits();
1709 }
1710
Mike Stump11289f42009-09-09 15:08:12 +00001711 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001712 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1713 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1714 NumElements = CAType->getSize().getZExtValue();
1715 // Simple heuristic so that we don't allocate a very large
1716 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001717 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001718 NumElements = 0;
1719 }
John McCall9dd450b2009-09-21 23:43:11 +00001720 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001721 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001722 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001723 RecordDecl *RDecl = RType->getDecl();
1724 if (RDecl->isUnion())
1725 NumElements = 1;
1726 else
Mike Stump11289f42009-09-09 15:08:12 +00001727 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001728 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001729 }
1730
Douglas Gregor221c9a52009-03-21 18:13:52 +00001731 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001732 NumElements = IList->getNumInits();
1733
1734 Result->reserveInits(NumElements);
1735
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001736 // Link this new initializer list into the structured initializer
1737 // lists.
1738 if (StructuredList)
1739 StructuredList->updateInit(StructuredIndex, Result);
1740 else {
1741 Result->setSyntacticForm(IList);
1742 SyntacticToSemantic[IList] = Result;
1743 }
1744
1745 return Result;
1746}
1747
1748/// Update the initializer at index @p StructuredIndex within the
1749/// structured initializer list to the value @p expr.
1750void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1751 unsigned &StructuredIndex,
1752 Expr *expr) {
1753 // No structured initializer list to update
1754 if (!StructuredList)
1755 return;
1756
1757 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1758 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001759 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001760 diag::warn_initializer_overrides)
1761 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001762 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001763 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001764 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001765 << PrevInit->getSourceRange();
1766 }
Mike Stump11289f42009-09-09 15:08:12 +00001767
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001768 ++StructuredIndex;
1769}
1770
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771/// Check that the given Index expression is a valid array designator
1772/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001773/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001774/// and produces a reasonable diagnostic if there is a
1775/// failure. Returns true if there was an error, false otherwise. If
1776/// everything went okay, Value will receive the value of the constant
1777/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001778static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001779CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001780 SourceLocation Loc = Index->getSourceRange().getBegin();
1781
1782 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001783 if (S.VerifyIntegerConstantExpression(Index, &Value))
1784 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001785
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001786 if (Value.isSigned() && Value.isNegative())
1787 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001788 << Value.toString(10) << Index->getSourceRange();
1789
Douglas Gregor51650d32009-01-23 21:04:18 +00001790 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001791 return false;
1792}
1793
1794Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1795 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001796 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001797 OwningExprResult Init) {
1798 typedef DesignatedInitExpr::Designator ASTDesignator;
1799
1800 bool Invalid = false;
1801 llvm::SmallVector<ASTDesignator, 32> Designators;
1802 llvm::SmallVector<Expr *, 32> InitExpressions;
1803
1804 // Build designators and check array designator expressions.
1805 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1806 const Designator &D = Desig.getDesignator(Idx);
1807 switch (D.getKind()) {
1808 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001809 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001810 D.getFieldLoc()));
1811 break;
1812
1813 case Designator::ArrayDesignator: {
1814 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1815 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001816 if (!Index->isTypeDependent() &&
1817 !Index->isValueDependent() &&
1818 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001819 Invalid = true;
1820 else {
1821 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001822 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001823 D.getRBracketLoc()));
1824 InitExpressions.push_back(Index);
1825 }
1826 break;
1827 }
1828
1829 case Designator::ArrayRangeDesignator: {
1830 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1831 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1832 llvm::APSInt StartValue;
1833 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001834 bool StartDependent = StartIndex->isTypeDependent() ||
1835 StartIndex->isValueDependent();
1836 bool EndDependent = EndIndex->isTypeDependent() ||
1837 EndIndex->isValueDependent();
1838 if ((!StartDependent &&
1839 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1840 (!EndDependent &&
1841 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001842 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001843 else {
1844 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001845 if (StartDependent || EndDependent) {
1846 // Nothing to compute.
1847 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001848 EndValue.extend(StartValue.getBitWidth());
1849 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1850 StartValue.extend(EndValue.getBitWidth());
1851
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001852 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001853 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001854 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001855 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1856 Invalid = true;
1857 } else {
1858 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001859 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001860 D.getEllipsisLoc(),
1861 D.getRBracketLoc()));
1862 InitExpressions.push_back(StartIndex);
1863 InitExpressions.push_back(EndIndex);
1864 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001865 }
1866 break;
1867 }
1868 }
1869 }
1870
1871 if (Invalid || Init.isInvalid())
1872 return ExprError();
1873
1874 // Clear out the expressions within the designation.
1875 Desig.ClearExprs(*this);
1876
1877 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001878 = DesignatedInitExpr::Create(Context,
1879 Designators.data(), Designators.size(),
1880 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001881 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001882 return Owned(DIE);
1883}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001884
Douglas Gregor723796a2009-12-16 06:35:08 +00001885bool Sema::CheckInitList(const InitializedEntity &Entity,
1886 InitListExpr *&InitList, QualType &DeclType) {
1887 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001888 if (!CheckInitList.HadError())
1889 InitList = CheckInitList.getFullyStructuredList();
1890
1891 return CheckInitList.HadError();
1892}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001893
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001894//===----------------------------------------------------------------------===//
1895// Initialization entity
1896//===----------------------------------------------------------------------===//
1897
Douglas Gregor723796a2009-12-16 06:35:08 +00001898InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1899 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001900 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001901{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001902 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1903 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001904 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001905 } else {
1906 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001907 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001908 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001909}
1910
1911InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1912 CXXBaseSpecifier *Base)
1913{
1914 InitializedEntity Result;
1915 Result.Kind = EK_Base;
1916 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001917 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001918 return Result;
1919}
1920
Douglas Gregor85dabae2009-12-16 01:38:02 +00001921DeclarationName InitializedEntity::getName() const {
1922 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001923 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001924 if (!VariableOrMember)
1925 return DeclarationName();
1926 // Fall through
1927
1928 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001929 case EK_Member:
1930 return VariableOrMember->getDeclName();
1931
1932 case EK_Result:
1933 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001934 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001935 case EK_Temporary:
1936 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001937 case EK_ArrayElement:
1938 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001939 return DeclarationName();
1940 }
1941
1942 // Silence GCC warning
1943 return DeclarationName();
1944}
1945
Douglas Gregora4b592a2009-12-19 03:01:41 +00001946DeclaratorDecl *InitializedEntity::getDecl() const {
1947 switch (getKind()) {
1948 case EK_Variable:
1949 case EK_Parameter:
1950 case EK_Member:
1951 return VariableOrMember;
1952
1953 case EK_Result:
1954 case EK_Exception:
1955 case EK_New:
1956 case EK_Temporary:
1957 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001958 case EK_ArrayElement:
1959 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001960 return 0;
1961 }
1962
1963 // Silence GCC warning
1964 return 0;
1965}
1966
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001967//===----------------------------------------------------------------------===//
1968// Initialization sequence
1969//===----------------------------------------------------------------------===//
1970
1971void InitializationSequence::Step::Destroy() {
1972 switch (Kind) {
1973 case SK_ResolveAddressOfOverloadedFunction:
1974 case SK_CastDerivedToBaseRValue:
1975 case SK_CastDerivedToBaseLValue:
1976 case SK_BindReference:
1977 case SK_BindReferenceToTemporary:
1978 case SK_UserConversion:
1979 case SK_QualificationConversionRValue:
1980 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001981 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001982 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001983 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001984 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001985 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001986 break;
1987
1988 case SK_ConversionSequence:
1989 delete ICS;
1990 }
1991}
1992
1993void InitializationSequence::AddAddressOverloadResolutionStep(
1994 FunctionDecl *Function) {
1995 Step S;
1996 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1997 S.Type = Function->getType();
1998 S.Function = Function;
1999 Steps.push_back(S);
2000}
2001
2002void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2003 bool IsLValue) {
2004 Step S;
2005 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2006 S.Type = BaseType;
2007 Steps.push_back(S);
2008}
2009
2010void InitializationSequence::AddReferenceBindingStep(QualType T,
2011 bool BindingTemporary) {
2012 Step S;
2013 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2014 S.Type = T;
2015 Steps.push_back(S);
2016}
2017
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002018void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2019 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002020 Step S;
2021 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002022 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002023 S.Function = Function;
2024 Steps.push_back(S);
2025}
2026
2027void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2028 bool IsLValue) {
2029 Step S;
2030 S.Kind = IsLValue? SK_QualificationConversionLValue
2031 : SK_QualificationConversionRValue;
2032 S.Type = Ty;
2033 Steps.push_back(S);
2034}
2035
2036void InitializationSequence::AddConversionSequenceStep(
2037 const ImplicitConversionSequence &ICS,
2038 QualType T) {
2039 Step S;
2040 S.Kind = SK_ConversionSequence;
2041 S.Type = T;
2042 S.ICS = new ImplicitConversionSequence(ICS);
2043 Steps.push_back(S);
2044}
2045
Douglas Gregor51e77d52009-12-10 17:56:55 +00002046void InitializationSequence::AddListInitializationStep(QualType T) {
2047 Step S;
2048 S.Kind = SK_ListInitialization;
2049 S.Type = T;
2050 Steps.push_back(S);
2051}
2052
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002053void
2054InitializationSequence::AddConstructorInitializationStep(
2055 CXXConstructorDecl *Constructor,
2056 QualType T) {
2057 Step S;
2058 S.Kind = SK_ConstructorInitialization;
2059 S.Type = T;
2060 S.Function = Constructor;
2061 Steps.push_back(S);
2062}
2063
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002064void InitializationSequence::AddZeroInitializationStep(QualType T) {
2065 Step S;
2066 S.Kind = SK_ZeroInitialization;
2067 S.Type = T;
2068 Steps.push_back(S);
2069}
2070
Douglas Gregore1314a62009-12-18 05:02:21 +00002071void InitializationSequence::AddCAssignmentStep(QualType T) {
2072 Step S;
2073 S.Kind = SK_CAssignment;
2074 S.Type = T;
2075 Steps.push_back(S);
2076}
2077
Eli Friedman78275202009-12-19 08:11:05 +00002078void InitializationSequence::AddStringInitStep(QualType T) {
2079 Step S;
2080 S.Kind = SK_StringInit;
2081 S.Type = T;
2082 Steps.push_back(S);
2083}
2084
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002085void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2086 OverloadingResult Result) {
2087 SequenceKind = FailedSequence;
2088 this->Failure = Failure;
2089 this->FailedOverloadResult = Result;
2090}
2091
2092//===----------------------------------------------------------------------===//
2093// Attempt initialization
2094//===----------------------------------------------------------------------===//
2095
2096/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002097static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002098 const InitializedEntity &Entity,
2099 const InitializationKind &Kind,
2100 InitListExpr *InitList,
2101 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002102 // FIXME: We only perform rudimentary checking of list
2103 // initializations at this point, then assume that any list
2104 // initialization of an array, aggregate, or scalar will be
2105 // well-formed. We we actually "perform" list initialization, we'll
2106 // do all of the necessary checking. C++0x initializer lists will
2107 // force us to perform more checking here.
2108 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2109
Douglas Gregor1b303932009-12-22 15:35:07 +00002110 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002111
2112 // C++ [dcl.init]p13:
2113 // If T is a scalar type, then a declaration of the form
2114 //
2115 // T x = { a };
2116 //
2117 // is equivalent to
2118 //
2119 // T x = a;
2120 if (DestType->isScalarType()) {
2121 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2122 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2123 return;
2124 }
2125
2126 // Assume scalar initialization from a single value works.
2127 } else if (DestType->isAggregateType()) {
2128 // Assume aggregate initialization works.
2129 } else if (DestType->isVectorType()) {
2130 // Assume vector initialization works.
2131 } else if (DestType->isReferenceType()) {
2132 // FIXME: C++0x defines behavior for this.
2133 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2134 return;
2135 } else if (DestType->isRecordType()) {
2136 // FIXME: C++0x defines behavior for this
2137 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2138 }
2139
2140 // Add a general "list initialization" step.
2141 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002142}
2143
2144/// \brief Try a reference initialization that involves calling a conversion
2145/// function.
2146///
2147/// FIXME: look intos DRs 656, 896
2148static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2149 const InitializedEntity &Entity,
2150 const InitializationKind &Kind,
2151 Expr *Initializer,
2152 bool AllowRValues,
2153 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002154 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002155 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2156 QualType T1 = cv1T1.getUnqualifiedType();
2157 QualType cv2T2 = Initializer->getType();
2158 QualType T2 = cv2T2.getUnqualifiedType();
2159
2160 bool DerivedToBase;
2161 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2162 T1, T2, DerivedToBase) &&
2163 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002164 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002165
2166 // Build the candidate set directly in the initialization sequence
2167 // structure, so that it will persist if we fail.
2168 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2169 CandidateSet.clear();
2170
2171 // Determine whether we are allowed to call explicit constructors or
2172 // explicit conversion operators.
2173 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2174
2175 const RecordType *T1RecordType = 0;
2176 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2177 // The type we're converting to is a class type. Enumerate its constructors
2178 // to see if there is a suitable conversion.
2179 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2180
2181 DeclarationName ConstructorName
2182 = S.Context.DeclarationNames.getCXXConstructorName(
2183 S.Context.getCanonicalType(T1).getUnqualifiedType());
2184 DeclContext::lookup_iterator Con, ConEnd;
2185 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2186 Con != ConEnd; ++Con) {
2187 // Find the constructor (which may be a template).
2188 CXXConstructorDecl *Constructor = 0;
2189 FunctionTemplateDecl *ConstructorTmpl
2190 = dyn_cast<FunctionTemplateDecl>(*Con);
2191 if (ConstructorTmpl)
2192 Constructor = cast<CXXConstructorDecl>(
2193 ConstructorTmpl->getTemplatedDecl());
2194 else
2195 Constructor = cast<CXXConstructorDecl>(*Con);
2196
2197 if (!Constructor->isInvalidDecl() &&
2198 Constructor->isConvertingConstructor(AllowExplicit)) {
2199 if (ConstructorTmpl)
2200 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2201 &Initializer, 1, CandidateSet);
2202 else
2203 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2204 }
2205 }
2206 }
2207
2208 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2209 // The type we're converting from is a class type, enumerate its conversion
2210 // functions.
2211 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2212
2213 // Determine the type we are converting to. If we are allowed to
2214 // convert to an rvalue, take the type that the destination type
2215 // refers to.
2216 QualType ToType = AllowRValues? cv1T1 : DestType;
2217
John McCallad371252010-01-20 00:46:10 +00002218 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002219 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002220 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2221 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002222 NamedDecl *D = *I;
2223 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2224 if (isa<UsingShadowDecl>(D))
2225 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2226
2227 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2228 CXXConversionDecl *Conv;
2229 if (ConvTemplate)
2230 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2231 else
2232 Conv = cast<CXXConversionDecl>(*I);
2233
2234 // If the conversion function doesn't return a reference type,
2235 // it can't be considered for this conversion unless we're allowed to
2236 // consider rvalues.
2237 // FIXME: Do we need to make sure that we only consider conversion
2238 // candidates with reference-compatible results? That might be needed to
2239 // break recursion.
2240 if ((AllowExplicit || !Conv->isExplicit()) &&
2241 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2242 if (ConvTemplate)
2243 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2244 ToType, CandidateSet);
2245 else
2246 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2247 CandidateSet);
2248 }
2249 }
2250 }
2251
2252 SourceLocation DeclLoc = Initializer->getLocStart();
2253
2254 // Perform overload resolution. If it fails, return the failed result.
2255 OverloadCandidateSet::iterator Best;
2256 if (OverloadingResult Result
2257 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2258 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002259
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002260 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002261
2262 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002263 if (isa<CXXConversionDecl>(Function))
2264 T2 = Function->getResultType();
2265 else
2266 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002267
2268 // Add the user-defined conversion step.
2269 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2270
2271 // Determine whether we need to perform derived-to-base or
2272 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002273 bool NewDerivedToBase = false;
2274 Sema::ReferenceCompareResult NewRefRelationship
2275 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2276 NewDerivedToBase);
2277 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2278 "Overload resolution picked a bad conversion function");
2279 (void)NewRefRelationship;
2280 if (NewDerivedToBase)
2281 Sequence.AddDerivedToBaseCastStep(
2282 S.Context.getQualifiedType(T1,
2283 T2.getNonReferenceType().getQualifiers()),
2284 /*isLValue=*/true);
2285
2286 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2287 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2288
2289 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2290 return OR_Success;
2291}
2292
2293/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2294static void TryReferenceInitialization(Sema &S,
2295 const InitializedEntity &Entity,
2296 const InitializationKind &Kind,
2297 Expr *Initializer,
2298 InitializationSequence &Sequence) {
2299 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2300
Douglas Gregor1b303932009-12-22 15:35:07 +00002301 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002302 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002303 Qualifiers T1Quals;
2304 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002305 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002306 Qualifiers T2Quals;
2307 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002308 SourceLocation DeclLoc = Initializer->getLocStart();
2309
2310 // If the initializer is the address of an overloaded function, try
2311 // to resolve the overloaded function. If all goes well, T2 is the
2312 // type of the resulting function.
2313 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2314 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2315 T1,
2316 false);
2317 if (!Fn) {
2318 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2319 return;
2320 }
2321
2322 Sequence.AddAddressOverloadResolutionStep(Fn);
2323 cv2T2 = Fn->getType();
2324 T2 = cv2T2.getUnqualifiedType();
2325 }
2326
2327 // FIXME: Rvalue references
2328 bool ForceRValue = false;
2329
2330 // Compute some basic properties of the types and the initializer.
2331 bool isLValueRef = DestType->isLValueReferenceType();
2332 bool isRValueRef = !isLValueRef;
2333 bool DerivedToBase = false;
2334 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2335 Initializer->isLvalue(S.Context);
2336 Sema::ReferenceCompareResult RefRelationship
2337 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2338
2339 // C++0x [dcl.init.ref]p5:
2340 // A reference to type "cv1 T1" is initialized by an expression of type
2341 // "cv2 T2" as follows:
2342 //
2343 // - If the reference is an lvalue reference and the initializer
2344 // expression
2345 OverloadingResult ConvOvlResult = OR_Success;
2346 if (isLValueRef) {
2347 if (InitLvalue == Expr::LV_Valid &&
2348 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2349 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2350 // reference-compatible with "cv2 T2," or
2351 //
2352 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2353 // bit-field when we're determining whether the reference initialization
2354 // can occur. This property will be checked by PerformInitialization.
2355 if (DerivedToBase)
2356 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002357 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002358 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002359 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002360 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2361 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2362 return;
2363 }
2364
2365 // - has a class type (i.e., T2 is a class type), where T1 is not
2366 // reference-related to T2, and can be implicitly converted to an
2367 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2368 // with "cv3 T3" (this conversion is selected by enumerating the
2369 // applicable conversion functions (13.3.1.6) and choosing the best
2370 // one through overload resolution (13.3)),
2371 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2372 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2373 Initializer,
2374 /*AllowRValues=*/false,
2375 Sequence);
2376 if (ConvOvlResult == OR_Success)
2377 return;
John McCall0d1da222010-01-12 00:44:57 +00002378 if (ConvOvlResult != OR_No_Viable_Function) {
2379 Sequence.SetOverloadFailure(
2380 InitializationSequence::FK_ReferenceInitOverloadFailed,
2381 ConvOvlResult);
2382 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002383 }
2384 }
2385
2386 // - Otherwise, the reference shall be an lvalue reference to a
2387 // non-volatile const type (i.e., cv1 shall be const), or the reference
2388 // shall be an rvalue reference and the initializer expression shall
2389 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002390 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002391 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2392 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2393 Sequence.SetOverloadFailure(
2394 InitializationSequence::FK_ReferenceInitOverloadFailed,
2395 ConvOvlResult);
2396 else if (isLValueRef)
2397 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2398 ? (RefRelationship == Sema::Ref_Related
2399 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2400 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2401 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2402 else
2403 Sequence.SetFailed(
2404 InitializationSequence::FK_RValueReferenceBindingToLValue);
2405
2406 return;
2407 }
2408
2409 // - If T1 and T2 are class types and
2410 if (T1->isRecordType() && T2->isRecordType()) {
2411 // - the initializer expression is an rvalue and "cv1 T1" is
2412 // reference-compatible with "cv2 T2", or
2413 if (InitLvalue != Expr::LV_Valid &&
2414 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2415 if (DerivedToBase)
2416 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002417 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002419 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002420 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2421 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2422 return;
2423 }
2424
2425 // - T1 is not reference-related to T2 and the initializer expression
2426 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2427 // conversion is selected by enumerating the applicable conversion
2428 // functions (13.3.1.6) and choosing the best one through overload
2429 // resolution (13.3)),
2430 if (RefRelationship == Sema::Ref_Incompatible) {
2431 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2432 Kind, Initializer,
2433 /*AllowRValues=*/true,
2434 Sequence);
2435 if (ConvOvlResult)
2436 Sequence.SetOverloadFailure(
2437 InitializationSequence::FK_ReferenceInitOverloadFailed,
2438 ConvOvlResult);
2439
2440 return;
2441 }
2442
2443 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2444 return;
2445 }
2446
2447 // - If the initializer expression is an rvalue, with T2 an array type,
2448 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2449 // is bound to the object represented by the rvalue (see 3.10).
2450 // FIXME: How can an array type be reference-compatible with anything?
2451 // Don't we mean the element types of T1 and T2?
2452
2453 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2454 // from the initializer expression using the rules for a non-reference
2455 // copy initialization (8.5). The reference is then bound to the
2456 // temporary. [...]
2457 // Determine whether we are allowed to call explicit constructors or
2458 // explicit conversion operators.
2459 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2460 ImplicitConversionSequence ICS
2461 = S.TryImplicitConversion(Initializer, cv1T1,
2462 /*SuppressUserConversions=*/false, AllowExplicit,
2463 /*ForceRValue=*/false,
2464 /*FIXME:InOverloadResolution=*/false,
2465 /*UserCast=*/Kind.isExplicitCast());
2466
John McCall0d1da222010-01-12 00:44:57 +00002467 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002468 // FIXME: Use the conversion function set stored in ICS to turn
2469 // this into an overloading ambiguity diagnostic. However, we need
2470 // to keep that set as an OverloadCandidateSet rather than as some
2471 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002472 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2473 Sequence.SetOverloadFailure(
2474 InitializationSequence::FK_ReferenceInitOverloadFailed,
2475 ConvOvlResult);
2476 else
2477 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002478 return;
2479 }
2480
2481 // [...] If T1 is reference-related to T2, cv1 must be the
2482 // same cv-qualification as, or greater cv-qualification
2483 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002484 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2485 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002486 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002487 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2489 return;
2490 }
2491
2492 // Perform the actual conversion.
2493 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2494 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2495 return;
2496}
2497
2498/// \brief Attempt character array initialization from a string literal
2499/// (C++ [dcl.init.string], C99 6.7.8).
2500static void TryStringLiteralInitialization(Sema &S,
2501 const InitializedEntity &Entity,
2502 const InitializationKind &Kind,
2503 Expr *Initializer,
2504 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002505 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002506 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002507}
2508
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002509/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2510/// enumerates the constructors of the initialized entity and performs overload
2511/// resolution to select the best.
2512static void TryConstructorInitialization(Sema &S,
2513 const InitializedEntity &Entity,
2514 const InitializationKind &Kind,
2515 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002516 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002517 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002518 if (Kind.getKind() == InitializationKind::IK_Copy)
2519 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2520 else
2521 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002522
2523 // Build the candidate set directly in the initialization sequence
2524 // structure, so that it will persist if we fail.
2525 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2526 CandidateSet.clear();
2527
2528 // Determine whether we are allowed to call explicit constructors or
2529 // explicit conversion operators.
2530 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2531 Kind.getKind() == InitializationKind::IK_Value ||
2532 Kind.getKind() == InitializationKind::IK_Default);
2533
2534 // The type we're converting to is a class type. Enumerate its constructors
2535 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002536 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2537 assert(DestRecordType && "Constructor initialization requires record type");
2538 CXXRecordDecl *DestRecordDecl
2539 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2540
2541 DeclarationName ConstructorName
2542 = S.Context.DeclarationNames.getCXXConstructorName(
2543 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2544 DeclContext::lookup_iterator Con, ConEnd;
2545 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2546 Con != ConEnd; ++Con) {
2547 // Find the constructor (which may be a template).
2548 CXXConstructorDecl *Constructor = 0;
2549 FunctionTemplateDecl *ConstructorTmpl
2550 = dyn_cast<FunctionTemplateDecl>(*Con);
2551 if (ConstructorTmpl)
2552 Constructor = cast<CXXConstructorDecl>(
2553 ConstructorTmpl->getTemplatedDecl());
2554 else
2555 Constructor = cast<CXXConstructorDecl>(*Con);
2556
2557 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002558 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002559 if (ConstructorTmpl)
2560 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2561 Args, NumArgs, CandidateSet);
2562 else
2563 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2564 }
2565 }
2566
2567 SourceLocation DeclLoc = Kind.getLocation();
2568
2569 // Perform overload resolution. If it fails, return the failed result.
2570 OverloadCandidateSet::iterator Best;
2571 if (OverloadingResult Result
2572 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2573 Sequence.SetOverloadFailure(
2574 InitializationSequence::FK_ConstructorOverloadFailed,
2575 Result);
2576 return;
2577 }
2578
2579 // Add the constructor initialization step. Any cv-qualification conversion is
2580 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002581 if (Kind.getKind() == InitializationKind::IK_Copy) {
2582 Sequence.AddUserConversionStep(Best->Function, DestType);
2583 } else {
2584 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002585 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002586 DestType);
2587 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002588}
2589
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002590/// \brief Attempt value initialization (C++ [dcl.init]p7).
2591static void TryValueInitialization(Sema &S,
2592 const InitializedEntity &Entity,
2593 const InitializationKind &Kind,
2594 InitializationSequence &Sequence) {
2595 // C++ [dcl.init]p5:
2596 //
2597 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002598 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002599
2600 // -- if T is an array type, then each element is value-initialized;
2601 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2602 T = AT->getElementType();
2603
2604 if (const RecordType *RT = T->getAs<RecordType>()) {
2605 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2606 // -- if T is a class type (clause 9) with a user-declared
2607 // constructor (12.1), then the default constructor for T is
2608 // called (and the initialization is ill-formed if T has no
2609 // accessible default constructor);
2610 //
2611 // FIXME: we really want to refer to a single subobject of the array,
2612 // but Entity doesn't have a way to capture that (yet).
2613 if (ClassDecl->hasUserDeclaredConstructor())
2614 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2615
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002616 // -- if T is a (possibly cv-qualified) non-union class type
2617 // without a user-provided constructor, then the object is
2618 // zero-initialized and, if T’s implicitly-declared default
2619 // constructor is non-trivial, that constructor is called.
2620 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2621 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2622 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002623 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002624 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2625 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002626 }
2627 }
2628
Douglas Gregor1b303932009-12-22 15:35:07 +00002629 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002630 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2631}
2632
Douglas Gregor85dabae2009-12-16 01:38:02 +00002633/// \brief Attempt default initialization (C++ [dcl.init]p6).
2634static void TryDefaultInitialization(Sema &S,
2635 const InitializedEntity &Entity,
2636 const InitializationKind &Kind,
2637 InitializationSequence &Sequence) {
2638 assert(Kind.getKind() == InitializationKind::IK_Default);
2639
2640 // C++ [dcl.init]p6:
2641 // To default-initialize an object of type T means:
2642 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002643 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002644 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2645 DestType = Array->getElementType();
2646
2647 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2648 // constructor for T is called (and the initialization is ill-formed if
2649 // T has no accessible default constructor);
2650 if (DestType->isRecordType()) {
2651 // FIXME: If a program calls for the default initialization of an object of
2652 // a const-qualified type T, T shall be a class type with a user-provided
2653 // default constructor.
2654 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2655 Sequence);
2656 }
2657
2658 // - otherwise, no initialization is performed.
2659 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2660
2661 // If a program calls for the default initialization of an object of
2662 // a const-qualified type T, T shall be a class type with a user-provided
2663 // default constructor.
2664 if (DestType.isConstQualified())
2665 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2666}
2667
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002668/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2669/// which enumerates all conversion functions and performs overload resolution
2670/// to select the best.
2671static void TryUserDefinedConversion(Sema &S,
2672 const InitializedEntity &Entity,
2673 const InitializationKind &Kind,
2674 Expr *Initializer,
2675 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002676 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2677
Douglas Gregor1b303932009-12-22 15:35:07 +00002678 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002679 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2680 QualType SourceType = Initializer->getType();
2681 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2682 "Must have a class type to perform a user-defined conversion");
2683
2684 // Build the candidate set directly in the initialization sequence
2685 // structure, so that it will persist if we fail.
2686 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2687 CandidateSet.clear();
2688
2689 // Determine whether we are allowed to call explicit constructors or
2690 // explicit conversion operators.
2691 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2692
2693 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2694 // The type we're converting to is a class type. Enumerate its constructors
2695 // to see if there is a suitable conversion.
2696 CXXRecordDecl *DestRecordDecl
2697 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2698
2699 DeclarationName ConstructorName
2700 = S.Context.DeclarationNames.getCXXConstructorName(
2701 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2702 DeclContext::lookup_iterator Con, ConEnd;
2703 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2704 Con != ConEnd; ++Con) {
2705 // Find the constructor (which may be a template).
2706 CXXConstructorDecl *Constructor = 0;
2707 FunctionTemplateDecl *ConstructorTmpl
2708 = dyn_cast<FunctionTemplateDecl>(*Con);
2709 if (ConstructorTmpl)
2710 Constructor = cast<CXXConstructorDecl>(
2711 ConstructorTmpl->getTemplatedDecl());
2712 else
2713 Constructor = cast<CXXConstructorDecl>(*Con);
2714
2715 if (!Constructor->isInvalidDecl() &&
2716 Constructor->isConvertingConstructor(AllowExplicit)) {
2717 if (ConstructorTmpl)
2718 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2719 &Initializer, 1, CandidateSet);
2720 else
2721 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2722 }
2723 }
2724 }
Eli Friedman78275202009-12-19 08:11:05 +00002725
2726 SourceLocation DeclLoc = Initializer->getLocStart();
2727
Douglas Gregor540c3b02009-12-14 17:27:33 +00002728 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2729 // The type we're converting from is a class type, enumerate its conversion
2730 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002731
Eli Friedman4afe9a32009-12-20 22:12:03 +00002732 // We can only enumerate the conversion functions for a complete type; if
2733 // the type isn't complete, simply skip this step.
2734 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2735 CXXRecordDecl *SourceRecordDecl
2736 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002737
John McCallad371252010-01-20 00:46:10 +00002738 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002739 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002740 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002741 E = Conversions->end();
2742 I != E; ++I) {
2743 NamedDecl *D = *I;
2744 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2745 if (isa<UsingShadowDecl>(D))
2746 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2747
2748 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2749 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002750 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002751 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002752 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002753 Conv = cast<CXXConversionDecl>(*I);
2754
2755 if (AllowExplicit || !Conv->isExplicit()) {
2756 if (ConvTemplate)
2757 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2758 Initializer, DestType,
2759 CandidateSet);
2760 else
2761 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2762 CandidateSet);
2763 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002764 }
2765 }
2766 }
2767
Douglas Gregor540c3b02009-12-14 17:27:33 +00002768 // Perform overload resolution. If it fails, return the failed result.
2769 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002770 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002771 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2772 Sequence.SetOverloadFailure(
2773 InitializationSequence::FK_UserConversionOverloadFailed,
2774 Result);
2775 return;
2776 }
John McCall0d1da222010-01-12 00:44:57 +00002777
Douglas Gregor540c3b02009-12-14 17:27:33 +00002778 FunctionDecl *Function = Best->Function;
2779
2780 if (isa<CXXConstructorDecl>(Function)) {
2781 // Add the user-defined conversion step. Any cv-qualification conversion is
2782 // subsumed by the initialization.
2783 Sequence.AddUserConversionStep(Function, DestType);
2784 return;
2785 }
2786
2787 // Add the user-defined conversion step that calls the conversion function.
2788 QualType ConvType = Function->getResultType().getNonReferenceType();
2789 Sequence.AddUserConversionStep(Function, ConvType);
2790
2791 // If the conversion following the call to the conversion function is
2792 // interesting, add it as a separate step.
2793 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2794 Best->FinalConversion.Third) {
2795 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002796 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002797 ICS.Standard = Best->FinalConversion;
2798 Sequence.AddConversionSequenceStep(ICS, DestType);
2799 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002800}
2801
2802/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2803/// non-class type to another.
2804static void TryImplicitConversion(Sema &S,
2805 const InitializedEntity &Entity,
2806 const InitializationKind &Kind,
2807 Expr *Initializer,
2808 InitializationSequence &Sequence) {
2809 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002810 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002811 /*SuppressUserConversions=*/true,
2812 /*AllowExplicit=*/false,
2813 /*ForceRValue=*/false,
2814 /*FIXME:InOverloadResolution=*/false,
2815 /*UserCast=*/Kind.isExplicitCast());
2816
John McCall0d1da222010-01-12 00:44:57 +00002817 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002818 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2819 return;
2820 }
2821
Douglas Gregor1b303932009-12-22 15:35:07 +00002822 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002823}
2824
2825InitializationSequence::InitializationSequence(Sema &S,
2826 const InitializedEntity &Entity,
2827 const InitializationKind &Kind,
2828 Expr **Args,
2829 unsigned NumArgs) {
2830 ASTContext &Context = S.Context;
2831
2832 // C++0x [dcl.init]p16:
2833 // The semantics of initializers are as follows. The destination type is
2834 // the type of the object or reference being initialized and the source
2835 // type is the type of the initializer expression. The source type is not
2836 // defined when the initializer is a braced-init-list or when it is a
2837 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002838 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002839
2840 if (DestType->isDependentType() ||
2841 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2842 SequenceKind = DependentSequence;
2843 return;
2844 }
2845
2846 QualType SourceType;
2847 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002848 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002849 Initializer = Args[0];
2850 if (!isa<InitListExpr>(Initializer))
2851 SourceType = Initializer->getType();
2852 }
2853
2854 // - If the initializer is a braced-init-list, the object is
2855 // list-initialized (8.5.4).
2856 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2857 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002858 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002859 }
2860
2861 // - If the destination type is a reference type, see 8.5.3.
2862 if (DestType->isReferenceType()) {
2863 // C++0x [dcl.init.ref]p1:
2864 // A variable declared to be a T& or T&&, that is, "reference to type T"
2865 // (8.3.2), shall be initialized by an object, or function, of type T or
2866 // by an object that can be converted into a T.
2867 // (Therefore, multiple arguments are not permitted.)
2868 if (NumArgs != 1)
2869 SetFailed(FK_TooManyInitsForReference);
2870 else
2871 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2872 return;
2873 }
2874
2875 // - If the destination type is an array of characters, an array of
2876 // char16_t, an array of char32_t, or an array of wchar_t, and the
2877 // initializer is a string literal, see 8.5.2.
2878 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2879 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2880 return;
2881 }
2882
2883 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002884 if (Kind.getKind() == InitializationKind::IK_Value ||
2885 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002886 TryValueInitialization(S, Entity, Kind, *this);
2887 return;
2888 }
2889
Douglas Gregor85dabae2009-12-16 01:38:02 +00002890 // Handle default initialization.
2891 if (Kind.getKind() == InitializationKind::IK_Default){
2892 TryDefaultInitialization(S, Entity, Kind, *this);
2893 return;
2894 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002895
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002896 // - Otherwise, if the destination type is an array, the program is
2897 // ill-formed.
2898 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2899 if (AT->getElementType()->isAnyCharacterType())
2900 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2901 else
2902 SetFailed(FK_ArrayNeedsInitList);
2903
2904 return;
2905 }
Eli Friedman78275202009-12-19 08:11:05 +00002906
2907 // Handle initialization in C
2908 if (!S.getLangOptions().CPlusPlus) {
2909 setSequenceKind(CAssignment);
2910 AddCAssignmentStep(DestType);
2911 return;
2912 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002913
2914 // - If the destination type is a (possibly cv-qualified) class type:
2915 if (DestType->isRecordType()) {
2916 // - If the initialization is direct-initialization, or if it is
2917 // copy-initialization where the cv-unqualified version of the
2918 // source type is the same class as, or a derived class of, the
2919 // class of the destination, constructors are considered. [...]
2920 if (Kind.getKind() == InitializationKind::IK_Direct ||
2921 (Kind.getKind() == InitializationKind::IK_Copy &&
2922 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2923 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002924 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002925 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002926 // - Otherwise (i.e., for the remaining copy-initialization cases),
2927 // user-defined conversion sequences that can convert from the source
2928 // type to the destination type or (when a conversion function is
2929 // used) to a derived class thereof are enumerated as described in
2930 // 13.3.1.4, and the best one is chosen through overload resolution
2931 // (13.3).
2932 else
2933 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2934 return;
2935 }
2936
Douglas Gregor85dabae2009-12-16 01:38:02 +00002937 if (NumArgs > 1) {
2938 SetFailed(FK_TooManyInitsForScalar);
2939 return;
2940 }
2941 assert(NumArgs == 1 && "Zero-argument case handled above");
2942
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002943 // - Otherwise, if the source type is a (possibly cv-qualified) class
2944 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002945 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002946 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2947 return;
2948 }
2949
2950 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002951 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002952 // conversions (Clause 4) will be used, if necessary, to convert the
2953 // initializer expression to the cv-unqualified version of the
2954 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002955 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002956 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2957}
2958
2959InitializationSequence::~InitializationSequence() {
2960 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2961 StepEnd = Steps.end();
2962 Step != StepEnd; ++Step)
2963 Step->Destroy();
2964}
2965
2966//===----------------------------------------------------------------------===//
2967// Perform initialization
2968//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002969static Sema::AssignmentAction
2970getAssignmentAction(const InitializedEntity &Entity) {
2971 switch(Entity.getKind()) {
2972 case InitializedEntity::EK_Variable:
2973 case InitializedEntity::EK_New:
2974 return Sema::AA_Initializing;
2975
2976 case InitializedEntity::EK_Parameter:
2977 // FIXME: Can we tell when we're sending vs. passing?
2978 return Sema::AA_Passing;
2979
2980 case InitializedEntity::EK_Result:
2981 return Sema::AA_Returning;
2982
2983 case InitializedEntity::EK_Exception:
2984 case InitializedEntity::EK_Base:
2985 llvm_unreachable("No assignment action for C++-specific initialization");
2986 break;
2987
2988 case InitializedEntity::EK_Temporary:
2989 // FIXME: Can we tell apart casting vs. converting?
2990 return Sema::AA_Casting;
2991
2992 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002993 case InitializedEntity::EK_ArrayElement:
2994 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00002995 return Sema::AA_Initializing;
2996 }
2997
2998 return Sema::AA_Converting;
2999}
3000
3001static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3002 bool IsCopy) {
3003 switch (Entity.getKind()) {
3004 case InitializedEntity::EK_Result:
3005 case InitializedEntity::EK_Exception:
3006 return !IsCopy;
3007
3008 case InitializedEntity::EK_New:
3009 case InitializedEntity::EK_Variable:
3010 case InitializedEntity::EK_Base:
3011 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003012 case InitializedEntity::EK_ArrayElement:
3013 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003014 return false;
3015
3016 case InitializedEntity::EK_Parameter:
3017 case InitializedEntity::EK_Temporary:
3018 return true;
3019 }
3020
3021 llvm_unreachable("missed an InitializedEntity kind?");
3022}
3023
3024/// \brief If we need to perform an additional copy of the initialized object
3025/// for this kind of entity (e.g., the result of a function or an object being
3026/// thrown), make the copy.
3027static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3028 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003029 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003030 Sema::OwningExprResult CurInit) {
3031 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003032
3033 switch (Entity.getKind()) {
3034 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003035 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003036 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003037 Loc = Entity.getReturnLoc();
3038 break;
3039
3040 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003041 Loc = Entity.getThrowLoc();
3042 break;
3043
3044 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003045 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003046 Kind.getKind() != InitializationKind::IK_Copy)
3047 return move(CurInit);
3048 Loc = Entity.getDecl()->getLocation();
3049 break;
3050
Douglas Gregore1314a62009-12-18 05:02:21 +00003051 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003052 // FIXME: Do we need this initialization for a parameter?
3053 return move(CurInit);
3054
Douglas Gregore1314a62009-12-18 05:02:21 +00003055 case InitializedEntity::EK_New:
3056 case InitializedEntity::EK_Temporary:
3057 case InitializedEntity::EK_Base:
3058 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003059 case InitializedEntity::EK_ArrayElement:
3060 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003061 // We don't need to copy for any of these initialized entities.
3062 return move(CurInit);
3063 }
3064
3065 Expr *CurInitExpr = (Expr *)CurInit.get();
3066 CXXRecordDecl *Class = 0;
3067 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3068 Class = cast<CXXRecordDecl>(Record->getDecl());
3069 if (!Class)
3070 return move(CurInit);
3071
3072 // Perform overload resolution using the class's copy constructors.
3073 DeclarationName ConstructorName
3074 = S.Context.DeclarationNames.getCXXConstructorName(
3075 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3076 DeclContext::lookup_iterator Con, ConEnd;
3077 OverloadCandidateSet CandidateSet;
3078 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3079 Con != ConEnd; ++Con) {
3080 // Find the constructor (which may be a template).
3081 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3082 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003083 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003084 continue;
3085
3086 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3087 }
3088
3089 OverloadCandidateSet::iterator Best;
3090 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3091 case OR_Success:
3092 break;
3093
3094 case OR_No_Viable_Function:
3095 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003096 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003097 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003098 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3099 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003100 return S.ExprError();
3101
3102 case OR_Ambiguous:
3103 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003104 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003105 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003106 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3107 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003108 return S.ExprError();
3109
3110 case OR_Deleted:
3111 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003112 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003113 << CurInitExpr->getSourceRange();
3114 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3115 << Best->Function->isDeleted();
3116 return S.ExprError();
3117 }
3118
3119 CurInit.release();
3120 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3121 cast<CXXConstructorDecl>(Best->Function),
3122 /*Elidable=*/true,
3123 Sema::MultiExprArg(S,
3124 (void**)&CurInitExpr, 1));
3125}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003126
3127Action::OwningExprResult
3128InitializationSequence::Perform(Sema &S,
3129 const InitializedEntity &Entity,
3130 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003131 Action::MultiExprArg Args,
3132 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003133 if (SequenceKind == FailedSequence) {
3134 unsigned NumArgs = Args.size();
3135 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3136 return S.ExprError();
3137 }
3138
3139 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003140 // If the declaration is a non-dependent, incomplete array type
3141 // that has an initializer, then its type will be completed once
3142 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003143 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003144 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003145 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003146 if (const IncompleteArrayType *ArrayT
3147 = S.Context.getAsIncompleteArrayType(DeclType)) {
3148 // FIXME: We don't currently have the ability to accurately
3149 // compute the length of an initializer list without
3150 // performing full type-checking of the initializer list
3151 // (since we have to determine where braces are implicitly
3152 // introduced and such). So, we fall back to making the array
3153 // type a dependently-sized array type with no specified
3154 // bound.
3155 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3156 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003157
Douglas Gregor51e77d52009-12-10 17:56:55 +00003158 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003159 if (DeclaratorDecl *DD = Entity.getDecl()) {
3160 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3161 TypeLoc TL = TInfo->getTypeLoc();
3162 if (IncompleteArrayTypeLoc *ArrayLoc
3163 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3164 Brackets = ArrayLoc->getBracketsRange();
3165 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003166 }
3167
3168 *ResultType
3169 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3170 /*NumElts=*/0,
3171 ArrayT->getSizeModifier(),
3172 ArrayT->getIndexTypeCVRQualifiers(),
3173 Brackets);
3174 }
3175
3176 }
3177 }
3178
Eli Friedmana553d4a2009-12-22 02:35:53 +00003179 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003180 return Sema::OwningExprResult(S, Args.release()[0]);
3181
3182 unsigned NumArgs = Args.size();
3183 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3184 SourceLocation(),
3185 (Expr **)Args.release(),
3186 NumArgs,
3187 SourceLocation()));
3188 }
3189
Douglas Gregor85dabae2009-12-16 01:38:02 +00003190 if (SequenceKind == NoInitialization)
3191 return S.Owned((Expr *)0);
3192
Douglas Gregor1b303932009-12-22 15:35:07 +00003193 QualType DestType = Entity.getType().getNonReferenceType();
3194 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003195 // the same as Entity.getDecl()->getType() in cases involving type merging,
3196 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003197 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003198 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003199 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003200
Douglas Gregor85dabae2009-12-16 01:38:02 +00003201 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3202
3203 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3204
3205 // For initialization steps that start with a single initializer,
3206 // grab the only argument out the Args and place it into the "current"
3207 // initializer.
3208 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003209 case SK_ResolveAddressOfOverloadedFunction:
3210 case SK_CastDerivedToBaseRValue:
3211 case SK_CastDerivedToBaseLValue:
3212 case SK_BindReference:
3213 case SK_BindReferenceToTemporary:
3214 case SK_UserConversion:
3215 case SK_QualificationConversionLValue:
3216 case SK_QualificationConversionRValue:
3217 case SK_ConversionSequence:
3218 case SK_ListInitialization:
3219 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003220 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003221 assert(Args.size() == 1);
3222 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3223 if (CurInit.isInvalid())
3224 return S.ExprError();
3225 break;
3226
3227 case SK_ConstructorInitialization:
3228 case SK_ZeroInitialization:
3229 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003230 }
3231
3232 // Walk through the computed steps for the initialization sequence,
3233 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003234 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003235 for (step_iterator Step = step_begin(), StepEnd = step_end();
3236 Step != StepEnd; ++Step) {
3237 if (CurInit.isInvalid())
3238 return S.ExprError();
3239
3240 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003241 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003242
3243 switch (Step->Kind) {
3244 case SK_ResolveAddressOfOverloadedFunction:
3245 // Overload resolution determined which function invoke; update the
3246 // initializer to reflect that choice.
3247 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3248 break;
3249
3250 case SK_CastDerivedToBaseRValue:
3251 case SK_CastDerivedToBaseLValue: {
3252 // We have a derived-to-base cast that produces either an rvalue or an
3253 // lvalue. Perform that cast.
3254
3255 // Casts to inaccessible base classes are allowed with C-style casts.
3256 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3257 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3258 CurInitExpr->getLocStart(),
3259 CurInitExpr->getSourceRange(),
3260 IgnoreBaseAccess))
3261 return S.ExprError();
3262
3263 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3264 CastExpr::CK_DerivedToBase,
3265 (Expr*)CurInit.release(),
3266 Step->Kind == SK_CastDerivedToBaseLValue));
3267 break;
3268 }
3269
3270 case SK_BindReference:
3271 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3272 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3273 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003274 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003275 << BitField->getDeclName()
3276 << CurInitExpr->getSourceRange();
3277 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3278 return S.ExprError();
3279 }
3280
3281 // Reference binding does not have any corresponding ASTs.
3282
3283 // Check exception specifications
3284 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3285 return S.ExprError();
3286 break;
3287
3288 case SK_BindReferenceToTemporary:
3289 // Check exception specifications
3290 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3291 return S.ExprError();
3292
3293 // FIXME: At present, we have no AST to describe when we need to make a
3294 // temporary to bind a reference to. We should.
3295 break;
3296
3297 case SK_UserConversion: {
3298 // We have a user-defined conversion that invokes either a constructor
3299 // or a conversion function.
3300 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003301 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003302 if (CXXConstructorDecl *Constructor
3303 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3304 // Build a call to the selected constructor.
3305 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3306 SourceLocation Loc = CurInitExpr->getLocStart();
3307 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3308
3309 // Determine the arguments required to actually perform the constructor
3310 // call.
3311 if (S.CompleteConstructorCall(Constructor,
3312 Sema::MultiExprArg(S,
3313 (void **)&CurInitExpr,
3314 1),
3315 Loc, ConstructorArgs))
3316 return S.ExprError();
3317
3318 // Build the an expression that constructs a temporary.
3319 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3320 move_arg(ConstructorArgs));
3321 if (CurInit.isInvalid())
3322 return S.ExprError();
3323
3324 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003325 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3326 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3327 S.IsDerivedFrom(SourceType, Class))
3328 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 } else {
3330 // Build a call to the conversion function.
3331 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003332
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003333 // FIXME: Should we move this initialization into a separate
3334 // derived-to-base conversion? I believe the answer is "no", because
3335 // we don't want to turn off access control here for c-style casts.
3336 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3337 return S.ExprError();
3338
3339 // Do a little dance to make sure that CurInit has the proper
3340 // pointer.
3341 CurInit.release();
3342
3343 // Build the actual call to the conversion function.
3344 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3345 if (CurInit.isInvalid() || !CurInit.get())
3346 return S.ExprError();
3347
3348 CastKind = CastExpr::CK_UserDefinedConversion;
3349 }
3350
Douglas Gregore1314a62009-12-18 05:02:21 +00003351 if (shouldBindAsTemporary(Entity, IsCopy))
3352 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3353
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003354 CurInitExpr = CurInit.takeAs<Expr>();
3355 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3356 CastKind,
3357 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003358 false));
3359
3360 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003361 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003362 break;
3363 }
3364
3365 case SK_QualificationConversionLValue:
3366 case SK_QualificationConversionRValue:
3367 // Perform a qualification conversion; these can never go wrong.
3368 S.ImpCastExprToType(CurInitExpr, Step->Type,
3369 CastExpr::CK_NoOp,
3370 Step->Kind == SK_QualificationConversionLValue);
3371 CurInit.release();
3372 CurInit = S.Owned(CurInitExpr);
3373 break;
3374
3375 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003376 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003377 false, false, *Step->ICS))
3378 return S.ExprError();
3379
3380 CurInit.release();
3381 CurInit = S.Owned(CurInitExpr);
3382 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003383
3384 case SK_ListInitialization: {
3385 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3386 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003387 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003388 return S.ExprError();
3389
3390 CurInit.release();
3391 CurInit = S.Owned(InitList);
3392 break;
3393 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003394
3395 case SK_ConstructorInitialization: {
3396 CXXConstructorDecl *Constructor
3397 = cast<CXXConstructorDecl>(Step->Function);
3398
3399 // Build a call to the selected constructor.
3400 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3401 SourceLocation Loc = Kind.getLocation();
3402
3403 // Determine the arguments required to actually perform the constructor
3404 // call.
3405 if (S.CompleteConstructorCall(Constructor, move(Args),
3406 Loc, ConstructorArgs))
3407 return S.ExprError();
3408
3409 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003410 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003411 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003412 move_arg(ConstructorArgs),
3413 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003414 if (CurInit.isInvalid())
3415 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003416
3417 bool Elidable
3418 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3419 if (shouldBindAsTemporary(Entity, Elidable))
3420 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3421
3422 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003423 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003424 break;
3425 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003426
3427 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003428 step_iterator NextStep = Step;
3429 ++NextStep;
3430 if (NextStep != StepEnd &&
3431 NextStep->Kind == SK_ConstructorInitialization) {
3432 // The need for zero-initialization is recorded directly into
3433 // the call to the object's constructor within the next step.
3434 ConstructorInitRequiresZeroInit = true;
3435 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3436 S.getLangOptions().CPlusPlus &&
3437 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003438 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3439 Kind.getRange().getBegin(),
3440 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003441 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003442 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003443 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003444 break;
3445 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003446
3447 case SK_CAssignment: {
3448 QualType SourceType = CurInitExpr->getType();
3449 Sema::AssignConvertType ConvTy =
3450 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003451
3452 // If this is a call, allow conversion to a transparent union.
3453 if (ConvTy != Sema::Compatible &&
3454 Entity.getKind() == InitializedEntity::EK_Parameter &&
3455 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3456 == Sema::Compatible)
3457 ConvTy = Sema::Compatible;
3458
Douglas Gregore1314a62009-12-18 05:02:21 +00003459 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3460 Step->Type, SourceType,
3461 CurInitExpr, getAssignmentAction(Entity)))
3462 return S.ExprError();
3463
3464 CurInit.release();
3465 CurInit = S.Owned(CurInitExpr);
3466 break;
3467 }
Eli Friedman78275202009-12-19 08:11:05 +00003468
3469 case SK_StringInit: {
3470 QualType Ty = Step->Type;
3471 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3472 break;
3473 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003474 }
3475 }
3476
3477 return move(CurInit);
3478}
3479
3480//===----------------------------------------------------------------------===//
3481// Diagnose initialization failures
3482//===----------------------------------------------------------------------===//
3483bool InitializationSequence::Diagnose(Sema &S,
3484 const InitializedEntity &Entity,
3485 const InitializationKind &Kind,
3486 Expr **Args, unsigned NumArgs) {
3487 if (SequenceKind != FailedSequence)
3488 return false;
3489
Douglas Gregor1b303932009-12-22 15:35:07 +00003490 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003491 switch (Failure) {
3492 case FK_TooManyInitsForReference:
3493 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3494 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3495 break;
3496
3497 case FK_ArrayNeedsInitList:
3498 case FK_ArrayNeedsInitListOrStringLiteral:
3499 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3500 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3501 break;
3502
3503 case FK_AddressOfOverloadFailed:
3504 S.ResolveAddressOfOverloadedFunction(Args[0],
3505 DestType.getNonReferenceType(),
3506 true);
3507 break;
3508
3509 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003510 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003511 switch (FailedOverloadResult) {
3512 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003513 if (Failure == FK_UserConversionOverloadFailed)
3514 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3515 << Args[0]->getType() << DestType
3516 << Args[0]->getSourceRange();
3517 else
3518 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3519 << DestType << Args[0]->getType()
3520 << Args[0]->getSourceRange();
3521
John McCallad907772010-01-12 07:18:19 +00003522 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3523 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003524 break;
3525
3526 case OR_No_Viable_Function:
3527 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3528 << Args[0]->getType() << DestType.getNonReferenceType()
3529 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003530 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3531 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003532 break;
3533
3534 case OR_Deleted: {
3535 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3536 << Args[0]->getType() << DestType.getNonReferenceType()
3537 << Args[0]->getSourceRange();
3538 OverloadCandidateSet::iterator Best;
3539 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3540 Kind.getLocation(),
3541 Best);
3542 if (Ovl == OR_Deleted) {
3543 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3544 << Best->Function->isDeleted();
3545 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003546 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003547 }
3548 break;
3549 }
3550
3551 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003552 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003553 break;
3554 }
3555 break;
3556
3557 case FK_NonConstLValueReferenceBindingToTemporary:
3558 case FK_NonConstLValueReferenceBindingToUnrelated:
3559 S.Diag(Kind.getLocation(),
3560 Failure == FK_NonConstLValueReferenceBindingToTemporary
3561 ? diag::err_lvalue_reference_bind_to_temporary
3562 : diag::err_lvalue_reference_bind_to_unrelated)
3563 << DestType.getNonReferenceType()
3564 << Args[0]->getType()
3565 << Args[0]->getSourceRange();
3566 break;
3567
3568 case FK_RValueReferenceBindingToLValue:
3569 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3570 << Args[0]->getSourceRange();
3571 break;
3572
3573 case FK_ReferenceInitDropsQualifiers:
3574 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3575 << DestType.getNonReferenceType()
3576 << Args[0]->getType()
3577 << Args[0]->getSourceRange();
3578 break;
3579
3580 case FK_ReferenceInitFailed:
3581 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3582 << DestType.getNonReferenceType()
3583 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3584 << Args[0]->getType()
3585 << Args[0]->getSourceRange();
3586 break;
3587
3588 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003589 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3590 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003591 << DestType
3592 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3593 << Args[0]->getType()
3594 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003595 break;
3596
3597 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003598 SourceRange R;
3599
3600 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3601 R = SourceRange(InitList->getInit(1)->getLocStart(),
3602 InitList->getLocEnd());
3603 else
3604 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003605
3606 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003607 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003608 break;
3609 }
3610
3611 case FK_ReferenceBindingToInitList:
3612 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3613 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3614 break;
3615
3616 case FK_InitListBadDestinationType:
3617 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3618 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3619 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003620
3621 case FK_ConstructorOverloadFailed: {
3622 SourceRange ArgsRange;
3623 if (NumArgs)
3624 ArgsRange = SourceRange(Args[0]->getLocStart(),
3625 Args[NumArgs - 1]->getLocEnd());
3626
3627 // FIXME: Using "DestType" for the entity we're printing is probably
3628 // bad.
3629 switch (FailedOverloadResult) {
3630 case OR_Ambiguous:
3631 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3632 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003633 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003634 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003635 break;
3636
3637 case OR_No_Viable_Function:
3638 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3639 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003640 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3641 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003642 break;
3643
3644 case OR_Deleted: {
3645 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3646 << true << DestType << ArgsRange;
3647 OverloadCandidateSet::iterator Best;
3648 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3649 Kind.getLocation(),
3650 Best);
3651 if (Ovl == OR_Deleted) {
3652 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3653 << Best->Function->isDeleted();
3654 } else {
3655 llvm_unreachable("Inconsistent overload resolution?");
3656 }
3657 break;
3658 }
3659
3660 case OR_Success:
3661 llvm_unreachable("Conversion did not fail!");
3662 break;
3663 }
3664 break;
3665 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003666
3667 case FK_DefaultInitOfConst:
3668 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3669 << DestType;
3670 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003671 }
3672
3673 return true;
3674}
Douglas Gregore1314a62009-12-18 05:02:21 +00003675
3676//===----------------------------------------------------------------------===//
3677// Initialization helper functions
3678//===----------------------------------------------------------------------===//
3679Sema::OwningExprResult
3680Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3681 SourceLocation EqualLoc,
3682 OwningExprResult Init) {
3683 if (Init.isInvalid())
3684 return ExprError();
3685
3686 Expr *InitE = (Expr *)Init.get();
3687 assert(InitE && "No initialization expression?");
3688
3689 if (EqualLoc.isInvalid())
3690 EqualLoc = InitE->getLocStart();
3691
3692 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3693 EqualLoc);
3694 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3695 Init.release();
3696 return Seq.Perform(*this, Entity, Kind,
3697 MultiExprArg(*this, (void**)&InitE, 1));
3698}