blob: 66b938ff0713b8c42de9fafd8c031f2238677220 [file] [log] [blame]
Steve Naroff0cca7492008-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//
10// This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000015#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
Douglas Gregor4c678342009-01-28 21:54:33 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner20c6b3b2009-01-27 18:30:58 +000019#include "clang/Basic/DiagnosticSema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000020using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000021
Douglas Gregor4c678342009-01-28 21:54:33 +000022/// Recursively replaces NULL values within the given initializer list
23/// with expressions that perform value-initialization of the
24/// appropriate type.
25static void fillInValueInitializations(ASTContext &Context, InitListExpr *ILE) {
26 assert((ILE->getType() != Context.VoidTy) && "Should not have void type");
27 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
28 unsigned Init = 0, NumInits = ILE->getNumInits();
29 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
30 FieldEnd = RType->getDecl()->field_end();
31 Field != FieldEnd; ++Field) {
32 if (Field->isUnnamedBitfield())
33 continue;
34
35 if (Init >= NumInits)
36 break;
37
38 // FIXME: Check for fields with reference type in C++?
39 if (!ILE->getInit(Init))
40 ILE->setInit(Init,
41 new (Context) CXXZeroInitValueExpr(Field->getType(),
42 SourceLocation(),
43 SourceLocation()));
44 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
45 fillInValueInitializations(Context, InnerILE);
46 ++Init;
47 }
48
49 return;
50 }
51
52 QualType ElementType;
53
54 if (const ArrayType *AType = Context.getAsArrayType(ILE->getType()))
55 ElementType = AType->getElementType();
56 else if (const VectorType *VType = ILE->getType()->getAsVectorType())
57 ElementType = VType->getElementType();
58 else
59 ElementType = ILE->getType();
60
61 for (unsigned Init = 0, NumInits = ILE->getNumInits(); Init != NumInits;
62 ++Init) {
63 if (!ILE->getInit(Init))
64 ILE->setInit(Init, new (Context) CXXZeroInitValueExpr(ElementType,
65 SourceLocation(),
66 SourceLocation()));
67 else if (InitListExpr *InnerILE = dyn_cast<InitListExpr>(ILE->getInit(Init)))
68 fillInValueInitializations(Context, InnerILE);
69 }
70}
71
Steve Naroff0cca7492008-05-01 22:18:59 +000072InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
73 hadError = false;
74 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +000075
Eli Friedmanb85f7072008-05-19 19:16:24 +000076 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +000077 unsigned newStructuredIndex = 0;
78 FullyStructuredList
79 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
80 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +000081
Douglas Gregor4c678342009-01-28 21:54:33 +000082 if (!hadError) {
83 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
84 }
Steve Naroff0cca7492008-05-01 22:18:59 +000085}
86
87int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +000088 // FIXME: use a proper constant
89 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +000090 if (const ConstantArrayType *CAT =
91 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +000092 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
93 }
94 return maxElements;
95}
96
97int InitListChecker::numStructUnionElements(QualType DeclType) {
98 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +000099 int InitializableMembers = 0;
100 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
101 FieldEnd = structDecl->field_end();
102 Field != FieldEnd; ++Field) {
103 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
104 ++InitializableMembers;
105 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000106 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000107 return std::min(InitializableMembers, 1);
108 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000109}
110
111void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000112 QualType T, unsigned &Index,
113 InitListExpr *StructuredList,
114 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000115 int maxElements = 0;
116
117 if (T->isArrayType())
118 maxElements = numArrayElements(T);
119 else if (T->isStructureType() || T->isUnionType())
120 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000121 else if (T->isVectorType())
122 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000123 else
124 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000125
Douglas Gregor4c678342009-01-28 21:54:33 +0000126 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedman402256f2008-05-25 13:49:22 +0000127 if (maxElements == 0) {
128 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
129 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000130 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000131 hadError = true;
132 return;
133 }
134
Douglas Gregor4c678342009-01-28 21:54:33 +0000135 // Build a structured initializer list corresponding to this subobject.
136 InitListExpr *StructuredSubobjectInitList
137 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
138 StructuredIndex,
139 ParentIList->getInit(Index)->getSourceRange());
140 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000141
Douglas Gregor4c678342009-01-28 21:54:33 +0000142 // Check the element types and build the structural subobject.
143 CheckListElementTypes(ParentIList, T, false, Index,
144 StructuredSubobjectInitList,
145 StructuredSubobjectInitIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000146}
147
Steve Naroffa647caa2008-05-06 00:23:44 +0000148void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000149 unsigned &Index,
150 InitListExpr *StructuredList,
151 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000152 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000153 SyntacticToSemantic[IList] = StructuredList;
154 StructuredList->setSyntacticForm(IList);
155 CheckListElementTypes(IList, T, true, Index, StructuredList,
156 StructuredIndex);
Steve Naroffa647caa2008-05-06 00:23:44 +0000157 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000158 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000159 if (hadError)
160 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000161
Eli Friedman638e1442008-05-25 13:22:35 +0000162 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000163 // We have leftover initializers
164 if (IList->getNumInits() > 0 &&
165 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000166 // Special-case
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000167 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000168 diag::err_excess_initializers_in_char_array_initializer)
169 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000170 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000171 } else if (!T->isIncompleteType()) {
172 // Don't warn for incomplete types, since we'll get an error elsewhere
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000173 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000174 diag::warn_excess_initializers)
175 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000176 }
177 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000178
Eli Friedman638e1442008-05-25 13:22:35 +0000179 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000180 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
181 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000182}
183
Eli Friedmanb85f7072008-05-19 19:16:24 +0000184void InitListChecker::CheckListElementTypes(InitListExpr *IList,
185 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000186 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000187 unsigned &Index,
188 InitListExpr *StructuredList,
189 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000190 if (DeclType->isScalarType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000191 CheckScalarType(IList, DeclType, 0, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000192 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000193 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000194 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000195 if (DeclType->isStructureType() || DeclType->isUnionType()) {
196 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
197 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000198 SubobjectIsDesignatorContext, Index,
199 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000200 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000201 llvm::APSInt Zero(
202 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
203 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000204 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
205 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000206 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000207 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000208 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000209 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
210 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000211 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000212 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000213 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000214 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000215 } else {
216 // In C, all types are either scalars or aggregates, but
217 // additional handling is needed here for C++ (and possibly others?).
218 assert(0 && "Unsupported initializer type");
219 }
220}
221
Eli Friedmanb85f7072008-05-19 19:16:24 +0000222void InitListChecker::CheckSubElementType(InitListExpr *IList,
223 QualType ElemType,
Douglas Gregor05c13a32009-01-22 00:58:24 +0000224 Expr *expr,
Douglas Gregor4c678342009-01-28 21:54:33 +0000225 unsigned &Index,
226 InitListExpr *StructuredList,
227 unsigned &StructuredIndex) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000228 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
229 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000230 unsigned newStructuredIndex = 0;
231 InitListExpr *newStructuredList
232 = getStructuredSubobjectInit(IList, Index, ElemType,
233 StructuredList, StructuredIndex,
234 SubInitList->getSourceRange());
235 CheckExplicitInitList(SubInitList, ElemType, newIndex,
236 newStructuredList, newStructuredIndex);
237 ++StructuredIndex;
238 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000239 } else if (StringLiteral *lit =
240 SemaRef->IsStringLiteralInit(expr, ElemType)) {
241 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000242 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
243 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000244 } else if (ElemType->isScalarType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000245 CheckScalarType(IList, ElemType, expr, Index, StructuredList,
246 StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000247 } else if (expr->getType()->getAsRecordType() &&
Eli Friedmanc92e5e42008-06-09 03:52:40 +0000248 SemaRef->Context.typesAreCompatible(
249 expr->getType().getUnqualifiedType(),
250 ElemType.getUnqualifiedType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000251 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
252 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000253 // FIXME: Add checking
254 } else {
Douglas Gregor4c678342009-01-28 21:54:33 +0000255 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
256 StructuredIndex);
257 ++StructuredIndex;
258 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000259}
260
Douglas Gregor05c13a32009-01-22 00:58:24 +0000261void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000262 Expr *expr, unsigned &Index,
263 InitListExpr *StructuredList,
264 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000265 if (Index < IList->getNumInits()) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000266 if (!expr)
267 expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000268 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000269 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000270 diag::err_many_braces_around_scalar_init)
271 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000272 hadError = true;
273 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000274 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000275 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000276 } else if (isa<DesignatedInitExpr>(expr)) {
277 SemaRef->Diag(expr->getSourceRange().getBegin(),
278 diag::err_designator_for_scalar_init)
279 << DeclType << expr->getSourceRange();
280 hadError = true;
281 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000282 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000283 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000284 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000285
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000286 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000287 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000288 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000289 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000290 // The type was promoted, update initializer list.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000291 if (DesignatedInitExpr *DIE
292 = dyn_cast<DesignatedInitExpr>(IList->getInit(Index)))
293 DIE->setInit(expr);
294 else
295 IList->setInit(Index, expr);
Douglas Gregor4c678342009-01-28 21:54:33 +0000296
Douglas Gregor05c13a32009-01-22 00:58:24 +0000297 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000298 if (hadError)
299 ++StructuredIndex;
300 else
301 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000302 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000303 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000304 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
305 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000306 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000307 ++Index;
308 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000309 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000310 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000311}
312
313void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000314 unsigned &Index,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000317 if (Index < IList->getNumInits()) {
318 const VectorType *VT = DeclType->getAsVectorType();
319 int maxElements = VT->getNumElements();
320 QualType elementType = VT->getElementType();
321
322 for (int i = 0; i < maxElements; ++i) {
323 // Don't attempt to go past the end of the init list
324 if (Index >= IList->getNumInits())
325 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000326 CheckSubElementType(IList, elementType, IList->getInit(Index), Index,
327 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000328 }
329 }
330}
331
332void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000333 llvm::APSInt elementIndex,
334 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000335 unsigned &Index,
336 InitListExpr *StructuredList,
337 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000338 // Check for the special-case of initializing an array with a string.
339 if (Index < IList->getNumInits()) {
340 if (StringLiteral *lit =
341 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
342 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000343 // We place the string literal directly into the resulting
344 // initializer list. This is the only place where the structure
345 // of the structured initializer list doesn't match exactly,
346 // because doing so would involve allocating one character
347 // constant for each string.
348 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
349 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000350 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000351 return;
352 }
353 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000354 if (const VariableArrayType *VAT =
355 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000356 // Check for VLAs; in standard C it would be possible to check this
357 // earlier, but I don't know where clang accepts VLAs (gcc accepts
358 // them in all sorts of strange places).
359 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000360 diag::err_variable_object_no_init)
361 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000362 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000363 ++Index;
364 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000365 return;
366 }
367
Douglas Gregor05c13a32009-01-22 00:58:24 +0000368 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000369 llvm::APSInt maxElements(elementIndex.getBitWidth(),
370 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000371 bool maxElementsKnown = false;
372 if (const ConstantArrayType *CAT =
373 SemaRef->Context.getAsConstantArrayType(DeclType)) {
374 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000375 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000376 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000377 maxElementsKnown = true;
378 }
379
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000380 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
381 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000382 while (Index < IList->getNumInits()) {
383 Expr *Init = IList->getInit(Index);
384 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000385 // If we're not the subobject that matches up with the '{' for
386 // the designator, we shouldn't be handling the
387 // designator. Return immediately.
388 if (!SubobjectIsDesignatorContext)
389 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000390
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000391 // Handle this designated initializer. elementIndex will be
392 // updated to be the next array element we'll initialize.
393 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000394 DeclType, 0, &elementIndex, Index,
395 StructuredList, StructuredIndex)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000396 hadError = true;
397 continue;
398 }
399
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000400 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
401 maxElements.extend(elementIndex.getBitWidth());
402 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
403 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000404 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000405
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000406 // If the array is of incomplete type, keep track of the number of
407 // elements in the initializer.
408 if (!maxElementsKnown && elementIndex > maxElements)
409 maxElements = elementIndex;
410
Douglas Gregor05c13a32009-01-22 00:58:24 +0000411 continue;
412 }
413
414 // If we know the maximum number of elements, and we've already
415 // hit it, stop consuming elements in the initializer list.
416 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000417 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000418
419 // Check this element.
Douglas Gregor4c678342009-01-28 21:54:33 +0000420 CheckSubElementType(IList, elementType, IList->getInit(Index), Index,
421 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000422 ++elementIndex;
423
424 // If the array is of incomplete type, keep track of the number of
425 // elements in the initializer.
426 if (!maxElementsKnown && elementIndex > maxElements)
427 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000428 }
429 if (DeclType->isIncompleteArrayType()) {
430 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000431 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000432 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000433 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000434 // Sizing an array implicitly to zero is not allowed by ISO C,
435 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000436 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000437 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000438 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000439
Douglas Gregor05c13a32009-01-22 00:58:24 +0000440 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000441 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000442 }
443}
444
445void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
446 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000447 RecordDecl::field_iterator Field,
448 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000449 unsigned &Index,
450 InitListExpr *StructuredList,
451 unsigned &StructuredIndex) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000452 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000453
Eli Friedmanb85f7072008-05-19 19:16:24 +0000454 // If the record is invalid, some of it's members are invalid. To avoid
455 // confusion, we forgo checking the intializer for the entire record.
456 if (structDecl->isInvalidDecl()) {
457 hadError = true;
458 return;
459 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000460 // If structDecl is a forward declaration, this loop won't do
461 // anything except look at designated initializers; That's okay,
462 // because an error should get printed out elsewhere. It might be
463 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000464 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000465 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000466 while (Index < IList->getNumInits()) {
467 Expr *Init = IList->getInit(Index);
468
469 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000470 // If we're not the subobject that matches up with the '{' for
471 // the designator, we shouldn't be handling the
472 // designator. Return immediately.
473 if (!SubobjectIsDesignatorContext)
474 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000475
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000476 // Handle this designated initializer. Field will be updated to
477 // the next field that we'll be initializing.
478 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 DeclType, &Field, 0, Index,
480 StructuredList, StructuredIndex))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000481 hadError = true;
482
Douglas Gregor05c13a32009-01-22 00:58:24 +0000483 continue;
484 }
485
486 if (Field == FieldEnd) {
487 // We've run out of fields. We're done.
488 break;
489 }
490
Douglas Gregor44b43212008-12-11 16:49:14 +0000491 // If we've hit the flexible array member at the end, we're done.
492 if (Field->getType()->isIncompleteArrayType())
493 break;
494
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 if (!Field->getIdentifier() && Field->isBitField()) {
496 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000497 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000498 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000500
Douglas Gregor4c678342009-01-28 21:54:33 +0000501 CheckSubElementType(IList, Field->getType(), IList->getInit(Index), Index,
502 StructuredList, StructuredIndex);
Douglas Gregor34e79462009-01-28 23:36:17 +0000503 if (DeclType->isUnionType())
Eli Friedmanb85f7072008-05-19 19:16:24 +0000504 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000505
506 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000507 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000508
Eli Friedmanb85f7072008-05-19 19:16:24 +0000509 // FIXME: Implement flexible array initialization GCC extension (it's a
510 // really messy extension to implement, unfortunately...the necessary
511 // information isn't actually even here!)
Steve Naroff0cca7492008-05-01 22:18:59 +0000512}
Steve Naroff0cca7492008-05-01 22:18:59 +0000513
Douglas Gregor05c13a32009-01-22 00:58:24 +0000514/// @brief Check the well-formedness of a C99 designated initializer.
515///
516/// Determines whether the designated initializer @p DIE, which
517/// resides at the given @p Index within the initializer list @p
518/// IList, is well-formed for a current object of type @p DeclType
519/// (C99 6.7.8). The actual subobject that this designator refers to
520/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000521/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000522///
523/// @param IList The initializer list in which this designated
524/// initializer occurs.
525///
526/// @param DIE The designated initializer and its initialization
527/// expression.
528///
529/// @param DeclType The type of the "current object" (C99 6.7.8p17),
530/// into which the designation in @p DIE should refer.
531///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000532/// @param NextField If non-NULL and the first designator in @p DIE is
533/// a field, this will be set to the field declaration corresponding
534/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000535///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000536/// @param NextElementIndex If non-NULL and the first designator in @p
537/// DIE is an array designator or GNU array-range designator, this
538/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000539///
540/// @param Index Index into @p IList where the designated initializer
541/// @p DIE occurs.
542///
Douglas Gregor4c678342009-01-28 21:54:33 +0000543/// @param StructuredList The initializer list expression that
544/// describes all of the subobject initializers in the order they'll
545/// actually be initialized.
546///
Douglas Gregor05c13a32009-01-22 00:58:24 +0000547/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000548bool
549InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
550 DesignatedInitExpr *DIE,
551 DesignatedInitExpr::designators_iterator D,
552 QualType &CurrentObjectType,
553 RecordDecl::field_iterator *NextField,
554 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000555 unsigned &Index,
556 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +0000557 unsigned &StructuredIndex,
558 bool FinishSubobjectInit) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000559 if (D == DIE->designators_end()) {
560 // Check the actual initialization for the designated object type.
561 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +0000562 CheckSubElementType(IList, CurrentObjectType, DIE->getInit(), Index,
563 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000564 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000565 }
566
Douglas Gregor4c678342009-01-28 21:54:33 +0000567 bool IsFirstDesignator = (D == DIE->designators_begin());
568 assert((IsFirstDesignator || StructuredList) &&
569 "Need a non-designated initializer list to start from");
570
571 // Determine the structural initializer list that corresponds to the
572 // current subobject.
573 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
574 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
575 StructuredIndex,
576 SourceRange(D->getStartLocation(),
577 DIE->getSourceRange().getEnd()));
578 assert(StructuredList && "Expected a structured initializer list");
579
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000580 if (D->isFieldDesignator()) {
581 // C99 6.7.8p7:
582 //
583 // If a designator has the form
584 //
585 // . identifier
586 //
587 // then the current object (defined below) shall have
588 // structure or union type and the identifier shall be the
589 // name of a member of that type.
590 const RecordType *RT = CurrentObjectType->getAsRecordType();
591 if (!RT) {
592 SourceLocation Loc = D->getDotLoc();
593 if (Loc.isInvalid())
594 Loc = D->getFieldLoc();
595 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
596 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
597 ++Index;
598 return true;
599 }
600
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 // Note: we perform a linear search of the fields here, despite
602 // the fact that we have a faster lookup method, because we always
603 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000604 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 unsigned FieldIndex = 0;
606 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
607 FieldEnd = RT->getDecl()->field_end();
608 for (; Field != FieldEnd; ++Field) {
609 if (Field->isUnnamedBitfield())
610 continue;
611
612 if (Field->getIdentifier() == FieldName)
613 break;
614
615 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000616 }
617
Douglas Gregor4c678342009-01-28 21:54:33 +0000618 if (Field == FieldEnd) {
619 // We did not find the field we're looking for. Produce a
620 // suitable diagnostic and return a failure.
621 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
622 if (Lookup.first == Lookup.second) {
623 // Name lookup didn't find anything.
624 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
625 << FieldName << CurrentObjectType;
626 } else {
627 // Name lookup found something, but it wasn't a field.
628 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
629 << FieldName;
630 SemaRef->Diag((*Lookup.first)->getLocation(),
631 diag::note_field_designator_found);
632 }
633
634 ++Index;
635 return true;
636 } else if (cast<RecordDecl>((*Field)->getDeclContext())
637 ->isAnonymousStructOrUnion()) {
638 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
639 << FieldName
640 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
641 (int)SemaRef->getLangOptions().CPlusPlus);
642 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000643 ++Index;
644 return true;
645 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000646
647 // All of the fields of a union are located at the same place in
648 // the initializer list.
Douglas Gregor34e79462009-01-28 23:36:17 +0000649 if (RT->getDecl()->isUnion())
Douglas Gregor4c678342009-01-28 21:54:33 +0000650 FieldIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000651
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000652 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +0000653 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000654
Douglas Gregor4c678342009-01-28 21:54:33 +0000655 // Make sure that our non-designated initializer list has space
656 // for a subobject corresponding to this field.
657 if (FieldIndex >= StructuredList->getNumInits())
658 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
659
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000660 // Recurse to check later designated subobjects.
Douglas Gregor4c678342009-01-28 21:54:33 +0000661 QualType FieldType = (*Field)->getType();
662 unsigned newStructuredIndex = FieldIndex;
663 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
664 StructuredList, newStructuredIndex))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000665 return true;
666
667 // Find the position of the next field to be initialized in this
668 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000669 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +0000670 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000671
672 // If this the first designator, our caller will continue checking
673 // the rest of this struct/class/union subobject.
674 if (IsFirstDesignator) {
675 if (NextField)
676 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +0000677 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000678 return false;
679 }
680
Douglas Gregor34e79462009-01-28 23:36:17 +0000681 if (!FinishSubobjectInit)
682 return false;
683
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000684 // Check the remaining fields within this class/struct/union subobject.
685 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +0000686 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
687 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000688 return hadError && !prevHadError;
689 }
690
691 // C99 6.7.8p6:
692 //
693 // If a designator has the form
694 //
695 // [ constant-expression ]
696 //
697 // then the current object (defined below) shall have array
698 // type and the expression shall be an integer constant
699 // expression. If the array is of unknown size, any
700 // nonnegative value is valid.
701 //
702 // Additionally, cope with the GNU extension that permits
703 // designators of the form
704 //
705 // [ constant-expression ... constant-expression ]
706 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
707 if (!AT) {
708 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
709 << CurrentObjectType;
710 ++Index;
711 return true;
712 }
713
714 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +0000715 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
716 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000717 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +0000718
719 bool ConstExpr
720 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
721 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
722
723 DesignatedEndIndex = DesignatedStartIndex;
724 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000725 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +0000726
727 bool StartConstExpr
728 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
729 SemaRef->Context);
730 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
731
732 bool EndConstExpr
733 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
734 SemaRef->Context);
735 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
736
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000737 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +0000738
739 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
740 SemaRef->Diag(D->getEllipsisLoc(),
741 diag::warn_gnu_array_range_designator_side_effects)
742 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000743 }
744
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000745 if (isa<ConstantArrayType>(AT)) {
746 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +0000747 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
748 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
749 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
750 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
751 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000752 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
753 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +0000754 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000755 << IndexExpr->getSourceRange();
756 ++Index;
757 return true;
758 }
Douglas Gregor34e79462009-01-28 23:36:17 +0000759 } else {
760 // Make sure the bit-widths and signedness match.
761 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
762 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
763 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
764 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
765 DesignatedStartIndex.setIsUnsigned(true);
766 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000767 }
768
Douglas Gregor4c678342009-01-28 21:54:33 +0000769 // Make sure that our non-designated initializer list has space
770 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +0000771 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
772 StructuredList->resizeInits(SemaRef->Context,
773 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +0000774
Douglas Gregor34e79462009-01-28 23:36:17 +0000775 // Repeatedly perform subobject initializations in the range
776 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000777
Douglas Gregor34e79462009-01-28 23:36:17 +0000778 // Move to the next designator
779 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
780 unsigned OldIndex = Index;
781 ++D;
782 while (DesignatedStartIndex <= DesignatedEndIndex) {
783 // Recurse to check later designated subobjects.
784 QualType ElementType = AT->getElementType();
785 Index = OldIndex;
786 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
787 StructuredList, ElementIndex,
788 (DesignatedStartIndex == DesignatedEndIndex)))
789 return true;
790
791 // Move to the next index in the array that we'll be initializing.
792 ++DesignatedStartIndex;
793 ElementIndex = DesignatedStartIndex.getZExtValue();
794 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000795
796 // If this the first designator, our caller will continue checking
797 // the rest of this array subobject.
798 if (IsFirstDesignator) {
799 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +0000800 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +0000801 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000802 return false;
803 }
Douglas Gregor34e79462009-01-28 23:36:17 +0000804
805 if (!FinishSubobjectInit)
806 return false;
807
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000808 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000809 bool prevHadError = hadError;
Douglas Gregor34e79462009-01-28 23:36:17 +0000810 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000811 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000812 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000813}
814
Douglas Gregor4c678342009-01-28 21:54:33 +0000815// Get the structured initializer list for a subobject of type
816// @p CurrentObjectType.
817InitListExpr *
818InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
819 QualType CurrentObjectType,
820 InitListExpr *StructuredList,
821 unsigned StructuredIndex,
822 SourceRange InitRange) {
823 Expr *ExistingInit = 0;
824 if (!StructuredList)
825 ExistingInit = SyntacticToSemantic[IList];
826 else if (StructuredIndex < StructuredList->getNumInits())
827 ExistingInit = StructuredList->getInit(StructuredIndex);
828
829 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
830 return Result;
831
832 if (ExistingInit) {
833 // We are creating an initializer list that initializes the
834 // subobjects of the current object, but there was already an
835 // initialization that completely initialized the current
836 // subobject, e.g., by a compound literal:
837 //
838 // struct X { int a, b; };
839 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
840 //
841 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
842 // designated initializer re-initializes the whole
843 // subobject [0], overwriting previous initializers.
844 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
845 << InitRange;
846 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
847 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +0000848 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +0000849 << ExistingInit->getSourceRange();
850 }
851
852 InitListExpr *Result
853 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
854 SourceLocation());
855 Result->setType(CurrentObjectType);
856
857 // Link this new initializer list into the structured initializer
858 // lists.
859 if (StructuredList)
860 StructuredList->updateInit(StructuredIndex, Result);
861 else {
862 Result->setSyntacticForm(IList);
863 SyntacticToSemantic[IList] = Result;
864 }
865
866 return Result;
867}
868
869/// Update the initializer at index @p StructuredIndex within the
870/// structured initializer list to the value @p expr.
871void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
872 unsigned &StructuredIndex,
873 Expr *expr) {
874 // No structured initializer list to update
875 if (!StructuredList)
876 return;
877
878 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
879 // This initializer overwrites a previous initializer. Warn.
880 SemaRef->Diag(expr->getSourceRange().getBegin(),
881 diag::warn_initializer_overrides)
882 << expr->getSourceRange();
883 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
884 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +0000885 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +0000886 << PrevInit->getSourceRange();
887 }
888
889 ++StructuredIndex;
890}
891
Douglas Gregor05c13a32009-01-22 00:58:24 +0000892/// Check that the given Index expression is a valid array designator
893/// value. This is essentailly just a wrapper around
894/// Expr::isIntegerConstantExpr that also checks for negative values
895/// and produces a reasonable diagnostic if there is a
896/// failure. Returns true if there was an error, false otherwise. If
897/// everything went okay, Value will receive the value of the constant
898/// expression.
899static bool
900CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
901 SourceLocation Loc = Index->getSourceRange().getBegin();
902
903 // Make sure this is an integer constant expression.
904 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
905 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
906 << Index->getSourceRange();
907
908 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000909 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
910 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000911 if (Value < Zero)
912 return Self.Diag(Loc, diag::err_array_designator_negative)
913 << Value.toString(10) << Index->getSourceRange();
914
Douglas Gregor53d3d8e2009-01-23 21:04:18 +0000915 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000916 return false;
917}
918
919Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
920 SourceLocation Loc,
921 bool UsedColonSyntax,
922 OwningExprResult Init) {
923 typedef DesignatedInitExpr::Designator ASTDesignator;
924
925 bool Invalid = false;
926 llvm::SmallVector<ASTDesignator, 32> Designators;
927 llvm::SmallVector<Expr *, 32> InitExpressions;
928
929 // Build designators and check array designator expressions.
930 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
931 const Designator &D = Desig.getDesignator(Idx);
932 switch (D.getKind()) {
933 case Designator::FieldDesignator:
934 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
935 D.getFieldLoc()));
936 break;
937
938 case Designator::ArrayDesignator: {
939 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
940 llvm::APSInt IndexValue;
941 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
942 Invalid = true;
943 else {
944 Designators.push_back(ASTDesignator(InitExpressions.size(),
945 D.getLBracketLoc(),
946 D.getRBracketLoc()));
947 InitExpressions.push_back(Index);
948 }
949 break;
950 }
951
952 case Designator::ArrayRangeDesignator: {
953 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
954 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
955 llvm::APSInt StartValue;
956 llvm::APSInt EndValue;
957 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
958 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
959 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +0000960 else {
961 // Make sure we're comparing values with the same bit width.
962 if (StartValue.getBitWidth() > EndValue.getBitWidth())
963 EndValue.extend(StartValue.getBitWidth());
964 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
965 StartValue.extend(EndValue.getBitWidth());
966
967 if (EndValue < StartValue) {
968 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
969 << StartValue.toString(10) << EndValue.toString(10)
970 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
971 Invalid = true;
972 } else {
973 Designators.push_back(ASTDesignator(InitExpressions.size(),
974 D.getLBracketLoc(),
975 D.getEllipsisLoc(),
976 D.getRBracketLoc()));
977 InitExpressions.push_back(StartIndex);
978 InitExpressions.push_back(EndIndex);
979 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000980 }
981 break;
982 }
983 }
984 }
985
986 if (Invalid || Init.isInvalid())
987 return ExprError();
988
989 // Clear out the expressions within the designation.
990 Desig.ClearExprs(*this);
991
992 DesignatedInitExpr *DIE
993 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
994 &InitExpressions[0], InitExpressions.size(),
995 Loc, UsedColonSyntax,
996 static_cast<Expr *>(Init.release()));
997 return Owned(DIE);
998}