blob: 4b08e2813605c950a9f051a2fe17de05d7f23000 [file] [log] [blame]
Steve Naroffc4d4a482008-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 Lattnerd3a00502009-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 Lattnere76e9bf2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroffc4d4a482008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
21#include "clang/AST/Expr.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000022#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000023using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000024
Chris Lattnerd3a00502009-02-24 22:27:37 +000025//===----------------------------------------------------------------------===//
26// Sema Initialization Checking
27//===----------------------------------------------------------------------===//
28
Chris Lattner89b91072009-02-24 22:36:59 +000029static StringLiteral *IsStringInit(Expr *Init, QualType DeclType,
30 ASTContext &Context) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000031 if (const ArrayType *AT = Context.getAsArrayType(DeclType))
32 if (AT->getElementType()->isCharType())
33 return dyn_cast<StringLiteral>(Init->IgnoreParens());
34 return 0;
35}
36
Chris Lattner160da072009-02-24 22:46:58 +000037static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
38 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000039 // Get the type before calling CheckSingleAssignmentConstraints(), since
40 // it can promote the expression.
41 QualType InitType = Init->getType();
42
Chris Lattner160da072009-02-24 22:46:58 +000043 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000044 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000045 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
46 return S.Diag(Init->getSourceRange().getBegin(),
47 diag::err_typecheck_convert_incompatible)
48 << DeclType << Init->getType() << "initializing"
49 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000050 return false;
51 }
52
Chris Lattner160da072009-02-24 22:46:58 +000053 Sema::AssignConvertType ConvTy =
54 S.CheckSingleAssignmentConstraints(DeclType, Init);
55 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000056 InitType, Init, "initializing");
57}
58
Chris Lattner45d6fd62009-02-24 22:41:04 +000059static bool CheckStringLiteralInit(StringLiteral *Str, QualType &DeclT,
60 Sema &S) {
61 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000062
63 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
64 // C99 6.7.8p14. We have an array of character type with unknown size
65 // being initialized to a string literal.
66 llvm::APSInt ConstVal(32);
Chris Lattner45d6fd62009-02-24 22:41:04 +000067 ConstVal = Str->getByteLength() + 1;
Chris Lattnerd3a00502009-02-24 22:27:37 +000068 // Return a new array type (C99 6.7.8p22).
Chris Lattner45d6fd62009-02-24 22:41:04 +000069 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
70 ArrayType::Normal, 0);
Chris Lattnerd3a00502009-02-24 22:27:37 +000071 } else {
72 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
73 // C99 6.7.8p14. We have an array of character type with known size.
74 // FIXME: Avoid truncation for 64-bit length strings.
Chris Lattner45d6fd62009-02-24 22:41:04 +000075 if (Str->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
76 S.Diag(Str->getSourceRange().getBegin(),
77 diag::warn_initializer_string_for_char_array_too_long)
78 << Str->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000079 }
80 // Set type from "char *" to "constant array of char".
Chris Lattner45d6fd62009-02-24 22:41:04 +000081 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000082 // For now, we always return false (meaning success).
83 return false;
84}
85
86bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
87 SourceLocation InitLoc,
88 DeclarationName InitEntity,
89 bool DirectInit) {
90 if (DeclType->isDependentType() || Init->isTypeDependent())
91 return false;
92
93 // C++ [dcl.init.ref]p1:
94 // A variable declared to be a T&, that is "reference to type T"
95 // (8.3.2), shall be initialized by an object, or function, of
96 // type T or by an object that can be converted into a T.
97 if (DeclType->isReferenceType())
98 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
99
100 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
101 // of unknown size ("[]") or an object type that is not a variable array type.
102 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
103 return Diag(InitLoc, diag::err_variable_object_no_init)
104 << VAT->getSizeExpr()->getSourceRange();
105
106 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
107 if (!InitList) {
108 // FIXME: Handle wide strings
Chris Lattner45d6fd62009-02-24 22:41:04 +0000109 if (StringLiteral *Str = IsStringInit(Init, DeclType, Context))
110 return CheckStringLiteralInit(Str, DeclType, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000111
112 // C++ [dcl.init]p14:
113 // -- If the destination type is a (possibly cv-qualified) class
114 // type:
115 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
116 QualType DeclTypeC = Context.getCanonicalType(DeclType);
117 QualType InitTypeC = Context.getCanonicalType(Init->getType());
118
119 // -- If the initialization is direct-initialization, or if it is
120 // copy-initialization where the cv-unqualified version of the
121 // source type is the same class as, or a derived class of, the
122 // class of the destination, constructors are considered.
123 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
124 IsDerivedFrom(InitTypeC, DeclTypeC)) {
125 CXXConstructorDecl *Constructor
126 = PerformInitializationByConstructor(DeclType, &Init, 1,
127 InitLoc, Init->getSourceRange(),
128 InitEntity,
129 DirectInit? IK_Direct : IK_Copy);
130 return Constructor == 0;
131 }
132
133 // -- Otherwise (i.e., for the remaining copy-initialization
134 // cases), user-defined conversion sequences that can
135 // convert from the source type to the destination type or
136 // (when a conversion function is used) to a derived class
137 // thereof are enumerated as described in 13.3.1.4, and the
138 // best one is chosen through overload resolution
139 // (13.3). If the conversion cannot be done or is
140 // ambiguous, the initialization is ill-formed. The
141 // function selected is called with the initializer
142 // expression as its argument; if the function is a
143 // constructor, the call initializes a temporary of the
144 // destination type.
145 // FIXME: We're pretending to do copy elision here; return to
146 // this when we have ASTs for such things.
147 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
148 return false;
149
150 if (InitEntity)
151 return Diag(InitLoc, diag::err_cannot_initialize_decl)
152 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
153 << Init->getType() << Init->getSourceRange();
154 else
155 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
156 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
157 << Init->getType() << Init->getSourceRange();
158 }
159
160 // C99 6.7.8p16.
161 if (DeclType->isArrayType())
162 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
163 << Init->getSourceRange();
164
Chris Lattner160da072009-02-24 22:46:58 +0000165 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000166 }
167
168 bool hadError = CheckInitList(InitList, DeclType);
169 Init = InitList;
170 return hadError;
171}
172
173//===----------------------------------------------------------------------===//
174// Semantic checking for initializer lists.
175//===----------------------------------------------------------------------===//
176
Douglas Gregoraaa20962009-01-29 01:05:33 +0000177/// @brief Semantic checking for initializer lists.
178///
179/// The InitListChecker class contains a set of routines that each
180/// handle the initialization of a certain kind of entity, e.g.,
181/// arrays, vectors, struct/union types, scalars, etc. The
182/// InitListChecker itself performs a recursive walk of the subobject
183/// structure of the type to be initialized, while stepping through
184/// the initializer list one element at a time. The IList and Index
185/// parameters to each of the Check* routines contain the active
186/// (syntactic) initializer list and the index into that initializer
187/// list that represents the current initializer. Each routine is
188/// responsible for moving that Index forward as it consumes elements.
189///
190/// Each Check* routine also has a StructuredList/StructuredIndex
191/// arguments, which contains the current the "structured" (semantic)
192/// initializer list and the index into that initializer list where we
193/// are copying initializers as we map them over to the semantic
194/// list. Once we have completed our recursive walk of the subobject
195/// structure, we will have constructed a full semantic initializer
196/// list.
197///
198/// C99 designators cause changes in the initializer list traversal,
199/// because they make the initialization "jump" into a specific
200/// subobject and then continue the initialization from that
201/// point. CheckDesignatedInitializer() recursively steps into the
202/// designated subobject and manages backing out the recursion to
203/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000204namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000205class InitListChecker {
206 Sema *SemaRef;
207 bool hadError;
208 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
209 InitListExpr *FullyStructuredList;
210
211 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000212 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000213 unsigned &StructuredIndex,
214 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000215 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000216 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000217 unsigned &StructuredIndex,
218 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000219 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
220 bool SubobjectIsDesignatorContext,
221 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000225 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
226 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000229 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000230 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000231 InitListExpr *StructuredList,
232 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000233 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
234 unsigned &Index,
235 InitListExpr *StructuredList,
236 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000237 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000240 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
241 RecordDecl::field_iterator Field,
242 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000243 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000244 unsigned &StructuredIndex,
245 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000246 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
247 llvm::APSInt elementIndex,
248 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000249 InitListExpr *StructuredList,
250 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000251 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
252 DesignatedInitExpr::designators_iterator D,
253 QualType &CurrentObjectType,
254 RecordDecl::field_iterator *NextField,
255 llvm::APSInt *NextElementIndex,
256 unsigned &Index,
257 InitListExpr *StructuredList,
258 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000259 bool FinishSubobjectInit,
260 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000261 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
262 QualType CurrentObjectType,
263 InitListExpr *StructuredList,
264 unsigned StructuredIndex,
265 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000266 void UpdateStructuredListElement(InitListExpr *StructuredList,
267 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000268 Expr *expr);
269 int numArrayElements(QualType DeclType);
270 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000271
272 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000273public:
274 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
275 bool HadError() { return hadError; }
276
277 // @brief Retrieves the fully-structured initializer list used for
278 // semantic analysis and code generation.
279 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
280};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000281} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000282
Douglas Gregorf603b472009-01-28 21:54:33 +0000283/// Recursively replaces NULL values within the given initializer list
284/// with expressions that perform value-initialization of the
285/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000286void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
287 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
288 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000289 SourceLocation Loc = ILE->getSourceRange().getBegin();
290 if (ILE->getSyntacticForm())
291 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
292
Douglas Gregorf603b472009-01-28 21:54:33 +0000293 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
294 unsigned Init = 0, NumInits = ILE->getNumInits();
295 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
296 FieldEnd = RType->getDecl()->field_end();
297 Field != FieldEnd; ++Field) {
298 if (Field->isUnnamedBitfield())
299 continue;
300
Douglas Gregor538a4c22009-02-02 17:43:21 +0000301 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000302 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.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000307 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000308 << Field->getType()
309 << ILE->getSyntacticForm()->getSourceRange();
310 SemaRef->Diag(Field->getLocation(),
311 diag::note_uninit_reference_member);
312 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000313 return;
314 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
315 hadError = true;
316 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000317 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000318
319 // FIXME: If value-initialization involves calling a
320 // constructor, should we make that call explicit in the
321 // representation (even when it means extending the
322 // initializer list)?
323 if (Init < NumInits && !hadError)
324 ILE->setInit(Init,
325 new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
326 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000327 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000328 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000329 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000330
331 // Only look at the first initialization of a union.
332 if (RType->getDecl()->isUnion())
333 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000334 }
335
336 return;
337 }
338
339 QualType ElementType;
340
Douglas Gregor538a4c22009-02-02 17:43:21 +0000341 unsigned NumInits = ILE->getNumInits();
342 unsigned NumElements = NumInits;
343 if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000344 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000345 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346 NumElements = CAType->getSize().getZExtValue();
347 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000348 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000349 NumElements = VType->getNumElements();
350 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000351 ElementType = ILE->getType();
352
Douglas Gregor538a4c22009-02-02 17:43:21 +0000353 for (unsigned Init = 0; Init != NumElements; ++Init) {
354 if (Init >= NumInits || !ILE->getInit(Init)) {
355 if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
356 hadError = true;
357 return;
358 }
359
360 // FIXME: If value-initialization involves calling a
361 // constructor, should we make that call explicit in the
362 // representation (even when it means extending the
363 // initializer list)?
364 if (Init < NumInits && !hadError)
365 ILE->setInit(Init,
366 new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
367 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000368 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000369 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000370 }
371}
372
Chris Lattner1aa25a72009-01-29 05:10:57 +0000373
Steve Naroffc4d4a482008-05-01 22:18:59 +0000374InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
375 hadError = false;
376 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000377
Eli Friedman683cedf2008-05-19 19:16:24 +0000378 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000379 unsigned newStructuredIndex = 0;
380 FullyStructuredList
381 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000382 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
383 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000384
Douglas Gregord45210d2009-01-30 22:09:00 +0000385 if (!hadError)
386 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000387}
388
389int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000390 // FIXME: use a proper constant
391 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000392 if (const ConstantArrayType *CAT =
393 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000394 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
395 }
396 return maxElements;
397}
398
399int InitListChecker::numStructUnionElements(QualType DeclType) {
400 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000401 int InitializableMembers = 0;
402 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
403 FieldEnd = structDecl->field_end();
404 Field != FieldEnd; ++Field) {
405 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
406 ++InitializableMembers;
407 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000408 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000409 return std::min(InitializableMembers, 1);
410 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000411}
412
413void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000414 QualType T, unsigned &Index,
415 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000416 unsigned &StructuredIndex,
417 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000418 int maxElements = 0;
419
420 if (T->isArrayType())
421 maxElements = numArrayElements(T);
422 else if (T->isStructureType() || T->isUnionType())
423 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000424 else if (T->isVectorType())
425 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000426 else
427 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000428
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000429 if (maxElements == 0) {
430 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
431 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000432 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000433 hadError = true;
434 return;
435 }
436
Douglas Gregorf603b472009-01-28 21:54:33 +0000437 // Build a structured initializer list corresponding to this subobject.
438 InitListExpr *StructuredSubobjectInitList
439 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
440 StructuredIndex,
441 ParentIList->getInit(Index)->getSourceRange());
442 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000443
Douglas Gregorf603b472009-01-28 21:54:33 +0000444 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000445 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000446 CheckListElementTypes(ParentIList, T, false, Index,
447 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000448 StructuredSubobjectInitIndex,
449 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000450 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
451
452 // Update the structured sub-object initialize so that it's ending
453 // range corresponds with the end of the last initializer it used.
454 if (EndIndex < ParentIList->getNumInits()) {
455 SourceLocation EndLoc
456 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
457 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
458 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000459}
460
Steve Naroff56099522008-05-06 00:23:44 +0000461void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000462 unsigned &Index,
463 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000464 unsigned &StructuredIndex,
465 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000466 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000467 SyntacticToSemantic[IList] = StructuredList;
468 StructuredList->setSyntacticForm(IList);
469 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000470 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000471 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000472 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000473 if (hadError)
474 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000475
Eli Friedman46f81662008-05-25 13:22:35 +0000476 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000477 // We have leftover initializers
478 if (IList->getNumInits() > 0 &&
Chris Lattner89b91072009-02-24 22:36:59 +0000479 IsStringInit(IList->getInit(Index), T, SemaRef->Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000480 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
481 if (SemaRef->getLangOptions().CPlusPlus)
482 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000483 // Special-case
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000484 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000485 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000486 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000487 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000488 // Don't complain for incomplete types, since we'll get an error
489 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000490 QualType CurrentObjectType = StructuredList->getType();
491 int initKind =
492 CurrentObjectType->isArrayType()? 0 :
493 CurrentObjectType->isVectorType()? 1 :
494 CurrentObjectType->isScalarType()? 2 :
495 CurrentObjectType->isUnionType()? 3 :
496 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000497
498 unsigned DK = diag::warn_excess_initializers;
499 if (SemaRef->getLangOptions().CPlusPlus)
500 DK = diag::err_excess_initializers;
501
502 SemaRef->Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000503 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000504 }
505 }
Eli Friedman455f7622008-05-19 20:20:43 +0000506
Eli Friedman46f81662008-05-25 13:22:35 +0000507 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000508 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
509 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000510}
511
Eli Friedman683cedf2008-05-19 19:16:24 +0000512void InitListChecker::CheckListElementTypes(InitListExpr *IList,
513 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000514 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000515 unsigned &Index,
516 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000517 unsigned &StructuredIndex,
518 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000519 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000520 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000521 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000522 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000523 } else if (DeclType->isAggregateType()) {
524 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000525 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
526 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000527 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000528 StructuredList, StructuredIndex,
529 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000530 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000531 llvm::APSInt Zero(
532 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
533 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000534 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
535 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000536 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000537 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000538 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000539 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
540 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000541 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000542 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000543 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000544 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000545 } else if (DeclType->isRecordType()) {
546 // C++ [dcl.init]p14:
547 // [...] If the class is an aggregate (8.5.1), and the initializer
548 // is a brace-enclosed list, see 8.5.1.
549 //
550 // Note: 8.5.1 is handled below; here, we diagnose the case where
551 // we have an initializer list and a destination type that is not
552 // an aggregate.
553 // FIXME: In C++0x, this is yet another form of initialization.
554 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
555 << DeclType << IList->getSourceRange();
556 hadError = true;
557 } else if (DeclType->isReferenceType()) {
558 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000559 } else {
560 // In C, all types are either scalars or aggregates, but
561 // additional handling is needed here for C++ (and possibly others?).
562 assert(0 && "Unsupported initializer type");
563 }
564}
565
Eli Friedman683cedf2008-05-19 19:16:24 +0000566void InitListChecker::CheckSubElementType(InitListExpr *IList,
567 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000568 unsigned &Index,
569 InitListExpr *StructuredList,
570 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000571 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000572 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
573 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000574 unsigned newStructuredIndex = 0;
575 InitListExpr *newStructuredList
576 = getStructuredSubobjectInit(IList, Index, ElemType,
577 StructuredList, StructuredIndex,
578 SubInitList->getSourceRange());
579 CheckExplicitInitList(SubInitList, ElemType, newIndex,
580 newStructuredList, newStructuredIndex);
581 ++StructuredIndex;
582 ++Index;
Chris Lattner45d6fd62009-02-24 22:41:04 +0000583 } else if (StringLiteral *Str = IsStringInit(expr, ElemType,
Chris Lattner89b91072009-02-24 22:36:59 +0000584 SemaRef->Context)) {
Chris Lattner45d6fd62009-02-24 22:41:04 +0000585 CheckStringLiteralInit(Str, ElemType, *SemaRef);
586 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000587 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000588 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000589 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000590 } else if (ElemType->isReferenceType()) {
591 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000592 } else {
Douglas Gregord45210d2009-01-30 22:09:00 +0000593 if (SemaRef->getLangOptions().CPlusPlus) {
594 // C++ [dcl.init.aggr]p12:
595 // All implicit type conversions (clause 4) are considered when
596 // initializing the aggregate member with an ini- tializer from
597 // an initializer-list. If the initializer can initialize a
598 // member, the member is initialized. [...]
599 ImplicitConversionSequence ICS
600 = SemaRef->TryCopyInitialization(expr, ElemType);
601 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
602 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
603 "initializing"))
604 hadError = true;
605 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
606 ++Index;
607 return;
608 }
609
610 // Fall through for subaggregate initialization
611 } else {
612 // C99 6.7.8p13:
613 //
614 // The initializer for a structure or union object that has
615 // automatic storage duration shall be either an initializer
616 // list as described below, or a single expression that has
617 // compatible structure or union type. In the latter case, the
618 // initial value of the object, including unnamed members, is
619 // that of the expression.
620 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
621 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
622 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
623 ElemTypeCanon.getUnqualifiedType())) {
624 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
625 ++Index;
626 return;
627 }
628
629 // Fall through for subaggregate initialization
630 }
631
632 // C++ [dcl.init.aggr]p12:
633 //
634 // [...] Otherwise, if the member is itself a non-empty
635 // subaggregate, brace elision is assumed and the initializer is
636 // considered for the initialization of the first member of
637 // the subaggregate.
638 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
639 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
640 StructuredIndex);
641 ++StructuredIndex;
642 } else {
643 // We cannot initialize this element, so let
644 // PerformCopyInitialization produce the appropriate diagnostic.
645 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
646 hadError = true;
647 ++Index;
648 ++StructuredIndex;
649 }
650 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000651}
652
Douglas Gregord45210d2009-01-30 22:09:00 +0000653void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000654 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000655 InitListExpr *StructuredList,
656 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000657 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000658 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000659 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000660 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000661 diag::err_many_braces_around_scalar_init)
662 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000663 hadError = true;
664 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000665 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000666 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000667 } else if (isa<DesignatedInitExpr>(expr)) {
668 SemaRef->Diag(expr->getSourceRange().getBegin(),
669 diag::err_designator_for_scalar_init)
670 << DeclType << expr->getSourceRange();
671 hadError = true;
672 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000673 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000674 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000675 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000676
Eli Friedmand8535af2008-05-19 20:00:43 +0000677 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner160da072009-02-24 22:46:58 +0000678 if (CheckSingleInitializer(expr, DeclType, false, *SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000679 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000680 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000681 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000682 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000683 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000684 if (hadError)
685 ++StructuredIndex;
686 else
687 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000688 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000689 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000690 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
691 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000692 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000693 ++Index;
694 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000695 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000696 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000697}
698
Douglas Gregord45210d2009-01-30 22:09:00 +0000699void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
700 unsigned &Index,
701 InitListExpr *StructuredList,
702 unsigned &StructuredIndex) {
703 if (Index < IList->getNumInits()) {
704 Expr *expr = IList->getInit(Index);
705 if (isa<InitListExpr>(expr)) {
706 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
707 << DeclType << IList->getSourceRange();
708 hadError = true;
709 ++Index;
710 ++StructuredIndex;
711 return;
712 }
713
714 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
715 if (SemaRef->CheckReferenceInit(expr, DeclType))
716 hadError = true;
717 else if (savExpr != expr) {
718 // The type was promoted, update initializer list.
719 IList->setInit(Index, expr);
720 }
721 if (hadError)
722 ++StructuredIndex;
723 else
724 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
725 ++Index;
726 } else {
727 // FIXME: It would be wonderful if we could point at the actual
728 // member. In general, it would be useful to pass location
729 // information down the stack, so that we know the location (or
730 // decl) of the "current object" being initialized.
731 SemaRef->Diag(IList->getLocStart(),
732 diag::err_init_reference_member_uninitialized)
733 << DeclType
734 << IList->getSourceRange();
735 hadError = true;
736 ++Index;
737 ++StructuredIndex;
738 return;
739 }
740}
741
Steve Naroffc4d4a482008-05-01 22:18:59 +0000742void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000743 unsigned &Index,
744 InitListExpr *StructuredList,
745 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000746 if (Index < IList->getNumInits()) {
747 const VectorType *VT = DeclType->getAsVectorType();
748 int maxElements = VT->getNumElements();
749 QualType elementType = VT->getElementType();
750
751 for (int i = 0; i < maxElements; ++i) {
752 // Don't attempt to go past the end of the init list
753 if (Index >= IList->getNumInits())
754 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000755 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000756 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000757 }
758 }
759}
760
761void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000762 llvm::APSInt elementIndex,
763 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000764 unsigned &Index,
765 InitListExpr *StructuredList,
766 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000767 // Check for the special-case of initializing an array with a string.
768 if (Index < IList->getNumInits()) {
Chris Lattner45d6fd62009-02-24 22:41:04 +0000769 if (StringLiteral *Str = IsStringInit(IList->getInit(Index), DeclType,
Chris Lattner89b91072009-02-24 22:36:59 +0000770 SemaRef->Context)) {
Chris Lattner45d6fd62009-02-24 22:41:04 +0000771 CheckStringLiteralInit(Str, DeclType, *SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000772 // We place the string literal directly into the resulting
773 // initializer list. This is the only place where the structure
774 // of the structured initializer list doesn't match exactly,
775 // because doing so would involve allocating one character
776 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000777 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000778 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000779 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000780 return;
781 }
782 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000783 if (const VariableArrayType *VAT =
784 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000785 // Check for VLAs; in standard C it would be possible to check this
786 // earlier, but I don't know where clang accepts VLAs (gcc accepts
787 // them in all sorts of strange places).
788 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000789 diag::err_variable_object_no_init)
790 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000791 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000792 ++Index;
793 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000794 return;
795 }
796
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000797 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000798 llvm::APSInt maxElements(elementIndex.getBitWidth(),
799 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000800 bool maxElementsKnown = false;
801 if (const ConstantArrayType *CAT =
802 SemaRef->Context.getAsConstantArrayType(DeclType)) {
803 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000804 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000805 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000806 maxElementsKnown = true;
807 }
808
Chris Lattnera1923f62008-08-04 07:31:14 +0000809 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
810 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000811 while (Index < IList->getNumInits()) {
812 Expr *Init = IList->getInit(Index);
813 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000814 // If we're not the subobject that matches up with the '{' for
815 // the designator, we shouldn't be handling the
816 // designator. Return immediately.
817 if (!SubobjectIsDesignatorContext)
818 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000819
Douglas Gregor710f6d42009-01-22 23:26:18 +0000820 // Handle this designated initializer. elementIndex will be
821 // updated to be the next array element we'll initialize.
822 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000823 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000824 StructuredList, StructuredIndex, true,
825 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000826 hadError = true;
827 continue;
828 }
829
Douglas Gregor5a203a62009-01-23 16:54:12 +0000830 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
831 maxElements.extend(elementIndex.getBitWidth());
832 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
833 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000834 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000835
Douglas Gregor710f6d42009-01-22 23:26:18 +0000836 // If the array is of incomplete type, keep track of the number of
837 // elements in the initializer.
838 if (!maxElementsKnown && elementIndex > maxElements)
839 maxElements = elementIndex;
840
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000841 continue;
842 }
843
844 // If we know the maximum number of elements, and we've already
845 // hit it, stop consuming elements in the initializer list.
846 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000847 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000848
849 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000850 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000851 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000852 ++elementIndex;
853
854 // If the array is of incomplete type, keep track of the number of
855 // elements in the initializer.
856 if (!maxElementsKnown && elementIndex > maxElements)
857 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000858 }
859 if (DeclType->isIncompleteArrayType()) {
860 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000861 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000862 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000863 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000864 // Sizing an array implicitly to zero is not allowed by ISO C,
865 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000866 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000867 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000868 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000869
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000870 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000871 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000872 }
873}
874
875void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
876 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000877 RecordDecl::field_iterator Field,
878 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000879 unsigned &Index,
880 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000881 unsigned &StructuredIndex,
882 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000883 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000884
Eli Friedman683cedf2008-05-19 19:16:24 +0000885 // If the record is invalid, some of it's members are invalid. To avoid
886 // confusion, we forgo checking the intializer for the entire record.
887 if (structDecl->isInvalidDecl()) {
888 hadError = true;
889 return;
890 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000891
892 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
893 // Value-initialize the first named member of the union.
894 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
895 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
896 Field != FieldEnd; ++Field) {
897 if (Field->getDeclName()) {
898 StructuredList->setInitializedFieldInUnion(*Field);
899 break;
900 }
901 }
902 return;
903 }
904
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000905 // If structDecl is a forward declaration, this loop won't do
906 // anything except look at designated initializers; That's okay,
907 // because an error should get printed out elsewhere. It might be
908 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000909 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000910 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000911 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000912 while (Index < IList->getNumInits()) {
913 Expr *Init = IList->getInit(Index);
914
915 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000916 // If we're not the subobject that matches up with the '{' for
917 // the designator, we shouldn't be handling the
918 // designator. Return immediately.
919 if (!SubobjectIsDesignatorContext)
920 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000921
Douglas Gregor710f6d42009-01-22 23:26:18 +0000922 // Handle this designated initializer. Field will be updated to
923 // the next field that we'll be initializing.
924 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000925 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000926 StructuredList, StructuredIndex,
927 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000928 hadError = true;
929
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000930 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000931 continue;
932 }
933
934 if (Field == FieldEnd) {
935 // We've run out of fields. We're done.
936 break;
937 }
938
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000939 // We've already initialized a member of a union. We're done.
940 if (InitializedSomething && DeclType->isUnionType())
941 break;
942
Douglas Gregor8acb7272008-12-11 16:49:14 +0000943 // If we've hit the flexible array member at the end, we're done.
944 if (Field->getType()->isIncompleteArrayType())
945 break;
946
Douglas Gregor82462762009-01-29 16:53:55 +0000947 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000948 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000949 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000950 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000951 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000952
Douglas Gregor36859eb2009-01-29 00:39:20 +0000953 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000954 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000955 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +0000956
957 if (DeclType->isUnionType()) {
958 // Initialize the first field within the union.
959 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +0000960 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000961
962 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000963 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000964
Douglas Gregorbe69b162009-02-04 22:46:25 +0000965 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
966 Index >= IList->getNumInits() ||
967 !isa<InitListExpr>(IList->getInit(Index)))
968 return;
969
970 // Handle GNU flexible array initializers.
971 if (!TopLevelObject &&
972 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
973 SemaRef->Diag(IList->getInit(Index)->getSourceRange().getBegin(),
974 diag::err_flexible_array_init_nonempty)
975 << IList->getInit(Index)->getSourceRange().getBegin();
976 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
977 << *Field;
978 hadError = true;
979 }
980
981 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
982 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000983}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000984
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000985/// @brief Check the well-formedness of a C99 designated initializer.
986///
987/// Determines whether the designated initializer @p DIE, which
988/// resides at the given @p Index within the initializer list @p
989/// IList, is well-formed for a current object of type @p DeclType
990/// (C99 6.7.8). The actual subobject that this designator refers to
991/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000992/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000993///
994/// @param IList The initializer list in which this designated
995/// initializer occurs.
996///
997/// @param DIE The designated initializer and its initialization
998/// expression.
999///
1000/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1001/// into which the designation in @p DIE should refer.
1002///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001003/// @param NextField If non-NULL and the first designator in @p DIE is
1004/// a field, this will be set to the field declaration corresponding
1005/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001006///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001007/// @param NextElementIndex If non-NULL and the first designator in @p
1008/// DIE is an array designator or GNU array-range designator, this
1009/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001010///
1011/// @param Index Index into @p IList where the designated initializer
1012/// @p DIE occurs.
1013///
Douglas Gregorf603b472009-01-28 21:54:33 +00001014/// @param StructuredList The initializer list expression that
1015/// describes all of the subobject initializers in the order they'll
1016/// actually be initialized.
1017///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001018/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001019bool
1020InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1021 DesignatedInitExpr *DIE,
1022 DesignatedInitExpr::designators_iterator D,
1023 QualType &CurrentObjectType,
1024 RecordDecl::field_iterator *NextField,
1025 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001026 unsigned &Index,
1027 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001028 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001029 bool FinishSubobjectInit,
1030 bool TopLevelObject) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001031 if (D == DIE->designators_end()) {
1032 // Check the actual initialization for the designated object type.
1033 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001034
1035 // Temporarily remove the designator expression from the
1036 // initializer list that the child calls see, so that we don't try
1037 // to re-process the designator.
1038 unsigned OldIndex = Index;
1039 IList->setInit(OldIndex, DIE->getInit());
1040
1041 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001042 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001043
1044 // Restore the designated initializer expression in the syntactic
1045 // form of the initializer list.
1046 if (IList->getInit(OldIndex) != DIE->getInit())
1047 DIE->setInit(IList->getInit(OldIndex));
1048 IList->setInit(OldIndex, DIE);
1049
Douglas Gregor710f6d42009-01-22 23:26:18 +00001050 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001051 }
1052
Douglas Gregorf603b472009-01-28 21:54:33 +00001053 bool IsFirstDesignator = (D == DIE->designators_begin());
1054 assert((IsFirstDesignator || StructuredList) &&
1055 "Need a non-designated initializer list to start from");
1056
1057 // Determine the structural initializer list that corresponds to the
1058 // current subobject.
1059 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1060 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
1061 StructuredIndex,
1062 SourceRange(D->getStartLocation(),
1063 DIE->getSourceRange().getEnd()));
1064 assert(StructuredList && "Expected a structured initializer list");
1065
Douglas Gregor710f6d42009-01-22 23:26:18 +00001066 if (D->isFieldDesignator()) {
1067 // C99 6.7.8p7:
1068 //
1069 // If a designator has the form
1070 //
1071 // . identifier
1072 //
1073 // then the current object (defined below) shall have
1074 // structure or union type and the identifier shall be the
1075 // name of a member of that type.
1076 const RecordType *RT = CurrentObjectType->getAsRecordType();
1077 if (!RT) {
1078 SourceLocation Loc = D->getDotLoc();
1079 if (Loc.isInvalid())
1080 Loc = D->getFieldLoc();
1081 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
1082 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
1083 ++Index;
1084 return true;
1085 }
1086
Douglas Gregorf603b472009-01-28 21:54:33 +00001087 // Note: we perform a linear search of the fields here, despite
1088 // the fact that we have a faster lookup method, because we always
1089 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001090 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001091 unsigned FieldIndex = 0;
1092 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
1093 FieldEnd = RT->getDecl()->field_end();
1094 for (; Field != FieldEnd; ++Field) {
1095 if (Field->isUnnamedBitfield())
1096 continue;
1097
1098 if (Field->getIdentifier() == FieldName)
1099 break;
1100
1101 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001102 }
1103
Douglas Gregorf603b472009-01-28 21:54:33 +00001104 if (Field == FieldEnd) {
1105 // We did not find the field we're looking for. Produce a
1106 // suitable diagnostic and return a failure.
1107 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1108 if (Lookup.first == Lookup.second) {
1109 // Name lookup didn't find anything.
1110 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1111 << FieldName << CurrentObjectType;
1112 } else {
1113 // Name lookup found something, but it wasn't a field.
1114 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1115 << FieldName;
1116 SemaRef->Diag((*Lookup.first)->getLocation(),
1117 diag::note_field_designator_found);
1118 }
1119
1120 ++Index;
1121 return true;
1122 } else if (cast<RecordDecl>((*Field)->getDeclContext())
1123 ->isAnonymousStructOrUnion()) {
1124 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
1125 << FieldName
1126 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
1127 (int)SemaRef->getLangOptions().CPlusPlus);
1128 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001129 ++Index;
1130 return true;
1131 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001132
1133 // All of the fields of a union are located at the same place in
1134 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001135 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001136 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001137 StructuredList->setInitializedFieldInUnion(*Field);
1138 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001139
Douglas Gregor710f6d42009-01-22 23:26:18 +00001140 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001141 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001142
Douglas Gregorf603b472009-01-28 21:54:33 +00001143 // Make sure that our non-designated initializer list has space
1144 // for a subobject corresponding to this field.
1145 if (FieldIndex >= StructuredList->getNumInits())
1146 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
1147
Douglas Gregorbe69b162009-02-04 22:46:25 +00001148 // This designator names a flexible array member.
1149 if (Field->getType()->isIncompleteArrayType()) {
1150 bool Invalid = false;
1151 DesignatedInitExpr::designators_iterator NextD = D;
1152 ++NextD;
1153 if (NextD != DIE->designators_end()) {
1154 // We can't designate an object within the flexible array
1155 // member (because GCC doesn't allow it).
1156 SemaRef->Diag(NextD->getStartLocation(),
1157 diag::err_designator_into_flexible_array_member)
1158 << SourceRange(NextD->getStartLocation(),
1159 DIE->getSourceRange().getEnd());
1160 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1161 << *Field;
1162 Invalid = true;
1163 }
1164
1165 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1166 // The initializer is not an initializer list.
1167 SemaRef->Diag(DIE->getInit()->getSourceRange().getBegin(),
1168 diag::err_flexible_array_init_needs_braces)
1169 << DIE->getInit()->getSourceRange();
1170 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1171 << *Field;
1172 Invalid = true;
1173 }
1174
1175 // Handle GNU flexible array initializers.
1176 if (!Invalid && !TopLevelObject &&
1177 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1178 SemaRef->Diag(DIE->getSourceRange().getBegin(),
1179 diag::err_flexible_array_init_nonempty)
1180 << DIE->getSourceRange().getBegin();
1181 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1182 << *Field;
1183 Invalid = true;
1184 }
1185
1186 if (Invalid) {
1187 ++Index;
1188 return true;
1189 }
1190
1191 // Initialize the array.
1192 bool prevHadError = hadError;
1193 unsigned newStructuredIndex = FieldIndex;
1194 unsigned OldIndex = Index;
1195 IList->setInit(Index, DIE->getInit());
1196 CheckSubElementType(IList, Field->getType(), Index,
1197 StructuredList, newStructuredIndex);
1198 IList->setInit(OldIndex, DIE);
1199 if (hadError && !prevHadError) {
1200 ++Field;
1201 ++FieldIndex;
1202 if (NextField)
1203 *NextField = Field;
1204 StructuredIndex = FieldIndex;
1205 return true;
1206 }
1207 } else {
1208 // Recurse to check later designated subobjects.
1209 QualType FieldType = (*Field)->getType();
1210 unsigned newStructuredIndex = FieldIndex;
1211 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1212 StructuredList, newStructuredIndex,
1213 true, false))
1214 return true;
1215 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001216
1217 // Find the position of the next field to be initialized in this
1218 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001219 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001220 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001221
1222 // If this the first designator, our caller will continue checking
1223 // the rest of this struct/class/union subobject.
1224 if (IsFirstDesignator) {
1225 if (NextField)
1226 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001227 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001228 return false;
1229 }
1230
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001231 if (!FinishSubobjectInit)
1232 return false;
1233
Douglas Gregor710f6d42009-01-22 23:26:18 +00001234 // Check the remaining fields within this class/struct/union subobject.
1235 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001236 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1237 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001238 return hadError && !prevHadError;
1239 }
1240
1241 // C99 6.7.8p6:
1242 //
1243 // If a designator has the form
1244 //
1245 // [ constant-expression ]
1246 //
1247 // then the current object (defined below) shall have array
1248 // type and the expression shall be an integer constant
1249 // expression. If the array is of unknown size, any
1250 // nonnegative value is valid.
1251 //
1252 // Additionally, cope with the GNU extension that permits
1253 // designators of the form
1254 //
1255 // [ constant-expression ... constant-expression ]
1256 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
1257 if (!AT) {
1258 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1259 << CurrentObjectType;
1260 ++Index;
1261 return true;
1262 }
1263
1264 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001265 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1266 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001267 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001268
1269 bool ConstExpr
1270 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1271 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1272
1273 DesignatedEndIndex = DesignatedStartIndex;
1274 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001275 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001276
1277 bool StartConstExpr
1278 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1279 SemaRef->Context);
1280 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1281
1282 bool EndConstExpr
1283 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1284 SemaRef->Context);
1285 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1286
Douglas Gregor710f6d42009-01-22 23:26:18 +00001287 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001288
1289 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001290 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001291 }
1292
Douglas Gregor710f6d42009-01-22 23:26:18 +00001293 if (isa<ConstantArrayType>(AT)) {
1294 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001295 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1296 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1297 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1298 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1299 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001300 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1301 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001302 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001303 << IndexExpr->getSourceRange();
1304 ++Index;
1305 return true;
1306 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001307 } else {
1308 // Make sure the bit-widths and signedness match.
1309 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1310 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1311 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1312 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1313 DesignatedStartIndex.setIsUnsigned(true);
1314 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001315 }
1316
Douglas Gregorf603b472009-01-28 21:54:33 +00001317 // Make sure that our non-designated initializer list has space
1318 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001319 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1320 StructuredList->resizeInits(SemaRef->Context,
1321 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001322
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001323 // Repeatedly perform subobject initializations in the range
1324 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001325
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001326 // Move to the next designator
1327 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1328 unsigned OldIndex = Index;
1329 ++D;
1330 while (DesignatedStartIndex <= DesignatedEndIndex) {
1331 // Recurse to check later designated subobjects.
1332 QualType ElementType = AT->getElementType();
1333 Index = OldIndex;
1334 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1335 StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001336 (DesignatedStartIndex == DesignatedEndIndex),
1337 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001338 return true;
1339
1340 // Move to the next index in the array that we'll be initializing.
1341 ++DesignatedStartIndex;
1342 ElementIndex = DesignatedStartIndex.getZExtValue();
1343 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001344
1345 // If this the first designator, our caller will continue checking
1346 // the rest of this array subobject.
1347 if (IsFirstDesignator) {
1348 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001349 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001350 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001351 return false;
1352 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001353
1354 if (!FinishSubobjectInit)
1355 return false;
1356
Douglas Gregor710f6d42009-01-22 23:26:18 +00001357 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001358 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001359 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001360 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001361 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001362}
1363
Douglas Gregorf603b472009-01-28 21:54:33 +00001364// Get the structured initializer list for a subobject of type
1365// @p CurrentObjectType.
1366InitListExpr *
1367InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1368 QualType CurrentObjectType,
1369 InitListExpr *StructuredList,
1370 unsigned StructuredIndex,
1371 SourceRange InitRange) {
1372 Expr *ExistingInit = 0;
1373 if (!StructuredList)
1374 ExistingInit = SyntacticToSemantic[IList];
1375 else if (StructuredIndex < StructuredList->getNumInits())
1376 ExistingInit = StructuredList->getInit(StructuredIndex);
1377
1378 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1379 return Result;
1380
1381 if (ExistingInit) {
1382 // We are creating an initializer list that initializes the
1383 // subobjects of the current object, but there was already an
1384 // initialization that completely initialized the current
1385 // subobject, e.g., by a compound literal:
1386 //
1387 // struct X { int a, b; };
1388 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1389 //
1390 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1391 // designated initializer re-initializes the whole
1392 // subobject [0], overwriting previous initializers.
1393 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1394 << InitRange;
1395 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1396 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001397 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001398 << ExistingInit->getSourceRange();
1399 }
1400
Douglas Gregor538a4c22009-02-02 17:43:21 +00001401 SourceLocation StartLoc;
1402 if (Index < IList->getNumInits())
1403 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregorf603b472009-01-28 21:54:33 +00001404 InitListExpr *Result
Douglas Gregor538a4c22009-02-02 17:43:21 +00001405 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1406 IList->getSourceRange().getEnd());
Douglas Gregorf603b472009-01-28 21:54:33 +00001407 Result->setType(CurrentObjectType);
1408
1409 // Link this new initializer list into the structured initializer
1410 // lists.
1411 if (StructuredList)
1412 StructuredList->updateInit(StructuredIndex, Result);
1413 else {
1414 Result->setSyntacticForm(IList);
1415 SyntacticToSemantic[IList] = Result;
1416 }
1417
1418 return Result;
1419}
1420
1421/// Update the initializer at index @p StructuredIndex within the
1422/// structured initializer list to the value @p expr.
1423void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1424 unsigned &StructuredIndex,
1425 Expr *expr) {
1426 // No structured initializer list to update
1427 if (!StructuredList)
1428 return;
1429
1430 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1431 // This initializer overwrites a previous initializer. Warn.
1432 SemaRef->Diag(expr->getSourceRange().getBegin(),
1433 diag::warn_initializer_overrides)
1434 << expr->getSourceRange();
1435 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1436 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001437 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001438 << PrevInit->getSourceRange();
1439 }
1440
1441 ++StructuredIndex;
1442}
1443
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001444/// Check that the given Index expression is a valid array designator
1445/// value. This is essentailly just a wrapper around
1446/// Expr::isIntegerConstantExpr that also checks for negative values
1447/// and produces a reasonable diagnostic if there is a
1448/// failure. Returns true if there was an error, false otherwise. If
1449/// everything went okay, Value will receive the value of the constant
1450/// expression.
1451static bool
1452CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1453 SourceLocation Loc = Index->getSourceRange().getBegin();
1454
1455 // Make sure this is an integer constant expression.
1456 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1457 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1458 << Index->getSourceRange();
1459
1460 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +00001461 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1462 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001463 if (Value < Zero)
1464 return Self.Diag(Loc, diag::err_array_designator_negative)
1465 << Value.toString(10) << Index->getSourceRange();
1466
Douglas Gregore498e372009-01-23 21:04:18 +00001467 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001468 return false;
1469}
1470
1471Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1472 SourceLocation Loc,
1473 bool UsedColonSyntax,
1474 OwningExprResult Init) {
1475 typedef DesignatedInitExpr::Designator ASTDesignator;
1476
1477 bool Invalid = false;
1478 llvm::SmallVector<ASTDesignator, 32> Designators;
1479 llvm::SmallVector<Expr *, 32> InitExpressions;
1480
1481 // Build designators and check array designator expressions.
1482 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1483 const Designator &D = Desig.getDesignator(Idx);
1484 switch (D.getKind()) {
1485 case Designator::FieldDesignator:
1486 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1487 D.getFieldLoc()));
1488 break;
1489
1490 case Designator::ArrayDesignator: {
1491 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1492 llvm::APSInt IndexValue;
1493 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1494 Invalid = true;
1495 else {
1496 Designators.push_back(ASTDesignator(InitExpressions.size(),
1497 D.getLBracketLoc(),
1498 D.getRBracketLoc()));
1499 InitExpressions.push_back(Index);
1500 }
1501 break;
1502 }
1503
1504 case Designator::ArrayRangeDesignator: {
1505 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1506 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1507 llvm::APSInt StartValue;
1508 llvm::APSInt EndValue;
1509 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1510 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1511 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001512 else {
1513 // Make sure we're comparing values with the same bit width.
1514 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1515 EndValue.extend(StartValue.getBitWidth());
1516 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1517 StartValue.extend(EndValue.getBitWidth());
1518
1519 if (EndValue < StartValue) {
1520 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1521 << StartValue.toString(10) << EndValue.toString(10)
1522 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1523 Invalid = true;
1524 } else {
1525 Designators.push_back(ASTDesignator(InitExpressions.size(),
1526 D.getLBracketLoc(),
1527 D.getEllipsisLoc(),
1528 D.getRBracketLoc()));
1529 InitExpressions.push_back(StartIndex);
1530 InitExpressions.push_back(EndIndex);
1531 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001532 }
1533 break;
1534 }
1535 }
1536 }
1537
1538 if (Invalid || Init.isInvalid())
1539 return ExprError();
1540
1541 // Clear out the expressions within the designation.
1542 Desig.ClearExprs(*this);
1543
1544 DesignatedInitExpr *DIE
1545 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1546 &InitExpressions[0], InitExpressions.size(),
1547 Loc, UsedColonSyntax,
1548 static_cast<Expr *>(Init.release()));
1549 return Owned(DIE);
1550}
Douglas Gregor849afc32009-01-29 00:45:39 +00001551
1552bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1553 InitListChecker CheckInitList(this, InitList, DeclType);
1554 if (!CheckInitList.HadError())
1555 InitList = CheckInitList.getFullyStructuredList();
1556
1557 return CheckInitList.HadError();
1558}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001559
1560/// \brief Diagnose any semantic errors with value-initialization of
1561/// the given type.
1562///
1563/// Value-initialization effectively zero-initializes any types
1564/// without user-declared constructors, and calls the default
1565/// constructor for a for any type that has a user-declared
1566/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1567/// a type with a user-declared constructor does not have an
1568/// accessible, non-deleted default constructor. In C, everything can
1569/// be value-initialized, which corresponds to C's notion of
1570/// initializing objects with static storage duration when no
1571/// initializer is provided for that object.
1572///
1573/// \returns true if there was an error, false otherwise.
1574bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1575 // C++ [dcl.init]p5:
1576 //
1577 // To value-initialize an object of type T means:
1578
1579 // -- if T is an array type, then each element is value-initialized;
1580 if (const ArrayType *AT = Context.getAsArrayType(Type))
1581 return CheckValueInitialization(AT->getElementType(), Loc);
1582
1583 if (const RecordType *RT = Type->getAsRecordType()) {
1584 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1585 // -- if T is a class type (clause 9) with a user-declared
1586 // constructor (12.1), then the default constructor for T is
1587 // called (and the initialization is ill-formed if T has no
1588 // accessible default constructor);
1589 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1590 // FIXME: Eventually, we'll need to put the constructor decl
1591 // into the AST.
1592 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1593 SourceRange(Loc),
1594 DeclarationName(),
1595 IK_Direct);
1596 }
1597 }
1598
1599 if (Type->isReferenceType()) {
1600 // C++ [dcl.init]p5:
1601 // [...] A program that calls for default-initialization or
1602 // value-initialization of an entity of reference type is
1603 // ill-formed. [...]
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001604 // FIXME: Once we have code that goes through this path, add an
1605 // actual diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001606 }
1607
1608 return false;
1609}