blob: b78fc7b1e6292d6740ed240e7d31fee10b86cc03 [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//
10// This file implements semantic analysis for initializers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000015#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
Douglas Gregorf603b472009-01-28 21:54:33 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner52a425b2009-01-27 18:30:58 +000019#include "clang/Basic/DiagnosticSema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000020using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000021
Douglas Gregorf603b472009-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 Naroffc4d4a482008-05-01 22:18:59 +000072InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
73 hadError = false;
74 SemaRef = S;
Eli Friedmand8535af2008-05-19 20:00:43 +000075
Eli Friedman683cedf2008-05-19 19:16:24 +000076 unsigned newIndex = 0;
Douglas Gregorf603b472009-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 Friedmand8535af2008-05-19 20:00:43 +000081
Douglas Gregorf603b472009-01-28 21:54:33 +000082 if (!hadError) {
83 fillInValueInitializations(SemaRef->Context, FullyStructuredList);
84 }
Steve Naroffc4d4a482008-05-01 22:18:59 +000085}
86
87int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +000088 // FIXME: use a proper constant
89 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +000090 if (const ConstantArrayType *CAT =
91 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-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 Gregorf603b472009-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 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000106 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000107 return std::min(InitializableMembers, 1);
108 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000109}
110
111void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000112 QualType T, unsigned &Index,
113 InitListExpr *StructuredList,
114 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-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 Friedman683cedf2008-05-19 19:16:24 +0000121 else if (T->isVectorType())
122 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000123 else
124 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000125
Douglas Gregorf603b472009-01-28 21:54:33 +0000126 // FIXME: Perhaps we should move this warning elsewhere?
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000127 if (maxElements == 0) {
128 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
129 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000130 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000131 hadError = true;
132 return;
133 }
134
Douglas Gregorf603b472009-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 Friedman683cedf2008-05-19 19:16:24 +0000141
Douglas Gregorf603b472009-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 Naroffc4d4a482008-05-01 22:18:59 +0000146}
147
Steve Naroff56099522008-05-06 00:23:44 +0000148void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000149 unsigned &Index,
150 InitListExpr *StructuredList,
151 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000152 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000153 SyntacticToSemantic[IList] = StructuredList;
154 StructuredList->setSyntacticForm(IList);
155 CheckListElementTypes(IList, T, true, Index, StructuredList,
156 StructuredIndex);
Steve Naroff56099522008-05-06 00:23:44 +0000157 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000158 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000159 if (hadError)
160 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000161
Eli Friedman46f81662008-05-25 13:22:35 +0000162 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000163 // We have leftover initializers
164 if (IList->getNumInits() > 0 &&
165 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000166 // Special-case
Eli Friedmand8535af2008-05-19 20:00:43 +0000167 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000168 diag::err_excess_initializers_in_char_array_initializer)
169 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000170 hadError = true;
Eli Friedmanb9ea6bc2008-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 Friedmand8535af2008-05-19 20:00:43 +0000173 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000174 diag::warn_excess_initializers)
175 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000176 }
177 }
Eli Friedman455f7622008-05-19 20:20:43 +0000178
Eli Friedman46f81662008-05-25 13:22:35 +0000179 if (T->isScalarType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000180 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
181 << IList->getSourceRange();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000182}
183
Eli Friedman683cedf2008-05-19 19:16:24 +0000184void InitListChecker::CheckListElementTypes(InitListExpr *IList,
185 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000186 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000187 unsigned &Index,
188 InitListExpr *StructuredList,
189 unsigned &StructuredIndex) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000190 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000191 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000192 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000193 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000194 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
Douglas Gregor710f6d42009-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 Gregorf603b472009-01-28 21:54:33 +0000198 SubobjectIsDesignatorContext, Index,
199 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000200 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000201 llvm::APSInt Zero(
202 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
203 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000204 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
205 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000206 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000207 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000208 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000209 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
210 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000211 ++Index;
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000212 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000213 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000214 hadError = true;
Steve Naroffc4d4a482008-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 Friedman683cedf2008-05-19 19:16:24 +0000222void InitListChecker::CheckSubElementType(InitListExpr *IList,
223 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000224 unsigned &Index,
225 InitListExpr *StructuredList,
226 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000227 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000228 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
229 unsigned newIndex = 0;
Douglas Gregorf603b472009-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 Friedman683cedf2008-05-19 19:16:24 +0000239 } else if (StringLiteral *lit =
240 SemaRef->IsStringLiteralInit(expr, ElemType)) {
241 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000242 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
243 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000244 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000245 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000246 } else if (expr->getType()->getAsRecordType() &&
Eli Friedman2ccfb512008-06-09 03:52:40 +0000247 SemaRef->Context.typesAreCompatible(
248 expr->getType().getUnqualifiedType(),
249 ElemType.getUnqualifiedType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000250 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
251 ++Index;
Eli Friedman683cedf2008-05-19 19:16:24 +0000252 // FIXME: Add checking
253 } else {
Douglas Gregorf603b472009-01-28 21:54:33 +0000254 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
255 StructuredIndex);
256 ++StructuredIndex;
257 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000258}
259
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000260void InitListChecker::CheckScalarType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000261 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000262 InitListExpr *StructuredList,
263 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000264 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000265 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000266 if (isa<InitListExpr>(expr)) {
Eli Friedman71de9eb2008-05-19 20:12:18 +0000267 SemaRef->Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000268 diag::err_many_braces_around_scalar_init)
269 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000270 hadError = true;
271 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000272 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000273 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000274 } else if (isa<DesignatedInitExpr>(expr)) {
275 SemaRef->Diag(expr->getSourceRange().getBegin(),
276 diag::err_designator_for_scalar_init)
277 << DeclType << expr->getSourceRange();
278 hadError = true;
279 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000280 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000281 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000282 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000283
Eli Friedmand8535af2008-05-19 20:00:43 +0000284 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000285 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000286 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000287 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000288 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000289 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000290 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000291 if (hadError)
292 ++StructuredIndex;
293 else
294 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000295 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000296 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000297 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
298 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000299 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000300 ++Index;
301 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000302 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000303 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000304}
305
306void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000307 unsigned &Index,
308 InitListExpr *StructuredList,
309 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000310 if (Index < IList->getNumInits()) {
311 const VectorType *VT = DeclType->getAsVectorType();
312 int maxElements = VT->getNumElements();
313 QualType elementType = VT->getElementType();
314
315 for (int i = 0; i < maxElements; ++i) {
316 // Don't attempt to go past the end of the init list
317 if (Index >= IList->getNumInits())
318 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000319 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000320 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000321 }
322 }
323}
324
325void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000326 llvm::APSInt elementIndex,
327 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000328 unsigned &Index,
329 InitListExpr *StructuredList,
330 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000331 // Check for the special-case of initializing an array with a string.
332 if (Index < IList->getNumInits()) {
333 if (StringLiteral *lit =
334 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
335 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +0000336 // We place the string literal directly into the resulting
337 // initializer list. This is the only place where the structure
338 // of the structured initializer list doesn't match exactly,
339 // because doing so would involve allocating one character
340 // constant for each string.
341 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
342 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000343 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000344 return;
345 }
346 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000347 if (const VariableArrayType *VAT =
348 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000349 // Check for VLAs; in standard C it would be possible to check this
350 // earlier, but I don't know where clang accepts VLAs (gcc accepts
351 // them in all sorts of strange places).
352 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000353 diag::err_variable_object_no_init)
354 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000355 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000356 ++Index;
357 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000358 return;
359 }
360
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000361 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000362 llvm::APSInt maxElements(elementIndex.getBitWidth(),
363 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000364 bool maxElementsKnown = false;
365 if (const ConstantArrayType *CAT =
366 SemaRef->Context.getAsConstantArrayType(DeclType)) {
367 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000368 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000369 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000370 maxElementsKnown = true;
371 }
372
Chris Lattnera1923f62008-08-04 07:31:14 +0000373 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
374 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000375 while (Index < IList->getNumInits()) {
376 Expr *Init = IList->getInit(Index);
377 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000378 // If we're not the subobject that matches up with the '{' for
379 // the designator, we shouldn't be handling the
380 // designator. Return immediately.
381 if (!SubobjectIsDesignatorContext)
382 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000383
Douglas Gregor710f6d42009-01-22 23:26:18 +0000384 // Handle this designated initializer. elementIndex will be
385 // updated to be the next array element we'll initialize.
386 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000387 DeclType, 0, &elementIndex, Index,
388 StructuredList, StructuredIndex)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000389 hadError = true;
390 continue;
391 }
392
Douglas Gregor5a203a62009-01-23 16:54:12 +0000393 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
394 maxElements.extend(elementIndex.getBitWidth());
395 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
396 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000397 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000398
Douglas Gregor710f6d42009-01-22 23:26:18 +0000399 // If the array is of incomplete type, keep track of the number of
400 // elements in the initializer.
401 if (!maxElementsKnown && elementIndex > maxElements)
402 maxElements = elementIndex;
403
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000404 continue;
405 }
406
407 // If we know the maximum number of elements, and we've already
408 // hit it, stop consuming elements in the initializer list.
409 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000410 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000411
412 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000413 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000414 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000415 ++elementIndex;
416
417 // If the array is of incomplete type, keep track of the number of
418 // elements in the initializer.
419 if (!maxElementsKnown && elementIndex > maxElements)
420 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000421 }
422 if (DeclType->isIncompleteArrayType()) {
423 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000424 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000425 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000426 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000427 // Sizing an array implicitly to zero is not allowed by ISO C,
428 // but is supported by GNU.
Steve Naroffc4d4a482008-05-01 22:18:59 +0000429 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000430 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000431 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000432
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000433 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000434 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000435 }
436}
437
438void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
439 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000440 RecordDecl::field_iterator Field,
441 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000442 unsigned &Index,
443 InitListExpr *StructuredList,
444 unsigned &StructuredIndex) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000445 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000446
Eli Friedman683cedf2008-05-19 19:16:24 +0000447 // If the record is invalid, some of it's members are invalid. To avoid
448 // confusion, we forgo checking the intializer for the entire record.
449 if (structDecl->isInvalidDecl()) {
450 hadError = true;
451 return;
452 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000453 // If structDecl is a forward declaration, this loop won't do
454 // anything except look at designated initializers; That's okay,
455 // because an error should get printed out elsewhere. It might be
456 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000457 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor710f6d42009-01-22 23:26:18 +0000458 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000459 while (Index < IList->getNumInits()) {
460 Expr *Init = IList->getInit(Index);
461
462 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000463 // If we're not the subobject that matches up with the '{' for
464 // the designator, we shouldn't be handling the
465 // designator. Return immediately.
466 if (!SubobjectIsDesignatorContext)
467 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000468
Douglas Gregor710f6d42009-01-22 23:26:18 +0000469 // Handle this designated initializer. Field will be updated to
470 // the next field that we'll be initializing.
471 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000472 DeclType, &Field, 0, Index,
473 StructuredList, StructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000474 hadError = true;
475
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000476 continue;
477 }
478
479 if (Field == FieldEnd) {
480 // We've run out of fields. We're done.
481 break;
482 }
483
Douglas Gregor8acb7272008-12-11 16:49:14 +0000484 // If we've hit the flexible array member at the end, we're done.
485 if (Field->getType()->isIncompleteArrayType())
486 break;
487
Douglas Gregorf603b472009-01-28 21:54:33 +0000488 if (!Field->getIdentifier() && Field->isBitField()) {
489 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000490 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000491 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000492 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000493
Douglas Gregor36859eb2009-01-29 00:39:20 +0000494 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 StructuredList, StructuredIndex);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000496 if (DeclType->isUnionType())
Eli Friedman683cedf2008-05-19 19:16:24 +0000497 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000498
499 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000500 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000501
Eli Friedman683cedf2008-05-19 19:16:24 +0000502 // FIXME: Implement flexible array initialization GCC extension (it's a
503 // really messy extension to implement, unfortunately...the necessary
504 // information isn't actually even here!)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000505}
Steve Naroffc4d4a482008-05-01 22:18:59 +0000506
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000507/// @brief Check the well-formedness of a C99 designated initializer.
508///
509/// Determines whether the designated initializer @p DIE, which
510/// resides at the given @p Index within the initializer list @p
511/// IList, is well-formed for a current object of type @p DeclType
512/// (C99 6.7.8). The actual subobject that this designator refers to
513/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +0000514/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000515///
516/// @param IList The initializer list in which this designated
517/// initializer occurs.
518///
519/// @param DIE The designated initializer and its initialization
520/// expression.
521///
522/// @param DeclType The type of the "current object" (C99 6.7.8p17),
523/// into which the designation in @p DIE should refer.
524///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000525/// @param NextField If non-NULL and the first designator in @p DIE is
526/// a field, this will be set to the field declaration corresponding
527/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000528///
Douglas Gregor710f6d42009-01-22 23:26:18 +0000529/// @param NextElementIndex If non-NULL and the first designator in @p
530/// DIE is an array designator or GNU array-range designator, this
531/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000532///
533/// @param Index Index into @p IList where the designated initializer
534/// @p DIE occurs.
535///
Douglas Gregorf603b472009-01-28 21:54:33 +0000536/// @param StructuredList The initializer list expression that
537/// describes all of the subobject initializers in the order they'll
538/// actually be initialized.
539///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000540/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000541bool
542InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
543 DesignatedInitExpr *DIE,
544 DesignatedInitExpr::designators_iterator D,
545 QualType &CurrentObjectType,
546 RecordDecl::field_iterator *NextField,
547 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +0000548 unsigned &Index,
549 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000550 unsigned &StructuredIndex,
551 bool FinishSubobjectInit) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000552 if (D == DIE->designators_end()) {
553 // Check the actual initialization for the designated object type.
554 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000555
556 // Temporarily remove the designator expression from the
557 // initializer list that the child calls see, so that we don't try
558 // to re-process the designator.
559 unsigned OldIndex = Index;
560 IList->setInit(OldIndex, DIE->getInit());
561
562 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000563 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +0000564
565 // Restore the designated initializer expression in the syntactic
566 // form of the initializer list.
567 if (IList->getInit(OldIndex) != DIE->getInit())
568 DIE->setInit(IList->getInit(OldIndex));
569 IList->setInit(OldIndex, DIE);
570
Douglas Gregor710f6d42009-01-22 23:26:18 +0000571 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000572 }
573
Douglas Gregorf603b472009-01-28 21:54:33 +0000574 bool IsFirstDesignator = (D == DIE->designators_begin());
575 assert((IsFirstDesignator || StructuredList) &&
576 "Need a non-designated initializer list to start from");
577
578 // Determine the structural initializer list that corresponds to the
579 // current subobject.
580 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
581 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
582 StructuredIndex,
583 SourceRange(D->getStartLocation(),
584 DIE->getSourceRange().getEnd()));
585 assert(StructuredList && "Expected a structured initializer list");
586
Douglas Gregor710f6d42009-01-22 23:26:18 +0000587 if (D->isFieldDesignator()) {
588 // C99 6.7.8p7:
589 //
590 // If a designator has the form
591 //
592 // . identifier
593 //
594 // then the current object (defined below) shall have
595 // structure or union type and the identifier shall be the
596 // name of a member of that type.
597 const RecordType *RT = CurrentObjectType->getAsRecordType();
598 if (!RT) {
599 SourceLocation Loc = D->getDotLoc();
600 if (Loc.isInvalid())
601 Loc = D->getFieldLoc();
602 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
603 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
604 ++Index;
605 return true;
606 }
607
Douglas Gregorf603b472009-01-28 21:54:33 +0000608 // Note: we perform a linear search of the fields here, despite
609 // the fact that we have a faster lookup method, because we always
610 // need to compute the field's index.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000611 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +0000612 unsigned FieldIndex = 0;
613 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
614 FieldEnd = RT->getDecl()->field_end();
615 for (; Field != FieldEnd; ++Field) {
616 if (Field->isUnnamedBitfield())
617 continue;
618
619 if (Field->getIdentifier() == FieldName)
620 break;
621
622 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000623 }
624
Douglas Gregorf603b472009-01-28 21:54:33 +0000625 if (Field == FieldEnd) {
626 // We did not find the field we're looking for. Produce a
627 // suitable diagnostic and return a failure.
628 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
629 if (Lookup.first == Lookup.second) {
630 // Name lookup didn't find anything.
631 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
632 << FieldName << CurrentObjectType;
633 } else {
634 // Name lookup found something, but it wasn't a field.
635 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
636 << FieldName;
637 SemaRef->Diag((*Lookup.first)->getLocation(),
638 diag::note_field_designator_found);
639 }
640
641 ++Index;
642 return true;
643 } else if (cast<RecordDecl>((*Field)->getDeclContext())
644 ->isAnonymousStructOrUnion()) {
645 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
646 << FieldName
647 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
648 (int)SemaRef->getLangOptions().CPlusPlus);
649 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000650 ++Index;
651 return true;
652 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000653
654 // All of the fields of a union are located at the same place in
655 // the initializer list.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000656 if (RT->getDecl()->isUnion())
Douglas Gregorf603b472009-01-28 21:54:33 +0000657 FieldIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000658
Douglas Gregor710f6d42009-01-22 23:26:18 +0000659 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +0000660 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000661
Douglas Gregorf603b472009-01-28 21:54:33 +0000662 // Make sure that our non-designated initializer list has space
663 // for a subobject corresponding to this field.
664 if (FieldIndex >= StructuredList->getNumInits())
665 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
666
Douglas Gregor710f6d42009-01-22 23:26:18 +0000667 // Recurse to check later designated subobjects.
Douglas Gregorf603b472009-01-28 21:54:33 +0000668 QualType FieldType = (*Field)->getType();
669 unsigned newStructuredIndex = FieldIndex;
670 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
671 StructuredList, newStructuredIndex))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000672 return true;
673
674 // Find the position of the next field to be initialized in this
675 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +0000676 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000677 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000678
679 // If this the first designator, our caller will continue checking
680 // the rest of this struct/class/union subobject.
681 if (IsFirstDesignator) {
682 if (NextField)
683 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +0000684 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000685 return false;
686 }
687
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000688 if (!FinishSubobjectInit)
689 return false;
690
Douglas Gregor710f6d42009-01-22 23:26:18 +0000691 // Check the remaining fields within this class/struct/union subobject.
692 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +0000693 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
694 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000695 return hadError && !prevHadError;
696 }
697
698 // C99 6.7.8p6:
699 //
700 // If a designator has the form
701 //
702 // [ constant-expression ]
703 //
704 // then the current object (defined below) shall have array
705 // type and the expression shall be an integer constant
706 // expression. If the array is of unknown size, any
707 // nonnegative value is valid.
708 //
709 // Additionally, cope with the GNU extension that permits
710 // designators of the form
711 //
712 // [ constant-expression ... constant-expression ]
713 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
714 if (!AT) {
715 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
716 << CurrentObjectType;
717 ++Index;
718 return true;
719 }
720
721 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000722 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
723 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000724 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000725
726 bool ConstExpr
727 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
728 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
729
730 DesignatedEndIndex = DesignatedStartIndex;
731 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000732 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000733
734 bool StartConstExpr
735 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
736 SemaRef->Context);
737 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
738
739 bool EndConstExpr
740 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
741 SemaRef->Context);
742 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
743
Douglas Gregor710f6d42009-01-22 23:26:18 +0000744 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000745
746 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
747 SemaRef->Diag(D->getEllipsisLoc(),
748 diag::warn_gnu_array_range_designator_side_effects)
749 << SourceRange(D->getLBracketLoc(), D->getRBracketLoc());
Douglas Gregor710f6d42009-01-22 23:26:18 +0000750 }
751
Douglas Gregor710f6d42009-01-22 23:26:18 +0000752 if (isa<ConstantArrayType>(AT)) {
753 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000754 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
755 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
756 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
757 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
758 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000759 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
760 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000761 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +0000762 << IndexExpr->getSourceRange();
763 ++Index;
764 return true;
765 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000766 } else {
767 // Make sure the bit-widths and signedness match.
768 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
769 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
770 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
771 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
772 DesignatedStartIndex.setIsUnsigned(true);
773 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000774 }
775
Douglas Gregorf603b472009-01-28 21:54:33 +0000776 // Make sure that our non-designated initializer list has space
777 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000778 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
779 StructuredList->resizeInits(SemaRef->Context,
780 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +0000781
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000782 // Repeatedly perform subobject initializations in the range
783 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +0000784
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000785 // Move to the next designator
786 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
787 unsigned OldIndex = Index;
788 ++D;
789 while (DesignatedStartIndex <= DesignatedEndIndex) {
790 // Recurse to check later designated subobjects.
791 QualType ElementType = AT->getElementType();
792 Index = OldIndex;
793 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
794 StructuredList, ElementIndex,
795 (DesignatedStartIndex == DesignatedEndIndex)))
796 return true;
797
798 // Move to the next index in the array that we'll be initializing.
799 ++DesignatedStartIndex;
800 ElementIndex = DesignatedStartIndex.getZExtValue();
801 }
Douglas Gregor710f6d42009-01-22 23:26:18 +0000802
803 // If this the first designator, our caller will continue checking
804 // the rest of this array subobject.
805 if (IsFirstDesignator) {
806 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000807 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +0000808 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +0000809 return false;
810 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000811
812 if (!FinishSubobjectInit)
813 return false;
814
Douglas Gregor710f6d42009-01-22 23:26:18 +0000815 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000816 bool prevHadError = hadError;
Douglas Gregor36dd0c52009-01-28 23:36:17 +0000817 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, true, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000818 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000819 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000820}
821
Douglas Gregorf603b472009-01-28 21:54:33 +0000822// Get the structured initializer list for a subobject of type
823// @p CurrentObjectType.
824InitListExpr *
825InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
826 QualType CurrentObjectType,
827 InitListExpr *StructuredList,
828 unsigned StructuredIndex,
829 SourceRange InitRange) {
830 Expr *ExistingInit = 0;
831 if (!StructuredList)
832 ExistingInit = SyntacticToSemantic[IList];
833 else if (StructuredIndex < StructuredList->getNumInits())
834 ExistingInit = StructuredList->getInit(StructuredIndex);
835
836 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
837 return Result;
838
839 if (ExistingInit) {
840 // We are creating an initializer list that initializes the
841 // subobjects of the current object, but there was already an
842 // initialization that completely initialized the current
843 // subobject, e.g., by a compound literal:
844 //
845 // struct X { int a, b; };
846 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
847 //
848 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
849 // designated initializer re-initializes the whole
850 // subobject [0], overwriting previous initializers.
851 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
852 << InitRange;
853 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
854 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000855 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000856 << ExistingInit->getSourceRange();
857 }
858
859 InitListExpr *Result
860 = new (SemaRef->Context) InitListExpr(SourceLocation(), 0, 0,
861 SourceLocation());
862 Result->setType(CurrentObjectType);
863
864 // Link this new initializer list into the structured initializer
865 // lists.
866 if (StructuredList)
867 StructuredList->updateInit(StructuredIndex, Result);
868 else {
869 Result->setSyntacticForm(IList);
870 SyntacticToSemantic[IList] = Result;
871 }
872
873 return Result;
874}
875
876/// Update the initializer at index @p StructuredIndex within the
877/// structured initializer list to the value @p expr.
878void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
879 unsigned &StructuredIndex,
880 Expr *expr) {
881 // No structured initializer list to update
882 if (!StructuredList)
883 return;
884
885 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
886 // This initializer overwrites a previous initializer. Warn.
887 SemaRef->Diag(expr->getSourceRange().getBegin(),
888 diag::warn_initializer_overrides)
889 << expr->getSourceRange();
890 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
891 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +0000892 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +0000893 << PrevInit->getSourceRange();
894 }
895
896 ++StructuredIndex;
897}
898
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000899/// Check that the given Index expression is a valid array designator
900/// value. This is essentailly just a wrapper around
901/// Expr::isIntegerConstantExpr that also checks for negative values
902/// and produces a reasonable diagnostic if there is a
903/// failure. Returns true if there was an error, false otherwise. If
904/// everything went okay, Value will receive the value of the constant
905/// expression.
906static bool
907CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
908 SourceLocation Loc = Index->getSourceRange().getBegin();
909
910 // Make sure this is an integer constant expression.
911 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
912 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
913 << Index->getSourceRange();
914
915 // Make sure this constant expression is non-negative.
Douglas Gregor69722702009-01-23 18:58:42 +0000916 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
917 Value.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000918 if (Value < Zero)
919 return Self.Diag(Loc, diag::err_array_designator_negative)
920 << Value.toString(10) << Index->getSourceRange();
921
Douglas Gregore498e372009-01-23 21:04:18 +0000922 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000923 return false;
924}
925
926Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
927 SourceLocation Loc,
928 bool UsedColonSyntax,
929 OwningExprResult Init) {
930 typedef DesignatedInitExpr::Designator ASTDesignator;
931
932 bool Invalid = false;
933 llvm::SmallVector<ASTDesignator, 32> Designators;
934 llvm::SmallVector<Expr *, 32> InitExpressions;
935
936 // Build designators and check array designator expressions.
937 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
938 const Designator &D = Desig.getDesignator(Idx);
939 switch (D.getKind()) {
940 case Designator::FieldDesignator:
941 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
942 D.getFieldLoc()));
943 break;
944
945 case Designator::ArrayDesignator: {
946 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
947 llvm::APSInt IndexValue;
948 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
949 Invalid = true;
950 else {
951 Designators.push_back(ASTDesignator(InitExpressions.size(),
952 D.getLBracketLoc(),
953 D.getRBracketLoc()));
954 InitExpressions.push_back(Index);
955 }
956 break;
957 }
958
959 case Designator::ArrayRangeDesignator: {
960 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
961 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
962 llvm::APSInt StartValue;
963 llvm::APSInt EndValue;
964 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
965 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
966 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +0000967 else {
968 // Make sure we're comparing values with the same bit width.
969 if (StartValue.getBitWidth() > EndValue.getBitWidth())
970 EndValue.extend(StartValue.getBitWidth());
971 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
972 StartValue.extend(EndValue.getBitWidth());
973
974 if (EndValue < StartValue) {
975 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
976 << StartValue.toString(10) << EndValue.toString(10)
977 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
978 Invalid = true;
979 } else {
980 Designators.push_back(ASTDesignator(InitExpressions.size(),
981 D.getLBracketLoc(),
982 D.getEllipsisLoc(),
983 D.getRBracketLoc()));
984 InitExpressions.push_back(StartIndex);
985 InitExpressions.push_back(EndIndex);
986 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000987 }
988 break;
989 }
990 }
991 }
992
993 if (Invalid || Init.isInvalid())
994 return ExprError();
995
996 // Clear out the expressions within the designation.
997 Desig.ClearExprs(*this);
998
999 DesignatedInitExpr *DIE
1000 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1001 &InitExpressions[0], InitExpressions.size(),
1002 Loc, UsedColonSyntax,
1003 static_cast<Expr *>(Init.release()));
1004 return Owned(DIE);
1005}