blob: f7d93052760e7de1c31e7e728018ca0e53a5b360 [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);
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000239 void CheckStructUnionTypes(const InitializedEntity *Entity,
240 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000241 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000242 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000243 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000244 unsigned &StructuredIndex,
245 bool TopLevelObject = false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000246 void CheckArrayType(const InitializedEntity *Entity,
247 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000248 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000249 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000250 InitListExpr *StructuredList,
251 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000252 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000253 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000254 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000255 RecordDecl::field_iterator *NextField,
256 llvm::APSInt *NextElementIndex,
257 unsigned &Index,
258 InitListExpr *StructuredList,
259 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000260 bool FinishSubobjectInit,
261 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000262 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
263 QualType CurrentObjectType,
264 InitListExpr *StructuredList,
265 unsigned StructuredIndex,
266 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000267 void UpdateStructuredListElement(InitListExpr *StructuredList,
268 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000269 Expr *expr);
270 int numArrayElements(QualType DeclType);
271 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000272
Douglas Gregor2bb07652009-12-22 00:05:34 +0000273 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
274 const InitializedEntity &ParentEntity,
275 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000276 void FillInValueInitializations(const InitializedEntity &Entity,
277 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000278public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000279 InitListChecker(Sema &S, const InitializedEntity &Entity,
280 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000281 bool HadError() { return hadError; }
282
283 // @brief Retrieves the fully-structured initializer list used for
284 // semantic analysis and code generation.
285 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
286};
Chris Lattner9ececce2009-02-24 22:48:58 +0000287} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000288
Douglas Gregor2bb07652009-12-22 00:05:34 +0000289void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
290 const InitializedEntity &ParentEntity,
291 InitListExpr *ILE,
292 bool &RequiresSecondPass) {
293 SourceLocation Loc = ILE->getSourceRange().getBegin();
294 unsigned NumInits = ILE->getNumInits();
295 InitializedEntity MemberEntity
296 = InitializedEntity::InitializeMember(Field, &ParentEntity);
297 if (Init >= NumInits || !ILE->getInit(Init)) {
298 // FIXME: We probably don't need to handle references
299 // specially here, since value-initialization of references is
300 // handled in InitializationSequence.
301 if (Field->getType()->isReferenceType()) {
302 // C++ [dcl.init.aggr]p9:
303 // If an incomplete or empty initializer-list leaves a
304 // member of reference type uninitialized, the program is
305 // ill-formed.
306 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
307 << Field->getType()
308 << ILE->getSyntacticForm()->getSourceRange();
309 SemaRef.Diag(Field->getLocation(),
310 diag::note_uninit_reference_member);
311 hadError = true;
312 return;
313 }
314
315 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
316 true);
317 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
318 if (!InitSeq) {
319 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
320 hadError = true;
321 return;
322 }
323
324 Sema::OwningExprResult MemberInit
325 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
326 Sema::MultiExprArg(SemaRef, 0, 0));
327 if (MemberInit.isInvalid()) {
328 hadError = true;
329 return;
330 }
331
332 if (hadError) {
333 // Do nothing
334 } else if (Init < NumInits) {
335 ILE->setInit(Init, MemberInit.takeAs<Expr>());
336 } else if (InitSeq.getKind()
337 == InitializationSequence::ConstructorInitialization) {
338 // Value-initialization requires a constructor call, so
339 // extend the initializer list to include the constructor
340 // call and make a note that we'll need to take another pass
341 // through the initializer list.
342 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
343 RequiresSecondPass = true;
344 }
345 } else if (InitListExpr *InnerILE
346 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
347 FillInValueInitializations(MemberEntity, InnerILE,
348 RequiresSecondPass);
349}
350
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000351/// Recursively replaces NULL values within the given initializer list
352/// with expressions that perform value-initialization of the
353/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000354void
355InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
356 InitListExpr *ILE,
357 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000358 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000359 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000360 SourceLocation Loc = ILE->getSourceRange().getBegin();
361 if (ILE->getSyntacticForm())
362 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000363
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000364 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000365 if (RType->getDecl()->isUnion() &&
366 ILE->getInitializedFieldInUnion())
367 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
368 Entity, ILE, RequiresSecondPass);
369 else {
370 unsigned Init = 0;
371 for (RecordDecl::field_iterator
372 Field = RType->getDecl()->field_begin(),
373 FieldEnd = RType->getDecl()->field_end();
374 Field != FieldEnd; ++Field) {
375 if (Field->isUnnamedBitfield())
376 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000377
Douglas Gregor2bb07652009-12-22 00:05:34 +0000378 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000380
381 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
382 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000383 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000384
Douglas Gregor2bb07652009-12-22 00:05:34 +0000385 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000386
Douglas Gregor2bb07652009-12-22 00:05:34 +0000387 // Only look at the first initialization of a union.
388 if (RType->getDecl()->isUnion())
389 break;
390 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000391 }
392
393 return;
Mike Stump11289f42009-09-09 15:08:12 +0000394 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000395
396 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000397
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000399 unsigned NumInits = ILE->getNumInits();
400 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000401 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000402 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000403 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
404 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000405 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
406 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000407 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000408 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000409 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000410 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
411 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000412 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000413 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000414
Douglas Gregor723796a2009-12-16 06:35:08 +0000415
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000416 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000417 if (hadError)
418 return;
419
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000420 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
421 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000422 ElementEntity.setElementIndex(Init);
423
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000424 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000425 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
426 true);
427 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
428 if (!InitSeq) {
429 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000430 hadError = true;
431 return;
432 }
433
Douglas Gregor723796a2009-12-16 06:35:08 +0000434 Sema::OwningExprResult ElementInit
435 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
436 Sema::MultiExprArg(SemaRef, 0, 0));
437 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000438 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000439 return;
440 }
441
442 if (hadError) {
443 // Do nothing
444 } else if (Init < NumInits) {
445 ILE->setInit(Init, ElementInit.takeAs<Expr>());
446 } else if (InitSeq.getKind()
447 == InitializationSequence::ConstructorInitialization) {
448 // Value-initialization requires a constructor call, so
449 // extend the initializer list to include the constructor
450 // call and make a note that we'll need to take another pass
451 // through the initializer list.
452 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
453 RequiresSecondPass = true;
454 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000455 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000456 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
457 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000458 }
459}
460
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000461
Douglas Gregor723796a2009-12-16 06:35:08 +0000462InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
463 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000464 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000465 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000466
Eli Friedman23a9e312008-05-19 19:16:24 +0000467 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000468 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000470 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000471 CheckExplicitInitList(&Entity, IL, T, newIndex,
472 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000473 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000474
Douglas Gregor723796a2009-12-16 06:35:08 +0000475 if (!hadError) {
476 bool RequiresSecondPass = false;
477 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000478 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000479 FillInValueInitializations(Entity, FullyStructuredList,
480 RequiresSecondPass);
481 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000482}
483
484int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000485 // FIXME: use a proper constant
486 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000487 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000488 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000489 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
490 }
491 return maxElements;
492}
493
494int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000495 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000496 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000497 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000498 Field = structDecl->field_begin(),
499 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000500 Field != FieldEnd; ++Field) {
501 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
502 ++InitializableMembers;
503 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000504 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000505 return std::min(InitializableMembers, 1);
506 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000507}
508
Mike Stump11289f42009-09-09 15:08:12 +0000509void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000510 QualType T, unsigned &Index,
511 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000512 unsigned &StructuredIndex,
513 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000514 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Steve Narofff8ecff22008-05-01 22:18:59 +0000516 if (T->isArrayType())
517 maxElements = numArrayElements(T);
518 else if (T->isStructureType() || T->isUnionType())
519 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000520 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000521 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000522 else
523 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000524
Eli Friedmane0f832b2008-05-25 13:49:22 +0000525 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000526 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000527 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000528 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000529 hadError = true;
530 return;
531 }
532
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000533 // Build a structured initializer list corresponding to this subobject.
534 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000535 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
536 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000537 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
538 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000539 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000540
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000541 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000542 unsigned StartIndex = Index;
Anders Carlssond0849252010-01-23 19:55:29 +0000543 CheckListElementTypes(0, ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000544 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000545 StructuredSubobjectInitIndex,
546 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000547 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000548 StructuredSubobjectInitList->setType(T);
549
Douglas Gregor5741efb2009-03-01 17:12:46 +0000550 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000551 // range corresponds with the end of the last initializer it used.
552 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000553 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
555 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
556 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000557}
558
Anders Carlssond0849252010-01-23 19:55:29 +0000559void InitListChecker::CheckExplicitInitList(const InitializedEntity *Entity,
560 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000561 unsigned &Index,
562 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000563 unsigned &StructuredIndex,
564 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000565 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000566 SyntacticToSemantic[IList] = StructuredList;
567 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000568 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
569 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000570 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000571 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000572 if (hadError)
573 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000574
Eli Friedman85f54972008-05-25 13:22:35 +0000575 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000576 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000577 if (StructuredIndex == 1 &&
578 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000579 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000580 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000581 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000582 hadError = true;
583 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000584 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000586 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000587 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000588 // Don't complain for incomplete types, since we'll get an error
589 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000590 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000591 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000592 CurrentObjectType->isArrayType()? 0 :
593 CurrentObjectType->isVectorType()? 1 :
594 CurrentObjectType->isScalarType()? 2 :
595 CurrentObjectType->isUnionType()? 3 :
596 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000597
598 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000599 if (SemaRef.getLangOptions().CPlusPlus) {
600 DK = diag::err_excess_initializers;
601 hadError = true;
602 }
Nate Begeman425038c2009-07-07 21:53:06 +0000603 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
604 DK = diag::err_excess_initializers;
605 hadError = true;
606 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000607
Chris Lattnerb0912a52009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000609 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000610 }
611 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000612
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000613 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000614 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000615 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000616 << CodeModificationHint::CreateRemoval(IList->getLocStart())
617 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000618}
619
Anders Carlssond0849252010-01-23 19:55:29 +0000620void InitListChecker::CheckListElementTypes(const InitializedEntity *Entity,
621 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000622 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000623 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000626 unsigned &StructuredIndex,
627 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000628 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000629 CheckScalarType(Entity, IList, DeclType, Index,
630 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000631 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000632 CheckVectorType(Entity, IList, DeclType, Index,
633 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000634 } else if (DeclType->isAggregateType()) {
635 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000636 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000637 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000638 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000639 StructuredList, StructuredIndex,
640 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000641 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000642 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000643 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000644 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000645 CheckArrayType(Entity, IList, DeclType, Zero,
646 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000647 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000648 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000650 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
651 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000652 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000653 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000654 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000655 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000656 } else if (DeclType->isRecordType()) {
657 // C++ [dcl.init]p14:
658 // [...] If the class is an aggregate (8.5.1), and the initializer
659 // is a brace-enclosed list, see 8.5.1.
660 //
661 // Note: 8.5.1 is handled below; here, we diagnose the case where
662 // we have an initializer list and a destination type that is not
663 // an aggregate.
664 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000666 << DeclType << IList->getSourceRange();
667 hadError = true;
668 } else if (DeclType->isReferenceType()) {
669 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000670 } else {
671 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000672 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000673 assert(0 && "Unsupported initializer type");
674 }
675}
676
Anders Carlssond0849252010-01-23 19:55:29 +0000677void InitListChecker::CheckSubElementType(const InitializedEntity *Entity,
678 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000679 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000680 unsigned &Index,
681 InitListExpr *StructuredList,
682 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000683 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000684 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
685 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000686 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000687 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000688 = getStructuredSubobjectInit(IList, Index, ElemType,
689 StructuredList, StructuredIndex,
690 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000691 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000692 newStructuredList, newStructuredIndex);
693 ++StructuredIndex;
694 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000695 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
696 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000697 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000698 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000699 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000700 CheckScalarType(Entity, IList, ElemType, Index,
701 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000702 } else if (ElemType->isReferenceType()) {
703 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000704 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000705 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000706 // C++ [dcl.init.aggr]p12:
707 // All implicit type conversions (clause 4) are considered when
708 // initializing the aggregate member with an ini- tializer from
709 // an initializer-list. If the initializer can initialize a
710 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000711 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000712 = SemaRef.TryCopyInitialization(expr, ElemType,
713 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000714 /*ForceRValue=*/false,
715 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000716
John McCall0d1da222010-01-12 00:44:57 +0000717 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000718 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000719 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000720 hadError = true;
721 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
722 ++Index;
723 return;
724 }
725
726 // Fall through for subaggregate initialization
727 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000728 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000729 //
730 // The initializer for a structure or union object that has
731 // automatic storage duration shall be either an initializer
732 // list as described below, or a single expression that has
733 // compatible structure or union type. In the latter case, the
734 // initial value of the object, including unnamed members, is
735 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000736 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000737 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000738 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
739 ++Index;
740 return;
741 }
742
743 // Fall through for subaggregate initialization
744 }
745
746 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000747 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000748 // [...] Otherwise, if the member is itself a non-empty
749 // subaggregate, brace elision is assumed and the initializer is
750 // considered for the initialization of the first member of
751 // the subaggregate.
752 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000753 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000754 StructuredIndex);
755 ++StructuredIndex;
756 } else {
757 // We cannot initialize this element, so let
758 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000759 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000760 hadError = true;
761 ++Index;
762 ++StructuredIndex;
763 }
764 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000765}
766
Anders Carlssond0849252010-01-23 19:55:29 +0000767void InitListChecker::CheckScalarType(const InitializedEntity *Entity,
768 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000769 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000770 InitListExpr *StructuredList,
771 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000772 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000773 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000774 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000775 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000776 diag::err_many_braces_around_scalar_init)
777 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000778 hadError = true;
779 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000780 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000781 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000782 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000783 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000784 diag::err_designator_for_scalar_init)
785 << DeclType << expr->getSourceRange();
786 hadError = true;
787 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000788 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000789 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000790 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000791
Anders Carlsson26d05642010-01-23 18:35:41 +0000792 Sema::OwningExprResult Result =
Anders Carlssond0849252010-01-23 19:55:29 +0000793 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlsson26d05642010-01-23 18:35:41 +0000794
795 Expr *ResultExpr;
796
797 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000798 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000799 else {
800 ResultExpr = Result.takeAs<Expr>();
801
802 if (ResultExpr != expr) {
803 // The type was promoted, update initializer list.
804 IList->setInit(Index, ResultExpr);
805 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000806 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000807 if (hadError)
808 ++StructuredIndex;
809 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000810 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000811 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000812 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000813 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000814 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000815 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000816 ++Index;
817 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000818 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000819 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000820}
821
Douglas Gregord14247a2009-01-30 22:09:00 +0000822void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
823 unsigned &Index,
824 InitListExpr *StructuredList,
825 unsigned &StructuredIndex) {
826 if (Index < IList->getNumInits()) {
827 Expr *expr = IList->getInit(Index);
828 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000829 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000830 << DeclType << IList->getSourceRange();
831 hadError = true;
832 ++Index;
833 ++StructuredIndex;
834 return;
Mike Stump11289f42009-09-09 15:08:12 +0000835 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000836
837 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000838 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000839 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000840 /*SuppressUserConversions=*/false,
841 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000842 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000843 hadError = true;
844 else if (savExpr != expr) {
845 // The type was promoted, update initializer list.
846 IList->setInit(Index, expr);
847 }
848 if (hadError)
849 ++StructuredIndex;
850 else
851 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
852 ++Index;
853 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000854 // FIXME: It would be wonderful if we could point at the actual member. In
855 // general, it would be useful to pass location information down the stack,
856 // so that we know the location (or decl) of the "current object" being
857 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000858 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000859 diag::err_init_reference_member_uninitialized)
860 << DeclType
861 << IList->getSourceRange();
862 hadError = true;
863 ++Index;
864 ++StructuredIndex;
865 return;
866 }
867}
868
Anders Carlssond0849252010-01-23 19:55:29 +0000869void InitListChecker::CheckVectorType(const InitializedEntity *Entity,
870 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000871 unsigned &Index,
872 InitListExpr *StructuredList,
873 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000874 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000875 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000876 unsigned maxElements = VT->getNumElements();
877 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000878 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000879
Nate Begeman5ec4b312009-08-10 23:49:36 +0000880 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlssond0849252010-01-23 19:55:29 +0000881 // FIXME: Once we know Entity is never null we can remove this check,
882 // as well as the else block.
883 if (Entity) {
884 InitializedEntity ElementEntity =
885 InitializedEntity::InitializeElement(SemaRef.Context, 0, *Entity);
886
887 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
888 // Don't attempt to go past the end of the init list
889 if (Index >= IList->getNumInits())
890 break;
891
892 ElementEntity.setElementIndex(Index);
893 CheckSubElementType(&ElementEntity, IList, elementType, Index,
894 StructuredList, StructuredIndex);
895 }
896 } else {
897 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
898 // Don't attempt to go past the end of the init list
899 if (Index >= IList->getNumInits())
900 break;
901
902 CheckSubElementType(0, IList, elementType, Index,
903 StructuredList, StructuredIndex);
904 }
905 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000906 } else {
907 // OpenCL initializers allows vectors to be constructed from vectors.
908 for (unsigned i = 0; i < maxElements; ++i) {
909 // Don't attempt to go past the end of the init list
910 if (Index >= IList->getNumInits())
911 break;
912 QualType IType = IList->getInit(Index)->getType();
913 if (!IType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000914 CheckSubElementType(0, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000915 StructuredList, StructuredIndex);
916 ++numEltsInit;
917 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000918 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000919 unsigned numIElts = IVT->getNumElements();
920 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
921 numIElts);
Anders Carlssond0849252010-01-23 19:55:29 +0000922 CheckSubElementType(0, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000923 StructuredList, StructuredIndex);
924 numEltsInit += numIElts;
925 }
926 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Nate Begeman5ec4b312009-08-10 23:49:36 +0000929 // OpenCL & AltiVec require all elements to be initialized.
930 if (numEltsInit != maxElements)
931 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
932 SemaRef.Diag(IList->getSourceRange().getBegin(),
933 diag::err_vector_incorrect_num_initializers)
934 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000935 }
936}
937
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000938void InitListChecker::CheckArrayType(const InitializedEntity *Entity,
939 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000940 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000941 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000942 unsigned &Index,
943 InitListExpr *StructuredList,
944 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000945 // Check for the special-case of initializing an array with a string.
946 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000947 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
948 SemaRef.Context)) {
949 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000950 // We place the string literal directly into the resulting
951 // initializer list. This is the only place where the structure
952 // of the structured initializer list doesn't match exactly,
953 // because doing so would involve allocating one character
954 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000955 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000956 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000957 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000958 return;
959 }
960 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000961 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000962 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000963 // Check for VLAs; in standard C it would be possible to check this
964 // earlier, but I don't know where clang accepts VLAs (gcc accepts
965 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000966 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000967 diag::err_variable_object_no_init)
968 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000969 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000970 ++Index;
971 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000972 return;
973 }
974
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000975 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000976 llvm::APSInt maxElements(elementIndex.getBitWidth(),
977 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000978 bool maxElementsKnown = false;
979 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000980 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000981 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000982 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000983 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000984 maxElementsKnown = true;
985 }
986
Chris Lattnerb0912a52009-02-24 22:50:46 +0000987 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000988 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000989 while (Index < IList->getNumInits()) {
990 Expr *Init = IList->getInit(Index);
991 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000992 // If we're not the subobject that matches up with the '{' for
993 // the designator, we shouldn't be handling the
994 // designator. Return immediately.
995 if (!SubobjectIsDesignatorContext)
996 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000997
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000998 // Handle this designated initializer. elementIndex will be
999 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +00001000 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001001 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001002 StructuredList, StructuredIndex, true,
1003 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001004 hadError = true;
1005 continue;
1006 }
1007
Douglas Gregor033d1252009-01-23 16:54:12 +00001008 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1009 maxElements.extend(elementIndex.getBitWidth());
1010 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1011 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001012 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001013
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001014 // If the array is of incomplete type, keep track of the number of
1015 // elements in the initializer.
1016 if (!maxElementsKnown && elementIndex > maxElements)
1017 maxElements = elementIndex;
1018
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001019 continue;
1020 }
1021
1022 // If we know the maximum number of elements, and we've already
1023 // hit it, stop consuming elements in the initializer list.
1024 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001025 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001026
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001027 // FIXME: Once we know that Entity is not null, we can remove this check,
1028 // and the else block.
1029 if (Entity) {
1030 InitializedEntity ElementEntity =
1031 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1032 *Entity);
1033 // Check this element.
1034 CheckSubElementType(&ElementEntity, IList, elementType, Index,
1035 StructuredList, StructuredIndex);
1036 } else {
1037 // Check this element.
1038 CheckSubElementType(0, IList, elementType, Index,
1039 StructuredList, StructuredIndex);
1040 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001041 ++elementIndex;
1042
1043 // If the array is of incomplete type, keep track of the number of
1044 // elements in the initializer.
1045 if (!maxElementsKnown && elementIndex > maxElements)
1046 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001047 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001048 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001049 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001050 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001051 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001052 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001053 // Sizing an array implicitly to zero is not allowed by ISO C,
1054 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001055 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001056 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001057 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001058
Mike Stump11289f42009-09-09 15:08:12 +00001059 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001060 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001061 }
1062}
1063
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001064void InitListChecker::CheckStructUnionTypes(const InitializedEntity *Entity,
1065 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001066 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001067 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001068 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001069 unsigned &Index,
1070 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001071 unsigned &StructuredIndex,
1072 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001073 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Eli Friedman23a9e312008-05-19 19:16:24 +00001075 // If the record is invalid, some of it's members are invalid. To avoid
1076 // confusion, we forgo checking the intializer for the entire record.
1077 if (structDecl->isInvalidDecl()) {
1078 hadError = true;
1079 return;
Mike Stump11289f42009-09-09 15:08:12 +00001080 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001081
1082 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1083 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001084 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001085 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001086 Field != FieldEnd; ++Field) {
1087 if (Field->getDeclName()) {
1088 StructuredList->setInitializedFieldInUnion(*Field);
1089 break;
1090 }
1091 }
1092 return;
1093 }
1094
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001095 // If structDecl is a forward declaration, this loop won't do
1096 // anything except look at designated initializers; That's okay,
1097 // because an error should get printed out elsewhere. It might be
1098 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001099 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001100 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001101 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001102 while (Index < IList->getNumInits()) {
1103 Expr *Init = IList->getInit(Index);
1104
1105 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001106 // If we're not the subobject that matches up with the '{' for
1107 // the designator, we shouldn't be handling the
1108 // designator. Return immediately.
1109 if (!SubobjectIsDesignatorContext)
1110 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001111
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001112 // Handle this designated initializer. Field will be updated to
1113 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001114 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001115 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001116 StructuredList, StructuredIndex,
1117 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001118 hadError = true;
1119
Douglas Gregora9add4e2009-02-12 19:00:39 +00001120 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001121 continue;
1122 }
1123
1124 if (Field == FieldEnd) {
1125 // We've run out of fields. We're done.
1126 break;
1127 }
1128
Douglas Gregora9add4e2009-02-12 19:00:39 +00001129 // We've already initialized a member of a union. We're done.
1130 if (InitializedSomething && DeclType->isUnionType())
1131 break;
1132
Douglas Gregor91f84212008-12-11 16:49:14 +00001133 // If we've hit the flexible array member at the end, we're done.
1134 if (Field->getType()->isIncompleteArrayType())
1135 break;
1136
Douglas Gregor51695702009-01-29 16:53:55 +00001137 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001138 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001139 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001140 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001141 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001142
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001143 // FIXME: Once we know Entity is not null, we can get rid of the check
1144 // and the else block.
1145 if (Entity) {
1146 InitializedEntity MemberEntity =
1147 InitializedEntity::InitializeMember(*Field, Entity);
1148 CheckSubElementType(&MemberEntity, IList, Field->getType(), Index,
1149 StructuredList, StructuredIndex);
1150 } else {
1151 CheckSubElementType(0, IList, Field->getType(), Index,
1152 StructuredList, StructuredIndex);
1153 }
Douglas Gregora9add4e2009-02-12 19:00:39 +00001154 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001155
1156 if (DeclType->isUnionType()) {
1157 // Initialize the first field within the union.
1158 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001159 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001160
1161 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001162 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001163
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001165 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001166 return;
1167
1168 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001169 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001170 (!isa<InitListExpr>(IList->getInit(Index)) ||
1171 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001172 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001173 diag::err_flexible_array_init_nonempty)
1174 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001175 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001176 << *Field;
1177 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001178 ++Index;
1179 return;
1180 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001181 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001182 diag::ext_flexible_array_init)
1183 << IList->getInit(Index)->getSourceRange().getBegin();
1184 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1185 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001186 }
1187
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001188 if (isa<InitListExpr>(IList->getInit(Index)))
Anders Carlssond0849252010-01-23 19:55:29 +00001189 CheckSubElementType(0, IList, Field->getType(), Index, StructuredList,
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001190 StructuredIndex);
1191 else
1192 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1193 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001194}
Steve Narofff8ecff22008-05-01 22:18:59 +00001195
Douglas Gregord5846a12009-04-15 06:41:24 +00001196/// \brief Expand a field designator that refers to a member of an
1197/// anonymous struct or union into a series of field designators that
1198/// refers to the field within the appropriate subobject.
1199///
1200/// Field/FieldIndex will be updated to point to the (new)
1201/// currently-designated field.
1202static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001203 DesignatedInitExpr *DIE,
1204 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001205 FieldDecl *Field,
1206 RecordDecl::field_iterator &FieldIter,
1207 unsigned &FieldIndex) {
1208 typedef DesignatedInitExpr::Designator Designator;
1209
1210 // Build the path from the current object to the member of the
1211 // anonymous struct/union (backwards).
1212 llvm::SmallVector<FieldDecl *, 4> Path;
1213 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001214
Douglas Gregord5846a12009-04-15 06:41:24 +00001215 // Build the replacement designators.
1216 llvm::SmallVector<Designator, 4> Replacements;
1217 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1218 FI = Path.rbegin(), FIEnd = Path.rend();
1219 FI != FIEnd; ++FI) {
1220 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001221 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001222 DIE->getDesignator(DesigIdx)->getDotLoc(),
1223 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1224 else
1225 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1226 SourceLocation()));
1227 Replacements.back().setField(*FI);
1228 }
1229
1230 // Expand the current designator into the set of replacement
1231 // designators, so we have a full subobject path down to where the
1232 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001233 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001234 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001235
Douglas Gregord5846a12009-04-15 06:41:24 +00001236 // Update FieldIter/FieldIndex;
1237 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001238 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001239 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001240 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001241 FieldIter != FEnd; ++FieldIter) {
1242 if (FieldIter->isUnnamedBitfield())
1243 continue;
1244
1245 if (*FieldIter == Path.back())
1246 return;
1247
1248 ++FieldIndex;
1249 }
1250
1251 assert(false && "Unable to find anonymous struct/union field");
1252}
1253
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001254/// @brief Check the well-formedness of a C99 designated initializer.
1255///
1256/// Determines whether the designated initializer @p DIE, which
1257/// resides at the given @p Index within the initializer list @p
1258/// IList, is well-formed for a current object of type @p DeclType
1259/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001260/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001261/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001262///
1263/// @param IList The initializer list in which this designated
1264/// initializer occurs.
1265///
Douglas Gregora5324162009-04-15 04:56:10 +00001266/// @param DIE The designated initializer expression.
1267///
1268/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001269///
1270/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1271/// into which the designation in @p DIE should refer.
1272///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001273/// @param NextField If non-NULL and the first designator in @p DIE is
1274/// a field, this will be set to the field declaration corresponding
1275/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001276///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001277/// @param NextElementIndex If non-NULL and the first designator in @p
1278/// DIE is an array designator or GNU array-range designator, this
1279/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001280///
1281/// @param Index Index into @p IList where the designated initializer
1282/// @p DIE occurs.
1283///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001284/// @param StructuredList The initializer list expression that
1285/// describes all of the subobject initializers in the order they'll
1286/// actually be initialized.
1287///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001288/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001289bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001290InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001291 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001292 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001293 QualType &CurrentObjectType,
1294 RecordDecl::field_iterator *NextField,
1295 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001296 unsigned &Index,
1297 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001298 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001299 bool FinishSubobjectInit,
1300 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001301 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001302 // Check the actual initialization for the designated object type.
1303 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001304
1305 // Temporarily remove the designator expression from the
1306 // initializer list that the child calls see, so that we don't try
1307 // to re-process the designator.
1308 unsigned OldIndex = Index;
1309 IList->setInit(OldIndex, DIE->getInit());
1310
Anders Carlssond0849252010-01-23 19:55:29 +00001311 CheckSubElementType(0, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001312 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001313
1314 // Restore the designated initializer expression in the syntactic
1315 // form of the initializer list.
1316 if (IList->getInit(OldIndex) != DIE->getInit())
1317 DIE->setInit(IList->getInit(OldIndex));
1318 IList->setInit(OldIndex, DIE);
1319
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001320 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001321 }
1322
Douglas Gregora5324162009-04-15 04:56:10 +00001323 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001324 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001325 "Need a non-designated initializer list to start from");
1326
Douglas Gregora5324162009-04-15 04:56:10 +00001327 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001328 // Determine the structural initializer list that corresponds to the
1329 // current subobject.
1330 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001331 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001332 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001333 SourceRange(D->getStartLocation(),
1334 DIE->getSourceRange().getEnd()));
1335 assert(StructuredList && "Expected a structured initializer list");
1336
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001337 if (D->isFieldDesignator()) {
1338 // C99 6.7.8p7:
1339 //
1340 // If a designator has the form
1341 //
1342 // . identifier
1343 //
1344 // then the current object (defined below) shall have
1345 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001346 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001347 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001348 if (!RT) {
1349 SourceLocation Loc = D->getDotLoc();
1350 if (Loc.isInvalid())
1351 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001352 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1353 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001354 ++Index;
1355 return true;
1356 }
1357
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001358 // Note: we perform a linear search of the fields here, despite
1359 // the fact that we have a faster lookup method, because we always
1360 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001361 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001362 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001363 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001364 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001365 Field = RT->getDecl()->field_begin(),
1366 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 for (; Field != FieldEnd; ++Field) {
1368 if (Field->isUnnamedBitfield())
1369 continue;
1370
Douglas Gregord5846a12009-04-15 06:41:24 +00001371 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001372 break;
1373
1374 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001375 }
1376
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001377 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001378 // There was no normal field in the struct with the designated
1379 // name. Perform another lookup for this name, which may find
1380 // something that we can't designate (e.g., a member function),
1381 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001382 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001383 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001384 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001385 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001386 // Name lookup didn't find anything. Determine whether this
1387 // was a typo for another field name.
1388 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1389 Sema::LookupMemberName);
1390 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1391 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1392 ReplacementField->getDeclContext()->getLookupContext()
1393 ->Equals(RT->getDecl())) {
1394 SemaRef.Diag(D->getFieldLoc(),
1395 diag::err_field_designator_unknown_suggest)
1396 << FieldName << CurrentObjectType << R.getLookupName()
1397 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1398 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001399 SemaRef.Diag(ReplacementField->getLocation(),
1400 diag::note_previous_decl)
1401 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001402 } else {
1403 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1404 << FieldName << CurrentObjectType;
1405 ++Index;
1406 return true;
1407 }
1408 } else if (!KnownField) {
1409 // Determine whether we found a field at all.
1410 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1411 }
1412
1413 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001414 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001415 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001416 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001417 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001418 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001419 ++Index;
1420 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001421 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001422
1423 if (!KnownField &&
1424 cast<RecordDecl>((ReplacementField)->getDeclContext())
1425 ->isAnonymousStructOrUnion()) {
1426 // Handle an field designator that refers to a member of an
1427 // anonymous struct or union.
1428 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1429 ReplacementField,
1430 Field, FieldIndex);
1431 D = DIE->getDesignator(DesigIdx);
1432 } else if (!KnownField) {
1433 // The replacement field comes from typo correction; find it
1434 // in the list of fields.
1435 FieldIndex = 0;
1436 Field = RT->getDecl()->field_begin();
1437 for (; Field != FieldEnd; ++Field) {
1438 if (Field->isUnnamedBitfield())
1439 continue;
1440
1441 if (ReplacementField == *Field ||
1442 Field->getIdentifier() == ReplacementField->getIdentifier())
1443 break;
1444
1445 ++FieldIndex;
1446 }
1447 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001448 } else if (!KnownField &&
1449 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001450 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001451 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1452 Field, FieldIndex);
1453 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001454 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001455
1456 // All of the fields of a union are located at the same place in
1457 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001458 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001459 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001460 StructuredList->setInitializedFieldInUnion(*Field);
1461 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001462
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001463 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001464 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001466 // Make sure that our non-designated initializer list has space
1467 // for a subobject corresponding to this field.
1468 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001469 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001470
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001471 // This designator names a flexible array member.
1472 if (Field->getType()->isIncompleteArrayType()) {
1473 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001474 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001475 // We can't designate an object within the flexible array
1476 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001477 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001478 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001479 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001480 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001481 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001482 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001483 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001484 << *Field;
1485 Invalid = true;
1486 }
1487
1488 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1489 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001490 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 diag::err_flexible_array_init_needs_braces)
1492 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001493 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001494 << *Field;
1495 Invalid = true;
1496 }
1497
1498 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001499 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001500 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001501 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001502 diag::err_flexible_array_init_nonempty)
1503 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001504 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001505 << *Field;
1506 Invalid = true;
1507 }
1508
1509 if (Invalid) {
1510 ++Index;
1511 return true;
1512 }
1513
1514 // Initialize the array.
1515 bool prevHadError = hadError;
1516 unsigned newStructuredIndex = FieldIndex;
1517 unsigned OldIndex = Index;
1518 IList->setInit(Index, DIE->getInit());
Anders Carlssond0849252010-01-23 19:55:29 +00001519 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001520 StructuredList, newStructuredIndex);
1521 IList->setInit(OldIndex, DIE);
1522 if (hadError && !prevHadError) {
1523 ++Field;
1524 ++FieldIndex;
1525 if (NextField)
1526 *NextField = Field;
1527 StructuredIndex = FieldIndex;
1528 return true;
1529 }
1530 } else {
1531 // Recurse to check later designated subobjects.
1532 QualType FieldType = (*Field)->getType();
1533 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001534 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1535 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001536 true, false))
1537 return true;
1538 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001539
1540 // Find the position of the next field to be initialized in this
1541 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001542 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001543 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001544
1545 // If this the first designator, our caller will continue checking
1546 // the rest of this struct/class/union subobject.
1547 if (IsFirstDesignator) {
1548 if (NextField)
1549 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001550 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001551 return false;
1552 }
1553
Douglas Gregor17bd0942009-01-28 23:36:17 +00001554 if (!FinishSubobjectInit)
1555 return false;
1556
Douglas Gregord5846a12009-04-15 06:41:24 +00001557 // We've already initialized something in the union; we're done.
1558 if (RT->getDecl()->isUnion())
1559 return hadError;
1560
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001561 // Check the remaining fields within this class/struct/union subobject.
1562 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001563
1564 CheckStructUnionTypes(0, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001565 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001566 return hadError && !prevHadError;
1567 }
1568
1569 // C99 6.7.8p6:
1570 //
1571 // If a designator has the form
1572 //
1573 // [ constant-expression ]
1574 //
1575 // then the current object (defined below) shall have array
1576 // type and the expression shall be an integer constant
1577 // expression. If the array is of unknown size, any
1578 // nonnegative value is valid.
1579 //
1580 // Additionally, cope with the GNU extension that permits
1581 // designators of the form
1582 //
1583 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001584 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001585 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001586 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001587 << CurrentObjectType;
1588 ++Index;
1589 return true;
1590 }
1591
1592 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001593 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1594 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001595 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001596 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001597 DesignatedEndIndex = DesignatedStartIndex;
1598 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001599 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001600
Mike Stump11289f42009-09-09 15:08:12 +00001601
1602 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001603 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001604 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001605 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001606 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001607
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001608 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001609 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001610 }
1611
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612 if (isa<ConstantArrayType>(AT)) {
1613 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001614 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1615 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1616 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1617 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1618 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001619 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001620 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001621 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001622 << IndexExpr->getSourceRange();
1623 ++Index;
1624 return true;
1625 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001626 } else {
1627 // Make sure the bit-widths and signedness match.
1628 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1629 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001630 else if (DesignatedStartIndex.getBitWidth() <
1631 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001632 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1633 DesignatedStartIndex.setIsUnsigned(true);
1634 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001635 }
Mike Stump11289f42009-09-09 15:08:12 +00001636
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001637 // Make sure that our non-designated initializer list has space
1638 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001639 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001640 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001641 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001642
Douglas Gregor17bd0942009-01-28 23:36:17 +00001643 // Repeatedly perform subobject initializations in the range
1644 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001645
Douglas Gregor17bd0942009-01-28 23:36:17 +00001646 // Move to the next designator
1647 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1648 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001649 while (DesignatedStartIndex <= DesignatedEndIndex) {
1650 // Recurse to check later designated subobjects.
1651 QualType ElementType = AT->getElementType();
1652 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001653 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1654 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001655 (DesignatedStartIndex == DesignatedEndIndex),
1656 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001657 return true;
1658
1659 // Move to the next index in the array that we'll be initializing.
1660 ++DesignatedStartIndex;
1661 ElementIndex = DesignatedStartIndex.getZExtValue();
1662 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001663
1664 // If this the first designator, our caller will continue checking
1665 // the rest of this array subobject.
1666 if (IsFirstDesignator) {
1667 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001668 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001669 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001670 return false;
1671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
Douglas Gregor17bd0942009-01-28 23:36:17 +00001673 if (!FinishSubobjectInit)
1674 return false;
1675
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001676 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001677 bool prevHadError = hadError;
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001678 CheckArrayType(0, IList, CurrentObjectType, DesignatedStartIndex,
1679 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001680 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001681 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001682}
1683
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001684// Get the structured initializer list for a subobject of type
1685// @p CurrentObjectType.
1686InitListExpr *
1687InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1688 QualType CurrentObjectType,
1689 InitListExpr *StructuredList,
1690 unsigned StructuredIndex,
1691 SourceRange InitRange) {
1692 Expr *ExistingInit = 0;
1693 if (!StructuredList)
1694 ExistingInit = SyntacticToSemantic[IList];
1695 else if (StructuredIndex < StructuredList->getNumInits())
1696 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001697
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001698 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1699 return Result;
1700
1701 if (ExistingInit) {
1702 // We are creating an initializer list that initializes the
1703 // subobjects of the current object, but there was already an
1704 // initialization that completely initialized the current
1705 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001706 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001707 // struct X { int a, b; };
1708 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001709 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001710 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1711 // designated initializer re-initializes the whole
1712 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001713 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001714 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001715 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001716 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001717 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001718 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001719 << ExistingInit->getSourceRange();
1720 }
1721
Mike Stump11289f42009-09-09 15:08:12 +00001722 InitListExpr *Result
1723 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001724 InitRange.getEnd());
1725
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001726 Result->setType(CurrentObjectType);
1727
Douglas Gregor6d00c992009-03-20 23:58:33 +00001728 // Pre-allocate storage for the structured initializer list.
1729 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001730 unsigned NumInits = 0;
1731 if (!StructuredList)
1732 NumInits = IList->getNumInits();
1733 else if (Index < IList->getNumInits()) {
1734 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1735 NumInits = SubList->getNumInits();
1736 }
1737
Mike Stump11289f42009-09-09 15:08:12 +00001738 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001739 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1740 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1741 NumElements = CAType->getSize().getZExtValue();
1742 // Simple heuristic so that we don't allocate a very large
1743 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001744 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001745 NumElements = 0;
1746 }
John McCall9dd450b2009-09-21 23:43:11 +00001747 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001748 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001749 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001750 RecordDecl *RDecl = RType->getDecl();
1751 if (RDecl->isUnion())
1752 NumElements = 1;
1753 else
Mike Stump11289f42009-09-09 15:08:12 +00001754 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001755 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001756 }
1757
Douglas Gregor221c9a52009-03-21 18:13:52 +00001758 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001759 NumElements = IList->getNumInits();
1760
1761 Result->reserveInits(NumElements);
1762
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001763 // Link this new initializer list into the structured initializer
1764 // lists.
1765 if (StructuredList)
1766 StructuredList->updateInit(StructuredIndex, Result);
1767 else {
1768 Result->setSyntacticForm(IList);
1769 SyntacticToSemantic[IList] = Result;
1770 }
1771
1772 return Result;
1773}
1774
1775/// Update the initializer at index @p StructuredIndex within the
1776/// structured initializer list to the value @p expr.
1777void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1778 unsigned &StructuredIndex,
1779 Expr *expr) {
1780 // No structured initializer list to update
1781 if (!StructuredList)
1782 return;
1783
1784 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1785 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001786 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001787 diag::warn_initializer_overrides)
1788 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001789 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001790 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001791 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001792 << PrevInit->getSourceRange();
1793 }
Mike Stump11289f42009-09-09 15:08:12 +00001794
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001795 ++StructuredIndex;
1796}
1797
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001798/// Check that the given Index expression is a valid array designator
1799/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001800/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001801/// and produces a reasonable diagnostic if there is a
1802/// failure. Returns true if there was an error, false otherwise. If
1803/// everything went okay, Value will receive the value of the constant
1804/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001805static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001806CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001807 SourceLocation Loc = Index->getSourceRange().getBegin();
1808
1809 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001810 if (S.VerifyIntegerConstantExpression(Index, &Value))
1811 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001812
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001813 if (Value.isSigned() && Value.isNegative())
1814 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001815 << Value.toString(10) << Index->getSourceRange();
1816
Douglas Gregor51650d32009-01-23 21:04:18 +00001817 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818 return false;
1819}
1820
1821Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1822 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001823 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001824 OwningExprResult Init) {
1825 typedef DesignatedInitExpr::Designator ASTDesignator;
1826
1827 bool Invalid = false;
1828 llvm::SmallVector<ASTDesignator, 32> Designators;
1829 llvm::SmallVector<Expr *, 32> InitExpressions;
1830
1831 // Build designators and check array designator expressions.
1832 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1833 const Designator &D = Desig.getDesignator(Idx);
1834 switch (D.getKind()) {
1835 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001836 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001837 D.getFieldLoc()));
1838 break;
1839
1840 case Designator::ArrayDesignator: {
1841 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1842 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001843 if (!Index->isTypeDependent() &&
1844 !Index->isValueDependent() &&
1845 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001846 Invalid = true;
1847 else {
1848 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001849 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001850 D.getRBracketLoc()));
1851 InitExpressions.push_back(Index);
1852 }
1853 break;
1854 }
1855
1856 case Designator::ArrayRangeDesignator: {
1857 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1858 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1859 llvm::APSInt StartValue;
1860 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001861 bool StartDependent = StartIndex->isTypeDependent() ||
1862 StartIndex->isValueDependent();
1863 bool EndDependent = EndIndex->isTypeDependent() ||
1864 EndIndex->isValueDependent();
1865 if ((!StartDependent &&
1866 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1867 (!EndDependent &&
1868 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001869 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001870 else {
1871 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001872 if (StartDependent || EndDependent) {
1873 // Nothing to compute.
1874 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001875 EndValue.extend(StartValue.getBitWidth());
1876 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1877 StartValue.extend(EndValue.getBitWidth());
1878
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001879 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001880 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001881 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001882 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1883 Invalid = true;
1884 } else {
1885 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001886 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001887 D.getEllipsisLoc(),
1888 D.getRBracketLoc()));
1889 InitExpressions.push_back(StartIndex);
1890 InitExpressions.push_back(EndIndex);
1891 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001892 }
1893 break;
1894 }
1895 }
1896 }
1897
1898 if (Invalid || Init.isInvalid())
1899 return ExprError();
1900
1901 // Clear out the expressions within the designation.
1902 Desig.ClearExprs(*this);
1903
1904 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001905 = DesignatedInitExpr::Create(Context,
1906 Designators.data(), Designators.size(),
1907 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001908 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001909 return Owned(DIE);
1910}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001911
Douglas Gregor723796a2009-12-16 06:35:08 +00001912bool Sema::CheckInitList(const InitializedEntity &Entity,
1913 InitListExpr *&InitList, QualType &DeclType) {
1914 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001915 if (!CheckInitList.HadError())
1916 InitList = CheckInitList.getFullyStructuredList();
1917
1918 return CheckInitList.HadError();
1919}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001920
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001921//===----------------------------------------------------------------------===//
1922// Initialization entity
1923//===----------------------------------------------------------------------===//
1924
Douglas Gregor723796a2009-12-16 06:35:08 +00001925InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1926 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001927 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001928{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001929 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1930 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001931 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001932 } else {
1933 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001934 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001935 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001936}
1937
1938InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1939 CXXBaseSpecifier *Base)
1940{
1941 InitializedEntity Result;
1942 Result.Kind = EK_Base;
1943 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001944 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001945 return Result;
1946}
1947
Douglas Gregor85dabae2009-12-16 01:38:02 +00001948DeclarationName InitializedEntity::getName() const {
1949 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001950 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001951 if (!VariableOrMember)
1952 return DeclarationName();
1953 // Fall through
1954
1955 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001956 case EK_Member:
1957 return VariableOrMember->getDeclName();
1958
1959 case EK_Result:
1960 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001961 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001962 case EK_Temporary:
1963 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001964 case EK_ArrayElement:
1965 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001966 return DeclarationName();
1967 }
1968
1969 // Silence GCC warning
1970 return DeclarationName();
1971}
1972
Douglas Gregora4b592a2009-12-19 03:01:41 +00001973DeclaratorDecl *InitializedEntity::getDecl() const {
1974 switch (getKind()) {
1975 case EK_Variable:
1976 case EK_Parameter:
1977 case EK_Member:
1978 return VariableOrMember;
1979
1980 case EK_Result:
1981 case EK_Exception:
1982 case EK_New:
1983 case EK_Temporary:
1984 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001985 case EK_ArrayElement:
1986 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00001987 return 0;
1988 }
1989
1990 // Silence GCC warning
1991 return 0;
1992}
1993
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001994//===----------------------------------------------------------------------===//
1995// Initialization sequence
1996//===----------------------------------------------------------------------===//
1997
1998void InitializationSequence::Step::Destroy() {
1999 switch (Kind) {
2000 case SK_ResolveAddressOfOverloadedFunction:
2001 case SK_CastDerivedToBaseRValue:
2002 case SK_CastDerivedToBaseLValue:
2003 case SK_BindReference:
2004 case SK_BindReferenceToTemporary:
2005 case SK_UserConversion:
2006 case SK_QualificationConversionRValue:
2007 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002008 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002009 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002010 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002011 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002012 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002013 break;
2014
2015 case SK_ConversionSequence:
2016 delete ICS;
2017 }
2018}
2019
2020void InitializationSequence::AddAddressOverloadResolutionStep(
2021 FunctionDecl *Function) {
2022 Step S;
2023 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2024 S.Type = Function->getType();
2025 S.Function = Function;
2026 Steps.push_back(S);
2027}
2028
2029void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2030 bool IsLValue) {
2031 Step S;
2032 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2033 S.Type = BaseType;
2034 Steps.push_back(S);
2035}
2036
2037void InitializationSequence::AddReferenceBindingStep(QualType T,
2038 bool BindingTemporary) {
2039 Step S;
2040 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2041 S.Type = T;
2042 Steps.push_back(S);
2043}
2044
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002045void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2046 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002047 Step S;
2048 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002049 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002050 S.Function = Function;
2051 Steps.push_back(S);
2052}
2053
2054void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2055 bool IsLValue) {
2056 Step S;
2057 S.Kind = IsLValue? SK_QualificationConversionLValue
2058 : SK_QualificationConversionRValue;
2059 S.Type = Ty;
2060 Steps.push_back(S);
2061}
2062
2063void InitializationSequence::AddConversionSequenceStep(
2064 const ImplicitConversionSequence &ICS,
2065 QualType T) {
2066 Step S;
2067 S.Kind = SK_ConversionSequence;
2068 S.Type = T;
2069 S.ICS = new ImplicitConversionSequence(ICS);
2070 Steps.push_back(S);
2071}
2072
Douglas Gregor51e77d52009-12-10 17:56:55 +00002073void InitializationSequence::AddListInitializationStep(QualType T) {
2074 Step S;
2075 S.Kind = SK_ListInitialization;
2076 S.Type = T;
2077 Steps.push_back(S);
2078}
2079
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002080void
2081InitializationSequence::AddConstructorInitializationStep(
2082 CXXConstructorDecl *Constructor,
2083 QualType T) {
2084 Step S;
2085 S.Kind = SK_ConstructorInitialization;
2086 S.Type = T;
2087 S.Function = Constructor;
2088 Steps.push_back(S);
2089}
2090
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002091void InitializationSequence::AddZeroInitializationStep(QualType T) {
2092 Step S;
2093 S.Kind = SK_ZeroInitialization;
2094 S.Type = T;
2095 Steps.push_back(S);
2096}
2097
Douglas Gregore1314a62009-12-18 05:02:21 +00002098void InitializationSequence::AddCAssignmentStep(QualType T) {
2099 Step S;
2100 S.Kind = SK_CAssignment;
2101 S.Type = T;
2102 Steps.push_back(S);
2103}
2104
Eli Friedman78275202009-12-19 08:11:05 +00002105void InitializationSequence::AddStringInitStep(QualType T) {
2106 Step S;
2107 S.Kind = SK_StringInit;
2108 S.Type = T;
2109 Steps.push_back(S);
2110}
2111
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002112void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2113 OverloadingResult Result) {
2114 SequenceKind = FailedSequence;
2115 this->Failure = Failure;
2116 this->FailedOverloadResult = Result;
2117}
2118
2119//===----------------------------------------------------------------------===//
2120// Attempt initialization
2121//===----------------------------------------------------------------------===//
2122
2123/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002124static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002125 const InitializedEntity &Entity,
2126 const InitializationKind &Kind,
2127 InitListExpr *InitList,
2128 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002129 // FIXME: We only perform rudimentary checking of list
2130 // initializations at this point, then assume that any list
2131 // initialization of an array, aggregate, or scalar will be
2132 // well-formed. We we actually "perform" list initialization, we'll
2133 // do all of the necessary checking. C++0x initializer lists will
2134 // force us to perform more checking here.
2135 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2136
Douglas Gregor1b303932009-12-22 15:35:07 +00002137 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002138
2139 // C++ [dcl.init]p13:
2140 // If T is a scalar type, then a declaration of the form
2141 //
2142 // T x = { a };
2143 //
2144 // is equivalent to
2145 //
2146 // T x = a;
2147 if (DestType->isScalarType()) {
2148 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2149 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2150 return;
2151 }
2152
2153 // Assume scalar initialization from a single value works.
2154 } else if (DestType->isAggregateType()) {
2155 // Assume aggregate initialization works.
2156 } else if (DestType->isVectorType()) {
2157 // Assume vector initialization works.
2158 } else if (DestType->isReferenceType()) {
2159 // FIXME: C++0x defines behavior for this.
2160 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2161 return;
2162 } else if (DestType->isRecordType()) {
2163 // FIXME: C++0x defines behavior for this
2164 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2165 }
2166
2167 // Add a general "list initialization" step.
2168 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002169}
2170
2171/// \brief Try a reference initialization that involves calling a conversion
2172/// function.
2173///
2174/// FIXME: look intos DRs 656, 896
2175static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2176 const InitializedEntity &Entity,
2177 const InitializationKind &Kind,
2178 Expr *Initializer,
2179 bool AllowRValues,
2180 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002181 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002182 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2183 QualType T1 = cv1T1.getUnqualifiedType();
2184 QualType cv2T2 = Initializer->getType();
2185 QualType T2 = cv2T2.getUnqualifiedType();
2186
2187 bool DerivedToBase;
2188 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2189 T1, T2, DerivedToBase) &&
2190 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002191 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002192
2193 // Build the candidate set directly in the initialization sequence
2194 // structure, so that it will persist if we fail.
2195 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2196 CandidateSet.clear();
2197
2198 // Determine whether we are allowed to call explicit constructors or
2199 // explicit conversion operators.
2200 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2201
2202 const RecordType *T1RecordType = 0;
2203 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2204 // The type we're converting to is a class type. Enumerate its constructors
2205 // to see if there is a suitable conversion.
2206 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2207
2208 DeclarationName ConstructorName
2209 = S.Context.DeclarationNames.getCXXConstructorName(
2210 S.Context.getCanonicalType(T1).getUnqualifiedType());
2211 DeclContext::lookup_iterator Con, ConEnd;
2212 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2213 Con != ConEnd; ++Con) {
2214 // Find the constructor (which may be a template).
2215 CXXConstructorDecl *Constructor = 0;
2216 FunctionTemplateDecl *ConstructorTmpl
2217 = dyn_cast<FunctionTemplateDecl>(*Con);
2218 if (ConstructorTmpl)
2219 Constructor = cast<CXXConstructorDecl>(
2220 ConstructorTmpl->getTemplatedDecl());
2221 else
2222 Constructor = cast<CXXConstructorDecl>(*Con);
2223
2224 if (!Constructor->isInvalidDecl() &&
2225 Constructor->isConvertingConstructor(AllowExplicit)) {
2226 if (ConstructorTmpl)
2227 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2228 &Initializer, 1, CandidateSet);
2229 else
2230 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2231 }
2232 }
2233 }
2234
2235 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2236 // The type we're converting from is a class type, enumerate its conversion
2237 // functions.
2238 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2239
2240 // Determine the type we are converting to. If we are allowed to
2241 // convert to an rvalue, take the type that the destination type
2242 // refers to.
2243 QualType ToType = AllowRValues? cv1T1 : DestType;
2244
John McCallad371252010-01-20 00:46:10 +00002245 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002246 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002247 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2248 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002249 NamedDecl *D = *I;
2250 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2251 if (isa<UsingShadowDecl>(D))
2252 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2253
2254 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2255 CXXConversionDecl *Conv;
2256 if (ConvTemplate)
2257 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2258 else
2259 Conv = cast<CXXConversionDecl>(*I);
2260
2261 // If the conversion function doesn't return a reference type,
2262 // it can't be considered for this conversion unless we're allowed to
2263 // consider rvalues.
2264 // FIXME: Do we need to make sure that we only consider conversion
2265 // candidates with reference-compatible results? That might be needed to
2266 // break recursion.
2267 if ((AllowExplicit || !Conv->isExplicit()) &&
2268 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2269 if (ConvTemplate)
2270 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2271 ToType, CandidateSet);
2272 else
2273 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2274 CandidateSet);
2275 }
2276 }
2277 }
2278
2279 SourceLocation DeclLoc = Initializer->getLocStart();
2280
2281 // Perform overload resolution. If it fails, return the failed result.
2282 OverloadCandidateSet::iterator Best;
2283 if (OverloadingResult Result
2284 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2285 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002286
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002287 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002288
2289 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002290 if (isa<CXXConversionDecl>(Function))
2291 T2 = Function->getResultType();
2292 else
2293 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002294
2295 // Add the user-defined conversion step.
2296 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2297
2298 // Determine whether we need to perform derived-to-base or
2299 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002300 bool NewDerivedToBase = false;
2301 Sema::ReferenceCompareResult NewRefRelationship
2302 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2303 NewDerivedToBase);
2304 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2305 "Overload resolution picked a bad conversion function");
2306 (void)NewRefRelationship;
2307 if (NewDerivedToBase)
2308 Sequence.AddDerivedToBaseCastStep(
2309 S.Context.getQualifiedType(T1,
2310 T2.getNonReferenceType().getQualifiers()),
2311 /*isLValue=*/true);
2312
2313 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2314 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2315
2316 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2317 return OR_Success;
2318}
2319
2320/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2321static void TryReferenceInitialization(Sema &S,
2322 const InitializedEntity &Entity,
2323 const InitializationKind &Kind,
2324 Expr *Initializer,
2325 InitializationSequence &Sequence) {
2326 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2327
Douglas Gregor1b303932009-12-22 15:35:07 +00002328 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002329 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002330 Qualifiers T1Quals;
2331 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002332 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002333 Qualifiers T2Quals;
2334 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002335 SourceLocation DeclLoc = Initializer->getLocStart();
2336
2337 // If the initializer is the address of an overloaded function, try
2338 // to resolve the overloaded function. If all goes well, T2 is the
2339 // type of the resulting function.
2340 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2341 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2342 T1,
2343 false);
2344 if (!Fn) {
2345 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2346 return;
2347 }
2348
2349 Sequence.AddAddressOverloadResolutionStep(Fn);
2350 cv2T2 = Fn->getType();
2351 T2 = cv2T2.getUnqualifiedType();
2352 }
2353
2354 // FIXME: Rvalue references
2355 bool ForceRValue = false;
2356
2357 // Compute some basic properties of the types and the initializer.
2358 bool isLValueRef = DestType->isLValueReferenceType();
2359 bool isRValueRef = !isLValueRef;
2360 bool DerivedToBase = false;
2361 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2362 Initializer->isLvalue(S.Context);
2363 Sema::ReferenceCompareResult RefRelationship
2364 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2365
2366 // C++0x [dcl.init.ref]p5:
2367 // A reference to type "cv1 T1" is initialized by an expression of type
2368 // "cv2 T2" as follows:
2369 //
2370 // - If the reference is an lvalue reference and the initializer
2371 // expression
2372 OverloadingResult ConvOvlResult = OR_Success;
2373 if (isLValueRef) {
2374 if (InitLvalue == Expr::LV_Valid &&
2375 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2376 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2377 // reference-compatible with "cv2 T2," or
2378 //
2379 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2380 // bit-field when we're determining whether the reference initialization
2381 // can occur. This property will be checked by PerformInitialization.
2382 if (DerivedToBase)
2383 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002384 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002385 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002386 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002387 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2388 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2389 return;
2390 }
2391
2392 // - has a class type (i.e., T2 is a class type), where T1 is not
2393 // reference-related to T2, and can be implicitly converted to an
2394 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2395 // with "cv3 T3" (this conversion is selected by enumerating the
2396 // applicable conversion functions (13.3.1.6) and choosing the best
2397 // one through overload resolution (13.3)),
2398 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2399 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2400 Initializer,
2401 /*AllowRValues=*/false,
2402 Sequence);
2403 if (ConvOvlResult == OR_Success)
2404 return;
John McCall0d1da222010-01-12 00:44:57 +00002405 if (ConvOvlResult != OR_No_Viable_Function) {
2406 Sequence.SetOverloadFailure(
2407 InitializationSequence::FK_ReferenceInitOverloadFailed,
2408 ConvOvlResult);
2409 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002410 }
2411 }
2412
2413 // - Otherwise, the reference shall be an lvalue reference to a
2414 // non-volatile const type (i.e., cv1 shall be const), or the reference
2415 // shall be an rvalue reference and the initializer expression shall
2416 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002417 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002418 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2419 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2420 Sequence.SetOverloadFailure(
2421 InitializationSequence::FK_ReferenceInitOverloadFailed,
2422 ConvOvlResult);
2423 else if (isLValueRef)
2424 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2425 ? (RefRelationship == Sema::Ref_Related
2426 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2427 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2428 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2429 else
2430 Sequence.SetFailed(
2431 InitializationSequence::FK_RValueReferenceBindingToLValue);
2432
2433 return;
2434 }
2435
2436 // - If T1 and T2 are class types and
2437 if (T1->isRecordType() && T2->isRecordType()) {
2438 // - the initializer expression is an rvalue and "cv1 T1" is
2439 // reference-compatible with "cv2 T2", or
2440 if (InitLvalue != Expr::LV_Valid &&
2441 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2442 if (DerivedToBase)
2443 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002444 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002445 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002446 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002447 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2448 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2449 return;
2450 }
2451
2452 // - T1 is not reference-related to T2 and the initializer expression
2453 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2454 // conversion is selected by enumerating the applicable conversion
2455 // functions (13.3.1.6) and choosing the best one through overload
2456 // resolution (13.3)),
2457 if (RefRelationship == Sema::Ref_Incompatible) {
2458 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2459 Kind, Initializer,
2460 /*AllowRValues=*/true,
2461 Sequence);
2462 if (ConvOvlResult)
2463 Sequence.SetOverloadFailure(
2464 InitializationSequence::FK_ReferenceInitOverloadFailed,
2465 ConvOvlResult);
2466
2467 return;
2468 }
2469
2470 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2471 return;
2472 }
2473
2474 // - If the initializer expression is an rvalue, with T2 an array type,
2475 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2476 // is bound to the object represented by the rvalue (see 3.10).
2477 // FIXME: How can an array type be reference-compatible with anything?
2478 // Don't we mean the element types of T1 and T2?
2479
2480 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2481 // from the initializer expression using the rules for a non-reference
2482 // copy initialization (8.5). The reference is then bound to the
2483 // temporary. [...]
2484 // Determine whether we are allowed to call explicit constructors or
2485 // explicit conversion operators.
2486 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2487 ImplicitConversionSequence ICS
2488 = S.TryImplicitConversion(Initializer, cv1T1,
2489 /*SuppressUserConversions=*/false, AllowExplicit,
2490 /*ForceRValue=*/false,
2491 /*FIXME:InOverloadResolution=*/false,
2492 /*UserCast=*/Kind.isExplicitCast());
2493
John McCall0d1da222010-01-12 00:44:57 +00002494 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002495 // FIXME: Use the conversion function set stored in ICS to turn
2496 // this into an overloading ambiguity diagnostic. However, we need
2497 // to keep that set as an OverloadCandidateSet rather than as some
2498 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002499 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2500 Sequence.SetOverloadFailure(
2501 InitializationSequence::FK_ReferenceInitOverloadFailed,
2502 ConvOvlResult);
2503 else
2504 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002505 return;
2506 }
2507
2508 // [...] If T1 is reference-related to T2, cv1 must be the
2509 // same cv-qualification as, or greater cv-qualification
2510 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002511 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2512 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002513 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002514 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002515 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2516 return;
2517 }
2518
2519 // Perform the actual conversion.
2520 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2521 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2522 return;
2523}
2524
2525/// \brief Attempt character array initialization from a string literal
2526/// (C++ [dcl.init.string], C99 6.7.8).
2527static void TryStringLiteralInitialization(Sema &S,
2528 const InitializedEntity &Entity,
2529 const InitializationKind &Kind,
2530 Expr *Initializer,
2531 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002532 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002533 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002534}
2535
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002536/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2537/// enumerates the constructors of the initialized entity and performs overload
2538/// resolution to select the best.
2539static void TryConstructorInitialization(Sema &S,
2540 const InitializedEntity &Entity,
2541 const InitializationKind &Kind,
2542 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002543 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002544 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002545 if (Kind.getKind() == InitializationKind::IK_Copy)
2546 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2547 else
2548 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002549
2550 // Build the candidate set directly in the initialization sequence
2551 // structure, so that it will persist if we fail.
2552 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2553 CandidateSet.clear();
2554
2555 // Determine whether we are allowed to call explicit constructors or
2556 // explicit conversion operators.
2557 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2558 Kind.getKind() == InitializationKind::IK_Value ||
2559 Kind.getKind() == InitializationKind::IK_Default);
2560
2561 // The type we're converting to is a class type. Enumerate its constructors
2562 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002563 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2564 assert(DestRecordType && "Constructor initialization requires record type");
2565 CXXRecordDecl *DestRecordDecl
2566 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2567
2568 DeclarationName ConstructorName
2569 = S.Context.DeclarationNames.getCXXConstructorName(
2570 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2571 DeclContext::lookup_iterator Con, ConEnd;
2572 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2573 Con != ConEnd; ++Con) {
2574 // Find the constructor (which may be a template).
2575 CXXConstructorDecl *Constructor = 0;
2576 FunctionTemplateDecl *ConstructorTmpl
2577 = dyn_cast<FunctionTemplateDecl>(*Con);
2578 if (ConstructorTmpl)
2579 Constructor = cast<CXXConstructorDecl>(
2580 ConstructorTmpl->getTemplatedDecl());
2581 else
2582 Constructor = cast<CXXConstructorDecl>(*Con);
2583
2584 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002585 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002586 if (ConstructorTmpl)
2587 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2588 Args, NumArgs, CandidateSet);
2589 else
2590 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2591 }
2592 }
2593
2594 SourceLocation DeclLoc = Kind.getLocation();
2595
2596 // Perform overload resolution. If it fails, return the failed result.
2597 OverloadCandidateSet::iterator Best;
2598 if (OverloadingResult Result
2599 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2600 Sequence.SetOverloadFailure(
2601 InitializationSequence::FK_ConstructorOverloadFailed,
2602 Result);
2603 return;
2604 }
2605
2606 // Add the constructor initialization step. Any cv-qualification conversion is
2607 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002608 if (Kind.getKind() == InitializationKind::IK_Copy) {
2609 Sequence.AddUserConversionStep(Best->Function, DestType);
2610 } else {
2611 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002612 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002613 DestType);
2614 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002615}
2616
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002617/// \brief Attempt value initialization (C++ [dcl.init]p7).
2618static void TryValueInitialization(Sema &S,
2619 const InitializedEntity &Entity,
2620 const InitializationKind &Kind,
2621 InitializationSequence &Sequence) {
2622 // C++ [dcl.init]p5:
2623 //
2624 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002625 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002626
2627 // -- if T is an array type, then each element is value-initialized;
2628 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2629 T = AT->getElementType();
2630
2631 if (const RecordType *RT = T->getAs<RecordType>()) {
2632 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2633 // -- if T is a class type (clause 9) with a user-declared
2634 // constructor (12.1), then the default constructor for T is
2635 // called (and the initialization is ill-formed if T has no
2636 // accessible default constructor);
2637 //
2638 // FIXME: we really want to refer to a single subobject of the array,
2639 // but Entity doesn't have a way to capture that (yet).
2640 if (ClassDecl->hasUserDeclaredConstructor())
2641 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2642
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002643 // -- if T is a (possibly cv-qualified) non-union class type
2644 // without a user-provided constructor, then the object is
2645 // zero-initialized and, if T’s implicitly-declared default
2646 // constructor is non-trivial, that constructor is called.
2647 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2648 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2649 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002650 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002651 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2652 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002653 }
2654 }
2655
Douglas Gregor1b303932009-12-22 15:35:07 +00002656 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002657 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2658}
2659
Douglas Gregor85dabae2009-12-16 01:38:02 +00002660/// \brief Attempt default initialization (C++ [dcl.init]p6).
2661static void TryDefaultInitialization(Sema &S,
2662 const InitializedEntity &Entity,
2663 const InitializationKind &Kind,
2664 InitializationSequence &Sequence) {
2665 assert(Kind.getKind() == InitializationKind::IK_Default);
2666
2667 // C++ [dcl.init]p6:
2668 // To default-initialize an object of type T means:
2669 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002670 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002671 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2672 DestType = Array->getElementType();
2673
2674 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2675 // constructor for T is called (and the initialization is ill-formed if
2676 // T has no accessible default constructor);
2677 if (DestType->isRecordType()) {
2678 // FIXME: If a program calls for the default initialization of an object of
2679 // a const-qualified type T, T shall be a class type with a user-provided
2680 // default constructor.
2681 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2682 Sequence);
2683 }
2684
2685 // - otherwise, no initialization is performed.
2686 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2687
2688 // If a program calls for the default initialization of an object of
2689 // a const-qualified type T, T shall be a class type with a user-provided
2690 // default constructor.
2691 if (DestType.isConstQualified())
2692 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2693}
2694
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002695/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2696/// which enumerates all conversion functions and performs overload resolution
2697/// to select the best.
2698static void TryUserDefinedConversion(Sema &S,
2699 const InitializedEntity &Entity,
2700 const InitializationKind &Kind,
2701 Expr *Initializer,
2702 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002703 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2704
Douglas Gregor1b303932009-12-22 15:35:07 +00002705 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002706 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2707 QualType SourceType = Initializer->getType();
2708 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2709 "Must have a class type to perform a user-defined conversion");
2710
2711 // Build the candidate set directly in the initialization sequence
2712 // structure, so that it will persist if we fail.
2713 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2714 CandidateSet.clear();
2715
2716 // Determine whether we are allowed to call explicit constructors or
2717 // explicit conversion operators.
2718 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2719
2720 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2721 // The type we're converting to is a class type. Enumerate its constructors
2722 // to see if there is a suitable conversion.
2723 CXXRecordDecl *DestRecordDecl
2724 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2725
2726 DeclarationName ConstructorName
2727 = S.Context.DeclarationNames.getCXXConstructorName(
2728 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2729 DeclContext::lookup_iterator Con, ConEnd;
2730 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2731 Con != ConEnd; ++Con) {
2732 // Find the constructor (which may be a template).
2733 CXXConstructorDecl *Constructor = 0;
2734 FunctionTemplateDecl *ConstructorTmpl
2735 = dyn_cast<FunctionTemplateDecl>(*Con);
2736 if (ConstructorTmpl)
2737 Constructor = cast<CXXConstructorDecl>(
2738 ConstructorTmpl->getTemplatedDecl());
2739 else
2740 Constructor = cast<CXXConstructorDecl>(*Con);
2741
2742 if (!Constructor->isInvalidDecl() &&
2743 Constructor->isConvertingConstructor(AllowExplicit)) {
2744 if (ConstructorTmpl)
2745 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2746 &Initializer, 1, CandidateSet);
2747 else
2748 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2749 }
2750 }
2751 }
Eli Friedman78275202009-12-19 08:11:05 +00002752
2753 SourceLocation DeclLoc = Initializer->getLocStart();
2754
Douglas Gregor540c3b02009-12-14 17:27:33 +00002755 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2756 // The type we're converting from is a class type, enumerate its conversion
2757 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002758
Eli Friedman4afe9a32009-12-20 22:12:03 +00002759 // We can only enumerate the conversion functions for a complete type; if
2760 // the type isn't complete, simply skip this step.
2761 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2762 CXXRecordDecl *SourceRecordDecl
2763 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002764
John McCallad371252010-01-20 00:46:10 +00002765 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002766 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002767 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002768 E = Conversions->end();
2769 I != E; ++I) {
2770 NamedDecl *D = *I;
2771 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2772 if (isa<UsingShadowDecl>(D))
2773 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2774
2775 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2776 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002777 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002778 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002779 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002780 Conv = cast<CXXConversionDecl>(*I);
2781
2782 if (AllowExplicit || !Conv->isExplicit()) {
2783 if (ConvTemplate)
2784 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2785 Initializer, DestType,
2786 CandidateSet);
2787 else
2788 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2789 CandidateSet);
2790 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002791 }
2792 }
2793 }
2794
Douglas Gregor540c3b02009-12-14 17:27:33 +00002795 // Perform overload resolution. If it fails, return the failed result.
2796 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002797 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002798 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2799 Sequence.SetOverloadFailure(
2800 InitializationSequence::FK_UserConversionOverloadFailed,
2801 Result);
2802 return;
2803 }
John McCall0d1da222010-01-12 00:44:57 +00002804
Douglas Gregor540c3b02009-12-14 17:27:33 +00002805 FunctionDecl *Function = Best->Function;
2806
2807 if (isa<CXXConstructorDecl>(Function)) {
2808 // Add the user-defined conversion step. Any cv-qualification conversion is
2809 // subsumed by the initialization.
2810 Sequence.AddUserConversionStep(Function, DestType);
2811 return;
2812 }
2813
2814 // Add the user-defined conversion step that calls the conversion function.
2815 QualType ConvType = Function->getResultType().getNonReferenceType();
2816 Sequence.AddUserConversionStep(Function, ConvType);
2817
2818 // If the conversion following the call to the conversion function is
2819 // interesting, add it as a separate step.
2820 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2821 Best->FinalConversion.Third) {
2822 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002823 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002824 ICS.Standard = Best->FinalConversion;
2825 Sequence.AddConversionSequenceStep(ICS, DestType);
2826 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002827}
2828
2829/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2830/// non-class type to another.
2831static void TryImplicitConversion(Sema &S,
2832 const InitializedEntity &Entity,
2833 const InitializationKind &Kind,
2834 Expr *Initializer,
2835 InitializationSequence &Sequence) {
2836 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002837 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002838 /*SuppressUserConversions=*/true,
2839 /*AllowExplicit=*/false,
2840 /*ForceRValue=*/false,
2841 /*FIXME:InOverloadResolution=*/false,
2842 /*UserCast=*/Kind.isExplicitCast());
2843
John McCall0d1da222010-01-12 00:44:57 +00002844 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002845 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2846 return;
2847 }
2848
Douglas Gregor1b303932009-12-22 15:35:07 +00002849 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002850}
2851
2852InitializationSequence::InitializationSequence(Sema &S,
2853 const InitializedEntity &Entity,
2854 const InitializationKind &Kind,
2855 Expr **Args,
2856 unsigned NumArgs) {
2857 ASTContext &Context = S.Context;
2858
2859 // C++0x [dcl.init]p16:
2860 // The semantics of initializers are as follows. The destination type is
2861 // the type of the object or reference being initialized and the source
2862 // type is the type of the initializer expression. The source type is not
2863 // defined when the initializer is a braced-init-list or when it is a
2864 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002865 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002866
2867 if (DestType->isDependentType() ||
2868 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2869 SequenceKind = DependentSequence;
2870 return;
2871 }
2872
2873 QualType SourceType;
2874 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002875 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002876 Initializer = Args[0];
2877 if (!isa<InitListExpr>(Initializer))
2878 SourceType = Initializer->getType();
2879 }
2880
2881 // - If the initializer is a braced-init-list, the object is
2882 // list-initialized (8.5.4).
2883 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2884 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002885 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002886 }
2887
2888 // - If the destination type is a reference type, see 8.5.3.
2889 if (DestType->isReferenceType()) {
2890 // C++0x [dcl.init.ref]p1:
2891 // A variable declared to be a T& or T&&, that is, "reference to type T"
2892 // (8.3.2), shall be initialized by an object, or function, of type T or
2893 // by an object that can be converted into a T.
2894 // (Therefore, multiple arguments are not permitted.)
2895 if (NumArgs != 1)
2896 SetFailed(FK_TooManyInitsForReference);
2897 else
2898 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2899 return;
2900 }
2901
2902 // - If the destination type is an array of characters, an array of
2903 // char16_t, an array of char32_t, or an array of wchar_t, and the
2904 // initializer is a string literal, see 8.5.2.
2905 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2906 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2907 return;
2908 }
2909
2910 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002911 if (Kind.getKind() == InitializationKind::IK_Value ||
2912 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002913 TryValueInitialization(S, Entity, Kind, *this);
2914 return;
2915 }
2916
Douglas Gregor85dabae2009-12-16 01:38:02 +00002917 // Handle default initialization.
2918 if (Kind.getKind() == InitializationKind::IK_Default){
2919 TryDefaultInitialization(S, Entity, Kind, *this);
2920 return;
2921 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002922
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002923 // - Otherwise, if the destination type is an array, the program is
2924 // ill-formed.
2925 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2926 if (AT->getElementType()->isAnyCharacterType())
2927 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2928 else
2929 SetFailed(FK_ArrayNeedsInitList);
2930
2931 return;
2932 }
Eli Friedman78275202009-12-19 08:11:05 +00002933
2934 // Handle initialization in C
2935 if (!S.getLangOptions().CPlusPlus) {
2936 setSequenceKind(CAssignment);
2937 AddCAssignmentStep(DestType);
2938 return;
2939 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002940
2941 // - If the destination type is a (possibly cv-qualified) class type:
2942 if (DestType->isRecordType()) {
2943 // - If the initialization is direct-initialization, or if it is
2944 // copy-initialization where the cv-unqualified version of the
2945 // source type is the same class as, or a derived class of, the
2946 // class of the destination, constructors are considered. [...]
2947 if (Kind.getKind() == InitializationKind::IK_Direct ||
2948 (Kind.getKind() == InitializationKind::IK_Copy &&
2949 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2950 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002951 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002952 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002953 // - Otherwise (i.e., for the remaining copy-initialization cases),
2954 // user-defined conversion sequences that can convert from the source
2955 // type to the destination type or (when a conversion function is
2956 // used) to a derived class thereof are enumerated as described in
2957 // 13.3.1.4, and the best one is chosen through overload resolution
2958 // (13.3).
2959 else
2960 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2961 return;
2962 }
2963
Douglas Gregor85dabae2009-12-16 01:38:02 +00002964 if (NumArgs > 1) {
2965 SetFailed(FK_TooManyInitsForScalar);
2966 return;
2967 }
2968 assert(NumArgs == 1 && "Zero-argument case handled above");
2969
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002970 // - Otherwise, if the source type is a (possibly cv-qualified) class
2971 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002972 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002973 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2974 return;
2975 }
2976
2977 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002978 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002979 // conversions (Clause 4) will be used, if necessary, to convert the
2980 // initializer expression to the cv-unqualified version of the
2981 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002982 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002983 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2984}
2985
2986InitializationSequence::~InitializationSequence() {
2987 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2988 StepEnd = Steps.end();
2989 Step != StepEnd; ++Step)
2990 Step->Destroy();
2991}
2992
2993//===----------------------------------------------------------------------===//
2994// Perform initialization
2995//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002996static Sema::AssignmentAction
2997getAssignmentAction(const InitializedEntity &Entity) {
2998 switch(Entity.getKind()) {
2999 case InitializedEntity::EK_Variable:
3000 case InitializedEntity::EK_New:
3001 return Sema::AA_Initializing;
3002
3003 case InitializedEntity::EK_Parameter:
3004 // FIXME: Can we tell when we're sending vs. passing?
3005 return Sema::AA_Passing;
3006
3007 case InitializedEntity::EK_Result:
3008 return Sema::AA_Returning;
3009
3010 case InitializedEntity::EK_Exception:
3011 case InitializedEntity::EK_Base:
3012 llvm_unreachable("No assignment action for C++-specific initialization");
3013 break;
3014
3015 case InitializedEntity::EK_Temporary:
3016 // FIXME: Can we tell apart casting vs. converting?
3017 return Sema::AA_Casting;
3018
3019 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003020 case InitializedEntity::EK_ArrayElement:
3021 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003022 return Sema::AA_Initializing;
3023 }
3024
3025 return Sema::AA_Converting;
3026}
3027
3028static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3029 bool IsCopy) {
3030 switch (Entity.getKind()) {
3031 case InitializedEntity::EK_Result:
3032 case InitializedEntity::EK_Exception:
3033 return !IsCopy;
3034
3035 case InitializedEntity::EK_New:
3036 case InitializedEntity::EK_Variable:
3037 case InitializedEntity::EK_Base:
3038 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003039 case InitializedEntity::EK_ArrayElement:
3040 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003041 return false;
3042
3043 case InitializedEntity::EK_Parameter:
3044 case InitializedEntity::EK_Temporary:
3045 return true;
3046 }
3047
3048 llvm_unreachable("missed an InitializedEntity kind?");
3049}
3050
3051/// \brief If we need to perform an additional copy of the initialized object
3052/// for this kind of entity (e.g., the result of a function or an object being
3053/// thrown), make the copy.
3054static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3055 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003056 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003057 Sema::OwningExprResult CurInit) {
3058 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003059
3060 switch (Entity.getKind()) {
3061 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003062 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003063 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003064 Loc = Entity.getReturnLoc();
3065 break;
3066
3067 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003068 Loc = Entity.getThrowLoc();
3069 break;
3070
3071 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003072 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003073 Kind.getKind() != InitializationKind::IK_Copy)
3074 return move(CurInit);
3075 Loc = Entity.getDecl()->getLocation();
3076 break;
3077
Douglas Gregore1314a62009-12-18 05:02:21 +00003078 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003079 // FIXME: Do we need this initialization for a parameter?
3080 return move(CurInit);
3081
Douglas Gregore1314a62009-12-18 05:02:21 +00003082 case InitializedEntity::EK_New:
3083 case InitializedEntity::EK_Temporary:
3084 case InitializedEntity::EK_Base:
3085 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003086 case InitializedEntity::EK_ArrayElement:
3087 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003088 // We don't need to copy for any of these initialized entities.
3089 return move(CurInit);
3090 }
3091
3092 Expr *CurInitExpr = (Expr *)CurInit.get();
3093 CXXRecordDecl *Class = 0;
3094 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3095 Class = cast<CXXRecordDecl>(Record->getDecl());
3096 if (!Class)
3097 return move(CurInit);
3098
3099 // Perform overload resolution using the class's copy constructors.
3100 DeclarationName ConstructorName
3101 = S.Context.DeclarationNames.getCXXConstructorName(
3102 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3103 DeclContext::lookup_iterator Con, ConEnd;
3104 OverloadCandidateSet CandidateSet;
3105 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3106 Con != ConEnd; ++Con) {
3107 // Find the constructor (which may be a template).
3108 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3109 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003110 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003111 continue;
3112
3113 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3114 }
3115
3116 OverloadCandidateSet::iterator Best;
3117 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3118 case OR_Success:
3119 break;
3120
3121 case OR_No_Viable_Function:
3122 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003123 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003124 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003125 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3126 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003127 return S.ExprError();
3128
3129 case OR_Ambiguous:
3130 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003131 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003132 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003133 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3134 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003135 return S.ExprError();
3136
3137 case OR_Deleted:
3138 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003139 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003140 << CurInitExpr->getSourceRange();
3141 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3142 << Best->Function->isDeleted();
3143 return S.ExprError();
3144 }
3145
3146 CurInit.release();
3147 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3148 cast<CXXConstructorDecl>(Best->Function),
3149 /*Elidable=*/true,
3150 Sema::MultiExprArg(S,
3151 (void**)&CurInitExpr, 1));
3152}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003153
3154Action::OwningExprResult
3155InitializationSequence::Perform(Sema &S,
3156 const InitializedEntity &Entity,
3157 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003158 Action::MultiExprArg Args,
3159 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003160 if (SequenceKind == FailedSequence) {
3161 unsigned NumArgs = Args.size();
3162 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3163 return S.ExprError();
3164 }
3165
3166 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003167 // If the declaration is a non-dependent, incomplete array type
3168 // that has an initializer, then its type will be completed once
3169 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003170 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003171 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003172 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003173 if (const IncompleteArrayType *ArrayT
3174 = S.Context.getAsIncompleteArrayType(DeclType)) {
3175 // FIXME: We don't currently have the ability to accurately
3176 // compute the length of an initializer list without
3177 // performing full type-checking of the initializer list
3178 // (since we have to determine where braces are implicitly
3179 // introduced and such). So, we fall back to making the array
3180 // type a dependently-sized array type with no specified
3181 // bound.
3182 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3183 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003184
Douglas Gregor51e77d52009-12-10 17:56:55 +00003185 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003186 if (DeclaratorDecl *DD = Entity.getDecl()) {
3187 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3188 TypeLoc TL = TInfo->getTypeLoc();
3189 if (IncompleteArrayTypeLoc *ArrayLoc
3190 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3191 Brackets = ArrayLoc->getBracketsRange();
3192 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003193 }
3194
3195 *ResultType
3196 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3197 /*NumElts=*/0,
3198 ArrayT->getSizeModifier(),
3199 ArrayT->getIndexTypeCVRQualifiers(),
3200 Brackets);
3201 }
3202
3203 }
3204 }
3205
Eli Friedmana553d4a2009-12-22 02:35:53 +00003206 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003207 return Sema::OwningExprResult(S, Args.release()[0]);
3208
3209 unsigned NumArgs = Args.size();
3210 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3211 SourceLocation(),
3212 (Expr **)Args.release(),
3213 NumArgs,
3214 SourceLocation()));
3215 }
3216
Douglas Gregor85dabae2009-12-16 01:38:02 +00003217 if (SequenceKind == NoInitialization)
3218 return S.Owned((Expr *)0);
3219
Douglas Gregor1b303932009-12-22 15:35:07 +00003220 QualType DestType = Entity.getType().getNonReferenceType();
3221 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003222 // the same as Entity.getDecl()->getType() in cases involving type merging,
3223 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003224 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003225 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003226 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003227
Douglas Gregor85dabae2009-12-16 01:38:02 +00003228 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3229
3230 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3231
3232 // For initialization steps that start with a single initializer,
3233 // grab the only argument out the Args and place it into the "current"
3234 // initializer.
3235 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003236 case SK_ResolveAddressOfOverloadedFunction:
3237 case SK_CastDerivedToBaseRValue:
3238 case SK_CastDerivedToBaseLValue:
3239 case SK_BindReference:
3240 case SK_BindReferenceToTemporary:
3241 case SK_UserConversion:
3242 case SK_QualificationConversionLValue:
3243 case SK_QualificationConversionRValue:
3244 case SK_ConversionSequence:
3245 case SK_ListInitialization:
3246 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003247 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003248 assert(Args.size() == 1);
3249 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3250 if (CurInit.isInvalid())
3251 return S.ExprError();
3252 break;
3253
3254 case SK_ConstructorInitialization:
3255 case SK_ZeroInitialization:
3256 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003257 }
3258
3259 // Walk through the computed steps for the initialization sequence,
3260 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003261 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003262 for (step_iterator Step = step_begin(), StepEnd = step_end();
3263 Step != StepEnd; ++Step) {
3264 if (CurInit.isInvalid())
3265 return S.ExprError();
3266
3267 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003268 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003269
3270 switch (Step->Kind) {
3271 case SK_ResolveAddressOfOverloadedFunction:
3272 // Overload resolution determined which function invoke; update the
3273 // initializer to reflect that choice.
3274 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3275 break;
3276
3277 case SK_CastDerivedToBaseRValue:
3278 case SK_CastDerivedToBaseLValue: {
3279 // We have a derived-to-base cast that produces either an rvalue or an
3280 // lvalue. Perform that cast.
3281
3282 // Casts to inaccessible base classes are allowed with C-style casts.
3283 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3284 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3285 CurInitExpr->getLocStart(),
3286 CurInitExpr->getSourceRange(),
3287 IgnoreBaseAccess))
3288 return S.ExprError();
3289
3290 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3291 CastExpr::CK_DerivedToBase,
3292 (Expr*)CurInit.release(),
3293 Step->Kind == SK_CastDerivedToBaseLValue));
3294 break;
3295 }
3296
3297 case SK_BindReference:
3298 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3299 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3300 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003301 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003302 << BitField->getDeclName()
3303 << CurInitExpr->getSourceRange();
3304 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3305 return S.ExprError();
3306 }
3307
3308 // Reference binding does not have any corresponding ASTs.
3309
3310 // Check exception specifications
3311 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3312 return S.ExprError();
3313 break;
3314
3315 case SK_BindReferenceToTemporary:
3316 // Check exception specifications
3317 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3318 return S.ExprError();
3319
3320 // FIXME: At present, we have no AST to describe when we need to make a
3321 // temporary to bind a reference to. We should.
3322 break;
3323
3324 case SK_UserConversion: {
3325 // We have a user-defined conversion that invokes either a constructor
3326 // or a conversion function.
3327 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003328 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003329 if (CXXConstructorDecl *Constructor
3330 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3331 // Build a call to the selected constructor.
3332 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3333 SourceLocation Loc = CurInitExpr->getLocStart();
3334 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3335
3336 // Determine the arguments required to actually perform the constructor
3337 // call.
3338 if (S.CompleteConstructorCall(Constructor,
3339 Sema::MultiExprArg(S,
3340 (void **)&CurInitExpr,
3341 1),
3342 Loc, ConstructorArgs))
3343 return S.ExprError();
3344
3345 // Build the an expression that constructs a temporary.
3346 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3347 move_arg(ConstructorArgs));
3348 if (CurInit.isInvalid())
3349 return S.ExprError();
3350
3351 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003352 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3353 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3354 S.IsDerivedFrom(SourceType, Class))
3355 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003356 } else {
3357 // Build a call to the conversion function.
3358 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003359
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003360 // FIXME: Should we move this initialization into a separate
3361 // derived-to-base conversion? I believe the answer is "no", because
3362 // we don't want to turn off access control here for c-style casts.
3363 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3364 return S.ExprError();
3365
3366 // Do a little dance to make sure that CurInit has the proper
3367 // pointer.
3368 CurInit.release();
3369
3370 // Build the actual call to the conversion function.
3371 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3372 if (CurInit.isInvalid() || !CurInit.get())
3373 return S.ExprError();
3374
3375 CastKind = CastExpr::CK_UserDefinedConversion;
3376 }
3377
Douglas Gregore1314a62009-12-18 05:02:21 +00003378 if (shouldBindAsTemporary(Entity, IsCopy))
3379 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3380
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003381 CurInitExpr = CurInit.takeAs<Expr>();
3382 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3383 CastKind,
3384 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003385 false));
3386
3387 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003388 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003389 break;
3390 }
3391
3392 case SK_QualificationConversionLValue:
3393 case SK_QualificationConversionRValue:
3394 // Perform a qualification conversion; these can never go wrong.
3395 S.ImpCastExprToType(CurInitExpr, Step->Type,
3396 CastExpr::CK_NoOp,
3397 Step->Kind == SK_QualificationConversionLValue);
3398 CurInit.release();
3399 CurInit = S.Owned(CurInitExpr);
3400 break;
3401
3402 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003403 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003404 false, false, *Step->ICS))
3405 return S.ExprError();
3406
3407 CurInit.release();
3408 CurInit = S.Owned(CurInitExpr);
3409 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003410
3411 case SK_ListInitialization: {
3412 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3413 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003414 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003415 return S.ExprError();
3416
3417 CurInit.release();
3418 CurInit = S.Owned(InitList);
3419 break;
3420 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003421
3422 case SK_ConstructorInitialization: {
3423 CXXConstructorDecl *Constructor
3424 = cast<CXXConstructorDecl>(Step->Function);
3425
3426 // Build a call to the selected constructor.
3427 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3428 SourceLocation Loc = Kind.getLocation();
3429
3430 // Determine the arguments required to actually perform the constructor
3431 // call.
3432 if (S.CompleteConstructorCall(Constructor, move(Args),
3433 Loc, ConstructorArgs))
3434 return S.ExprError();
3435
3436 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003437 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003438 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003439 move_arg(ConstructorArgs),
3440 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003441 if (CurInit.isInvalid())
3442 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003443
3444 bool Elidable
3445 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3446 if (shouldBindAsTemporary(Entity, Elidable))
3447 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3448
3449 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003450 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003451 break;
3452 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003453
3454 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003455 step_iterator NextStep = Step;
3456 ++NextStep;
3457 if (NextStep != StepEnd &&
3458 NextStep->Kind == SK_ConstructorInitialization) {
3459 // The need for zero-initialization is recorded directly into
3460 // the call to the object's constructor within the next step.
3461 ConstructorInitRequiresZeroInit = true;
3462 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3463 S.getLangOptions().CPlusPlus &&
3464 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003465 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3466 Kind.getRange().getBegin(),
3467 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003468 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003469 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003470 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003471 break;
3472 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003473
3474 case SK_CAssignment: {
3475 QualType SourceType = CurInitExpr->getType();
3476 Sema::AssignConvertType ConvTy =
3477 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003478
3479 // If this is a call, allow conversion to a transparent union.
3480 if (ConvTy != Sema::Compatible &&
3481 Entity.getKind() == InitializedEntity::EK_Parameter &&
3482 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3483 == Sema::Compatible)
3484 ConvTy = Sema::Compatible;
3485
Douglas Gregore1314a62009-12-18 05:02:21 +00003486 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3487 Step->Type, SourceType,
3488 CurInitExpr, getAssignmentAction(Entity)))
3489 return S.ExprError();
3490
3491 CurInit.release();
3492 CurInit = S.Owned(CurInitExpr);
3493 break;
3494 }
Eli Friedman78275202009-12-19 08:11:05 +00003495
3496 case SK_StringInit: {
3497 QualType Ty = Step->Type;
3498 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3499 break;
3500 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003501 }
3502 }
3503
3504 return move(CurInit);
3505}
3506
3507//===----------------------------------------------------------------------===//
3508// Diagnose initialization failures
3509//===----------------------------------------------------------------------===//
3510bool InitializationSequence::Diagnose(Sema &S,
3511 const InitializedEntity &Entity,
3512 const InitializationKind &Kind,
3513 Expr **Args, unsigned NumArgs) {
3514 if (SequenceKind != FailedSequence)
3515 return false;
3516
Douglas Gregor1b303932009-12-22 15:35:07 +00003517 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003518 switch (Failure) {
3519 case FK_TooManyInitsForReference:
3520 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3521 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3522 break;
3523
3524 case FK_ArrayNeedsInitList:
3525 case FK_ArrayNeedsInitListOrStringLiteral:
3526 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3527 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3528 break;
3529
3530 case FK_AddressOfOverloadFailed:
3531 S.ResolveAddressOfOverloadedFunction(Args[0],
3532 DestType.getNonReferenceType(),
3533 true);
3534 break;
3535
3536 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003537 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003538 switch (FailedOverloadResult) {
3539 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003540 if (Failure == FK_UserConversionOverloadFailed)
3541 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3542 << Args[0]->getType() << DestType
3543 << Args[0]->getSourceRange();
3544 else
3545 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3546 << DestType << Args[0]->getType()
3547 << Args[0]->getSourceRange();
3548
John McCallad907772010-01-12 07:18:19 +00003549 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3550 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003551 break;
3552
3553 case OR_No_Viable_Function:
3554 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3555 << Args[0]->getType() << DestType.getNonReferenceType()
3556 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003557 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3558 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003559 break;
3560
3561 case OR_Deleted: {
3562 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3563 << Args[0]->getType() << DestType.getNonReferenceType()
3564 << Args[0]->getSourceRange();
3565 OverloadCandidateSet::iterator Best;
3566 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3567 Kind.getLocation(),
3568 Best);
3569 if (Ovl == OR_Deleted) {
3570 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3571 << Best->Function->isDeleted();
3572 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003573 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003574 }
3575 break;
3576 }
3577
3578 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003579 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003580 break;
3581 }
3582 break;
3583
3584 case FK_NonConstLValueReferenceBindingToTemporary:
3585 case FK_NonConstLValueReferenceBindingToUnrelated:
3586 S.Diag(Kind.getLocation(),
3587 Failure == FK_NonConstLValueReferenceBindingToTemporary
3588 ? diag::err_lvalue_reference_bind_to_temporary
3589 : diag::err_lvalue_reference_bind_to_unrelated)
3590 << DestType.getNonReferenceType()
3591 << Args[0]->getType()
3592 << Args[0]->getSourceRange();
3593 break;
3594
3595 case FK_RValueReferenceBindingToLValue:
3596 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3597 << Args[0]->getSourceRange();
3598 break;
3599
3600 case FK_ReferenceInitDropsQualifiers:
3601 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3602 << DestType.getNonReferenceType()
3603 << Args[0]->getType()
3604 << Args[0]->getSourceRange();
3605 break;
3606
3607 case FK_ReferenceInitFailed:
3608 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3609 << DestType.getNonReferenceType()
3610 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3611 << Args[0]->getType()
3612 << Args[0]->getSourceRange();
3613 break;
3614
3615 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003616 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3617 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003618 << DestType
3619 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3620 << Args[0]->getType()
3621 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003622 break;
3623
3624 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003625 SourceRange R;
3626
3627 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3628 R = SourceRange(InitList->getInit(1)->getLocStart(),
3629 InitList->getLocEnd());
3630 else
3631 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003632
3633 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003634 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003635 break;
3636 }
3637
3638 case FK_ReferenceBindingToInitList:
3639 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3640 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3641 break;
3642
3643 case FK_InitListBadDestinationType:
3644 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3645 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3646 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003647
3648 case FK_ConstructorOverloadFailed: {
3649 SourceRange ArgsRange;
3650 if (NumArgs)
3651 ArgsRange = SourceRange(Args[0]->getLocStart(),
3652 Args[NumArgs - 1]->getLocEnd());
3653
3654 // FIXME: Using "DestType" for the entity we're printing is probably
3655 // bad.
3656 switch (FailedOverloadResult) {
3657 case OR_Ambiguous:
3658 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3659 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003660 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003661 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003662 break;
3663
3664 case OR_No_Viable_Function:
3665 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3666 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003667 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3668 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003669 break;
3670
3671 case OR_Deleted: {
3672 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3673 << true << DestType << ArgsRange;
3674 OverloadCandidateSet::iterator Best;
3675 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3676 Kind.getLocation(),
3677 Best);
3678 if (Ovl == OR_Deleted) {
3679 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3680 << Best->Function->isDeleted();
3681 } else {
3682 llvm_unreachable("Inconsistent overload resolution?");
3683 }
3684 break;
3685 }
3686
3687 case OR_Success:
3688 llvm_unreachable("Conversion did not fail!");
3689 break;
3690 }
3691 break;
3692 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003693
3694 case FK_DefaultInitOfConst:
3695 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3696 << DestType;
3697 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003698 }
3699
3700 return true;
3701}
Douglas Gregore1314a62009-12-18 05:02:21 +00003702
3703//===----------------------------------------------------------------------===//
3704// Initialization helper functions
3705//===----------------------------------------------------------------------===//
3706Sema::OwningExprResult
3707Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3708 SourceLocation EqualLoc,
3709 OwningExprResult Init) {
3710 if (Init.isInvalid())
3711 return ExprError();
3712
3713 Expr *InitE = (Expr *)Init.get();
3714 assert(InitE && "No initialization expression?");
3715
3716 if (EqualLoc.isInvalid())
3717 EqualLoc = InitE->getLocStart();
3718
3719 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3720 EqualLoc);
3721 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3722 Init.release();
3723 return Seq.Perform(*this, Entity, Kind,
3724 MultiExprArg(*this, (void**)&InitE, 1));
3725}