blob: 5dc57751ffb3799e902d3710ba67adbe37b81ff3 [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//
Douglas Gregoraaa20962009-01-29 01:05:33 +000010// This file implements semantic analysis for initializers. The entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Steve Naroffc4d4a482008-05-01 22:18:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000017#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf603b472009-01-28 21:54:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000021#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000022using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000023
Douglas Gregoraaa20962009-01-29 01:05:33 +000024/// @brief Semantic checking for initializer lists.
25///
26/// The InitListChecker class contains a set of routines that each
27/// handle the initialization of a certain kind of entity, e.g.,
28/// arrays, vectors, struct/union types, scalars, etc. The
29/// InitListChecker itself performs a recursive walk of the subobject
30/// structure of the type to be initialized, while stepping through
31/// the initializer list one element at a time. The IList and Index
32/// parameters to each of the Check* routines contain the active
33/// (syntactic) initializer list and the index into that initializer
34/// list that represents the current initializer. Each routine is
35/// responsible for moving that Index forward as it consumes elements.
36///
37/// Each Check* routine also has a StructuredList/StructuredIndex
38/// arguments, which contains the current the "structured" (semantic)
39/// initializer list and the index into that initializer list where we
40/// are copying initializers as we map them over to the semantic
41/// list. Once we have completed our recursive walk of the subobject
42/// structure, we will have constructed a full semantic initializer
43/// list.
44///
45/// C99 designators cause changes in the initializer list traversal,
46/// because they make the initialization "jump" into a specific
47/// subobject and then continue the initialization from that
48/// point. CheckDesignatedInitializer() recursively steps into the
49/// designated subobject and manages backing out the recursion to
50/// initialize the subobjects after the one designated.
Chris Lattner1aa25a72009-01-29 05:10:57 +000051namespace clang {
Douglas Gregor849afc32009-01-29 00:45:39 +000052class InitListChecker {
53 Sema *SemaRef;
54 bool hadError;
55 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
56 InitListExpr *FullyStructuredList;
57
58 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000059 unsigned &Index, InitListExpr *StructuredList,
60 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000061 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +000062 unsigned &Index, InitListExpr *StructuredList,
63 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000064 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
65 bool SubobjectIsDesignatorContext,
66 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000067 InitListExpr *StructuredList,
68 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000069 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
70 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000071 InitListExpr *StructuredList,
72 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000073 // FIXME: Does DeclType need to be a reference type?
74 void CheckScalarType(InitListExpr *IList, QualType &DeclType,
75 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000076 InitListExpr *StructuredList,
77 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000078 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000079 InitListExpr *StructuredList,
80 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000081 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
82 RecordDecl::field_iterator Field,
83 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000084 InitListExpr *StructuredList,
85 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000086 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
87 llvm::APSInt elementIndex,
88 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +000089 InitListExpr *StructuredList,
90 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +000091 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
92 DesignatedInitExpr::designators_iterator D,
93 QualType &CurrentObjectType,
94 RecordDecl::field_iterator *NextField,
95 llvm::APSInt *NextElementIndex,
96 unsigned &Index,
97 InitListExpr *StructuredList,
98 unsigned &StructuredIndex,
99 bool FinishSubobjectInit = true);
100 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
101 QualType CurrentObjectType,
102 InitListExpr *StructuredList,
103 unsigned StructuredIndex,
104 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000105 void UpdateStructuredListElement(InitListExpr *StructuredList,
106 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000107 Expr *expr);
108 int numArrayElements(QualType DeclType);
109 int numStructUnionElements(QualType DeclType);
110public:
111 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
112 bool HadError() { return hadError; }
113
114 // @brief Retrieves the fully-structured initializer list used for
115 // semantic analysis and code generation.
116 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
117};
Chris Lattner1aa25a72009-01-29 05:10:57 +0000118}
119
Douglas Gregor849afc32009-01-29 00:45:39 +0000120
Douglas Gregorf603b472009-01-28 21:54:33 +0000121/// Recursively replaces NULL values within the given initializer list
122/// with expressions that perform value-initialization of the
123/// appropriate type.
124static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
125 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
126 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
127 unsigned Init = 0, NumInits = ILE->getNumInits();
128 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
129 FieldEnd = RType->getDecl()->field_end();
130 Field != FieldEnd; ++Field) {
131 if (Field->isUnnamedBitfield())
132 continue;
133
134 if (Init >= NumInits)
135 break;
136
137 // FIXME: Check for fields with reference type in C++?
138 if (!ILE->getInit(Init))
139 ILE->setInit(Init,
140 new (Context) CXXZeroInitValueExpr(Field->getType(),
141 SourceLocation(),
142 SourceLocation()));
143 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
144 fillInValueInitializations(Context, InnerILE);
145 ++Init;
146 }
147
148 return;
149 }
150
151 QualType ElementType;
152
153 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
154 ElementType = AType->getElementType();
155 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
156 ElementType = VType->getElementType();
157 else
158 ElementType = ILE->getType();
159
160 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
161 ++Init) {
162 if (!ILE->getInit(Init))
163 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
164 SourceLocation(),
165 SourceLocation()));
Chris Lattner1aa25a72009-01-29 05:10:57 +0000166 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregorf603b472009-01-28 21:54:33 +0000167 fillInValueInitializations(Context, InnerILE);
168 }
169}
170
Chris Lattner1aa25a72009-01-29 05:10:57 +0000171
Steve Naroffc4d4a482008-05-01 22:18:59 +0000172InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
173 hadError = false;
174 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +0000175
Eli Friedman683cedf2008-05-19 19:16:24 +0000176 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000177 unsigned newStructuredIndex = 0;
178 FullyStructuredList
179 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
180 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000181
Douglas Gregorf603b472009-01-28 21:54:33 +0000182 if (!hadError) {
183 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
184 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000185}
186
187int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000188 // FIXME: use a proper constant
189 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000190 if (const ConstantArrayType *CAT =
191 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000192 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
193 }
194 return maxElements;
195}
196
197int InitListChecker::numStructUnionElements(QualType DeclType) {
198 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000199 int InitializableMembers = 0;
200 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
201 FieldEnd = structDecl->field_end();
202 Field != FieldEnd; ++Field) {
203 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
204 ++InitializableMembers;
205 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000206 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000207 return std::min(InitializableMembers, 1);
208 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000209}
210
211void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000212 QualType T, unsigned &Index,
213 InitListExpr *StructuredList,
214 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000215 int maxElements = 0;
216
217 if (T->isArrayType())
218 maxElements = numArrayElements(T);
219 else if (T->isStructureType() || T->isUnionType())
220 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000221 else if (T->isVectorType())
222 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000223 else
224 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000225
Douglas Gregorf603b472009-01-28 21:54:33 +0000226 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000227 if (maxElements == 0) {
228 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
229 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000230 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000231 hadError = true;
232 return;
233 }
234
Douglas Gregorf603b472009-01-28 21:54:33 +0000235 // Build a structured initializer list corresponding to this subobject.
236 InitListExpr *StructuredSubobjectInitList
237 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
238 StructuredIndex,
239 ParentIList->getInit(Index)->getSourceRange());
240 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000241
Douglas Gregorf603b472009-01-28 21:54:33 +0000242 // Check the element types and build the structural subobject.
243 CheckListElementTypes(ParentIList, T, false, Index,
244 StructuredSubobjectInitList,
245 StructuredSubobjectInitIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000246}
247
Steve Naroff56099522008-05-06 00:23:44 +0000248void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000249 unsigned &Index,
250 InitListExpr *StructuredList,
251 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000252 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000253 SyntacticToSemantic[IList] = StructuredList;
254 StructuredList->setSyntacticForm(IList);
255 CheckListElementTypes(IList, T, true, Index, StructuredList,
256 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000257 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000258 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000259 if (hadError)
260 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000261
Eli Friedman46f81662008-05-25 13:22:35 +0000262 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000263 // We have leftover initializers
264 if (IList->getNumInits() > 0 &&
265 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000266 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000267 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000268 diag::err_excess_initializers_in_char_array_initializer)
269 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000270 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000271 } else if (!T->isIncompleteType()) {
272 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmand8535af2008-05-19 20:00:43 +0000273 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000274 diag::warn_excess_initializers)
275 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000276 }
277 }
Eli Friedman455f7622008-05-19 20:20:43 +0000278
Eli Friedman46f81662008-05-25 13:22:35 +0000279 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000280 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
281 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000282}
283
Eli Friedman683cedf2008-05-19 19:16:24 +0000284void InitListChecker::CheckListElementTypes(InitListExpr *IList,
285 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000286 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000287 unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000290 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000291 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000292 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000293 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000294 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000295 if (DeclType->isStructureType() || DeclType->isUnionType()) {
296 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
297 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000298 SubobjectIsDesignatorContext, Index,
299 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000300 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000301 llvm::APSInt Zero(
302 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
303 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000304 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
305 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000306 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000307 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000308 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000309 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
310 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000311 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000312 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000313 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000314 hadError = true;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000315 } else {
316 // In C, all types are either scalars or aggregates, but
317 // additional handling is needed here for C++ (and possibly others?).
318 assert(0 && "Unsupported initializer type");
319 }
320}
321
Eli Friedman683cedf2008-05-19 19:16:24 +0000322void InitListChecker::CheckSubElementType(InitListExpr *IList,
323 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000324 unsigned &Index,
325 InitListExpr *StructuredList,
326 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000327 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000328 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
329 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000330 unsigned newStructuredIndex = 0;
331 InitListExpr *newStructuredList
332 = getStructuredSubobjectInit(IList, Index, ElemType,
333 StructuredList, StructuredIndex,
334 SubInitList->getSourceRange());
335 CheckExplicitInitList(SubInitList, ElemType, newIndex,
336 newStructuredList, newStructuredIndex);
337 ++StructuredIndex;
338 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000339 } else if (StringLiteral *lit =
340 SemaRef->IsStringLiteralInit(expr, ElemType)) {
341 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000342 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
343 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000344 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000345 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000346 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000347 SemaRef->Context.typesAreCompatible(
348 expr->getType().getUnqualifiedType(),
349 ElemType.getUnqualifiedType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000350 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
351 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000352 // FIXME: Add checking
353 } else {
Douglas Gregorf603b472009-01-28 21:54:33 +0000354 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
355 StructuredIndex);
356 ++StructuredIndex;
357 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000358}
359
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000360void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000361 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000362 InitListExpr *StructuredList,
363 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000364 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000365 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000366 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000367 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000368 diag::err_many_braces_around_scalar_init)
369 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000370 hadError = true;
371 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000372 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000373 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000374 } else if (isa<DesignatedInitExpr>(expr)) {
375 SemaRef->Diag(expr->getSourceRange().getBegin(),
376 diag::err_designator_for_scalar_init)
377 << DeclType << expr->getSourceRange();
378 hadError = true;
379 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000380 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000381 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000382 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000383
Eli Friedmand8535af2008-05-19 20:00:43 +0000384 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000385 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000386 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000387 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000388 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000389 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000390 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000391 if (hadError)
392 ++StructuredIndex;
393 else
394 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000395 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000396 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000397 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
398 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000399 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000400 ++Index;
401 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000402 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000403 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000404}
405
406void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000407 unsigned &Index,
408 InitListExpr *StructuredList,
409 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000410 if (Index < IList->getNumInits()) {
411 const VectorType *VT = DeclType->getAsVectorType();
412 int maxElements = VT->getNumElements();
413 QualType elementType = VT->getElementType();
414
415 for (int i = 0; i < maxElements; ++i) {
416 // Don't attempt to go past the end of the init list
417 if (Index >= IList->getNumInits())
418 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000419 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000420 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000421 }
422 }
423}
424
425void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000426 llvm::APSInt elementIndex,
427 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000428 unsigned &Index,
429 InitListExpr *StructuredList,
430 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000431 // Check for the special-case of initializing an array with a string.
432 if (Index < IList->getNumInits()) {
433 if (StringLiteral *lit =
434 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
435 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000436 // We place the string literal directly into the resulting
437 // initializer list. This is the only place where the structure
438 // of the structured initializer list doesn't match exactly,
439 // because doing so would involve allocating one character
440 // constant for each string.
441 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
442 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000443 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000444 return;
445 }
446 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000447 if (const VariableArrayType *VAT =
448 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000449 // Check for VLAs; in standard C it would be possible to check this
450 // earlier, but I don't know where clang accepts VLAs (gcc accepts
451 // them in all sorts of strange places).
452 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000453 diag::err_variable_object_no_init)
454 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000455 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000456 ++Index;
457 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000458 return;
459 }
460
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000461 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000462 llvm::APSInt maxElements(elementIndex.getBitWidth(),
463 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000464 bool maxElementsKnown = false;
465 if (const ConstantArrayType *CAT =
466 SemaRef->Context.getAsConstantArrayType(DeclType)) {
467 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000468 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000469 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000470 maxElementsKnown = true;
471 }
472
Chris Lattnera1923f62008-08-04 07:31:14 +0000473 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
474 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000475 while (Index < IList->getNumInits()) {
476 Expr *Init = IList->getInit(Index);
477 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000478 // If we're not the subobject that matches up with the '{' for
479 // the designator, we shouldn't be handling the
480 // designator. Return immediately.
481 if (!SubobjectIsDesignatorContext)
482 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000483
Douglas Gregor710f6d42009-01-22 23:26:18 +0000484 // Handle this designated initializer. elementIndex will be
485 // updated to be the next array element we'll initialize.
486 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000487 DeclType, 0, &elementIndex, Index,
488 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000489 hadError = true;
490 continue;
491 }
492
Douglas Gregor5a203a62009-01-23 16:54:12 +0000493 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
494 maxElements.extend(elementIndex.getBitWidth());
495 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
496 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000497 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000498
Douglas Gregor710f6d42009-01-22 23:26:18 +0000499 // If the array is of incomplete type, keep track of the number of
500 // elements in the initializer.
501 if (!maxElementsKnown && elementIndex > maxElements)
502 maxElements = elementIndex;
503
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000504 continue;
505 }
506
507 // If we know the maximum number of elements, and we've already
508 // hit it, stop consuming elements in the initializer list.
509 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000510 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000511
512 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000513 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000514 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000515 ++elementIndex;
516
517 // If the array is of incomplete type, keep track of the number of
518 // elements in the initializer.
519 if (!maxElementsKnown && elementIndex > maxElements)
520 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000521 }
522 if (DeclType->isIncompleteArrayType()) {
523 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000524 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000525 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000526 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000527 // Sizing an array implicitly to zero is not allowed by ISO C,
528 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000529 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000530 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000531 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000532
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000533 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000534 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000535 }
536}
537
538void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
539 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000540 RecordDecl::field_iterator Field,
541 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000542 unsigned &Index,
543 InitListExpr *StructuredList,
544 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000545 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000546
Eli Friedman683cedf2008-05-19 19:16:24 +0000547 // If the record is invalid, some of it's members are invalid. To avoid
548 // confusion, we forgo checking the intializer for the entire record.
549 if (structDecl->isInvalidDecl()) {
550 hadError = true;
551 return;
552 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000553 // If structDecl is a forward declaration, this loop won't do
554 // anything except look at designated initializers; That's okay,
555 // because an error should get printed out elsewhere. It might be
556 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000557 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000558 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000559 while (Index < IList->getNumInits()) {
560 Expr *Init = IList->getInit(Index);
561
562 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000563 // If we're not the subobject that matches up with the '{' for
564 // the designator, we shouldn't be handling the
565 // designator. Return immediately.
566 if (!SubobjectIsDesignatorContext)
567 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000568
Douglas Gregor710f6d42009-01-22 23:26:18 +0000569 // Handle this designated initializer. Field will be updated to
570 // the next field that we'll be initializing.
571 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000572 DeclType, &Field, 0, Index,
573 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000574 hadError = true;
575
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000576 continue;
577 }
578
579 if (Field == FieldEnd) {
580 // We've run out of fields. We're done.
581 break;
582 }
583
Douglas Gregor8acb7272008-12-11 16:49:14 +0000584 // If we've hit the flexible array member at the end, we're done.
585 if (Field->getType()->isIncompleteArrayType())
586 break;
587
Douglas Gregorf603b472009-01-28 21:54:33 +0000588 if (!Field->getIdentifier() && Field->isBitField()) {
589 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000590 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000591 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000592 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000593
Douglas Gregor36859eb2009-01-29 00:39:20 +0000594 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000595 StructuredList, StructuredIndex);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000596 if (DeclType->isUnionType())
Eli Friedman683cedf2008-05-19 19:16:24 +0000597 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000598
599 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000600 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000601
Eli Friedman683cedf2008-05-19 19:16:24 +0000602 // FIXME: Implement flexible array initialization GCC extension (it's a
603 // really messy extension to implement, unfortunately...the necessary
604 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000605}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000606
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000607/// @brief Check the well-formedness of a C99 designated initializer.
608///
609/// Determines whether the designated initializer @p DIE, which
610/// resides at the given @p Index within the initializer list @p
611/// IList, is well-formed for a current object of type @p DeclType
612/// (C99 6.7.8). The actual subobject that this designator refers to
613/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000614/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000615///
616/// @param IList The initializer list in which this designated
617/// initializer occurs.
618///
619/// @param DIE The designated initializer and its initialization
620/// expression.
621///
622/// @param DeclType The type of the "current object" (C99 6.7.8p17),
623/// into which the designation in @p DIE should refer.
624///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000625/// @param NextField If non-NULL and the first designator in @p DIE is
626/// a field, this will be set to the field declaration corresponding
627/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000628///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000629/// @param NextElementIndex If non-NULL and the first designator in @p
630/// DIE is an array designator or GNU array-range designator, this
631/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000632///
633/// @param Index Index into @p IList where the designated initializer
634/// @p DIE occurs.
635///
Douglas Gregorf603b472009-01-28 21:54:33 +0000636/// @param StructuredList The initializer list expression that
637/// describes all of the subobject initializers in the order they'll
638/// actually be initialized.
639///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000640/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000641bool
642InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
643 DesignatedInitExpr *DIE,
644 DesignatedInitExpr::designators_iterator D,
645 QualType &CurrentObjectType,
646 RecordDecl::field_iterator *NextField,
647 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000648 unsigned &Index,
649 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000650 unsigned &StructuredIndex,
651 bool FinishSubobjectInit) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000652 if (D == DIE->designators_end()) {
653 // Check the actual initialization for the designated object type.
654 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000655
656 // Temporarily remove the designator expression from the
657 // initializer list that the child calls see, so that we don't try
658 // to re-process the designator.
659 unsigned OldIndex = Index;
660 IList->setInit(OldIndex, DIE->getInit());
661
662 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000663 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000664
665 // Restore the designated initializer expression in the syntactic
666 // form of the initializer list.
667 if (IList->getInit(OldIndex) != DIE->getInit())
668 DIE->setInit(IList->getInit(OldIndex));
669 IList->setInit(OldIndex, DIE);
670
Douglas Gregor710f6d42009-01-22 23:26:18 +0000671 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000672 }
673
Douglas Gregorf603b472009-01-28 21:54:33 +0000674 bool IsFirstDesignator = (D == DIE->designators_begin());
675 assert((IsFirstDesignator || StructuredList) &&
676 "Need a non-designated initializer list to start from");
677
678 // Determine the structural initializer list that corresponds to the
679 // current subobject.
680 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
681 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
682 StructuredIndex,
683 SourceRange(D->getStartLocation(),
684 DIE->getSourceRange().getEnd()));
685 assert(StructuredList && "Expected a structured initializer list");
686
Douglas Gregor710f6d42009-01-22 23:26:18 +0000687 if (D->isFieldDesignator()) {
688 // C99 6.7.8p7:
689 //
690 // If a designator has the form
691 //
692 // . identifier
693 //
694 // then the current object (defined below) shall have
695 // structure or union type and the identifier shall be the
696 // name of a member of that type.
697 const RecordType *RT = CurrentObjectType->getAsRecordType();
698 if (!RT) {
699 SourceLocation Loc = D->getDotLoc();
700 if (Loc.isInvalid())
701 Loc = D->getFieldLoc();
702 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
703 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
704 ++Index;
705 return true;
706 }
707
Douglas Gregorf603b472009-01-28 21:54:33 +0000708 // Note: we perform a linear search of the fields here, despite
709 // the fact that we have a faster lookup method, because we always
710 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000711 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000712 unsigned FieldIndex = 0;
713 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
714 FieldEnd = RT->getDecl()->field_end();
715 for (; Field != FieldEnd; ++Field) {
716 if (Field->isUnnamedBitfield())
717 continue;
718
719 if (Field->getIdentifier() == FieldName)
720 break;
721
722 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000723 }
724
Douglas Gregorf603b472009-01-28 21:54:33 +0000725 if (Field == FieldEnd) {
726 // We did not find the field we're looking for. Produce a
727 // suitable diagnostic and return a failure.
728 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
729 if (Lookup.first == Lookup.second) {
730 // Name lookup didn't find anything.
731 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
732 << FieldName << CurrentObjectType;
733 } else {
734 // Name lookup found something, but it wasn't a field.
735 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
736 << FieldName;
737 SemaRef->Diag((*Lookup.first)->getLocation(),
738 diag::note_field_designator_found);
739 }
740
741 ++Index;
742 return true;
743 } else if (cast<RecordDecl>((*Field)->getDeclContext())
744 ->isAnonymousStructOrUnion()) {
745 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
746 << FieldName
747 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
748 (int)SemaRef->getLangOptions().CPlusPlus);
749 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000750 ++Index;
751 return true;
752 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000753
754 // All of the fields of a union are located at the same place in
755 // the initializer list.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000756 if (RT->getDecl()->isUnion())
Douglas Gregorf603b472009-01-28 21:54:33 +0000757 FieldIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000758
Douglas Gregor710f6d42009-01-22 23:26:18 +0000759 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000760 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000761
Douglas Gregorf603b472009-01-28 21:54:33 +0000762 // Make sure that our non-designated initializer list has space
763 // for a subobject corresponding to this field.
764 if (FieldIndex >= StructuredList->getNumInits())
765 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
766
Douglas Gregor710f6d42009-01-22 23:26:18 +0000767 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000768 QualType FieldType = (*Field)->getType();
769 unsigned newStructuredIndex = FieldIndex;
770 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
771 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000772 return true;
773
774 // Find the position of the next field to be initialized in this
775 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000776 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000777 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000778
779 // If this the first designator, our caller will continue checking
780 // the rest of this struct/class/union subobject.
781 if (IsFirstDesignator) {
782 if (NextField)
783 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000784 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000785 return false;
786 }
787
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000788 if (!FinishSubobjectInit)
789 return false;
790
Douglas Gregor710f6d42009-01-22 23:26:18 +0000791 // Check the remaining fields within this class/struct/union subobject.
792 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000793 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
794 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000795 return hadError && !prevHadError;
796 }
797
798 // C99 6.7.8p6:
799 //
800 // If a designator has the form
801 //
802 // [ constant-expression ]
803 //
804 // then the current object (defined below) shall have array
805 // type and the expression shall be an integer constant
806 // expression. If the array is of unknown size, any
807 // nonnegative value is valid.
808 //
809 // Additionally, cope with the GNU extension that permits
810 // designators of the form
811 //
812 // [ constant-expression ... constant-expression ]
813 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
814 if (!AT) {
815 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
816 << CurrentObjectType;
817 ++Index;
818 return true;
819 }
820
821 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000822 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
823 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000824 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000825
826 bool ConstExpr
827 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
828 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
829
830 DesignatedEndIndex = DesignatedStartIndex;
831 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000832 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000833
834 bool StartConstExpr
835 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
836 SemaRef->Context);
837 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
838
839 bool EndConstExpr
840 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
841 SemaRef->Context);
842 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
843
Douglas Gregor710f6d42009-01-22 23:26:18 +0000844 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000845
846 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
847 SemaRef->Diag(D->getEllipsisLoc(),
848 diag::warn_gnu_array_range_designator_side_effects)
849 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000850 }
851
Douglas Gregor710f6d42009-01-22 23:26:18 +0000852 if (isa<ConstantArrayType>(AT)) {
853 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000854 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
855 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
856 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
857 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
858 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000859 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
860 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000861 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +0000862 << IndexExpr->getSourceRange();
863 ++Index;
864 return true;
865 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000866 } else {
867 // Make sure the bit-widths and signedness match.
868 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
869 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
870 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
871 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
872 DesignatedStartIndex.setIsUnsigned(true);
873 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000874 }
875
Douglas Gregorf603b472009-01-28 21:54:33 +0000876 // Make sure that our non-designated initializer list has space
877 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000878 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
879 StructuredList->resizeInits(SemaRef->Context,
880 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +0000881
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000882 // Repeatedly perform subobject initializations in the range
883 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +0000884
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000885 // Move to the next designator
886 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
887 unsigned OldIndex = Index;
888 ++D;
889 while (DesignatedStartIndex <= DesignatedEndIndex) {
890 // Recurse to check later designated subobjects.
891 QualType ElementType = AT->getElementType();
892 Index = OldIndex;
893 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
894 StructuredList, ElementIndex,
895 (DesignatedStartIndex == DesignatedEndIndex)))
896 return true;
897
898 // Move to the next index in the array that we'll be initializing.
899 ++DesignatedStartIndex;
900 ElementIndex = DesignatedStartIndex.getZExtValue();
901 }
Douglas Gregor710f6d42009-01-22 23:26:18 +0000902
903 // If this the first designator, our caller will continue checking
904 // the rest of this array subobject.
905 if (IsFirstDesignator) {
906 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000907 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000908 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000909 return false;
910 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000911
912 if (!FinishSubobjectInit)
913 return false;
914
Douglas Gregor710f6d42009-01-22 23:26:18 +0000915 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000916 bool prevHadError = hadError;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000917 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000918 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000919 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000920}
921
Douglas Gregorf603b472009-01-28 21:54:33 +0000922// Get the structured initializer list for a subobject of type
923// @p CurrentObjectType.
924InitListExpr *
925InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
926 QualType CurrentObjectType,
927 InitListExpr *StructuredList,
928 unsigned StructuredIndex,
929 SourceRange InitRange) {
930 Expr *ExistingInit = 0;
931 if (!StructuredList)
932 ExistingInit = SyntacticToSemantic[IList];
933 else if (StructuredIndex < StructuredList->getNumInits())
934 ExistingInit = StructuredList->getInit(StructuredIndex);
935
936 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
937 return Result;
938
939 if (ExistingInit) {
940 // We are creating an initializer list that initializes the
941 // subobjects of the current object, but there was already an
942 // initialization that completely initialized the current
943 // subobject, e.g., by a compound literal:
944 //
945 // struct X { int a, b; };
946 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
947 //
948 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
949 // designated initializer re-initializes the whole
950 // subobject [0], overwriting previous initializers.
951 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
952 << InitRange;
953 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
954 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000955 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000956 << ExistingInit->getSourceRange();
957 }
958
959 InitListExpr *Result
960 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
961 SourceLocation());
962 Result->setType(CurrentObjectType);
963
964 // Link this new initializer list into the structured initializer
965 // lists.
966 if (StructuredList)
967 StructuredList->updateInit(StructuredIndex, Result);
968 else {
969 Result->setSyntacticForm(IList);
970 SyntacticToSemantic[IList] = Result;
971 }
972
973 return Result;
974}
975
976/// Update the initializer at index @p StructuredIndex within the
977/// structured initializer list to the value @p expr.
978void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
979 unsigned &StructuredIndex,
980 Expr *expr) {
981 // No structured initializer list to update
982 if (!StructuredList)
983 return;
984
985 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
986 // This initializer overwrites a previous initializer. Warn.
987 SemaRef->Diag(expr->getSourceRange().getBegin(),
988 diag::warn_initializer_overrides)
989 << expr->getSourceRange();
990 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
991 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000992 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000993 << PrevInit->getSourceRange();
994 }
995
996 ++StructuredIndex;
997}
998
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000999/// Check that the given Index expression is a valid array designator
1000/// value. This is essentailly just a wrapper around
1001/// Expr::isIntegerConstantExpr that also checks for negative values
1002/// and produces a reasonable diagnostic if there is a
1003/// failure. Returns true if there was an error, false otherwise. If
1004/// everything went okay, Value will receive the value of the constant
1005/// expression.
1006static bool
1007CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1008 SourceLocation Loc = Index->getSourceRange().getBegin();
1009
1010 // Make sure this is an integer constant expression.
1011 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1012 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1013 << Index->getSourceRange();
1014
1015 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +00001016 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1017 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001018 if (Value < Zero)
1019 return Self.Diag(Loc, diag::err_array_designator_negative)
1020 << Value.toString(10) << Index->getSourceRange();
1021
Douglas Gregore498e372009-01-23 21:04:18 +00001022 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001023 return false;
1024}
1025
1026Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1027 SourceLocation Loc,
1028 bool UsedColonSyntax,
1029 OwningExprResult Init) {
1030 typedef DesignatedInitExpr::Designator ASTDesignator;
1031
1032 bool Invalid = false;
1033 llvm::SmallVector<ASTDesignator, 32> Designators;
1034 llvm::SmallVector<Expr *, 32> InitExpressions;
1035
1036 // Build designators and check array designator expressions.
1037 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1038 const Designator &D = Desig.getDesignator(Idx);
1039 switch (D.getKind()) {
1040 case Designator::FieldDesignator:
1041 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1042 D.getFieldLoc()));
1043 break;
1044
1045 case Designator::ArrayDesignator: {
1046 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1047 llvm::APSInt IndexValue;
1048 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1049 Invalid = true;
1050 else {
1051 Designators.push_back(ASTDesignator(InitExpressions.size(),
1052 D.getLBracketLoc(),
1053 D.getRBracketLoc()));
1054 InitExpressions.push_back(Index);
1055 }
1056 break;
1057 }
1058
1059 case Designator::ArrayRangeDesignator: {
1060 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1061 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1062 llvm::APSInt StartValue;
1063 llvm::APSInt EndValue;
1064 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1065 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1066 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001067 else {
1068 // Make sure we're comparing values with the same bit width.
1069 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1070 EndValue.extend(StartValue.getBitWidth());
1071 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1072 StartValue.extend(EndValue.getBitWidth());
1073
1074 if (EndValue < StartValue) {
1075 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1076 << StartValue.toString(10) << EndValue.toString(10)
1077 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1078 Invalid = true;
1079 } else {
1080 Designators.push_back(ASTDesignator(InitExpressions.size(),
1081 D.getLBracketLoc(),
1082 D.getEllipsisLoc(),
1083 D.getRBracketLoc()));
1084 InitExpressions.push_back(StartIndex);
1085 InitExpressions.push_back(EndIndex);
1086 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001087 }
1088 break;
1089 }
1090 }
1091 }
1092
1093 if (Invalid || Init.isInvalid())
1094 return ExprError();
1095
1096 // Clear out the expressions within the designation.
1097 Desig.ClearExprs(*this);
1098
1099 DesignatedInitExpr *DIE
1100 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1101 &InitExpressions[0], InitExpressions.size(),
1102 Loc, UsedColonSyntax,
1103 static_cast<Expr *>(Init.release()));
1104 return Owned(DIE);
1105}
Douglas Gregor849afc32009-01-29 00:45:39 +00001106
1107bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1108 InitListChecker CheckInitList(this, InitList, DeclType);
1109 if (!CheckInitList.HadError())
1110 InitList = CheckInitList.getFullyStructuredList();
1111
1112 return CheckInitList.HadError();
1113}