blob: b54a8d674b2477f114c5bba56f88af40fa90f15b [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//
Douglas Gregor9e80f722009-01-29 01:05:33 +000010// This file implements semantic analysis for initializers. The entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Steve Naroff0cca7492008-05-01 22:18:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000017#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000020#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000021using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000022
Douglas Gregor9e80f722009-01-29 01:05:33 +000023/// @brief Semantic checking for initializer lists.
24///
25/// The InitListChecker class contains a set of routines that each
26/// handle the initialization of a certain kind of entity, e.g.,
27/// arrays, vectors, struct/union types, scalars, etc. The
28/// InitListChecker itself performs a recursive walk of the subobject
29/// structure of the type to be initialized, while stepping through
30/// the initializer list one element at a time. The IList and Index
31/// parameters to each of the Check* routines contain the active
32/// (syntactic) initializer list and the index into that initializer
33/// list that represents the current initializer. Each routine is
34/// responsible for moving that Index forward as it consumes elements.
35///
36/// Each Check* routine also has a StructuredList/StructuredIndex
37/// arguments, which contains the current the "structured" (semantic)
38/// initializer list and the index into that initializer list where we
39/// are copying initializers as we map them over to the semantic
40/// list. Once we have completed our recursive walk of the subobject
41/// structure, we will have constructed a full semantic initializer
42/// list.
43///
44/// C99 designators cause changes in the initializer list traversal,
45/// because they make the initialization "jump" into a specific
46/// subobject and then continue the initialization from that
47/// point. CheckDesignatedInitializer() recursively steps into the
48/// designated subobject and manages backing out the recursion to
49/// initialize the subobjects after the one designated.
Chris Lattner68355a52009-01-29 05:10:57 +000050namespace clang {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000051class InitListChecker {
52 Sema *SemaRef;
53 bool hadError;
54 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
55 InitListExpr *FullyStructuredList;
56
57 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000058 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000059 unsigned &StructuredIndex,
60 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000061 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +000062 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000063 unsigned &StructuredIndex,
64 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000065 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
66 bool SubobjectIsDesignatorContext,
67 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000068 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000069 unsigned &StructuredIndex,
70 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000071 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
72 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000073 InitListExpr *StructuredList,
74 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +000075 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000076 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000077 InitListExpr *StructuredList,
78 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +000079 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
80 unsigned &Index,
81 InitListExpr *StructuredList,
82 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000083 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000084 InitListExpr *StructuredList,
85 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000086 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
87 RecordDecl::field_iterator Field,
88 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000089 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +000090 unsigned &StructuredIndex,
91 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000092 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
93 llvm::APSInt elementIndex,
94 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +000095 InitListExpr *StructuredList,
96 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000097 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
98 DesignatedInitExpr::designators_iterator D,
99 QualType &CurrentObjectType,
100 RecordDecl::field_iterator *NextField,
101 llvm::APSInt *NextElementIndex,
102 unsigned &Index,
103 InitListExpr *StructuredList,
104 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000105 bool FinishSubobjectInit,
106 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000107 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
108 QualType CurrentObjectType,
109 InitListExpr *StructuredList,
110 unsigned StructuredIndex,
111 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000112 void UpdateStructuredListElement(InitListExpr *StructuredList,
113 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000114 Expr *expr);
115 int numArrayElements(QualType DeclType);
116 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000117
118 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000119public:
120 InitListChecker(Sema *S, InitListExpr *IL, QualType &T);
121 bool HadError() { return hadError; }
122
123 // @brief Retrieves the fully-structured initializer list used for
124 // semantic analysis and code generation.
125 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
126};
Chris Lattner68355a52009-01-29 05:10:57 +0000127}
128
Douglas Gregor4c678342009-01-28 21:54:33 +0000129/// Recursively replaces NULL values within the given initializer list
130/// with expressions that perform value-initialization of the
131/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000132void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
133 assert((ILE->getType() != SemaRef->Context.VoidTy) &&
134 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000135 SourceLocation Loc = ILE->getSourceRange().getBegin();
136 if (ILE->getSyntacticForm())
137 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
138
Douglas Gregor4c678342009-01-28 21:54:33 +0000139 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
140 unsigned Init = 0, NumInits = ILE->getNumInits();
141 for (RecordDecl::field_iterator Field = RType->getDecl()->field_begin(),
142 FieldEnd = RType->getDecl()->field_end();
143 Field != FieldEnd; ++Field) {
144 if (Field->isUnnamedBitfield())
145 continue;
146
Douglas Gregor87fd7032009-02-02 17:43:21 +0000147 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000148 if (Field->getType()->isReferenceType()) {
149 // C++ [dcl.init.aggr]p9:
150 // If an incomplete or empty initializer-list leaves a
151 // member of reference type uninitialized, the program is
152 // ill-formed.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000153 SemaRef->Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000154 << Field->getType()
155 << ILE->getSyntacticForm()->getSourceRange();
156 SemaRef->Diag(Field->getLocation(),
157 diag::note_uninit_reference_member);
158 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000159 return;
160 } else if (SemaRef->CheckValueInitialization(Field->getType(), Loc)) {
161 hadError = true;
162 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000163 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000164
165 // FIXME: If value-initialization involves calling a
166 // constructor, should we make that call explicit in the
167 // representation (even when it means extending the
168 // initializer list)?
169 if (Init < NumInits && !hadError)
170 ILE->setInit(Init,
171 new (SemaRef->Context) ImplicitValueInitExpr(Field->getType()));
172 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000173 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000174 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000175 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000176
177 // Only look at the first initialization of a union.
178 if (RType->getDecl()->isUnion())
179 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000180 }
181
182 return;
183 }
184
185 QualType ElementType;
186
Douglas Gregor87fd7032009-02-02 17:43:21 +0000187 unsigned NumInits = ILE->getNumInits();
188 unsigned NumElements = NumInits;
189 if (const ArrayType *AType = SemaRef->Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000190 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000191 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
192 NumElements = CAType->getSize().getZExtValue();
193 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000194 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000195 NumElements = VType->getNumElements();
196 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000197 ElementType = ILE->getType();
198
Douglas Gregor87fd7032009-02-02 17:43:21 +0000199 for (unsigned Init = 0; Init != NumElements; ++Init) {
200 if (Init >= NumInits || !ILE->getInit(Init)) {
201 if (SemaRef->CheckValueInitialization(ElementType, Loc)) {
202 hadError = true;
203 return;
204 }
205
206 // FIXME: If value-initialization involves calling a
207 // constructor, should we make that call explicit in the
208 // representation (even when it means extending the
209 // initializer list)?
210 if (Init < NumInits && !hadError)
211 ILE->setInit(Init,
212 new (SemaRef->Context) ImplicitValueInitExpr(ElementType));
213 }
Chris Lattner68355a52009-01-29 05:10:57 +0000214 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000215 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000216 }
217}
218
Chris Lattner68355a52009-01-29 05:10:57 +0000219
Steve Naroff0cca7492008-05-01 22:18:59 +0000220InitListChecker::InitListChecker(Sema *S, InitListExpr *IL, QualType &T) {
221 hadError = false;
222 SemaRef = S;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000223
Eli Friedmanb85f7072008-05-19 19:16:24 +0000224 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000225 unsigned newStructuredIndex = 0;
226 FullyStructuredList
227 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, SourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000228 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
229 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000230
Douglas Gregor930d8b52009-01-30 22:09:00 +0000231 if (!hadError)
232 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000233}
234
235int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000236 // FIXME: use a proper constant
237 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000238 if (const ConstantArrayType *CAT =
239 SemaRef->Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000240 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
241 }
242 return maxElements;
243}
244
245int InitListChecker::numStructUnionElements(QualType DeclType) {
246 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000247 int InitializableMembers = 0;
248 for (RecordDecl::field_iterator Field = structDecl->field_begin(),
249 FieldEnd = structDecl->field_end();
250 Field != FieldEnd; ++Field) {
251 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
252 ++InitializableMembers;
253 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000254 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000255 return std::min(InitializableMembers, 1);
256 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000257}
258
259void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000260 QualType T, unsigned &Index,
261 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000262 unsigned &StructuredIndex,
263 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000264 int maxElements = 0;
265
266 if (T->isArrayType())
267 maxElements = numArrayElements(T);
268 else if (T->isStructureType() || T->isUnionType())
269 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000270 else if (T->isVectorType())
271 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000272 else
273 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000274
Eli Friedman402256f2008-05-25 13:49:22 +0000275 if (maxElements == 0) {
276 SemaRef->Diag(ParentIList->getInit(Index)->getLocStart(),
277 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000278 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000279 hadError = true;
280 return;
281 }
282
Douglas Gregor4c678342009-01-28 21:54:33 +0000283 // Build a structured initializer list corresponding to this subobject.
284 InitListExpr *StructuredSubobjectInitList
285 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
286 StructuredIndex,
287 ParentIList->getInit(Index)->getSourceRange());
288 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000289
Douglas Gregor4c678342009-01-28 21:54:33 +0000290 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000291 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000292 CheckListElementTypes(ParentIList, T, false, Index,
293 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000294 StructuredSubobjectInitIndex,
295 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000296 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
297
298 // Update the structured sub-object initialize so that it's ending
299 // range corresponds with the end of the last initializer it used.
300 if (EndIndex < ParentIList->getNumInits()) {
301 SourceLocation EndLoc
302 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
303 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
304 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000305}
306
Steve Naroffa647caa2008-05-06 00:23:44 +0000307void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000308 unsigned &Index,
309 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000310 unsigned &StructuredIndex,
311 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000312 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000313 SyntacticToSemantic[IList] = StructuredList;
314 StructuredList->setSyntacticForm(IList);
315 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000316 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000317 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000318 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000319 if (hadError)
320 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000321
Eli Friedman638e1442008-05-25 13:22:35 +0000322 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000323 // We have leftover initializers
324 if (IList->getNumInits() > 0 &&
325 SemaRef->IsStringLiteralInit(IList->getInit(Index), T)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000326 // Special-case
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000327 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000328 diag::err_excess_initializers_in_char_array_initializer)
329 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000330 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000331 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000332 // Don't complain for incomplete types, since we'll get an error
333 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000334 QualType CurrentObjectType = StructuredList->getType();
335 int initKind =
336 CurrentObjectType->isArrayType()? 0 :
337 CurrentObjectType->isVectorType()? 1 :
338 CurrentObjectType->isScalarType()? 2 :
339 CurrentObjectType->isUnionType()? 3 :
340 4;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000341 SemaRef->Diag(IList->getInit(Index)->getLocStart(),
Douglas Gregorb574e562009-01-30 22:26:29 +0000342 diag::err_excess_initializers)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000343 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000344 }
345 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000346
Eli Friedman638e1442008-05-25 13:22:35 +0000347 if (T->isScalarType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000348 SemaRef->Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
349 << IList->getSourceRange();
Steve Naroff0cca7492008-05-01 22:18:59 +0000350}
351
Eli Friedmanb85f7072008-05-19 19:16:24 +0000352void InitListChecker::CheckListElementTypes(InitListExpr *IList,
353 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000354 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 unsigned &Index,
356 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000357 unsigned &StructuredIndex,
358 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000359 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000360 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000361 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000362 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000363 } else if (DeclType->isAggregateType()) {
364 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000365 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
366 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000367 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000368 StructuredList, StructuredIndex,
369 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000370 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000371 llvm::APSInt Zero(
372 SemaRef->Context.getTypeSize(SemaRef->Context.getSizeType()),
373 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000374 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
375 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000376 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000377 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000378 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000379 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
380 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ++Index;
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000382 SemaRef->Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000383 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000384 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000385 } else if (DeclType->isRecordType()) {
386 // C++ [dcl.init]p14:
387 // [...] If the class is an aggregate (8.5.1), and the initializer
388 // is a brace-enclosed list, see 8.5.1.
389 //
390 // Note: 8.5.1 is handled below; here, we diagnose the case where
391 // we have an initializer list and a destination type that is not
392 // an aggregate.
393 // FIXME: In C++0x, this is yet another form of initialization.
394 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
395 << DeclType << IList->getSourceRange();
396 hadError = true;
397 } else if (DeclType->isReferenceType()) {
398 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000399 } else {
400 // In C, all types are either scalars or aggregates, but
401 // additional handling is needed here for C++ (and possibly others?).
402 assert(0 && "Unsupported initializer type");
403 }
404}
405
Eli Friedmanb85f7072008-05-19 19:16:24 +0000406void InitListChecker::CheckSubElementType(InitListExpr *IList,
407 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000408 unsigned &Index,
409 InitListExpr *StructuredList,
410 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000411 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000412 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
413 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000414 unsigned newStructuredIndex = 0;
415 InitListExpr *newStructuredList
416 = getStructuredSubobjectInit(IList, Index, ElemType,
417 StructuredList, StructuredIndex,
418 SubInitList->getSourceRange());
419 CheckExplicitInitList(SubInitList, ElemType, newIndex,
420 newStructuredList, newStructuredIndex);
421 ++StructuredIndex;
422 ++Index;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000423 } else if (StringLiteral *lit =
424 SemaRef->IsStringLiteralInit(expr, ElemType)) {
425 SemaRef->CheckStringLiteralInit(lit, ElemType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000426 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
427 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000428 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000429 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000430 } else if (ElemType->isReferenceType()) {
431 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000432 } else {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 if (SemaRef->getLangOptions().CPlusPlus) {
434 // C++ [dcl.init.aggr]p12:
435 // All implicit type conversions (clause 4) are considered when
436 // initializing the aggregate member with an ini- tializer from
437 // an initializer-list. If the initializer can initialize a
438 // member, the member is initialized. [...]
439 ImplicitConversionSequence ICS
440 = SemaRef->TryCopyInitialization(expr, ElemType);
441 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
442 if (SemaRef->PerformImplicitConversion(expr, ElemType, ICS,
443 "initializing"))
444 hadError = true;
445 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
446 ++Index;
447 return;
448 }
449
450 // Fall through for subaggregate initialization
451 } else {
452 // C99 6.7.8p13:
453 //
454 // The initializer for a structure or union object that has
455 // automatic storage duration shall be either an initializer
456 // list as described below, or a single expression that has
457 // compatible structure or union type. In the latter case, the
458 // initial value of the object, including unnamed members, is
459 // that of the expression.
460 QualType ExprType = SemaRef->Context.getCanonicalType(expr->getType());
461 QualType ElemTypeCanon = SemaRef->Context.getCanonicalType(ElemType);
462 if (SemaRef->Context.typesAreCompatible(ExprType.getUnqualifiedType(),
463 ElemTypeCanon.getUnqualifiedType())) {
464 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
465 ++Index;
466 return;
467 }
468
469 // Fall through for subaggregate initialization
470 }
471
472 // C++ [dcl.init.aggr]p12:
473 //
474 // [...] Otherwise, if the member is itself a non-empty
475 // subaggregate, brace elision is assumed and the initializer is
476 // considered for the initialization of the first member of
477 // the subaggregate.
478 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
479 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
480 StructuredIndex);
481 ++StructuredIndex;
482 } else {
483 // We cannot initialize this element, so let
484 // PerformCopyInitialization produce the appropriate diagnostic.
485 SemaRef->PerformCopyInitialization(expr, ElemType, "initializing");
486 hadError = true;
487 ++Index;
488 ++StructuredIndex;
489 }
490 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000491}
492
Douglas Gregor930d8b52009-01-30 22:09:00 +0000493void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000494 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 InitListExpr *StructuredList,
496 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000497 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000498 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000499 if (isa<InitListExpr>(expr)) {
Eli Friedmanbb504d32008-05-19 20:12:18 +0000500 SemaRef->Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000501 diag::err_many_braces_around_scalar_init)
502 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000503 hadError = true;
504 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000505 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000506 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000507 } else if (isa<DesignatedInitExpr>(expr)) {
508 SemaRef->Diag(expr->getSourceRange().getBegin(),
509 diag::err_designator_for_scalar_init)
510 << DeclType << expr->getSourceRange();
511 hadError = true;
512 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000513 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000514 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000515 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000516
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000517 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000518 if (SemaRef->CheckSingleInitializer(expr, DeclType, false))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000519 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000520 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000522 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000523 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000524 if (hadError)
525 ++StructuredIndex;
526 else
527 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000528 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000529 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000530 SemaRef->Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
531 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000532 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000533 ++Index;
534 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000535 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000536 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000537}
538
Douglas Gregor930d8b52009-01-30 22:09:00 +0000539void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
540 unsigned &Index,
541 InitListExpr *StructuredList,
542 unsigned &StructuredIndex) {
543 if (Index < IList->getNumInits()) {
544 Expr *expr = IList->getInit(Index);
545 if (isa<InitListExpr>(expr)) {
546 SemaRef->Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
547 << DeclType << IList->getSourceRange();
548 hadError = true;
549 ++Index;
550 ++StructuredIndex;
551 return;
552 }
553
554 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
555 if (SemaRef->CheckReferenceInit(expr, DeclType))
556 hadError = true;
557 else if (savExpr != expr) {
558 // The type was promoted, update initializer list.
559 IList->setInit(Index, expr);
560 }
561 if (hadError)
562 ++StructuredIndex;
563 else
564 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
565 ++Index;
566 } else {
567 // FIXME: It would be wonderful if we could point at the actual
568 // member. In general, it would be useful to pass location
569 // information down the stack, so that we know the location (or
570 // decl) of the "current object" being initialized.
571 SemaRef->Diag(IList->getLocStart(),
572 diag::err_init_reference_member_uninitialized)
573 << DeclType
574 << IList->getSourceRange();
575 hadError = true;
576 ++Index;
577 ++StructuredIndex;
578 return;
579 }
580}
581
Steve Naroff0cca7492008-05-01 22:18:59 +0000582void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000583 unsigned &Index,
584 InitListExpr *StructuredList,
585 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000586 if (Index < IList->getNumInits()) {
587 const VectorType *VT = DeclType->getAsVectorType();
588 int maxElements = VT->getNumElements();
589 QualType elementType = VT->getElementType();
590
591 for (int i = 0; i < maxElements; ++i) {
592 // Don't attempt to go past the end of the init list
593 if (Index >= IList->getNumInits())
594 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000595 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000596 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000597 }
598 }
599}
600
601void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000602 llvm::APSInt elementIndex,
603 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 unsigned &Index,
605 InitListExpr *StructuredList,
606 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000607 // Check for the special-case of initializing an array with a string.
608 if (Index < IList->getNumInits()) {
609 if (StringLiteral *lit =
610 SemaRef->IsStringLiteralInit(IList->getInit(Index), DeclType)) {
611 SemaRef->CheckStringLiteralInit(lit, DeclType);
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 // We place the string literal directly into the resulting
613 // initializer list. This is the only place where the structure
614 // of the structured initializer list doesn't match exactly,
615 // because doing so would involve allocating one character
616 // constant for each string.
617 UpdateStructuredListElement(StructuredList, StructuredIndex, lit);
618 StructuredList->resizeInits(SemaRef->Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000619 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000620 return;
621 }
622 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000623 if (const VariableArrayType *VAT =
624 SemaRef->Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000625 // Check for VLAs; in standard C it would be possible to check this
626 // earlier, but I don't know where clang accepts VLAs (gcc accepts
627 // them in all sorts of strange places).
628 SemaRef->Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000629 diag::err_variable_object_no_init)
630 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000631 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000632 ++Index;
633 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000634 return;
635 }
636
Douglas Gregor05c13a32009-01-22 00:58:24 +0000637 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 llvm::APSInt maxElements(elementIndex.getBitWidth(),
639 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000640 bool maxElementsKnown = false;
641 if (const ConstantArrayType *CAT =
642 SemaRef->Context.getAsConstantArrayType(DeclType)) {
643 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000644 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000645 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000646 maxElementsKnown = true;
647 }
648
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000649 QualType elementType = SemaRef->Context.getAsArrayType(DeclType)
650 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000651 while (Index < IList->getNumInits()) {
652 Expr *Init = IList->getInit(Index);
653 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000654 // If we're not the subobject that matches up with the '{' for
655 // the designator, we shouldn't be handling the
656 // designator. Return immediately.
657 if (!SubobjectIsDesignatorContext)
658 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000659
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000660 // Handle this designated initializer. elementIndex will be
661 // updated to be the next array element we'll initialize.
662 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000663 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000664 StructuredList, StructuredIndex, true,
665 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000666 hadError = true;
667 continue;
668 }
669
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000670 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
671 maxElements.extend(elementIndex.getBitWidth());
672 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
673 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000674 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000675
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000676 // If the array is of incomplete type, keep track of the number of
677 // elements in the initializer.
678 if (!maxElementsKnown && elementIndex > maxElements)
679 maxElements = elementIndex;
680
Douglas Gregor05c13a32009-01-22 00:58:24 +0000681 continue;
682 }
683
684 // If we know the maximum number of elements, and we've already
685 // hit it, stop consuming elements in the initializer list.
686 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000687 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000688
689 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000690 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000692 ++elementIndex;
693
694 // If the array is of incomplete type, keep track of the number of
695 // elements in the initializer.
696 if (!maxElementsKnown && elementIndex > maxElements)
697 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000698 }
699 if (DeclType->isIncompleteArrayType()) {
700 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000701 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000702 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000703 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000704 // Sizing an array implicitly to zero is not allowed by ISO C,
705 // but is supported by GNU.
Steve Naroff0cca7492008-05-01 22:18:59 +0000706 SemaRef->Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000707 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000708 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000709
Douglas Gregor05c13a32009-01-22 00:58:24 +0000710 DeclType = SemaRef->Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000711 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000712 }
713}
714
715void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
716 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000717 RecordDecl::field_iterator Field,
718 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000719 unsigned &Index,
720 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000721 unsigned &StructuredIndex,
722 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000723 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000724
Eli Friedmanb85f7072008-05-19 19:16:24 +0000725 // If the record is invalid, some of it's members are invalid. To avoid
726 // confusion, we forgo checking the intializer for the entire record.
727 if (structDecl->isInvalidDecl()) {
728 hadError = true;
729 return;
730 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000731
732 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
733 // Value-initialize the first named member of the union.
734 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
735 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
736 Field != FieldEnd; ++Field) {
737 if (Field->getDeclName()) {
738 StructuredList->setInitializedFieldInUnion(*Field);
739 break;
740 }
741 }
742 return;
743 }
744
Douglas Gregor05c13a32009-01-22 00:58:24 +0000745 // If structDecl is a forward declaration, this loop won't do
746 // anything except look at designated initializers; That's okay,
747 // because an error should get printed out elsewhere. It might be
748 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000749 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000750 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +0000751 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000752 while (Index < IList->getNumInits()) {
753 Expr *Init = IList->getInit(Index);
754
755 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000756 // If we're not the subobject that matches up with the '{' for
757 // the designator, we shouldn't be handling the
758 // designator. Return immediately.
759 if (!SubobjectIsDesignatorContext)
760 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000761
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000762 // Handle this designated initializer. Field will be updated to
763 // the next field that we'll be initializing.
764 if (CheckDesignatedInitializer(IList, DIE, DIE->designators_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000765 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000766 StructuredList, StructuredIndex,
767 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000768 hadError = true;
769
Douglas Gregordfb5e592009-02-12 19:00:39 +0000770 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000771 continue;
772 }
773
774 if (Field == FieldEnd) {
775 // We've run out of fields. We're done.
776 break;
777 }
778
Douglas Gregordfb5e592009-02-12 19:00:39 +0000779 // We've already initialized a member of a union. We're done.
780 if (InitializedSomething && DeclType->isUnionType())
781 break;
782
Douglas Gregor44b43212008-12-11 16:49:14 +0000783 // If we've hit the flexible array member at the end, we're done.
784 if (Field->getType()->isIncompleteArrayType())
785 break;
786
Douglas Gregor0bb76892009-01-29 16:53:55 +0000787 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000788 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000789 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000790 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000791 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000792
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000793 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000794 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000795 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000796
797 if (DeclType->isUnionType()) {
798 // Initialize the first field within the union.
799 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000800 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000801
802 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000803 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000804
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000805 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
806 Index >= IList->getNumInits() ||
807 !isa<InitListExpr>(IList->getInit(Index)))
808 return;
809
810 // Handle GNU flexible array initializers.
811 if (!TopLevelObject &&
812 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0) {
813 SemaRef->Diag(IList->getInit(Index)->getSourceRange().getBegin(),
814 diag::err_flexible_array_init_nonempty)
815 << IList->getInit(Index)->getSourceRange().getBegin();
816 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
817 << *Field;
818 hadError = true;
819 }
820
821 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
822 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000823}
Steve Naroff0cca7492008-05-01 22:18:59 +0000824
Douglas Gregor05c13a32009-01-22 00:58:24 +0000825/// @brief Check the well-formedness of a C99 designated initializer.
826///
827/// Determines whether the designated initializer @p DIE, which
828/// resides at the given @p Index within the initializer list @p
829/// IList, is well-formed for a current object of type @p DeclType
830/// (C99 6.7.8). The actual subobject that this designator refers to
831/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +0000832/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +0000833///
834/// @param IList The initializer list in which this designated
835/// initializer occurs.
836///
837/// @param DIE The designated initializer and its initialization
838/// expression.
839///
840/// @param DeclType The type of the "current object" (C99 6.7.8p17),
841/// into which the designation in @p DIE should refer.
842///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000843/// @param NextField If non-NULL and the first designator in @p DIE is
844/// a field, this will be set to the field declaration corresponding
845/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000846///
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000847/// @param NextElementIndex If non-NULL and the first designator in @p
848/// DIE is an array designator or GNU array-range designator, this
849/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000850///
851/// @param Index Index into @p IList where the designated initializer
852/// @p DIE occurs.
853///
Douglas Gregor4c678342009-01-28 21:54:33 +0000854/// @param StructuredList The initializer list expression that
855/// describes all of the subobject initializers in the order they'll
856/// actually be initialized.
857///
Douglas Gregor05c13a32009-01-22 00:58:24 +0000858/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000859bool
860InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
861 DesignatedInitExpr *DIE,
862 DesignatedInitExpr::designators_iterator D,
863 QualType &CurrentObjectType,
864 RecordDecl::field_iterator *NextField,
865 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000866 unsigned &Index,
867 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +0000868 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000869 bool FinishSubobjectInit,
870 bool TopLevelObject) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000871 if (D == DIE->designators_end()) {
872 // Check the actual initialization for the designated object type.
873 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000874
875 // Temporarily remove the designator expression from the
876 // initializer list that the child calls see, so that we don't try
877 // to re-process the designator.
878 unsigned OldIndex = Index;
879 IList->setInit(OldIndex, DIE->getInit());
880
881 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000882 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000883
884 // Restore the designated initializer expression in the syntactic
885 // form of the initializer list.
886 if (IList->getInit(OldIndex) != DIE->getInit())
887 DIE->setInit(IList->getInit(OldIndex));
888 IList->setInit(OldIndex, DIE);
889
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000890 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000891 }
892
Douglas Gregor4c678342009-01-28 21:54:33 +0000893 bool IsFirstDesignator = (D == DIE->designators_begin());
894 assert((IsFirstDesignator || StructuredList) &&
895 "Need a non-designated initializer list to start from");
896
897 // Determine the structural initializer list that corresponds to the
898 // current subobject.
899 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
900 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, StructuredList,
901 StructuredIndex,
902 SourceRange(D->getStartLocation(),
903 DIE->getSourceRange().getEnd()));
904 assert(StructuredList && "Expected a structured initializer list");
905
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000906 if (D->isFieldDesignator()) {
907 // C99 6.7.8p7:
908 //
909 // If a designator has the form
910 //
911 // . identifier
912 //
913 // then the current object (defined below) shall have
914 // structure or union type and the identifier shall be the
915 // name of a member of that type.
916 const RecordType *RT = CurrentObjectType->getAsRecordType();
917 if (!RT) {
918 SourceLocation Loc = D->getDotLoc();
919 if (Loc.isInvalid())
920 Loc = D->getFieldLoc();
921 SemaRef->Diag(Loc, diag::err_field_designator_non_aggr)
922 << SemaRef->getLangOptions().CPlusPlus << CurrentObjectType;
923 ++Index;
924 return true;
925 }
926
Douglas Gregor4c678342009-01-28 21:54:33 +0000927 // Note: we perform a linear search of the fields here, despite
928 // the fact that we have a faster lookup method, because we always
929 // need to compute the field's index.
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000930 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +0000931 unsigned FieldIndex = 0;
932 RecordDecl::field_iterator Field = RT->getDecl()->field_begin(),
933 FieldEnd = RT->getDecl()->field_end();
934 for (; Field != FieldEnd; ++Field) {
935 if (Field->isUnnamedBitfield())
936 continue;
937
938 if (Field->getIdentifier() == FieldName)
939 break;
940
941 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000942 }
943
Douglas Gregor4c678342009-01-28 21:54:33 +0000944 if (Field == FieldEnd) {
945 // We did not find the field we're looking for. Produce a
946 // suitable diagnostic and return a failure.
947 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
948 if (Lookup.first == Lookup.second) {
949 // Name lookup didn't find anything.
950 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
951 << FieldName << CurrentObjectType;
952 } else {
953 // Name lookup found something, but it wasn't a field.
954 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
955 << FieldName;
956 SemaRef->Diag((*Lookup.first)->getLocation(),
957 diag::note_field_designator_found);
958 }
959
960 ++Index;
961 return true;
962 } else if (cast<RecordDecl>((*Field)->getDeclContext())
963 ->isAnonymousStructOrUnion()) {
964 SemaRef->Diag(D->getFieldLoc(), diag::err_field_designator_anon_class)
965 << FieldName
966 << (cast<RecordDecl>((*Field)->getDeclContext())->isUnion()? 2 :
967 (int)SemaRef->getLangOptions().CPlusPlus);
968 SemaRef->Diag((*Field)->getLocation(), diag::note_field_designator_found);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000969 ++Index;
970 return true;
971 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000972
973 // All of the fields of a union are located at the same place in
974 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +0000975 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000976 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000977 StructuredList->setInitializedFieldInUnion(*Field);
978 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000979
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000980 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +0000981 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000982
Douglas Gregor4c678342009-01-28 21:54:33 +0000983 // Make sure that our non-designated initializer list has space
984 // for a subobject corresponding to this field.
985 if (FieldIndex >= StructuredList->getNumInits())
986 StructuredList->resizeInits(SemaRef->Context, FieldIndex + 1);
987
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000988 // This designator names a flexible array member.
989 if (Field->getType()->isIncompleteArrayType()) {
990 bool Invalid = false;
991 DesignatedInitExpr::designators_iterator NextD = D;
992 ++NextD;
993 if (NextD != DIE->designators_end()) {
994 // We can't designate an object within the flexible array
995 // member (because GCC doesn't allow it).
996 SemaRef->Diag(NextD->getStartLocation(),
997 diag::err_designator_into_flexible_array_member)
998 << SourceRange(NextD->getStartLocation(),
999 DIE->getSourceRange().getEnd());
1000 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1001 << *Field;
1002 Invalid = true;
1003 }
1004
1005 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1006 // The initializer is not an initializer list.
1007 SemaRef->Diag(DIE->getInit()->getSourceRange().getBegin(),
1008 diag::err_flexible_array_init_needs_braces)
1009 << DIE->getInit()->getSourceRange();
1010 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1011 << *Field;
1012 Invalid = true;
1013 }
1014
1015 // Handle GNU flexible array initializers.
1016 if (!Invalid && !TopLevelObject &&
1017 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1018 SemaRef->Diag(DIE->getSourceRange().getBegin(),
1019 diag::err_flexible_array_init_nonempty)
1020 << DIE->getSourceRange().getBegin();
1021 SemaRef->Diag(Field->getLocation(), diag::note_flexible_array_member)
1022 << *Field;
1023 Invalid = true;
1024 }
1025
1026 if (Invalid) {
1027 ++Index;
1028 return true;
1029 }
1030
1031 // Initialize the array.
1032 bool prevHadError = hadError;
1033 unsigned newStructuredIndex = FieldIndex;
1034 unsigned OldIndex = Index;
1035 IList->setInit(Index, DIE->getInit());
1036 CheckSubElementType(IList, Field->getType(), Index,
1037 StructuredList, newStructuredIndex);
1038 IList->setInit(OldIndex, DIE);
1039 if (hadError && !prevHadError) {
1040 ++Field;
1041 ++FieldIndex;
1042 if (NextField)
1043 *NextField = Field;
1044 StructuredIndex = FieldIndex;
1045 return true;
1046 }
1047 } else {
1048 // Recurse to check later designated subobjects.
1049 QualType FieldType = (*Field)->getType();
1050 unsigned newStructuredIndex = FieldIndex;
1051 if (CheckDesignatedInitializer(IList, DIE, ++D, FieldType, 0, 0, Index,
1052 StructuredList, newStructuredIndex,
1053 true, false))
1054 return true;
1055 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001056
1057 // Find the position of the next field to be initialized in this
1058 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001059 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001060 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061
1062 // If this the first designator, our caller will continue checking
1063 // the rest of this struct/class/union subobject.
1064 if (IsFirstDesignator) {
1065 if (NextField)
1066 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001067 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001068 return false;
1069 }
1070
Douglas Gregor34e79462009-01-28 23:36:17 +00001071 if (!FinishSubobjectInit)
1072 return false;
1073
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001074 // Check the remaining fields within this class/struct/union subobject.
1075 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001076 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1077 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001078 return hadError && !prevHadError;
1079 }
1080
1081 // C99 6.7.8p6:
1082 //
1083 // If a designator has the form
1084 //
1085 // [ constant-expression ]
1086 //
1087 // then the current object (defined below) shall have array
1088 // type and the expression shall be an integer constant
1089 // expression. If the array is of unknown size, any
1090 // nonnegative value is valid.
1091 //
1092 // Additionally, cope with the GNU extension that permits
1093 // designators of the form
1094 //
1095 // [ constant-expression ... constant-expression ]
1096 const ArrayType *AT = SemaRef->Context.getAsArrayType(CurrentObjectType);
1097 if (!AT) {
1098 SemaRef->Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1099 << CurrentObjectType;
1100 ++Index;
1101 return true;
1102 }
1103
1104 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001105 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1106 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001107 IndexExpr = DIE->getArrayIndex(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001108
1109 bool ConstExpr
1110 = IndexExpr->isIntegerConstantExpr(DesignatedStartIndex, SemaRef->Context);
1111 assert(ConstExpr && "Expression must be constant"); (void)ConstExpr;
1112
1113 DesignatedEndIndex = DesignatedStartIndex;
1114 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001115 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001116
1117 bool StartConstExpr
1118 = DIE->getArrayRangeStart(*D)->isIntegerConstantExpr(DesignatedStartIndex,
1119 SemaRef->Context);
1120 assert(StartConstExpr && "Expression must be constant"); (void)StartConstExpr;
1121
1122 bool EndConstExpr
1123 = DIE->getArrayRangeEnd(*D)->isIntegerConstantExpr(DesignatedEndIndex,
1124 SemaRef->Context);
1125 assert(EndConstExpr && "Expression must be constant"); (void)EndConstExpr;
1126
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001127 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001128
1129 if (DesignatedStartIndex.getZExtValue() != DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001130 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001131 }
1132
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001133 if (isa<ConstantArrayType>(AT)) {
1134 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001135 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1136 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1137 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1138 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1139 if (DesignatedEndIndex >= MaxElements) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001140 SemaRef->Diag(IndexExpr->getSourceRange().getBegin(),
1141 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001142 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001143 << IndexExpr->getSourceRange();
1144 ++Index;
1145 return true;
1146 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001147 } else {
1148 // Make sure the bit-widths and signedness match.
1149 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1150 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1151 else if (DesignatedStartIndex.getBitWidth() < DesignatedEndIndex.getBitWidth())
1152 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1153 DesignatedStartIndex.setIsUnsigned(true);
1154 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001155 }
1156
Douglas Gregor4c678342009-01-28 21:54:33 +00001157 // Make sure that our non-designated initializer list has space
1158 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001159 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1160 StructuredList->resizeInits(SemaRef->Context,
1161 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001162
Douglas Gregor34e79462009-01-28 23:36:17 +00001163 // Repeatedly perform subobject initializations in the range
1164 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001165
Douglas Gregor34e79462009-01-28 23:36:17 +00001166 // Move to the next designator
1167 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1168 unsigned OldIndex = Index;
1169 ++D;
1170 while (DesignatedStartIndex <= DesignatedEndIndex) {
1171 // Recurse to check later designated subobjects.
1172 QualType ElementType = AT->getElementType();
1173 Index = OldIndex;
1174 if (CheckDesignatedInitializer(IList, DIE, D, ElementType, 0, 0, Index,
1175 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001176 (DesignatedStartIndex == DesignatedEndIndex),
1177 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001178 return true;
1179
1180 // Move to the next index in the array that we'll be initializing.
1181 ++DesignatedStartIndex;
1182 ElementIndex = DesignatedStartIndex.getZExtValue();
1183 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001184
1185 // If this the first designator, our caller will continue checking
1186 // the rest of this array subobject.
1187 if (IsFirstDesignator) {
1188 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001189 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001190 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001191 return false;
1192 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001193
1194 if (!FinishSubobjectInit)
1195 return false;
1196
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001197 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001198 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001199 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001200 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001201 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001202}
1203
Douglas Gregor4c678342009-01-28 21:54:33 +00001204// Get the structured initializer list for a subobject of type
1205// @p CurrentObjectType.
1206InitListExpr *
1207InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1208 QualType CurrentObjectType,
1209 InitListExpr *StructuredList,
1210 unsigned StructuredIndex,
1211 SourceRange InitRange) {
1212 Expr *ExistingInit = 0;
1213 if (!StructuredList)
1214 ExistingInit = SyntacticToSemantic[IList];
1215 else if (StructuredIndex < StructuredList->getNumInits())
1216 ExistingInit = StructuredList->getInit(StructuredIndex);
1217
1218 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1219 return Result;
1220
1221 if (ExistingInit) {
1222 // We are creating an initializer list that initializes the
1223 // subobjects of the current object, but there was already an
1224 // initialization that completely initialized the current
1225 // subobject, e.g., by a compound literal:
1226 //
1227 // struct X { int a, b; };
1228 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1229 //
1230 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1231 // designated initializer re-initializes the whole
1232 // subobject [0], overwriting previous initializers.
1233 SemaRef->Diag(InitRange.getBegin(), diag::warn_subobject_initializer_overrides)
1234 << InitRange;
1235 SemaRef->Diag(ExistingInit->getSourceRange().getBegin(),
1236 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001237 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001238 << ExistingInit->getSourceRange();
1239 }
1240
Douglas Gregor87fd7032009-02-02 17:43:21 +00001241 SourceLocation StartLoc;
1242 if (Index < IList->getNumInits())
1243 StartLoc = IList->getInit(Index)->getSourceRange().getBegin();
Douglas Gregor4c678342009-01-28 21:54:33 +00001244 InitListExpr *Result
Douglas Gregor87fd7032009-02-02 17:43:21 +00001245 = new (SemaRef->Context) InitListExpr(StartLoc, 0, 0,
1246 IList->getSourceRange().getEnd());
Douglas Gregor4c678342009-01-28 21:54:33 +00001247 Result->setType(CurrentObjectType);
1248
1249 // Link this new initializer list into the structured initializer
1250 // lists.
1251 if (StructuredList)
1252 StructuredList->updateInit(StructuredIndex, Result);
1253 else {
1254 Result->setSyntacticForm(IList);
1255 SyntacticToSemantic[IList] = Result;
1256 }
1257
1258 return Result;
1259}
1260
1261/// Update the initializer at index @p StructuredIndex within the
1262/// structured initializer list to the value @p expr.
1263void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1264 unsigned &StructuredIndex,
1265 Expr *expr) {
1266 // No structured initializer list to update
1267 if (!StructuredList)
1268 return;
1269
1270 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1271 // This initializer overwrites a previous initializer. Warn.
1272 SemaRef->Diag(expr->getSourceRange().getBegin(),
1273 diag::warn_initializer_overrides)
1274 << expr->getSourceRange();
1275 SemaRef->Diag(PrevInit->getSourceRange().getBegin(),
1276 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001277 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001278 << PrevInit->getSourceRange();
1279 }
1280
1281 ++StructuredIndex;
1282}
1283
Douglas Gregor05c13a32009-01-22 00:58:24 +00001284/// Check that the given Index expression is a valid array designator
1285/// value. This is essentailly just a wrapper around
1286/// Expr::isIntegerConstantExpr that also checks for negative values
1287/// and produces a reasonable diagnostic if there is a
1288/// failure. Returns true if there was an error, false otherwise. If
1289/// everything went okay, Value will receive the value of the constant
1290/// expression.
1291static bool
1292CheckArrayDesignatorExpr(Sema &Self, Expr *Index, llvm::APSInt &Value) {
1293 SourceLocation Loc = Index->getSourceRange().getBegin();
1294
1295 // Make sure this is an integer constant expression.
1296 if (!Index->isIntegerConstantExpr(Value, Self.Context, &Loc))
1297 return Self.Diag(Loc, diag::err_array_designator_nonconstant)
1298 << Index->getSourceRange();
1299
1300 // Make sure this constant expression is non-negative.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001301 llvm::APSInt Zero(llvm::APSInt::getNullValue(Value.getBitWidth()),
1302 Value.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001303 if (Value < Zero)
1304 return Self.Diag(Loc, diag::err_array_designator_negative)
1305 << Value.toString(10) << Index->getSourceRange();
1306
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001307 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001308 return false;
1309}
1310
1311Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1312 SourceLocation Loc,
1313 bool UsedColonSyntax,
1314 OwningExprResult Init) {
1315 typedef DesignatedInitExpr::Designator ASTDesignator;
1316
1317 bool Invalid = false;
1318 llvm::SmallVector<ASTDesignator, 32> Designators;
1319 llvm::SmallVector<Expr *, 32> InitExpressions;
1320
1321 // Build designators and check array designator expressions.
1322 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1323 const Designator &D = Desig.getDesignator(Idx);
1324 switch (D.getKind()) {
1325 case Designator::FieldDesignator:
1326 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1327 D.getFieldLoc()));
1328 break;
1329
1330 case Designator::ArrayDesignator: {
1331 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1332 llvm::APSInt IndexValue;
1333 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1334 Invalid = true;
1335 else {
1336 Designators.push_back(ASTDesignator(InitExpressions.size(),
1337 D.getLBracketLoc(),
1338 D.getRBracketLoc()));
1339 InitExpressions.push_back(Index);
1340 }
1341 break;
1342 }
1343
1344 case Designator::ArrayRangeDesignator: {
1345 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1346 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1347 llvm::APSInt StartValue;
1348 llvm::APSInt EndValue;
1349 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1350 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1351 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001352 else {
1353 // Make sure we're comparing values with the same bit width.
1354 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1355 EndValue.extend(StartValue.getBitWidth());
1356 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1357 StartValue.extend(EndValue.getBitWidth());
1358
1359 if (EndValue < StartValue) {
1360 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1361 << StartValue.toString(10) << EndValue.toString(10)
1362 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1363 Invalid = true;
1364 } else {
1365 Designators.push_back(ASTDesignator(InitExpressions.size(),
1366 D.getLBracketLoc(),
1367 D.getEllipsisLoc(),
1368 D.getRBracketLoc()));
1369 InitExpressions.push_back(StartIndex);
1370 InitExpressions.push_back(EndIndex);
1371 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001372 }
1373 break;
1374 }
1375 }
1376 }
1377
1378 if (Invalid || Init.isInvalid())
1379 return ExprError();
1380
1381 // Clear out the expressions within the designation.
1382 Desig.ClearExprs(*this);
1383
1384 DesignatedInitExpr *DIE
1385 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1386 &InitExpressions[0], InitExpressions.size(),
1387 Loc, UsedColonSyntax,
1388 static_cast<Expr *>(Init.release()));
1389 return Owned(DIE);
1390}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001391
1392bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
1393 InitListChecker CheckInitList(this, InitList, DeclType);
1394 if (!CheckInitList.HadError())
1395 InitList = CheckInitList.getFullyStructuredList();
1396
1397 return CheckInitList.HadError();
1398}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001399
1400/// \brief Diagnose any semantic errors with value-initialization of
1401/// the given type.
1402///
1403/// Value-initialization effectively zero-initializes any types
1404/// without user-declared constructors, and calls the default
1405/// constructor for a for any type that has a user-declared
1406/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1407/// a type with a user-declared constructor does not have an
1408/// accessible, non-deleted default constructor. In C, everything can
1409/// be value-initialized, which corresponds to C's notion of
1410/// initializing objects with static storage duration when no
1411/// initializer is provided for that object.
1412///
1413/// \returns true if there was an error, false otherwise.
1414bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1415 // C++ [dcl.init]p5:
1416 //
1417 // To value-initialize an object of type T means:
1418
1419 // -- if T is an array type, then each element is value-initialized;
1420 if (const ArrayType *AT = Context.getAsArrayType(Type))
1421 return CheckValueInitialization(AT->getElementType(), Loc);
1422
1423 if (const RecordType *RT = Type->getAsRecordType()) {
1424 if (const CXXRecordType *CXXRec = dyn_cast<CXXRecordType>(RT)) {
1425 // -- if T is a class type (clause 9) with a user-declared
1426 // constructor (12.1), then the default constructor for T is
1427 // called (and the initialization is ill-formed if T has no
1428 // accessible default constructor);
1429 if (CXXRec->getDecl()->hasUserDeclaredConstructor())
1430 // FIXME: Eventually, we'll need to put the constructor decl
1431 // into the AST.
1432 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1433 SourceRange(Loc),
1434 DeclarationName(),
1435 IK_Direct);
1436 }
1437 }
1438
1439 if (Type->isReferenceType()) {
1440 // C++ [dcl.init]p5:
1441 // [...] A program that calls for default-initialization or
1442 // value-initialization of an entity of reference type is
1443 // ill-formed. [...]
Douglas Gregord8635172009-02-02 21:35:47 +00001444 // FIXME: Once we have code that goes through this path, add an
1445 // actual diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001446 }
1447
1448 return false;
1449}