blob: 7c150db5995b7f5772c0ef4eed4159e00b779b53 [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
Anders Carlssondbb25a32010-01-23 20:47:59 +0000205 void CheckImplicitInitList(const InitializedEntity *Entity,
206 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000207 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000208 unsigned &StructuredIndex,
209 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000210 void CheckExplicitInitList(const InitializedEntity *Entity,
211 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000212 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000213 unsigned &StructuredIndex,
214 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000215 void CheckListElementTypes(const InitializedEntity *Entity,
216 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000217 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000218 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000219 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000220 unsigned &StructuredIndex,
221 bool TopLevelObject = false);
Anders Carlssond0849252010-01-23 19:55:29 +0000222 void CheckSubElementType(const InitializedEntity *Entity,
223 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000224 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000225 InitListExpr *StructuredList,
226 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000227 void CheckScalarType(const InitializedEntity *Entity,
228 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000229 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000230 InitListExpr *StructuredList,
231 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000232 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000233 unsigned &Index,
234 InitListExpr *StructuredList,
235 unsigned &StructuredIndex);
Anders Carlssond0849252010-01-23 19:55:29 +0000236 void CheckVectorType(const InitializedEntity *Entity,
237 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex);
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000240 void CheckStructUnionTypes(const InitializedEntity *Entity,
241 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000242 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000244 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000245 unsigned &StructuredIndex,
246 bool TopLevelObject = false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000247 void CheckArrayType(const InitializedEntity *Entity,
248 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000249 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000250 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000251 InitListExpr *StructuredList,
252 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000253 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000254 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000255 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000256 RecordDecl::field_iterator *NextField,
257 llvm::APSInt *NextElementIndex,
258 unsigned &Index,
259 InitListExpr *StructuredList,
260 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000261 bool FinishSubobjectInit,
262 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000263 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
264 QualType CurrentObjectType,
265 InitListExpr *StructuredList,
266 unsigned StructuredIndex,
267 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000268 void UpdateStructuredListElement(InitListExpr *StructuredList,
269 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000270 Expr *expr);
271 int numArrayElements(QualType DeclType);
272 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000273
Douglas Gregor2bb07652009-12-22 00:05:34 +0000274 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
275 const InitializedEntity &ParentEntity,
276 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000277 void FillInValueInitializations(const InitializedEntity &Entity,
278 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000279public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000280 InitListChecker(Sema &S, const InitializedEntity &Entity,
281 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000282 bool HadError() { return hadError; }
283
284 // @brief Retrieves the fully-structured initializer list used for
285 // semantic analysis and code generation.
286 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
287};
Chris Lattner9ececce2009-02-24 22:48:58 +0000288} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000289
Douglas Gregor2bb07652009-12-22 00:05:34 +0000290void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
291 const InitializedEntity &ParentEntity,
292 InitListExpr *ILE,
293 bool &RequiresSecondPass) {
294 SourceLocation Loc = ILE->getSourceRange().getBegin();
295 unsigned NumInits = ILE->getNumInits();
296 InitializedEntity MemberEntity
297 = InitializedEntity::InitializeMember(Field, &ParentEntity);
298 if (Init >= NumInits || !ILE->getInit(Init)) {
299 // FIXME: We probably don't need to handle references
300 // specially here, since value-initialization of references is
301 // handled in InitializationSequence.
302 if (Field->getType()->isReferenceType()) {
303 // C++ [dcl.init.aggr]p9:
304 // If an incomplete or empty initializer-list leaves a
305 // member of reference type uninitialized, the program is
306 // ill-formed.
307 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
308 << Field->getType()
309 << ILE->getSyntacticForm()->getSourceRange();
310 SemaRef.Diag(Field->getLocation(),
311 diag::note_uninit_reference_member);
312 hadError = true;
313 return;
314 }
315
316 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
317 true);
318 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
319 if (!InitSeq) {
320 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
321 hadError = true;
322 return;
323 }
324
325 Sema::OwningExprResult MemberInit
326 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
327 Sema::MultiExprArg(SemaRef, 0, 0));
328 if (MemberInit.isInvalid()) {
329 hadError = true;
330 return;
331 }
332
333 if (hadError) {
334 // Do nothing
335 } else if (Init < NumInits) {
336 ILE->setInit(Init, MemberInit.takeAs<Expr>());
337 } else if (InitSeq.getKind()
338 == InitializationSequence::ConstructorInitialization) {
339 // Value-initialization requires a constructor call, so
340 // extend the initializer list to include the constructor
341 // call and make a note that we'll need to take another pass
342 // through the initializer list.
343 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
344 RequiresSecondPass = true;
345 }
346 } else if (InitListExpr *InnerILE
347 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
348 FillInValueInitializations(MemberEntity, InnerILE,
349 RequiresSecondPass);
350}
351
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000352/// Recursively replaces NULL values within the given initializer list
353/// with expressions that perform value-initialization of the
354/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000355void
356InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
357 InitListExpr *ILE,
358 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000359 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000360 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000361 SourceLocation Loc = ILE->getSourceRange().getBegin();
362 if (ILE->getSyntacticForm())
363 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000364
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000365 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000366 if (RType->getDecl()->isUnion() &&
367 ILE->getInitializedFieldInUnion())
368 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
369 Entity, ILE, RequiresSecondPass);
370 else {
371 unsigned Init = 0;
372 for (RecordDecl::field_iterator
373 Field = RType->getDecl()->field_begin(),
374 FieldEnd = RType->getDecl()->field_end();
375 Field != FieldEnd; ++Field) {
376 if (Field->isUnnamedBitfield())
377 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000378
Douglas Gregor2bb07652009-12-22 00:05:34 +0000379 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000380 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000381
382 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
383 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000384 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000385
Douglas Gregor2bb07652009-12-22 00:05:34 +0000386 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000387
Douglas Gregor2bb07652009-12-22 00:05:34 +0000388 // Only look at the first initialization of a union.
389 if (RType->getDecl()->isUnion())
390 break;
391 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000392 }
393
394 return;
Mike Stump11289f42009-09-09 15:08:12 +0000395 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000396
397 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000398
Douglas Gregor723796a2009-12-16 06:35:08 +0000399 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000400 unsigned NumInits = ILE->getNumInits();
401 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000402 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000403 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000404 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
405 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
407 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000408 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000409 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000410 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000411 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
412 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000413 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000414 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000415
Douglas Gregor723796a2009-12-16 06:35:08 +0000416
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000417 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000418 if (hadError)
419 return;
420
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000421 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
422 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000423 ElementEntity.setElementIndex(Init);
424
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000425 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000426 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
427 true);
428 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
429 if (!InitSeq) {
430 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000431 hadError = true;
432 return;
433 }
434
Douglas Gregor723796a2009-12-16 06:35:08 +0000435 Sema::OwningExprResult ElementInit
436 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
437 Sema::MultiExprArg(SemaRef, 0, 0));
438 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000439 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000440 return;
441 }
442
443 if (hadError) {
444 // Do nothing
445 } else if (Init < NumInits) {
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
447 } else if (InitSeq.getKind()
448 == InitializationSequence::ConstructorInitialization) {
449 // Value-initialization requires a constructor call, so
450 // extend the initializer list to include the constructor
451 // call and make a note that we'll need to take another pass
452 // through the initializer list.
453 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
454 RequiresSecondPass = true;
455 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000456 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000457 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
458 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000459 }
460}
461
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000462
Douglas Gregor723796a2009-12-16 06:35:08 +0000463InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
464 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000465 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000466 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000467
Eli Friedman23a9e312008-05-19 19:16:24 +0000468 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000469 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000470 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000471 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000472 CheckExplicitInitList(&Entity, IL, T, newIndex,
473 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000474 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000475
Douglas Gregor723796a2009-12-16 06:35:08 +0000476 if (!hadError) {
477 bool RequiresSecondPass = false;
478 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000479 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000480 FillInValueInitializations(Entity, FullyStructuredList,
481 RequiresSecondPass);
482 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000483}
484
485int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000486 // FIXME: use a proper constant
487 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000488 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000489 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000490 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
491 }
492 return maxElements;
493}
494
495int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000496 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000497 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000498 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000499 Field = structDecl->field_begin(),
500 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000501 Field != FieldEnd; ++Field) {
502 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
503 ++InitializableMembers;
504 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000505 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000506 return std::min(InitializableMembers, 1);
507 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000508}
509
Anders Carlssondbb25a32010-01-23 20:47:59 +0000510void InitListChecker::CheckImplicitInitList(const InitializedEntity *Entity,
511 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000512 QualType T, unsigned &Index,
513 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000514 unsigned &StructuredIndex,
515 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000516 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Steve Narofff8ecff22008-05-01 22:18:59 +0000518 if (T->isArrayType())
519 maxElements = numArrayElements(T);
520 else if (T->isStructureType() || T->isUnionType())
521 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000522 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000523 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000524 else
525 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000526
Eli Friedmane0f832b2008-05-25 13:49:22 +0000527 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000528 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000529 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000530 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000531 hadError = true;
532 return;
533 }
534
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000535 // Build a structured initializer list corresponding to this subobject.
536 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000537 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
538 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000539 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
540 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000541 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000542
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000543 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000544 unsigned StartIndex = Index;
Anders Carlssondbb25a32010-01-23 20:47:59 +0000545 CheckListElementTypes(Entity, ParentIList, T,
546 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000547 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000548 StructuredSubobjectInitIndex,
549 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000550 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000551 StructuredSubobjectInitList->setType(T);
552
Douglas Gregor5741efb2009-03-01 17:12:46 +0000553 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000554 // range corresponds with the end of the last initializer it used.
555 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000556 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000557 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
558 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
559 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000560}
561
Anders Carlssond0849252010-01-23 19:55:29 +0000562void InitListChecker::CheckExplicitInitList(const InitializedEntity *Entity,
563 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000564 unsigned &Index,
565 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000566 unsigned &StructuredIndex,
567 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000568 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000569 SyntacticToSemantic[IList] = StructuredList;
570 StructuredList->setSyntacticForm(IList);
Anders Carlssond0849252010-01-23 19:55:29 +0000571 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
572 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000573 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000574 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000575 if (hadError)
576 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000577
Eli Friedman85f54972008-05-25 13:22:35 +0000578 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000579 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000580 if (StructuredIndex == 1 &&
581 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000582 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000583 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000584 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000585 hadError = true;
586 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000587 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000588 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000589 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000590 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000591 // Don't complain for incomplete types, since we'll get an error
592 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000593 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000594 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 CurrentObjectType->isArrayType()? 0 :
596 CurrentObjectType->isVectorType()? 1 :
597 CurrentObjectType->isScalarType()? 2 :
598 CurrentObjectType->isUnionType()? 3 :
599 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000600
601 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000602 if (SemaRef.getLangOptions().CPlusPlus) {
603 DK = diag::err_excess_initializers;
604 hadError = true;
605 }
Nate Begeman425038c2009-07-07 21:53:06 +0000606 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
607 DK = diag::err_excess_initializers;
608 hadError = true;
609 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000610
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000612 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000613 }
614 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000615
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000616 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000617 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000618 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000619 << CodeModificationHint::CreateRemoval(IList->getLocStart())
620 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000621}
622
Anders Carlssond0849252010-01-23 19:55:29 +0000623void InitListChecker::CheckListElementTypes(const InitializedEntity *Entity,
624 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000625 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000626 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000627 unsigned &Index,
628 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000629 unsigned &StructuredIndex,
630 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000631 if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000632 CheckScalarType(Entity, IList, DeclType, Index,
633 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000634 } else if (DeclType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000635 CheckVectorType(Entity, IList, DeclType, Index,
636 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000637 } else if (DeclType->isAggregateType()) {
638 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000639 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000640 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000641 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000642 StructuredList, StructuredIndex,
643 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000644 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000645 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000646 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000647 false);
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000648 CheckArrayType(Entity, IList, DeclType, Zero,
649 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000650 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000651 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000652 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000653 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
654 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000656 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000657 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000658 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000659 } else if (DeclType->isRecordType()) {
660 // C++ [dcl.init]p14:
661 // [...] If the class is an aggregate (8.5.1), and the initializer
662 // is a brace-enclosed list, see 8.5.1.
663 //
664 // Note: 8.5.1 is handled below; here, we diagnose the case where
665 // we have an initializer list and a destination type that is not
666 // an aggregate.
667 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000668 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000669 << DeclType << IList->getSourceRange();
670 hadError = true;
671 } else if (DeclType->isReferenceType()) {
672 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000673 } else {
674 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000675 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000676 assert(0 && "Unsupported initializer type");
677 }
678}
679
Anders Carlssond0849252010-01-23 19:55:29 +0000680void InitListChecker::CheckSubElementType(const InitializedEntity *Entity,
681 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000682 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000683 unsigned &Index,
684 InitListExpr *StructuredList,
685 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000686 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000687 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
688 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000689 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000690 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000691 = getStructuredSubobjectInit(IList, Index, ElemType,
692 StructuredList, StructuredIndex,
693 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000694 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000695 newStructuredList, newStructuredIndex);
696 ++StructuredIndex;
697 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000698 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
699 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000700 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000702 } else if (ElemType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000703 CheckScalarType(Entity, IList, ElemType, Index,
704 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000705 } else if (ElemType->isReferenceType()) {
706 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000707 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000708 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000709 // C++ [dcl.init.aggr]p12:
710 // All implicit type conversions (clause 4) are considered when
711 // initializing the aggregate member with an ini- tializer from
712 // an initializer-list. If the initializer can initialize a
713 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000714 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000715 = SemaRef.TryCopyInitialization(expr, ElemType,
716 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000717 /*ForceRValue=*/false,
718 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000719
John McCall0d1da222010-01-12 00:44:57 +0000720 if (!ICS.isBad()) {
Mike Stump11289f42009-09-09 15:08:12 +0000721 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000722 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000723 hadError = true;
724 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
725 ++Index;
726 return;
727 }
728
729 // Fall through for subaggregate initialization
730 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000731 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000732 //
733 // The initializer for a structure or union object that has
734 // automatic storage duration shall be either an initializer
735 // list as described below, or a single expression that has
736 // compatible structure or union type. In the latter case, the
737 // initial value of the object, including unnamed members, is
738 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000739 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000740 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000741 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
742 ++Index;
743 return;
744 }
745
746 // Fall through for subaggregate initialization
747 }
748
749 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000750 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000751 // [...] Otherwise, if the member is itself a non-empty
752 // subaggregate, brace elision is assumed and the initializer is
753 // considered for the initialization of the first member of
754 // the subaggregate.
755 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlssondbb25a32010-01-23 20:47:59 +0000756 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000757 StructuredIndex);
758 ++StructuredIndex;
759 } else {
760 // We cannot initialize this element, so let
761 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000762 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000763 hadError = true;
764 ++Index;
765 ++StructuredIndex;
766 }
767 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000768}
769
Anders Carlssond0849252010-01-23 19:55:29 +0000770void InitListChecker::CheckScalarType(const InitializedEntity *Entity,
771 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000772 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000773 InitListExpr *StructuredList,
774 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000775 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000776 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000777 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000778 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000779 diag::err_many_braces_around_scalar_init)
780 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000781 hadError = true;
782 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000783 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000784 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000785 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000786 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000787 diag::err_designator_for_scalar_init)
788 << DeclType << expr->getSourceRange();
789 hadError = true;
790 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000791 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000792 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000793 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000794
Anders Carlsson26d05642010-01-23 18:35:41 +0000795 Sema::OwningExprResult Result =
Anders Carlssond0849252010-01-23 19:55:29 +0000796 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlsson26d05642010-01-23 18:35:41 +0000797
798 Expr *ResultExpr;
799
800 if (Result.isInvalid())
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000801 hadError = true; // types weren't compatible.
Anders Carlsson26d05642010-01-23 18:35:41 +0000802 else {
803 ResultExpr = Result.takeAs<Expr>();
804
805 if (ResultExpr != expr) {
806 // The type was promoted, update initializer list.
807 IList->setInit(Index, ResultExpr);
808 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000809 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000810 if (hadError)
811 ++StructuredIndex;
812 else
Anders Carlsson26d05642010-01-23 18:35:41 +0000813 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000814 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000815 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000816 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000817 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000818 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000819 ++Index;
820 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000821 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000822 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000823}
824
Douglas Gregord14247a2009-01-30 22:09:00 +0000825void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
826 unsigned &Index,
827 InitListExpr *StructuredList,
828 unsigned &StructuredIndex) {
829 if (Index < IList->getNumInits()) {
830 Expr *expr = IList->getInit(Index);
831 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000832 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000833 << DeclType << IList->getSourceRange();
834 hadError = true;
835 ++Index;
836 ++StructuredIndex;
837 return;
Mike Stump11289f42009-09-09 15:08:12 +0000838 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000839
840 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000841 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000842 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000843 /*SuppressUserConversions=*/false,
844 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000845 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000846 hadError = true;
847 else if (savExpr != expr) {
848 // The type was promoted, update initializer list.
849 IList->setInit(Index, expr);
850 }
851 if (hadError)
852 ++StructuredIndex;
853 else
854 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
855 ++Index;
856 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000857 // FIXME: It would be wonderful if we could point at the actual member. In
858 // general, it would be useful to pass location information down the stack,
859 // so that we know the location (or decl) of the "current object" being
860 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000861 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000862 diag::err_init_reference_member_uninitialized)
863 << DeclType
864 << IList->getSourceRange();
865 hadError = true;
866 ++Index;
867 ++StructuredIndex;
868 return;
869 }
870}
871
Anders Carlssond0849252010-01-23 19:55:29 +0000872void InitListChecker::CheckVectorType(const InitializedEntity *Entity,
873 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000874 unsigned &Index,
875 InitListExpr *StructuredList,
876 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000877 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000878 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000879 unsigned maxElements = VT->getNumElements();
880 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000881 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000882
Nate Begeman5ec4b312009-08-10 23:49:36 +0000883 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlssond0849252010-01-23 19:55:29 +0000884 // FIXME: Once we know Entity is never null we can remove this check,
885 // as well as the else block.
886 if (Entity) {
887 InitializedEntity ElementEntity =
888 InitializedEntity::InitializeElement(SemaRef.Context, 0, *Entity);
889
890 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
891 // Don't attempt to go past the end of the init list
892 if (Index >= IList->getNumInits())
893 break;
894
895 ElementEntity.setElementIndex(Index);
896 CheckSubElementType(&ElementEntity, IList, elementType, Index,
897 StructuredList, StructuredIndex);
898 }
899 } else {
900 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
901 // Don't attempt to go past the end of the init list
902 if (Index >= IList->getNumInits())
903 break;
904
905 CheckSubElementType(0, IList, elementType, Index,
906 StructuredList, StructuredIndex);
907 }
908 }
Nate Begeman5ec4b312009-08-10 23:49:36 +0000909 } else {
910 // OpenCL initializers allows vectors to be constructed from vectors.
911 for (unsigned i = 0; i < maxElements; ++i) {
912 // Don't attempt to go past the end of the init list
913 if (Index >= IList->getNumInits())
914 break;
915 QualType IType = IList->getInit(Index)->getType();
916 if (!IType->isVectorType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000917 CheckSubElementType(0, IList, elementType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000918 StructuredList, StructuredIndex);
919 ++numEltsInit;
920 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000921 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000922 unsigned numIElts = IVT->getNumElements();
923 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
924 numIElts);
Anders Carlssond0849252010-01-23 19:55:29 +0000925 CheckSubElementType(0, IList, VecType, Index,
Nate Begeman5ec4b312009-08-10 23:49:36 +0000926 StructuredList, StructuredIndex);
927 numEltsInit += numIElts;
928 }
929 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Nate Begeman5ec4b312009-08-10 23:49:36 +0000932 // OpenCL & AltiVec require all elements to be initialized.
933 if (numEltsInit != maxElements)
934 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
935 SemaRef.Diag(IList->getSourceRange().getBegin(),
936 diag::err_vector_incorrect_num_initializers)
937 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000938 }
939}
940
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000941void InitListChecker::CheckArrayType(const InitializedEntity *Entity,
942 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000943 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000944 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000945 unsigned &Index,
946 InitListExpr *StructuredList,
947 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000948 // Check for the special-case of initializing an array with a string.
949 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000950 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
951 SemaRef.Context)) {
952 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000953 // We place the string literal directly into the resulting
954 // initializer list. This is the only place where the structure
955 // of the structured initializer list doesn't match exactly,
956 // because doing so would involve allocating one character
957 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000958 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000959 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000960 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000961 return;
962 }
963 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000964 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000965 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000966 // Check for VLAs; in standard C it would be possible to check this
967 // earlier, but I don't know where clang accepts VLAs (gcc accepts
968 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000969 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000970 diag::err_variable_object_no_init)
971 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000972 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000973 ++Index;
974 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000975 return;
976 }
977
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000978 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000979 llvm::APSInt maxElements(elementIndex.getBitWidth(),
980 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000981 bool maxElementsKnown = false;
982 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000983 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000984 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000985 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000986 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000987 maxElementsKnown = true;
988 }
989
Chris Lattnerb0912a52009-02-24 22:50:46 +0000990 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000991 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000992 while (Index < IList->getNumInits()) {
993 Expr *Init = IList->getInit(Index);
994 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000995 // If we're not the subobject that matches up with the '{' for
996 // the designator, we shouldn't be handling the
997 // designator. Return immediately.
998 if (!SubobjectIsDesignatorContext)
999 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001000
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001001 // Handle this designated initializer. elementIndex will be
1002 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +00001003 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001004 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001005 StructuredList, StructuredIndex, true,
1006 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001007 hadError = true;
1008 continue;
1009 }
1010
Douglas Gregor033d1252009-01-23 16:54:12 +00001011 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1012 maxElements.extend(elementIndex.getBitWidth());
1013 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1014 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001015 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001016
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001017 // If the array is of incomplete type, keep track of the number of
1018 // elements in the initializer.
1019 if (!maxElementsKnown && elementIndex > maxElements)
1020 maxElements = elementIndex;
1021
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001022 continue;
1023 }
1024
1025 // If we know the maximum number of elements, and we've already
1026 // hit it, stop consuming elements in the initializer list.
1027 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001028 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001029
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001030 // FIXME: Once we know that Entity is not null, we can remove this check,
1031 // and the else block.
1032 if (Entity) {
1033 InitializedEntity ElementEntity =
1034 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1035 *Entity);
1036 // Check this element.
1037 CheckSubElementType(&ElementEntity, IList, elementType, Index,
1038 StructuredList, StructuredIndex);
1039 } else {
1040 // Check this element.
1041 CheckSubElementType(0, IList, elementType, Index,
1042 StructuredList, StructuredIndex);
1043 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001044 ++elementIndex;
1045
1046 // If the array is of incomplete type, keep track of the number of
1047 // elements in the initializer.
1048 if (!maxElementsKnown && elementIndex > maxElements)
1049 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001050 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001051 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001052 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001053 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001054 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001055 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001056 // Sizing an array implicitly to zero is not allowed by ISO C,
1057 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001058 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001059 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001060 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001061
Mike Stump11289f42009-09-09 15:08:12 +00001062 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001063 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001064 }
1065}
1066
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001067void InitListChecker::CheckStructUnionTypes(const InitializedEntity *Entity,
1068 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001069 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001070 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001071 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001072 unsigned &Index,
1073 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001074 unsigned &StructuredIndex,
1075 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001076 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001077
Eli Friedman23a9e312008-05-19 19:16:24 +00001078 // If the record is invalid, some of it's members are invalid. To avoid
1079 // confusion, we forgo checking the intializer for the entire record.
1080 if (structDecl->isInvalidDecl()) {
1081 hadError = true;
1082 return;
Mike Stump11289f42009-09-09 15:08:12 +00001083 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001084
1085 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1086 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001087 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001088 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001089 Field != FieldEnd; ++Field) {
1090 if (Field->getDeclName()) {
1091 StructuredList->setInitializedFieldInUnion(*Field);
1092 break;
1093 }
1094 }
1095 return;
1096 }
1097
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001098 // If structDecl is a forward declaration, this loop won't do
1099 // anything except look at designated initializers; That's okay,
1100 // because an error should get printed out elsewhere. It might be
1101 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001102 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001103 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001104 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001105 while (Index < IList->getNumInits()) {
1106 Expr *Init = IList->getInit(Index);
1107
1108 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001109 // If we're not the subobject that matches up with the '{' for
1110 // the designator, we shouldn't be handling the
1111 // designator. Return immediately.
1112 if (!SubobjectIsDesignatorContext)
1113 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001114
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001115 // Handle this designated initializer. Field will be updated to
1116 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001117 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001118 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001119 StructuredList, StructuredIndex,
1120 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001121 hadError = true;
1122
Douglas Gregora9add4e2009-02-12 19:00:39 +00001123 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001124 continue;
1125 }
1126
1127 if (Field == FieldEnd) {
1128 // We've run out of fields. We're done.
1129 break;
1130 }
1131
Douglas Gregora9add4e2009-02-12 19:00:39 +00001132 // We've already initialized a member of a union. We're done.
1133 if (InitializedSomething && DeclType->isUnionType())
1134 break;
1135
Douglas Gregor91f84212008-12-11 16:49:14 +00001136 // If we've hit the flexible array member at the end, we're done.
1137 if (Field->getType()->isIncompleteArrayType())
1138 break;
1139
Douglas Gregor51695702009-01-29 16:53:55 +00001140 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001141 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001142 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001143 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001144 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001145
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001146 // FIXME: Once we know Entity is not null, we can get rid of the check
1147 // and the else block.
1148 if (Entity) {
1149 InitializedEntity MemberEntity =
1150 InitializedEntity::InitializeMember(*Field, Entity);
1151 CheckSubElementType(&MemberEntity, IList, Field->getType(), Index,
1152 StructuredList, StructuredIndex);
1153 } else {
1154 CheckSubElementType(0, IList, Field->getType(), Index,
1155 StructuredList, StructuredIndex);
1156 }
Douglas Gregora9add4e2009-02-12 19:00:39 +00001157 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001158
1159 if (DeclType->isUnionType()) {
1160 // Initialize the first field within the union.
1161 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001162 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001163
1164 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001165 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001166
Mike Stump11289f42009-09-09 15:08:12 +00001167 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001168 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001169 return;
1170
1171 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001172 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001173 (!isa<InitListExpr>(IList->getInit(Index)) ||
1174 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001175 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001176 diag::err_flexible_array_init_nonempty)
1177 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001178 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001179 << *Field;
1180 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001181 ++Index;
1182 return;
1183 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001184 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001185 diag::ext_flexible_array_init)
1186 << IList->getInit(Index)->getSourceRange().getBegin();
1187 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1188 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001189 }
1190
Anders Carlssondbb25a32010-01-23 20:47:59 +00001191 // FIXME: Once we know Entity is not null, we can get rid of the check
1192 // and the else block.
1193 if (Entity) {
1194 InitializedEntity MemberEntity =
1195 InitializedEntity::InitializeMember(*Field, Entity);
1196
1197 if (isa<InitListExpr>(IList->getInit(Index)))
1198 CheckSubElementType(&MemberEntity, IList, Field->getType(), Index,
1199 StructuredList, StructuredIndex);
1200 else
1201 CheckImplicitInitList(&MemberEntity, IList, Field->getType(), Index,
1202 StructuredList, StructuredIndex);
1203 } else {
1204 if (isa<InitListExpr>(IList->getInit(Index)))
1205 CheckSubElementType(0, IList, Field->getType(), Index,
1206 StructuredList, StructuredIndex);
1207 else
1208 CheckImplicitInitList(0, IList, Field->getType(), Index,
1209 StructuredList, StructuredIndex);
1210 }
Steve Narofff8ecff22008-05-01 22:18:59 +00001211}
Steve Narofff8ecff22008-05-01 22:18:59 +00001212
Douglas Gregord5846a12009-04-15 06:41:24 +00001213/// \brief Expand a field designator that refers to a member of an
1214/// anonymous struct or union into a series of field designators that
1215/// refers to the field within the appropriate subobject.
1216///
1217/// Field/FieldIndex will be updated to point to the (new)
1218/// currently-designated field.
1219static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001220 DesignatedInitExpr *DIE,
1221 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001222 FieldDecl *Field,
1223 RecordDecl::field_iterator &FieldIter,
1224 unsigned &FieldIndex) {
1225 typedef DesignatedInitExpr::Designator Designator;
1226
1227 // Build the path from the current object to the member of the
1228 // anonymous struct/union (backwards).
1229 llvm::SmallVector<FieldDecl *, 4> Path;
1230 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001231
Douglas Gregord5846a12009-04-15 06:41:24 +00001232 // Build the replacement designators.
1233 llvm::SmallVector<Designator, 4> Replacements;
1234 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1235 FI = Path.rbegin(), FIEnd = Path.rend();
1236 FI != FIEnd; ++FI) {
1237 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001238 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001239 DIE->getDesignator(DesigIdx)->getDotLoc(),
1240 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1241 else
1242 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1243 SourceLocation()));
1244 Replacements.back().setField(*FI);
1245 }
1246
1247 // Expand the current designator into the set of replacement
1248 // designators, so we have a full subobject path down to where the
1249 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001250 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001251 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001252
Douglas Gregord5846a12009-04-15 06:41:24 +00001253 // Update FieldIter/FieldIndex;
1254 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001255 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001256 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001257 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001258 FieldIter != FEnd; ++FieldIter) {
1259 if (FieldIter->isUnnamedBitfield())
1260 continue;
1261
1262 if (*FieldIter == Path.back())
1263 return;
1264
1265 ++FieldIndex;
1266 }
1267
1268 assert(false && "Unable to find anonymous struct/union field");
1269}
1270
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001271/// @brief Check the well-formedness of a C99 designated initializer.
1272///
1273/// Determines whether the designated initializer @p DIE, which
1274/// resides at the given @p Index within the initializer list @p
1275/// IList, is well-formed for a current object of type @p DeclType
1276/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001277/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001278/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001279///
1280/// @param IList The initializer list in which this designated
1281/// initializer occurs.
1282///
Douglas Gregora5324162009-04-15 04:56:10 +00001283/// @param DIE The designated initializer expression.
1284///
1285/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001286///
1287/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1288/// into which the designation in @p DIE should refer.
1289///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001290/// @param NextField If non-NULL and the first designator in @p DIE is
1291/// a field, this will be set to the field declaration corresponding
1292/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001293///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001294/// @param NextElementIndex If non-NULL and the first designator in @p
1295/// DIE is an array designator or GNU array-range designator, this
1296/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001297///
1298/// @param Index Index into @p IList where the designated initializer
1299/// @p DIE occurs.
1300///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001301/// @param StructuredList The initializer list expression that
1302/// describes all of the subobject initializers in the order they'll
1303/// actually be initialized.
1304///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001305/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001306bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001307InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001308 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001309 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001310 QualType &CurrentObjectType,
1311 RecordDecl::field_iterator *NextField,
1312 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001313 unsigned &Index,
1314 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001315 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001316 bool FinishSubobjectInit,
1317 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001318 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001319 // Check the actual initialization for the designated object type.
1320 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001321
1322 // Temporarily remove the designator expression from the
1323 // initializer list that the child calls see, so that we don't try
1324 // to re-process the designator.
1325 unsigned OldIndex = Index;
1326 IList->setInit(OldIndex, DIE->getInit());
1327
Anders Carlssond0849252010-01-23 19:55:29 +00001328 CheckSubElementType(0, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001329 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001330
1331 // Restore the designated initializer expression in the syntactic
1332 // form of the initializer list.
1333 if (IList->getInit(OldIndex) != DIE->getInit())
1334 DIE->setInit(IList->getInit(OldIndex));
1335 IList->setInit(OldIndex, DIE);
1336
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001337 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001338 }
1339
Douglas Gregora5324162009-04-15 04:56:10 +00001340 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001341 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001342 "Need a non-designated initializer list to start from");
1343
Douglas Gregora5324162009-04-15 04:56:10 +00001344 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001345 // Determine the structural initializer list that corresponds to the
1346 // current subobject.
1347 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001348 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001349 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001350 SourceRange(D->getStartLocation(),
1351 DIE->getSourceRange().getEnd()));
1352 assert(StructuredList && "Expected a structured initializer list");
1353
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001354 if (D->isFieldDesignator()) {
1355 // C99 6.7.8p7:
1356 //
1357 // If a designator has the form
1358 //
1359 // . identifier
1360 //
1361 // then the current object (defined below) shall have
1362 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001363 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001364 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001365 if (!RT) {
1366 SourceLocation Loc = D->getDotLoc();
1367 if (Loc.isInvalid())
1368 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001369 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1370 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001371 ++Index;
1372 return true;
1373 }
1374
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001375 // Note: we perform a linear search of the fields here, despite
1376 // the fact that we have a faster lookup method, because we always
1377 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001378 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001379 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001380 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001381 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001382 Field = RT->getDecl()->field_begin(),
1383 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001384 for (; Field != FieldEnd; ++Field) {
1385 if (Field->isUnnamedBitfield())
1386 continue;
1387
Douglas Gregord5846a12009-04-15 06:41:24 +00001388 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001389 break;
1390
1391 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001392 }
1393
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001395 // There was no normal field in the struct with the designated
1396 // name. Perform another lookup for this name, which may find
1397 // something that we can't designate (e.g., a member function),
1398 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001399 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001400 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001401 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001402 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001403 // Name lookup didn't find anything. Determine whether this
1404 // was a typo for another field name.
1405 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1406 Sema::LookupMemberName);
1407 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1408 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1409 ReplacementField->getDeclContext()->getLookupContext()
1410 ->Equals(RT->getDecl())) {
1411 SemaRef.Diag(D->getFieldLoc(),
1412 diag::err_field_designator_unknown_suggest)
1413 << FieldName << CurrentObjectType << R.getLookupName()
1414 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1415 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001416 SemaRef.Diag(ReplacementField->getLocation(),
1417 diag::note_previous_decl)
1418 << ReplacementField->getDeclName();
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001419 } else {
1420 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1421 << FieldName << CurrentObjectType;
1422 ++Index;
1423 return true;
1424 }
1425 } else if (!KnownField) {
1426 // Determine whether we found a field at all.
1427 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1428 }
1429
1430 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001431 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001432 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001433 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001434 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001435 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001436 ++Index;
1437 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001438 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001439
1440 if (!KnownField &&
1441 cast<RecordDecl>((ReplacementField)->getDeclContext())
1442 ->isAnonymousStructOrUnion()) {
1443 // Handle an field designator that refers to a member of an
1444 // anonymous struct or union.
1445 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1446 ReplacementField,
1447 Field, FieldIndex);
1448 D = DIE->getDesignator(DesigIdx);
1449 } else if (!KnownField) {
1450 // The replacement field comes from typo correction; find it
1451 // in the list of fields.
1452 FieldIndex = 0;
1453 Field = RT->getDecl()->field_begin();
1454 for (; Field != FieldEnd; ++Field) {
1455 if (Field->isUnnamedBitfield())
1456 continue;
1457
1458 if (ReplacementField == *Field ||
1459 Field->getIdentifier() == ReplacementField->getIdentifier())
1460 break;
1461
1462 ++FieldIndex;
1463 }
1464 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001465 } else if (!KnownField &&
1466 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001467 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001468 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1469 Field, FieldIndex);
1470 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001471 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001472
1473 // All of the fields of a union are located at the same place in
1474 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001475 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001476 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001477 StructuredList->setInitializedFieldInUnion(*Field);
1478 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001479
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001480 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001481 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001482
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001483 // Make sure that our non-designated initializer list has space
1484 // for a subobject corresponding to this field.
1485 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001486 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001487
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001488 // This designator names a flexible array member.
1489 if (Field->getType()->isIncompleteArrayType()) {
1490 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001491 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001492 // We can't designate an object within the flexible array
1493 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001494 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001495 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001496 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001497 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001498 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001499 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001500 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001501 << *Field;
1502 Invalid = true;
1503 }
1504
1505 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1506 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001507 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001508 diag::err_flexible_array_init_needs_braces)
1509 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001510 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001511 << *Field;
1512 Invalid = true;
1513 }
1514
1515 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001516 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001517 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001518 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001519 diag::err_flexible_array_init_nonempty)
1520 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001521 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001522 << *Field;
1523 Invalid = true;
1524 }
1525
1526 if (Invalid) {
1527 ++Index;
1528 return true;
1529 }
1530
1531 // Initialize the array.
1532 bool prevHadError = hadError;
1533 unsigned newStructuredIndex = FieldIndex;
1534 unsigned OldIndex = Index;
1535 IList->setInit(Index, DIE->getInit());
Anders Carlssond0849252010-01-23 19:55:29 +00001536 CheckSubElementType(0, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001537 StructuredList, newStructuredIndex);
1538 IList->setInit(OldIndex, DIE);
1539 if (hadError && !prevHadError) {
1540 ++Field;
1541 ++FieldIndex;
1542 if (NextField)
1543 *NextField = Field;
1544 StructuredIndex = FieldIndex;
1545 return true;
1546 }
1547 } else {
1548 // Recurse to check later designated subobjects.
1549 QualType FieldType = (*Field)->getType();
1550 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001551 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1552 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001553 true, false))
1554 return true;
1555 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001556
1557 // Find the position of the next field to be initialized in this
1558 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001559 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001560 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001561
1562 // If this the first designator, our caller will continue checking
1563 // the rest of this struct/class/union subobject.
1564 if (IsFirstDesignator) {
1565 if (NextField)
1566 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001567 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001568 return false;
1569 }
1570
Douglas Gregor17bd0942009-01-28 23:36:17 +00001571 if (!FinishSubobjectInit)
1572 return false;
1573
Douglas Gregord5846a12009-04-15 06:41:24 +00001574 // We've already initialized something in the union; we're done.
1575 if (RT->getDecl()->isUnion())
1576 return hadError;
1577
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578 // Check the remaining fields within this class/struct/union subobject.
1579 bool prevHadError = hadError;
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001580
1581 CheckStructUnionTypes(0, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001582 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001583 return hadError && !prevHadError;
1584 }
1585
1586 // C99 6.7.8p6:
1587 //
1588 // If a designator has the form
1589 //
1590 // [ constant-expression ]
1591 //
1592 // then the current object (defined below) shall have array
1593 // type and the expression shall be an integer constant
1594 // expression. If the array is of unknown size, any
1595 // nonnegative value is valid.
1596 //
1597 // Additionally, cope with the GNU extension that permits
1598 // designators of the form
1599 //
1600 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001601 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001602 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001603 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001604 << CurrentObjectType;
1605 ++Index;
1606 return true;
1607 }
1608
1609 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001610 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1611 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001612 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001613 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001614 DesignatedEndIndex = DesignatedStartIndex;
1615 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001616 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001617
Mike Stump11289f42009-09-09 15:08:12 +00001618
1619 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001620 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001621 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001622 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001623 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001624
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001625 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001626 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001627 }
1628
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001629 if (isa<ConstantArrayType>(AT)) {
1630 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001631 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1632 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1633 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1634 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1635 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001636 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001637 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001638 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001639 << IndexExpr->getSourceRange();
1640 ++Index;
1641 return true;
1642 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001643 } else {
1644 // Make sure the bit-widths and signedness match.
1645 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1646 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001647 else if (DesignatedStartIndex.getBitWidth() <
1648 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001649 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1650 DesignatedStartIndex.setIsUnsigned(true);
1651 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001654 // Make sure that our non-designated initializer list has space
1655 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001656 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001657 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001658 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001659
Douglas Gregor17bd0942009-01-28 23:36:17 +00001660 // Repeatedly perform subobject initializations in the range
1661 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001662
Douglas Gregor17bd0942009-01-28 23:36:17 +00001663 // Move to the next designator
1664 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1665 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001666 while (DesignatedStartIndex <= DesignatedEndIndex) {
1667 // Recurse to check later designated subobjects.
1668 QualType ElementType = AT->getElementType();
1669 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001670 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1671 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001672 (DesignatedStartIndex == DesignatedEndIndex),
1673 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001674 return true;
1675
1676 // Move to the next index in the array that we'll be initializing.
1677 ++DesignatedStartIndex;
1678 ElementIndex = DesignatedStartIndex.getZExtValue();
1679 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001680
1681 // If this the first designator, our caller will continue checking
1682 // the rest of this array subobject.
1683 if (IsFirstDesignator) {
1684 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001685 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001686 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001687 return false;
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Douglas Gregor17bd0942009-01-28 23:36:17 +00001690 if (!FinishSubobjectInit)
1691 return false;
1692
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001693 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001694 bool prevHadError = hadError;
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001695 CheckArrayType(0, IList, CurrentObjectType, DesignatedStartIndex,
1696 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001697 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001698 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001699}
1700
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001701// Get the structured initializer list for a subobject of type
1702// @p CurrentObjectType.
1703InitListExpr *
1704InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1705 QualType CurrentObjectType,
1706 InitListExpr *StructuredList,
1707 unsigned StructuredIndex,
1708 SourceRange InitRange) {
1709 Expr *ExistingInit = 0;
1710 if (!StructuredList)
1711 ExistingInit = SyntacticToSemantic[IList];
1712 else if (StructuredIndex < StructuredList->getNumInits())
1713 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001714
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001715 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1716 return Result;
1717
1718 if (ExistingInit) {
1719 // We are creating an initializer list that initializes the
1720 // subobjects of the current object, but there was already an
1721 // initialization that completely initialized the current
1722 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001723 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001724 // struct X { int a, b; };
1725 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001726 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001727 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1728 // designated initializer re-initializes the whole
1729 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001730 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001731 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001732 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001733 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001734 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001735 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001736 << ExistingInit->getSourceRange();
1737 }
1738
Mike Stump11289f42009-09-09 15:08:12 +00001739 InitListExpr *Result
1740 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001741 InitRange.getEnd());
1742
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 Result->setType(CurrentObjectType);
1744
Douglas Gregor6d00c992009-03-20 23:58:33 +00001745 // Pre-allocate storage for the structured initializer list.
1746 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001747 unsigned NumInits = 0;
1748 if (!StructuredList)
1749 NumInits = IList->getNumInits();
1750 else if (Index < IList->getNumInits()) {
1751 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1752 NumInits = SubList->getNumInits();
1753 }
1754
Mike Stump11289f42009-09-09 15:08:12 +00001755 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001756 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1757 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1758 NumElements = CAType->getSize().getZExtValue();
1759 // Simple heuristic so that we don't allocate a very large
1760 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001761 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001762 NumElements = 0;
1763 }
John McCall9dd450b2009-09-21 23:43:11 +00001764 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001765 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001766 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001767 RecordDecl *RDecl = RType->getDecl();
1768 if (RDecl->isUnion())
1769 NumElements = 1;
1770 else
Mike Stump11289f42009-09-09 15:08:12 +00001771 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001772 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001773 }
1774
Douglas Gregor221c9a52009-03-21 18:13:52 +00001775 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001776 NumElements = IList->getNumInits();
1777
1778 Result->reserveInits(NumElements);
1779
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001780 // Link this new initializer list into the structured initializer
1781 // lists.
1782 if (StructuredList)
1783 StructuredList->updateInit(StructuredIndex, Result);
1784 else {
1785 Result->setSyntacticForm(IList);
1786 SyntacticToSemantic[IList] = Result;
1787 }
1788
1789 return Result;
1790}
1791
1792/// Update the initializer at index @p StructuredIndex within the
1793/// structured initializer list to the value @p expr.
1794void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1795 unsigned &StructuredIndex,
1796 Expr *expr) {
1797 // No structured initializer list to update
1798 if (!StructuredList)
1799 return;
1800
1801 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1802 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001803 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001804 diag::warn_initializer_overrides)
1805 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001806 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001807 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001808 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001809 << PrevInit->getSourceRange();
1810 }
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001812 ++StructuredIndex;
1813}
1814
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001815/// Check that the given Index expression is a valid array designator
1816/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001817/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001818/// and produces a reasonable diagnostic if there is a
1819/// failure. Returns true if there was an error, false otherwise. If
1820/// everything went okay, Value will receive the value of the constant
1821/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001822static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001823CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001824 SourceLocation Loc = Index->getSourceRange().getBegin();
1825
1826 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001827 if (S.VerifyIntegerConstantExpression(Index, &Value))
1828 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001829
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001830 if (Value.isSigned() && Value.isNegative())
1831 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001832 << Value.toString(10) << Index->getSourceRange();
1833
Douglas Gregor51650d32009-01-23 21:04:18 +00001834 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001835 return false;
1836}
1837
1838Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1839 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001840 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001841 OwningExprResult Init) {
1842 typedef DesignatedInitExpr::Designator ASTDesignator;
1843
1844 bool Invalid = false;
1845 llvm::SmallVector<ASTDesignator, 32> Designators;
1846 llvm::SmallVector<Expr *, 32> InitExpressions;
1847
1848 // Build designators and check array designator expressions.
1849 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1850 const Designator &D = Desig.getDesignator(Idx);
1851 switch (D.getKind()) {
1852 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001853 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001854 D.getFieldLoc()));
1855 break;
1856
1857 case Designator::ArrayDesignator: {
1858 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1859 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001860 if (!Index->isTypeDependent() &&
1861 !Index->isValueDependent() &&
1862 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001863 Invalid = true;
1864 else {
1865 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001866 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001867 D.getRBracketLoc()));
1868 InitExpressions.push_back(Index);
1869 }
1870 break;
1871 }
1872
1873 case Designator::ArrayRangeDesignator: {
1874 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1875 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1876 llvm::APSInt StartValue;
1877 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001878 bool StartDependent = StartIndex->isTypeDependent() ||
1879 StartIndex->isValueDependent();
1880 bool EndDependent = EndIndex->isTypeDependent() ||
1881 EndIndex->isValueDependent();
1882 if ((!StartDependent &&
1883 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1884 (!EndDependent &&
1885 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001886 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001887 else {
1888 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001889 if (StartDependent || EndDependent) {
1890 // Nothing to compute.
1891 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001892 EndValue.extend(StartValue.getBitWidth());
1893 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1894 StartValue.extend(EndValue.getBitWidth());
1895
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001896 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001897 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001898 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001899 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1900 Invalid = true;
1901 } else {
1902 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001903 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001904 D.getEllipsisLoc(),
1905 D.getRBracketLoc()));
1906 InitExpressions.push_back(StartIndex);
1907 InitExpressions.push_back(EndIndex);
1908 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001909 }
1910 break;
1911 }
1912 }
1913 }
1914
1915 if (Invalid || Init.isInvalid())
1916 return ExprError();
1917
1918 // Clear out the expressions within the designation.
1919 Desig.ClearExprs(*this);
1920
1921 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001922 = DesignatedInitExpr::Create(Context,
1923 Designators.data(), Designators.size(),
1924 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001925 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001926 return Owned(DIE);
1927}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001928
Douglas Gregor723796a2009-12-16 06:35:08 +00001929bool Sema::CheckInitList(const InitializedEntity &Entity,
1930 InitListExpr *&InitList, QualType &DeclType) {
1931 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001932 if (!CheckInitList.HadError())
1933 InitList = CheckInitList.getFullyStructuredList();
1934
1935 return CheckInitList.HadError();
1936}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001937
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001938//===----------------------------------------------------------------------===//
1939// Initialization entity
1940//===----------------------------------------------------------------------===//
1941
Douglas Gregor723796a2009-12-16 06:35:08 +00001942InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1943 const InitializedEntity &Parent)
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001944 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00001945{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001946 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1947 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001948 Type = AT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001949 } else {
1950 Kind = EK_VectorElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00001951 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001952 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001953}
1954
1955InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1956 CXXBaseSpecifier *Base)
1957{
1958 InitializedEntity Result;
1959 Result.Kind = EK_Base;
1960 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001961 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001962 return Result;
1963}
1964
Douglas Gregor85dabae2009-12-16 01:38:02 +00001965DeclarationName InitializedEntity::getName() const {
1966 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001967 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001968 if (!VariableOrMember)
1969 return DeclarationName();
1970 // Fall through
1971
1972 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001973 case EK_Member:
1974 return VariableOrMember->getDeclName();
1975
1976 case EK_Result:
1977 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001978 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001979 case EK_Temporary:
1980 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00001981 case EK_ArrayElement:
1982 case EK_VectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001983 return DeclarationName();
1984 }
1985
1986 // Silence GCC warning
1987 return DeclarationName();
1988}
1989
Douglas Gregora4b592a2009-12-19 03:01:41 +00001990DeclaratorDecl *InitializedEntity::getDecl() const {
1991 switch (getKind()) {
1992 case EK_Variable:
1993 case EK_Parameter:
1994 case EK_Member:
1995 return VariableOrMember;
1996
1997 case EK_Result:
1998 case EK_Exception:
1999 case EK_New:
2000 case EK_Temporary:
2001 case EK_Base:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002002 case EK_ArrayElement:
2003 case EK_VectorElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002004 return 0;
2005 }
2006
2007 // Silence GCC warning
2008 return 0;
2009}
2010
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002011//===----------------------------------------------------------------------===//
2012// Initialization sequence
2013//===----------------------------------------------------------------------===//
2014
2015void InitializationSequence::Step::Destroy() {
2016 switch (Kind) {
2017 case SK_ResolveAddressOfOverloadedFunction:
2018 case SK_CastDerivedToBaseRValue:
2019 case SK_CastDerivedToBaseLValue:
2020 case SK_BindReference:
2021 case SK_BindReferenceToTemporary:
2022 case SK_UserConversion:
2023 case SK_QualificationConversionRValue:
2024 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002025 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002026 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002027 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002028 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002029 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002030 break;
2031
2032 case SK_ConversionSequence:
2033 delete ICS;
2034 }
2035}
2036
2037void InitializationSequence::AddAddressOverloadResolutionStep(
2038 FunctionDecl *Function) {
2039 Step S;
2040 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2041 S.Type = Function->getType();
2042 S.Function = Function;
2043 Steps.push_back(S);
2044}
2045
2046void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2047 bool IsLValue) {
2048 Step S;
2049 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2050 S.Type = BaseType;
2051 Steps.push_back(S);
2052}
2053
2054void InitializationSequence::AddReferenceBindingStep(QualType T,
2055 bool BindingTemporary) {
2056 Step S;
2057 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2058 S.Type = T;
2059 Steps.push_back(S);
2060}
2061
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002062void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2063 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002064 Step S;
2065 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002066 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002067 S.Function = Function;
2068 Steps.push_back(S);
2069}
2070
2071void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2072 bool IsLValue) {
2073 Step S;
2074 S.Kind = IsLValue? SK_QualificationConversionLValue
2075 : SK_QualificationConversionRValue;
2076 S.Type = Ty;
2077 Steps.push_back(S);
2078}
2079
2080void InitializationSequence::AddConversionSequenceStep(
2081 const ImplicitConversionSequence &ICS,
2082 QualType T) {
2083 Step S;
2084 S.Kind = SK_ConversionSequence;
2085 S.Type = T;
2086 S.ICS = new ImplicitConversionSequence(ICS);
2087 Steps.push_back(S);
2088}
2089
Douglas Gregor51e77d52009-12-10 17:56:55 +00002090void InitializationSequence::AddListInitializationStep(QualType T) {
2091 Step S;
2092 S.Kind = SK_ListInitialization;
2093 S.Type = T;
2094 Steps.push_back(S);
2095}
2096
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002097void
2098InitializationSequence::AddConstructorInitializationStep(
2099 CXXConstructorDecl *Constructor,
2100 QualType T) {
2101 Step S;
2102 S.Kind = SK_ConstructorInitialization;
2103 S.Type = T;
2104 S.Function = Constructor;
2105 Steps.push_back(S);
2106}
2107
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002108void InitializationSequence::AddZeroInitializationStep(QualType T) {
2109 Step S;
2110 S.Kind = SK_ZeroInitialization;
2111 S.Type = T;
2112 Steps.push_back(S);
2113}
2114
Douglas Gregore1314a62009-12-18 05:02:21 +00002115void InitializationSequence::AddCAssignmentStep(QualType T) {
2116 Step S;
2117 S.Kind = SK_CAssignment;
2118 S.Type = T;
2119 Steps.push_back(S);
2120}
2121
Eli Friedman78275202009-12-19 08:11:05 +00002122void InitializationSequence::AddStringInitStep(QualType T) {
2123 Step S;
2124 S.Kind = SK_StringInit;
2125 S.Type = T;
2126 Steps.push_back(S);
2127}
2128
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002129void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2130 OverloadingResult Result) {
2131 SequenceKind = FailedSequence;
2132 this->Failure = Failure;
2133 this->FailedOverloadResult = Result;
2134}
2135
2136//===----------------------------------------------------------------------===//
2137// Attempt initialization
2138//===----------------------------------------------------------------------===//
2139
2140/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002141static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002142 const InitializedEntity &Entity,
2143 const InitializationKind &Kind,
2144 InitListExpr *InitList,
2145 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002146 // FIXME: We only perform rudimentary checking of list
2147 // initializations at this point, then assume that any list
2148 // initialization of an array, aggregate, or scalar will be
2149 // well-formed. We we actually "perform" list initialization, we'll
2150 // do all of the necessary checking. C++0x initializer lists will
2151 // force us to perform more checking here.
2152 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2153
Douglas Gregor1b303932009-12-22 15:35:07 +00002154 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002155
2156 // C++ [dcl.init]p13:
2157 // If T is a scalar type, then a declaration of the form
2158 //
2159 // T x = { a };
2160 //
2161 // is equivalent to
2162 //
2163 // T x = a;
2164 if (DestType->isScalarType()) {
2165 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2166 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2167 return;
2168 }
2169
2170 // Assume scalar initialization from a single value works.
2171 } else if (DestType->isAggregateType()) {
2172 // Assume aggregate initialization works.
2173 } else if (DestType->isVectorType()) {
2174 // Assume vector initialization works.
2175 } else if (DestType->isReferenceType()) {
2176 // FIXME: C++0x defines behavior for this.
2177 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2178 return;
2179 } else if (DestType->isRecordType()) {
2180 // FIXME: C++0x defines behavior for this
2181 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2182 }
2183
2184 // Add a general "list initialization" step.
2185 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002186}
2187
2188/// \brief Try a reference initialization that involves calling a conversion
2189/// function.
2190///
2191/// FIXME: look intos DRs 656, 896
2192static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2193 const InitializedEntity &Entity,
2194 const InitializationKind &Kind,
2195 Expr *Initializer,
2196 bool AllowRValues,
2197 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002198 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002199 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2200 QualType T1 = cv1T1.getUnqualifiedType();
2201 QualType cv2T2 = Initializer->getType();
2202 QualType T2 = cv2T2.getUnqualifiedType();
2203
2204 bool DerivedToBase;
2205 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2206 T1, T2, DerivedToBase) &&
2207 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002208 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002209
2210 // Build the candidate set directly in the initialization sequence
2211 // structure, so that it will persist if we fail.
2212 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2213 CandidateSet.clear();
2214
2215 // Determine whether we are allowed to call explicit constructors or
2216 // explicit conversion operators.
2217 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2218
2219 const RecordType *T1RecordType = 0;
2220 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2221 // The type we're converting to is a class type. Enumerate its constructors
2222 // to see if there is a suitable conversion.
2223 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2224
2225 DeclarationName ConstructorName
2226 = S.Context.DeclarationNames.getCXXConstructorName(
2227 S.Context.getCanonicalType(T1).getUnqualifiedType());
2228 DeclContext::lookup_iterator Con, ConEnd;
2229 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2230 Con != ConEnd; ++Con) {
2231 // Find the constructor (which may be a template).
2232 CXXConstructorDecl *Constructor = 0;
2233 FunctionTemplateDecl *ConstructorTmpl
2234 = dyn_cast<FunctionTemplateDecl>(*Con);
2235 if (ConstructorTmpl)
2236 Constructor = cast<CXXConstructorDecl>(
2237 ConstructorTmpl->getTemplatedDecl());
2238 else
2239 Constructor = cast<CXXConstructorDecl>(*Con);
2240
2241 if (!Constructor->isInvalidDecl() &&
2242 Constructor->isConvertingConstructor(AllowExplicit)) {
2243 if (ConstructorTmpl)
2244 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2245 &Initializer, 1, CandidateSet);
2246 else
2247 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2248 }
2249 }
2250 }
2251
2252 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2253 // The type we're converting from is a class type, enumerate its conversion
2254 // functions.
2255 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2256
2257 // Determine the type we are converting to. If we are allowed to
2258 // convert to an rvalue, take the type that the destination type
2259 // refers to.
2260 QualType ToType = AllowRValues? cv1T1 : DestType;
2261
John McCallad371252010-01-20 00:46:10 +00002262 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002263 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002264 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2265 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002266 NamedDecl *D = *I;
2267 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2268 if (isa<UsingShadowDecl>(D))
2269 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2270
2271 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2272 CXXConversionDecl *Conv;
2273 if (ConvTemplate)
2274 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2275 else
2276 Conv = cast<CXXConversionDecl>(*I);
2277
2278 // If the conversion function doesn't return a reference type,
2279 // it can't be considered for this conversion unless we're allowed to
2280 // consider rvalues.
2281 // FIXME: Do we need to make sure that we only consider conversion
2282 // candidates with reference-compatible results? That might be needed to
2283 // break recursion.
2284 if ((AllowExplicit || !Conv->isExplicit()) &&
2285 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2286 if (ConvTemplate)
2287 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2288 ToType, CandidateSet);
2289 else
2290 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2291 CandidateSet);
2292 }
2293 }
2294 }
2295
2296 SourceLocation DeclLoc = Initializer->getLocStart();
2297
2298 // Perform overload resolution. If it fails, return the failed result.
2299 OverloadCandidateSet::iterator Best;
2300 if (OverloadingResult Result
2301 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2302 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002303
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002304 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002305
2306 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002307 if (isa<CXXConversionDecl>(Function))
2308 T2 = Function->getResultType();
2309 else
2310 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002311
2312 // Add the user-defined conversion step.
2313 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2314
2315 // Determine whether we need to perform derived-to-base or
2316 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002317 bool NewDerivedToBase = false;
2318 Sema::ReferenceCompareResult NewRefRelationship
2319 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2320 NewDerivedToBase);
2321 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2322 "Overload resolution picked a bad conversion function");
2323 (void)NewRefRelationship;
2324 if (NewDerivedToBase)
2325 Sequence.AddDerivedToBaseCastStep(
2326 S.Context.getQualifiedType(T1,
2327 T2.getNonReferenceType().getQualifiers()),
2328 /*isLValue=*/true);
2329
2330 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2331 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2332
2333 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2334 return OR_Success;
2335}
2336
2337/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2338static void TryReferenceInitialization(Sema &S,
2339 const InitializedEntity &Entity,
2340 const InitializationKind &Kind,
2341 Expr *Initializer,
2342 InitializationSequence &Sequence) {
2343 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2344
Douglas Gregor1b303932009-12-22 15:35:07 +00002345 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002346 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002347 Qualifiers T1Quals;
2348 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002349 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002350 Qualifiers T2Quals;
2351 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002352 SourceLocation DeclLoc = Initializer->getLocStart();
2353
2354 // If the initializer is the address of an overloaded function, try
2355 // to resolve the overloaded function. If all goes well, T2 is the
2356 // type of the resulting function.
2357 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2358 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2359 T1,
2360 false);
2361 if (!Fn) {
2362 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2363 return;
2364 }
2365
2366 Sequence.AddAddressOverloadResolutionStep(Fn);
2367 cv2T2 = Fn->getType();
2368 T2 = cv2T2.getUnqualifiedType();
2369 }
2370
2371 // FIXME: Rvalue references
2372 bool ForceRValue = false;
2373
2374 // Compute some basic properties of the types and the initializer.
2375 bool isLValueRef = DestType->isLValueReferenceType();
2376 bool isRValueRef = !isLValueRef;
2377 bool DerivedToBase = false;
2378 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2379 Initializer->isLvalue(S.Context);
2380 Sema::ReferenceCompareResult RefRelationship
2381 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2382
2383 // C++0x [dcl.init.ref]p5:
2384 // A reference to type "cv1 T1" is initialized by an expression of type
2385 // "cv2 T2" as follows:
2386 //
2387 // - If the reference is an lvalue reference and the initializer
2388 // expression
2389 OverloadingResult ConvOvlResult = OR_Success;
2390 if (isLValueRef) {
2391 if (InitLvalue == Expr::LV_Valid &&
2392 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2393 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2394 // reference-compatible with "cv2 T2," or
2395 //
2396 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2397 // bit-field when we're determining whether the reference initialization
2398 // can occur. This property will be checked by PerformInitialization.
2399 if (DerivedToBase)
2400 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002401 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002402 /*isLValue=*/true);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002403 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002404 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2405 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2406 return;
2407 }
2408
2409 // - has a class type (i.e., T2 is a class type), where T1 is not
2410 // reference-related to T2, and can be implicitly converted to an
2411 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2412 // with "cv3 T3" (this conversion is selected by enumerating the
2413 // applicable conversion functions (13.3.1.6) and choosing the best
2414 // one through overload resolution (13.3)),
2415 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2416 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2417 Initializer,
2418 /*AllowRValues=*/false,
2419 Sequence);
2420 if (ConvOvlResult == OR_Success)
2421 return;
John McCall0d1da222010-01-12 00:44:57 +00002422 if (ConvOvlResult != OR_No_Viable_Function) {
2423 Sequence.SetOverloadFailure(
2424 InitializationSequence::FK_ReferenceInitOverloadFailed,
2425 ConvOvlResult);
2426 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002427 }
2428 }
2429
2430 // - Otherwise, the reference shall be an lvalue reference to a
2431 // non-volatile const type (i.e., cv1 shall be const), or the reference
2432 // shall be an rvalue reference and the initializer expression shall
2433 // be an rvalue.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002434 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002435 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2436 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2437 Sequence.SetOverloadFailure(
2438 InitializationSequence::FK_ReferenceInitOverloadFailed,
2439 ConvOvlResult);
2440 else if (isLValueRef)
2441 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2442 ? (RefRelationship == Sema::Ref_Related
2443 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2444 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2445 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2446 else
2447 Sequence.SetFailed(
2448 InitializationSequence::FK_RValueReferenceBindingToLValue);
2449
2450 return;
2451 }
2452
2453 // - If T1 and T2 are class types and
2454 if (T1->isRecordType() && T2->isRecordType()) {
2455 // - the initializer expression is an rvalue and "cv1 T1" is
2456 // reference-compatible with "cv2 T2", or
2457 if (InitLvalue != Expr::LV_Valid &&
2458 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2459 if (DerivedToBase)
2460 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth04bdce62010-01-12 20:32:25 +00002461 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002462 /*isLValue=*/false);
Chandler Carruth04bdce62010-01-12 20:32:25 +00002463 if (T1Quals != T2Quals)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002464 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2465 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2466 return;
2467 }
2468
2469 // - T1 is not reference-related to T2 and the initializer expression
2470 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2471 // conversion is selected by enumerating the applicable conversion
2472 // functions (13.3.1.6) and choosing the best one through overload
2473 // resolution (13.3)),
2474 if (RefRelationship == Sema::Ref_Incompatible) {
2475 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2476 Kind, Initializer,
2477 /*AllowRValues=*/true,
2478 Sequence);
2479 if (ConvOvlResult)
2480 Sequence.SetOverloadFailure(
2481 InitializationSequence::FK_ReferenceInitOverloadFailed,
2482 ConvOvlResult);
2483
2484 return;
2485 }
2486
2487 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2488 return;
2489 }
2490
2491 // - If the initializer expression is an rvalue, with T2 an array type,
2492 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2493 // is bound to the object represented by the rvalue (see 3.10).
2494 // FIXME: How can an array type be reference-compatible with anything?
2495 // Don't we mean the element types of T1 and T2?
2496
2497 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2498 // from the initializer expression using the rules for a non-reference
2499 // copy initialization (8.5). The reference is then bound to the
2500 // temporary. [...]
2501 // Determine whether we are allowed to call explicit constructors or
2502 // explicit conversion operators.
2503 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2504 ImplicitConversionSequence ICS
2505 = S.TryImplicitConversion(Initializer, cv1T1,
2506 /*SuppressUserConversions=*/false, AllowExplicit,
2507 /*ForceRValue=*/false,
2508 /*FIXME:InOverloadResolution=*/false,
2509 /*UserCast=*/Kind.isExplicitCast());
2510
John McCall0d1da222010-01-12 00:44:57 +00002511 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002512 // FIXME: Use the conversion function set stored in ICS to turn
2513 // this into an overloading ambiguity diagnostic. However, we need
2514 // to keep that set as an OverloadCandidateSet rather than as some
2515 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002516 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2517 Sequence.SetOverloadFailure(
2518 InitializationSequence::FK_ReferenceInitOverloadFailed,
2519 ConvOvlResult);
2520 else
2521 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002522 return;
2523 }
2524
2525 // [...] If T1 is reference-related to T2, cv1 must be the
2526 // same cv-qualification as, or greater cv-qualification
2527 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00002528 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2529 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002530 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00002531 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002532 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2533 return;
2534 }
2535
2536 // Perform the actual conversion.
2537 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2538 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2539 return;
2540}
2541
2542/// \brief Attempt character array initialization from a string literal
2543/// (C++ [dcl.init.string], C99 6.7.8).
2544static void TryStringLiteralInitialization(Sema &S,
2545 const InitializedEntity &Entity,
2546 const InitializationKind &Kind,
2547 Expr *Initializer,
2548 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002549 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002550 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002551}
2552
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002553/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2554/// enumerates the constructors of the initialized entity and performs overload
2555/// resolution to select the best.
2556static void TryConstructorInitialization(Sema &S,
2557 const InitializedEntity &Entity,
2558 const InitializationKind &Kind,
2559 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002560 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002561 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002562 if (Kind.getKind() == InitializationKind::IK_Copy)
2563 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2564 else
2565 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002566
2567 // Build the candidate set directly in the initialization sequence
2568 // structure, so that it will persist if we fail.
2569 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2570 CandidateSet.clear();
2571
2572 // Determine whether we are allowed to call explicit constructors or
2573 // explicit conversion operators.
2574 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2575 Kind.getKind() == InitializationKind::IK_Value ||
2576 Kind.getKind() == InitializationKind::IK_Default);
2577
2578 // The type we're converting to is a class type. Enumerate its constructors
2579 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002580 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2581 assert(DestRecordType && "Constructor initialization requires record type");
2582 CXXRecordDecl *DestRecordDecl
2583 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2584
2585 DeclarationName ConstructorName
2586 = S.Context.DeclarationNames.getCXXConstructorName(
2587 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2588 DeclContext::lookup_iterator Con, ConEnd;
2589 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2590 Con != ConEnd; ++Con) {
2591 // Find the constructor (which may be a template).
2592 CXXConstructorDecl *Constructor = 0;
2593 FunctionTemplateDecl *ConstructorTmpl
2594 = dyn_cast<FunctionTemplateDecl>(*Con);
2595 if (ConstructorTmpl)
2596 Constructor = cast<CXXConstructorDecl>(
2597 ConstructorTmpl->getTemplatedDecl());
2598 else
2599 Constructor = cast<CXXConstructorDecl>(*Con);
2600
2601 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002602 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002603 if (ConstructorTmpl)
2604 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2605 Args, NumArgs, CandidateSet);
2606 else
2607 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2608 }
2609 }
2610
2611 SourceLocation DeclLoc = Kind.getLocation();
2612
2613 // Perform overload resolution. If it fails, return the failed result.
2614 OverloadCandidateSet::iterator Best;
2615 if (OverloadingResult Result
2616 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2617 Sequence.SetOverloadFailure(
2618 InitializationSequence::FK_ConstructorOverloadFailed,
2619 Result);
2620 return;
2621 }
2622
2623 // Add the constructor initialization step. Any cv-qualification conversion is
2624 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002625 if (Kind.getKind() == InitializationKind::IK_Copy) {
2626 Sequence.AddUserConversionStep(Best->Function, DestType);
2627 } else {
2628 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002629 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002630 DestType);
2631 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002632}
2633
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002634/// \brief Attempt value initialization (C++ [dcl.init]p7).
2635static void TryValueInitialization(Sema &S,
2636 const InitializedEntity &Entity,
2637 const InitializationKind &Kind,
2638 InitializationSequence &Sequence) {
2639 // C++ [dcl.init]p5:
2640 //
2641 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002642 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002643
2644 // -- if T is an array type, then each element is value-initialized;
2645 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2646 T = AT->getElementType();
2647
2648 if (const RecordType *RT = T->getAs<RecordType>()) {
2649 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2650 // -- if T is a class type (clause 9) with a user-declared
2651 // constructor (12.1), then the default constructor for T is
2652 // called (and the initialization is ill-formed if T has no
2653 // accessible default constructor);
2654 //
2655 // FIXME: we really want to refer to a single subobject of the array,
2656 // but Entity doesn't have a way to capture that (yet).
2657 if (ClassDecl->hasUserDeclaredConstructor())
2658 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2659
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002660 // -- if T is a (possibly cv-qualified) non-union class type
2661 // without a user-provided constructor, then the object is
2662 // zero-initialized and, if T’s implicitly-declared default
2663 // constructor is non-trivial, that constructor is called.
2664 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2665 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2666 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002667 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002668 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2669 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002670 }
2671 }
2672
Douglas Gregor1b303932009-12-22 15:35:07 +00002673 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002674 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2675}
2676
Douglas Gregor85dabae2009-12-16 01:38:02 +00002677/// \brief Attempt default initialization (C++ [dcl.init]p6).
2678static void TryDefaultInitialization(Sema &S,
2679 const InitializedEntity &Entity,
2680 const InitializationKind &Kind,
2681 InitializationSequence &Sequence) {
2682 assert(Kind.getKind() == InitializationKind::IK_Default);
2683
2684 // C++ [dcl.init]p6:
2685 // To default-initialize an object of type T means:
2686 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002687 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002688 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2689 DestType = Array->getElementType();
2690
2691 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2692 // constructor for T is called (and the initialization is ill-formed if
2693 // T has no accessible default constructor);
2694 if (DestType->isRecordType()) {
2695 // FIXME: If a program calls for the default initialization of an object of
2696 // a const-qualified type T, T shall be a class type with a user-provided
2697 // default constructor.
2698 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2699 Sequence);
2700 }
2701
2702 // - otherwise, no initialization is performed.
2703 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2704
2705 // If a program calls for the default initialization of an object of
2706 // a const-qualified type T, T shall be a class type with a user-provided
2707 // default constructor.
2708 if (DestType.isConstQualified())
2709 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2710}
2711
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002712/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2713/// which enumerates all conversion functions and performs overload resolution
2714/// to select the best.
2715static void TryUserDefinedConversion(Sema &S,
2716 const InitializedEntity &Entity,
2717 const InitializationKind &Kind,
2718 Expr *Initializer,
2719 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002720 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2721
Douglas Gregor1b303932009-12-22 15:35:07 +00002722 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002723 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2724 QualType SourceType = Initializer->getType();
2725 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2726 "Must have a class type to perform a user-defined conversion");
2727
2728 // Build the candidate set directly in the initialization sequence
2729 // structure, so that it will persist if we fail.
2730 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2731 CandidateSet.clear();
2732
2733 // Determine whether we are allowed to call explicit constructors or
2734 // explicit conversion operators.
2735 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2736
2737 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2738 // The type we're converting to is a class type. Enumerate its constructors
2739 // to see if there is a suitable conversion.
2740 CXXRecordDecl *DestRecordDecl
2741 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2742
2743 DeclarationName ConstructorName
2744 = S.Context.DeclarationNames.getCXXConstructorName(
2745 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2746 DeclContext::lookup_iterator Con, ConEnd;
2747 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2748 Con != ConEnd; ++Con) {
2749 // Find the constructor (which may be a template).
2750 CXXConstructorDecl *Constructor = 0;
2751 FunctionTemplateDecl *ConstructorTmpl
2752 = dyn_cast<FunctionTemplateDecl>(*Con);
2753 if (ConstructorTmpl)
2754 Constructor = cast<CXXConstructorDecl>(
2755 ConstructorTmpl->getTemplatedDecl());
2756 else
2757 Constructor = cast<CXXConstructorDecl>(*Con);
2758
2759 if (!Constructor->isInvalidDecl() &&
2760 Constructor->isConvertingConstructor(AllowExplicit)) {
2761 if (ConstructorTmpl)
2762 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2763 &Initializer, 1, CandidateSet);
2764 else
2765 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2766 }
2767 }
2768 }
Eli Friedman78275202009-12-19 08:11:05 +00002769
2770 SourceLocation DeclLoc = Initializer->getLocStart();
2771
Douglas Gregor540c3b02009-12-14 17:27:33 +00002772 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2773 // The type we're converting from is a class type, enumerate its conversion
2774 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002775
Eli Friedman4afe9a32009-12-20 22:12:03 +00002776 // We can only enumerate the conversion functions for a complete type; if
2777 // the type isn't complete, simply skip this step.
2778 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2779 CXXRecordDecl *SourceRecordDecl
2780 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002781
John McCallad371252010-01-20 00:46:10 +00002782 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00002783 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002784 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman4afe9a32009-12-20 22:12:03 +00002785 E = Conversions->end();
2786 I != E; ++I) {
2787 NamedDecl *D = *I;
2788 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2789 if (isa<UsingShadowDecl>(D))
2790 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2791
2792 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2793 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002794 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002795 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002796 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002797 Conv = cast<CXXConversionDecl>(*I);
2798
2799 if (AllowExplicit || !Conv->isExplicit()) {
2800 if (ConvTemplate)
2801 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2802 Initializer, DestType,
2803 CandidateSet);
2804 else
2805 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2806 CandidateSet);
2807 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002808 }
2809 }
2810 }
2811
Douglas Gregor540c3b02009-12-14 17:27:33 +00002812 // Perform overload resolution. If it fails, return the failed result.
2813 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00002814 if (OverloadingResult Result
Douglas Gregor540c3b02009-12-14 17:27:33 +00002815 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2816 Sequence.SetOverloadFailure(
2817 InitializationSequence::FK_UserConversionOverloadFailed,
2818 Result);
2819 return;
2820 }
John McCall0d1da222010-01-12 00:44:57 +00002821
Douglas Gregor540c3b02009-12-14 17:27:33 +00002822 FunctionDecl *Function = Best->Function;
2823
2824 if (isa<CXXConstructorDecl>(Function)) {
2825 // Add the user-defined conversion step. Any cv-qualification conversion is
2826 // subsumed by the initialization.
2827 Sequence.AddUserConversionStep(Function, DestType);
2828 return;
2829 }
2830
2831 // Add the user-defined conversion step that calls the conversion function.
2832 QualType ConvType = Function->getResultType().getNonReferenceType();
2833 Sequence.AddUserConversionStep(Function, ConvType);
2834
2835 // If the conversion following the call to the conversion function is
2836 // interesting, add it as a separate step.
2837 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2838 Best->FinalConversion.Third) {
2839 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00002840 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002841 ICS.Standard = Best->FinalConversion;
2842 Sequence.AddConversionSequenceStep(ICS, DestType);
2843 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002844}
2845
2846/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2847/// non-class type to another.
2848static void TryImplicitConversion(Sema &S,
2849 const InitializedEntity &Entity,
2850 const InitializationKind &Kind,
2851 Expr *Initializer,
2852 InitializationSequence &Sequence) {
2853 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002854 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002855 /*SuppressUserConversions=*/true,
2856 /*AllowExplicit=*/false,
2857 /*ForceRValue=*/false,
2858 /*FIXME:InOverloadResolution=*/false,
2859 /*UserCast=*/Kind.isExplicitCast());
2860
John McCall0d1da222010-01-12 00:44:57 +00002861 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002862 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2863 return;
2864 }
2865
Douglas Gregor1b303932009-12-22 15:35:07 +00002866 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002867}
2868
2869InitializationSequence::InitializationSequence(Sema &S,
2870 const InitializedEntity &Entity,
2871 const InitializationKind &Kind,
2872 Expr **Args,
2873 unsigned NumArgs) {
2874 ASTContext &Context = S.Context;
2875
2876 // C++0x [dcl.init]p16:
2877 // The semantics of initializers are as follows. The destination type is
2878 // the type of the object or reference being initialized and the source
2879 // type is the type of the initializer expression. The source type is not
2880 // defined when the initializer is a braced-init-list or when it is a
2881 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002882 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002883
2884 if (DestType->isDependentType() ||
2885 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2886 SequenceKind = DependentSequence;
2887 return;
2888 }
2889
2890 QualType SourceType;
2891 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002892 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002893 Initializer = Args[0];
2894 if (!isa<InitListExpr>(Initializer))
2895 SourceType = Initializer->getType();
2896 }
2897
2898 // - If the initializer is a braced-init-list, the object is
2899 // list-initialized (8.5.4).
2900 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2901 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002902 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002903 }
2904
2905 // - If the destination type is a reference type, see 8.5.3.
2906 if (DestType->isReferenceType()) {
2907 // C++0x [dcl.init.ref]p1:
2908 // A variable declared to be a T& or T&&, that is, "reference to type T"
2909 // (8.3.2), shall be initialized by an object, or function, of type T or
2910 // by an object that can be converted into a T.
2911 // (Therefore, multiple arguments are not permitted.)
2912 if (NumArgs != 1)
2913 SetFailed(FK_TooManyInitsForReference);
2914 else
2915 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2916 return;
2917 }
2918
2919 // - If the destination type is an array of characters, an array of
2920 // char16_t, an array of char32_t, or an array of wchar_t, and the
2921 // initializer is a string literal, see 8.5.2.
2922 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2923 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2924 return;
2925 }
2926
2927 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002928 if (Kind.getKind() == InitializationKind::IK_Value ||
2929 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002930 TryValueInitialization(S, Entity, Kind, *this);
2931 return;
2932 }
2933
Douglas Gregor85dabae2009-12-16 01:38:02 +00002934 // Handle default initialization.
2935 if (Kind.getKind() == InitializationKind::IK_Default){
2936 TryDefaultInitialization(S, Entity, Kind, *this);
2937 return;
2938 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002939
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002940 // - Otherwise, if the destination type is an array, the program is
2941 // ill-formed.
2942 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2943 if (AT->getElementType()->isAnyCharacterType())
2944 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2945 else
2946 SetFailed(FK_ArrayNeedsInitList);
2947
2948 return;
2949 }
Eli Friedman78275202009-12-19 08:11:05 +00002950
2951 // Handle initialization in C
2952 if (!S.getLangOptions().CPlusPlus) {
2953 setSequenceKind(CAssignment);
2954 AddCAssignmentStep(DestType);
2955 return;
2956 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002957
2958 // - If the destination type is a (possibly cv-qualified) class type:
2959 if (DestType->isRecordType()) {
2960 // - If the initialization is direct-initialization, or if it is
2961 // copy-initialization where the cv-unqualified version of the
2962 // source type is the same class as, or a derived class of, the
2963 // class of the destination, constructors are considered. [...]
2964 if (Kind.getKind() == InitializationKind::IK_Direct ||
2965 (Kind.getKind() == InitializationKind::IK_Copy &&
2966 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2967 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002968 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002969 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002970 // - Otherwise (i.e., for the remaining copy-initialization cases),
2971 // user-defined conversion sequences that can convert from the source
2972 // type to the destination type or (when a conversion function is
2973 // used) to a derived class thereof are enumerated as described in
2974 // 13.3.1.4, and the best one is chosen through overload resolution
2975 // (13.3).
2976 else
2977 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2978 return;
2979 }
2980
Douglas Gregor85dabae2009-12-16 01:38:02 +00002981 if (NumArgs > 1) {
2982 SetFailed(FK_TooManyInitsForScalar);
2983 return;
2984 }
2985 assert(NumArgs == 1 && "Zero-argument case handled above");
2986
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002987 // - Otherwise, if the source type is a (possibly cv-qualified) class
2988 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002989 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002990 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2991 return;
2992 }
2993
2994 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002995 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002996 // conversions (Clause 4) will be used, if necessary, to convert the
2997 // initializer expression to the cv-unqualified version of the
2998 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002999 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003000 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
3001}
3002
3003InitializationSequence::~InitializationSequence() {
3004 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3005 StepEnd = Steps.end();
3006 Step != StepEnd; ++Step)
3007 Step->Destroy();
3008}
3009
3010//===----------------------------------------------------------------------===//
3011// Perform initialization
3012//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00003013static Sema::AssignmentAction
3014getAssignmentAction(const InitializedEntity &Entity) {
3015 switch(Entity.getKind()) {
3016 case InitializedEntity::EK_Variable:
3017 case InitializedEntity::EK_New:
3018 return Sema::AA_Initializing;
3019
3020 case InitializedEntity::EK_Parameter:
3021 // FIXME: Can we tell when we're sending vs. passing?
3022 return Sema::AA_Passing;
3023
3024 case InitializedEntity::EK_Result:
3025 return Sema::AA_Returning;
3026
3027 case InitializedEntity::EK_Exception:
3028 case InitializedEntity::EK_Base:
3029 llvm_unreachable("No assignment action for C++-specific initialization");
3030 break;
3031
3032 case InitializedEntity::EK_Temporary:
3033 // FIXME: Can we tell apart casting vs. converting?
3034 return Sema::AA_Casting;
3035
3036 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003037 case InitializedEntity::EK_ArrayElement:
3038 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003039 return Sema::AA_Initializing;
3040 }
3041
3042 return Sema::AA_Converting;
3043}
3044
3045static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3046 bool IsCopy) {
3047 switch (Entity.getKind()) {
3048 case InitializedEntity::EK_Result:
3049 case InitializedEntity::EK_Exception:
3050 return !IsCopy;
3051
3052 case InitializedEntity::EK_New:
3053 case InitializedEntity::EK_Variable:
3054 case InitializedEntity::EK_Base:
3055 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003056 case InitializedEntity::EK_ArrayElement:
3057 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003058 return false;
3059
3060 case InitializedEntity::EK_Parameter:
3061 case InitializedEntity::EK_Temporary:
3062 return true;
3063 }
3064
3065 llvm_unreachable("missed an InitializedEntity kind?");
3066}
3067
3068/// \brief If we need to perform an additional copy of the initialized object
3069/// for this kind of entity (e.g., the result of a function or an object being
3070/// thrown), make the copy.
3071static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3072 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003073 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003074 Sema::OwningExprResult CurInit) {
3075 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003076
3077 switch (Entity.getKind()) {
3078 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00003079 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00003080 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003081 Loc = Entity.getReturnLoc();
3082 break;
3083
3084 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003085 Loc = Entity.getThrowLoc();
3086 break;
3087
3088 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00003089 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00003090 Kind.getKind() != InitializationKind::IK_Copy)
3091 return move(CurInit);
3092 Loc = Entity.getDecl()->getLocation();
3093 break;
3094
Douglas Gregore1314a62009-12-18 05:02:21 +00003095 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003096 // FIXME: Do we need this initialization for a parameter?
3097 return move(CurInit);
3098
Douglas Gregore1314a62009-12-18 05:02:21 +00003099 case InitializedEntity::EK_New:
3100 case InitializedEntity::EK_Temporary:
3101 case InitializedEntity::EK_Base:
3102 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003103 case InitializedEntity::EK_ArrayElement:
3104 case InitializedEntity::EK_VectorElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003105 // We don't need to copy for any of these initialized entities.
3106 return move(CurInit);
3107 }
3108
3109 Expr *CurInitExpr = (Expr *)CurInit.get();
3110 CXXRecordDecl *Class = 0;
3111 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3112 Class = cast<CXXRecordDecl>(Record->getDecl());
3113 if (!Class)
3114 return move(CurInit);
3115
3116 // Perform overload resolution using the class's copy constructors.
3117 DeclarationName ConstructorName
3118 = S.Context.DeclarationNames.getCXXConstructorName(
3119 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3120 DeclContext::lookup_iterator Con, ConEnd;
3121 OverloadCandidateSet CandidateSet;
3122 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3123 Con != ConEnd; ++Con) {
3124 // Find the constructor (which may be a template).
3125 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3126 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00003127 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00003128 continue;
3129
3130 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3131 }
3132
3133 OverloadCandidateSet::iterator Best;
3134 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3135 case OR_Success:
3136 break;
3137
3138 case OR_No_Viable_Function:
3139 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003140 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003141 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003142 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3143 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003144 return S.ExprError();
3145
3146 case OR_Ambiguous:
3147 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003148 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003149 << CurInitExpr->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003150 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3151 &CurInitExpr, 1);
Douglas Gregore1314a62009-12-18 05:02:21 +00003152 return S.ExprError();
3153
3154 case OR_Deleted:
3155 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003156 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003157 << CurInitExpr->getSourceRange();
3158 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3159 << Best->Function->isDeleted();
3160 return S.ExprError();
3161 }
3162
3163 CurInit.release();
3164 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3165 cast<CXXConstructorDecl>(Best->Function),
3166 /*Elidable=*/true,
3167 Sema::MultiExprArg(S,
3168 (void**)&CurInitExpr, 1));
3169}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003170
3171Action::OwningExprResult
3172InitializationSequence::Perform(Sema &S,
3173 const InitializedEntity &Entity,
3174 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003175 Action::MultiExprArg Args,
3176 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003177 if (SequenceKind == FailedSequence) {
3178 unsigned NumArgs = Args.size();
3179 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3180 return S.ExprError();
3181 }
3182
3183 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003184 // If the declaration is a non-dependent, incomplete array type
3185 // that has an initializer, then its type will be completed once
3186 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003187 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003188 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003189 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003190 if (const IncompleteArrayType *ArrayT
3191 = S.Context.getAsIncompleteArrayType(DeclType)) {
3192 // FIXME: We don't currently have the ability to accurately
3193 // compute the length of an initializer list without
3194 // performing full type-checking of the initializer list
3195 // (since we have to determine where braces are implicitly
3196 // introduced and such). So, we fall back to making the array
3197 // type a dependently-sized array type with no specified
3198 // bound.
3199 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3200 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003201
Douglas Gregor51e77d52009-12-10 17:56:55 +00003202 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003203 if (DeclaratorDecl *DD = Entity.getDecl()) {
3204 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3205 TypeLoc TL = TInfo->getTypeLoc();
3206 if (IncompleteArrayTypeLoc *ArrayLoc
3207 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3208 Brackets = ArrayLoc->getBracketsRange();
3209 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003210 }
3211
3212 *ResultType
3213 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3214 /*NumElts=*/0,
3215 ArrayT->getSizeModifier(),
3216 ArrayT->getIndexTypeCVRQualifiers(),
3217 Brackets);
3218 }
3219
3220 }
3221 }
3222
Eli Friedmana553d4a2009-12-22 02:35:53 +00003223 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003224 return Sema::OwningExprResult(S, Args.release()[0]);
3225
3226 unsigned NumArgs = Args.size();
3227 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3228 SourceLocation(),
3229 (Expr **)Args.release(),
3230 NumArgs,
3231 SourceLocation()));
3232 }
3233
Douglas Gregor85dabae2009-12-16 01:38:02 +00003234 if (SequenceKind == NoInitialization)
3235 return S.Owned((Expr *)0);
3236
Douglas Gregor1b303932009-12-22 15:35:07 +00003237 QualType DestType = Entity.getType().getNonReferenceType();
3238 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003239 // the same as Entity.getDecl()->getType() in cases involving type merging,
3240 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003241 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003242 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003243 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003244
Douglas Gregor85dabae2009-12-16 01:38:02 +00003245 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3246
3247 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3248
3249 // For initialization steps that start with a single initializer,
3250 // grab the only argument out the Args and place it into the "current"
3251 // initializer.
3252 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003253 case SK_ResolveAddressOfOverloadedFunction:
3254 case SK_CastDerivedToBaseRValue:
3255 case SK_CastDerivedToBaseLValue:
3256 case SK_BindReference:
3257 case SK_BindReferenceToTemporary:
3258 case SK_UserConversion:
3259 case SK_QualificationConversionLValue:
3260 case SK_QualificationConversionRValue:
3261 case SK_ConversionSequence:
3262 case SK_ListInitialization:
3263 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003264 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003265 assert(Args.size() == 1);
3266 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3267 if (CurInit.isInvalid())
3268 return S.ExprError();
3269 break;
3270
3271 case SK_ConstructorInitialization:
3272 case SK_ZeroInitialization:
3273 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003274 }
3275
3276 // Walk through the computed steps for the initialization sequence,
3277 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003278 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003279 for (step_iterator Step = step_begin(), StepEnd = step_end();
3280 Step != StepEnd; ++Step) {
3281 if (CurInit.isInvalid())
3282 return S.ExprError();
3283
3284 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003285 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003286
3287 switch (Step->Kind) {
3288 case SK_ResolveAddressOfOverloadedFunction:
3289 // Overload resolution determined which function invoke; update the
3290 // initializer to reflect that choice.
3291 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3292 break;
3293
3294 case SK_CastDerivedToBaseRValue:
3295 case SK_CastDerivedToBaseLValue: {
3296 // We have a derived-to-base cast that produces either an rvalue or an
3297 // lvalue. Perform that cast.
3298
3299 // Casts to inaccessible base classes are allowed with C-style casts.
3300 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3301 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3302 CurInitExpr->getLocStart(),
3303 CurInitExpr->getSourceRange(),
3304 IgnoreBaseAccess))
3305 return S.ExprError();
3306
3307 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3308 CastExpr::CK_DerivedToBase,
3309 (Expr*)CurInit.release(),
3310 Step->Kind == SK_CastDerivedToBaseLValue));
3311 break;
3312 }
3313
3314 case SK_BindReference:
3315 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3316 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3317 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003318 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003319 << BitField->getDeclName()
3320 << CurInitExpr->getSourceRange();
3321 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3322 return S.ExprError();
3323 }
3324
3325 // Reference binding does not have any corresponding ASTs.
3326
3327 // Check exception specifications
3328 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3329 return S.ExprError();
3330 break;
3331
3332 case SK_BindReferenceToTemporary:
3333 // Check exception specifications
3334 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3335 return S.ExprError();
3336
3337 // FIXME: At present, we have no AST to describe when we need to make a
3338 // temporary to bind a reference to. We should.
3339 break;
3340
3341 case SK_UserConversion: {
3342 // We have a user-defined conversion that invokes either a constructor
3343 // or a conversion function.
3344 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003345 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003346 if (CXXConstructorDecl *Constructor
3347 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3348 // Build a call to the selected constructor.
3349 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3350 SourceLocation Loc = CurInitExpr->getLocStart();
3351 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3352
3353 // Determine the arguments required to actually perform the constructor
3354 // call.
3355 if (S.CompleteConstructorCall(Constructor,
3356 Sema::MultiExprArg(S,
3357 (void **)&CurInitExpr,
3358 1),
3359 Loc, ConstructorArgs))
3360 return S.ExprError();
3361
3362 // Build the an expression that constructs a temporary.
3363 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3364 move_arg(ConstructorArgs));
3365 if (CurInit.isInvalid())
3366 return S.ExprError();
3367
3368 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003369 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3370 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3371 S.IsDerivedFrom(SourceType, Class))
3372 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003373 } else {
3374 // Build a call to the conversion function.
3375 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003376
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003377 // FIXME: Should we move this initialization into a separate
3378 // derived-to-base conversion? I believe the answer is "no", because
3379 // we don't want to turn off access control here for c-style casts.
3380 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3381 return S.ExprError();
3382
3383 // Do a little dance to make sure that CurInit has the proper
3384 // pointer.
3385 CurInit.release();
3386
3387 // Build the actual call to the conversion function.
3388 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3389 if (CurInit.isInvalid() || !CurInit.get())
3390 return S.ExprError();
3391
3392 CastKind = CastExpr::CK_UserDefinedConversion;
3393 }
3394
Douglas Gregore1314a62009-12-18 05:02:21 +00003395 if (shouldBindAsTemporary(Entity, IsCopy))
3396 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3397
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003398 CurInitExpr = CurInit.takeAs<Expr>();
3399 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3400 CastKind,
3401 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003402 false));
3403
3404 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003405 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003406 break;
3407 }
3408
3409 case SK_QualificationConversionLValue:
3410 case SK_QualificationConversionRValue:
3411 // Perform a qualification conversion; these can never go wrong.
3412 S.ImpCastExprToType(CurInitExpr, Step->Type,
3413 CastExpr::CK_NoOp,
3414 Step->Kind == SK_QualificationConversionLValue);
3415 CurInit.release();
3416 CurInit = S.Owned(CurInitExpr);
3417 break;
3418
3419 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003420 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003421 false, false, *Step->ICS))
3422 return S.ExprError();
3423
3424 CurInit.release();
3425 CurInit = S.Owned(CurInitExpr);
3426 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003427
3428 case SK_ListInitialization: {
3429 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3430 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003431 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003432 return S.ExprError();
3433
3434 CurInit.release();
3435 CurInit = S.Owned(InitList);
3436 break;
3437 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003438
3439 case SK_ConstructorInitialization: {
3440 CXXConstructorDecl *Constructor
3441 = cast<CXXConstructorDecl>(Step->Function);
3442
3443 // Build a call to the selected constructor.
3444 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3445 SourceLocation Loc = Kind.getLocation();
3446
3447 // Determine the arguments required to actually perform the constructor
3448 // call.
3449 if (S.CompleteConstructorCall(Constructor, move(Args),
3450 Loc, ConstructorArgs))
3451 return S.ExprError();
3452
3453 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003454 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003455 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003456 move_arg(ConstructorArgs),
3457 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003458 if (CurInit.isInvalid())
3459 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003460
3461 bool Elidable
3462 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3463 if (shouldBindAsTemporary(Entity, Elidable))
3464 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3465
3466 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003467 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003468 break;
3469 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003470
3471 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003472 step_iterator NextStep = Step;
3473 ++NextStep;
3474 if (NextStep != StepEnd &&
3475 NextStep->Kind == SK_ConstructorInitialization) {
3476 // The need for zero-initialization is recorded directly into
3477 // the call to the object's constructor within the next step.
3478 ConstructorInitRequiresZeroInit = true;
3479 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3480 S.getLangOptions().CPlusPlus &&
3481 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003482 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3483 Kind.getRange().getBegin(),
3484 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003485 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003486 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003487 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003488 break;
3489 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003490
3491 case SK_CAssignment: {
3492 QualType SourceType = CurInitExpr->getType();
3493 Sema::AssignConvertType ConvTy =
3494 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003495
3496 // If this is a call, allow conversion to a transparent union.
3497 if (ConvTy != Sema::Compatible &&
3498 Entity.getKind() == InitializedEntity::EK_Parameter &&
3499 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3500 == Sema::Compatible)
3501 ConvTy = Sema::Compatible;
3502
Douglas Gregore1314a62009-12-18 05:02:21 +00003503 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3504 Step->Type, SourceType,
3505 CurInitExpr, getAssignmentAction(Entity)))
3506 return S.ExprError();
3507
3508 CurInit.release();
3509 CurInit = S.Owned(CurInitExpr);
3510 break;
3511 }
Eli Friedman78275202009-12-19 08:11:05 +00003512
3513 case SK_StringInit: {
3514 QualType Ty = Step->Type;
3515 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3516 break;
3517 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003518 }
3519 }
3520
3521 return move(CurInit);
3522}
3523
3524//===----------------------------------------------------------------------===//
3525// Diagnose initialization failures
3526//===----------------------------------------------------------------------===//
3527bool InitializationSequence::Diagnose(Sema &S,
3528 const InitializedEntity &Entity,
3529 const InitializationKind &Kind,
3530 Expr **Args, unsigned NumArgs) {
3531 if (SequenceKind != FailedSequence)
3532 return false;
3533
Douglas Gregor1b303932009-12-22 15:35:07 +00003534 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003535 switch (Failure) {
3536 case FK_TooManyInitsForReference:
3537 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3538 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3539 break;
3540
3541 case FK_ArrayNeedsInitList:
3542 case FK_ArrayNeedsInitListOrStringLiteral:
3543 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3544 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3545 break;
3546
3547 case FK_AddressOfOverloadFailed:
3548 S.ResolveAddressOfOverloadedFunction(Args[0],
3549 DestType.getNonReferenceType(),
3550 true);
3551 break;
3552
3553 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003554 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003555 switch (FailedOverloadResult) {
3556 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003557 if (Failure == FK_UserConversionOverloadFailed)
3558 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3559 << Args[0]->getType() << DestType
3560 << Args[0]->getSourceRange();
3561 else
3562 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3563 << DestType << Args[0]->getType()
3564 << Args[0]->getSourceRange();
3565
John McCallad907772010-01-12 07:18:19 +00003566 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3567 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003568 break;
3569
3570 case OR_No_Viable_Function:
3571 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3572 << Args[0]->getType() << DestType.getNonReferenceType()
3573 << Args[0]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00003574 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3575 Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003576 break;
3577
3578 case OR_Deleted: {
3579 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3580 << Args[0]->getType() << DestType.getNonReferenceType()
3581 << Args[0]->getSourceRange();
3582 OverloadCandidateSet::iterator Best;
3583 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3584 Kind.getLocation(),
3585 Best);
3586 if (Ovl == OR_Deleted) {
3587 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3588 << Best->Function->isDeleted();
3589 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003590 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003591 }
3592 break;
3593 }
3594
3595 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003596 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003597 break;
3598 }
3599 break;
3600
3601 case FK_NonConstLValueReferenceBindingToTemporary:
3602 case FK_NonConstLValueReferenceBindingToUnrelated:
3603 S.Diag(Kind.getLocation(),
3604 Failure == FK_NonConstLValueReferenceBindingToTemporary
3605 ? diag::err_lvalue_reference_bind_to_temporary
3606 : diag::err_lvalue_reference_bind_to_unrelated)
3607 << DestType.getNonReferenceType()
3608 << Args[0]->getType()
3609 << Args[0]->getSourceRange();
3610 break;
3611
3612 case FK_RValueReferenceBindingToLValue:
3613 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3614 << Args[0]->getSourceRange();
3615 break;
3616
3617 case FK_ReferenceInitDropsQualifiers:
3618 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3619 << DestType.getNonReferenceType()
3620 << Args[0]->getType()
3621 << Args[0]->getSourceRange();
3622 break;
3623
3624 case FK_ReferenceInitFailed:
3625 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3626 << DestType.getNonReferenceType()
3627 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3628 << Args[0]->getType()
3629 << Args[0]->getSourceRange();
3630 break;
3631
3632 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003633 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3634 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003635 << DestType
3636 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3637 << Args[0]->getType()
3638 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003639 break;
3640
3641 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003642 SourceRange R;
3643
3644 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3645 R = SourceRange(InitList->getInit(1)->getLocStart(),
3646 InitList->getLocEnd());
3647 else
3648 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003649
3650 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003651 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003652 break;
3653 }
3654
3655 case FK_ReferenceBindingToInitList:
3656 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3657 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3658 break;
3659
3660 case FK_InitListBadDestinationType:
3661 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3662 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3663 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003664
3665 case FK_ConstructorOverloadFailed: {
3666 SourceRange ArgsRange;
3667 if (NumArgs)
3668 ArgsRange = SourceRange(Args[0]->getLocStart(),
3669 Args[NumArgs - 1]->getLocEnd());
3670
3671 // FIXME: Using "DestType" for the entity we're printing is probably
3672 // bad.
3673 switch (FailedOverloadResult) {
3674 case OR_Ambiguous:
3675 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3676 << DestType << ArgsRange;
John McCall12f97bc2010-01-08 04:41:39 +00003677 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallad907772010-01-12 07:18:19 +00003678 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003679 break;
3680
3681 case OR_No_Viable_Function:
3682 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3683 << DestType << ArgsRange;
John McCallad907772010-01-12 07:18:19 +00003684 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3685 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003686 break;
3687
3688 case OR_Deleted: {
3689 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3690 << true << DestType << ArgsRange;
3691 OverloadCandidateSet::iterator Best;
3692 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3693 Kind.getLocation(),
3694 Best);
3695 if (Ovl == OR_Deleted) {
3696 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3697 << Best->Function->isDeleted();
3698 } else {
3699 llvm_unreachable("Inconsistent overload resolution?");
3700 }
3701 break;
3702 }
3703
3704 case OR_Success:
3705 llvm_unreachable("Conversion did not fail!");
3706 break;
3707 }
3708 break;
3709 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003710
3711 case FK_DefaultInitOfConst:
3712 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3713 << DestType;
3714 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003715 }
3716
3717 return true;
3718}
Douglas Gregore1314a62009-12-18 05:02:21 +00003719
3720//===----------------------------------------------------------------------===//
3721// Initialization helper functions
3722//===----------------------------------------------------------------------===//
3723Sema::OwningExprResult
3724Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3725 SourceLocation EqualLoc,
3726 OwningExprResult Init) {
3727 if (Init.isInvalid())
3728 return ExprError();
3729
3730 Expr *InitE = (Expr *)Init.get();
3731 assert(InitE && "No initialization expression?");
3732
3733 if (EqualLoc.isInvalid())
3734 EqualLoc = InitE->getLocStart();
3735
3736 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3737 EqualLoc);
3738 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3739 Init.release();
3740 return Seq.Perform(*this, Entity, Kind,
3741 MultiExprArg(*this, (void**)&InitE, 1));
3742}