blob: 17113f68bd466f265b82e18b9ae9c0c61befc08a [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//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000021#include "clang/AST/ExprObjC.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000022#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000023using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000024
Chris Lattnerdd8e0062009-02-24 22:27:37 +000025//===----------------------------------------------------------------------===//
26// Sema Initialization Checking
27//===----------------------------------------------------------------------===//
28
Chris Lattner79e079d2009-02-24 23:10:27 +000029static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000030 const ArrayType *AT = Context.getAsArrayType(DeclType);
31 if (!AT) return 0;
32
33 // See if this is a string literal or @encode.
34 Init = Init->IgnoreParens();
35
36 // Handle @encode, which is a narrow string.
37 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
38 return Init;
39
40 // Otherwise we can only handle string literals.
41 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000042 if (SL == 0) return 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000043
44 // char array can be initialized with a narrow string.
45 // Only allow char x[] = "foo"; not char x[] = L"foo";
46 if (!SL->isWide())
47 return AT->getElementType()->isCharType() ? Init : 0;
48
49 // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
50 // "An array with element type compatible with wchar_t may be initialized by a
51 // wide string literal, optionally enclosed in braces."
Chris Lattner19753cf2009-02-26 23:36:02 +000052 if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo";
54 return Init;
55
Chris Lattnerdd8e0062009-02-24 22:27:37 +000056 return 0;
57}
58
Chris Lattner95e8d652009-02-24 22:46:58 +000059static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
60 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000061 // Get the type before calling CheckSingleAssignmentConstraints(), since
62 // it can promote the expression.
63 QualType InitType = Init->getType();
64
Chris Lattner95e8d652009-02-24 22:46:58 +000065 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 // FIXME: I dislike this error message. A lot.
Chris Lattner95e8d652009-02-24 22:46:58 +000067 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
68 return S.Diag(Init->getSourceRange().getBegin(),
69 diag::err_typecheck_convert_incompatible)
70 << DeclType << Init->getType() << "initializing"
71 << Init->getSourceRange();
Chris Lattnerdd8e0062009-02-24 22:27:37 +000072 return false;
73 }
74
Chris Lattner95e8d652009-02-24 22:46:58 +000075 Sema::AssignConvertType ConvTy =
76 S.CheckSingleAssignmentConstraints(DeclType, Init);
77 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000078 InitType, Init, "initializing");
79}
80
Chris Lattner79e079d2009-02-24 23:10:27 +000081static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
82 // Get the length of the string as parsed.
83 uint64_t StrLength =
84 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
85
Chris Lattnerdd8e0062009-02-24 22:27:37 +000086
Chris Lattner79e079d2009-02-24 23:10:27 +000087 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000088 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
89 // C99 6.7.8p14. We have an array of character type with unknown size
90 // being initialized to a string literal.
91 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000092 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000093 // Return a new array type (C99 6.7.8p22).
Chris Lattnerf71ae8d2009-02-24 22:41:04 +000094 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
95 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 }
Chris Lattner19da8cd2009-02-24 23:01:39 +000098
99 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
100
101 // C99 6.7.8p14. We have an array of character type with known size. However,
102 // the size may be smaller or larger than the string we are initializing.
103 // FIXME: Avoid truncation for 64-bit length strings.
Chris Lattner79e079d2009-02-24 23:10:27 +0000104 if (StrLength-1 > CAT->getSize().getZExtValue())
Chris Lattner19da8cd2009-02-24 23:01:39 +0000105 S.Diag(Str->getSourceRange().getBegin(),
106 diag::warn_initializer_string_for_char_array_too_long)
107 << Str->getSourceRange();
108
109 // Set the type to the actual size that we are initializing. If we have
110 // something like:
111 // char x[1] = "foo";
112 // then this will set the string literal's type to char[1].
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000113 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000114}
115
116bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
117 SourceLocation InitLoc,
118 DeclarationName InitEntity,
119 bool DirectInit) {
120 if (DeclType->isDependentType() || Init->isTypeDependent())
121 return false;
122
123 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000124 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000125 // (8.3.2), shall be initialized by an object, or function, of
126 // type T or by an object that can be converted into a T.
127 if (DeclType->isReferenceType())
128 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
129
130 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
131 // of unknown size ("[]") or an object type that is not a variable array type.
132 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
133 return Diag(InitLoc, diag::err_variable_object_no_init)
134 << VAT->getSizeExpr()->getSourceRange();
135
136 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
137 if (!InitList) {
138 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000139 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
140 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000141 return false;
142 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000143
144 // C++ [dcl.init]p14:
145 // -- If the destination type is a (possibly cv-qualified) class
146 // type:
147 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
148 QualType DeclTypeC = Context.getCanonicalType(DeclType);
149 QualType InitTypeC = Context.getCanonicalType(Init->getType());
150
151 // -- If the initialization is direct-initialization, or if it is
152 // copy-initialization where the cv-unqualified version of the
153 // source type is the same class as, or a derived class of, the
154 // class of the destination, constructors are considered.
155 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
156 IsDerivedFrom(InitTypeC, DeclTypeC)) {
157 CXXConstructorDecl *Constructor
158 = PerformInitializationByConstructor(DeclType, &Init, 1,
159 InitLoc, Init->getSourceRange(),
160 InitEntity,
161 DirectInit? IK_Direct : IK_Copy);
162 return Constructor == 0;
163 }
164
165 // -- Otherwise (i.e., for the remaining copy-initialization
166 // cases), user-defined conversion sequences that can
167 // convert from the source type to the destination type or
168 // (when a conversion function is used) to a derived class
169 // thereof are enumerated as described in 13.3.1.4, and the
170 // best one is chosen through overload resolution
171 // (13.3). If the conversion cannot be done or is
172 // ambiguous, the initialization is ill-formed. The
173 // function selected is called with the initializer
174 // expression as its argument; if the function is a
175 // constructor, the call initializes a temporary of the
176 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000177 // FIXME: We're pretending to do copy elision here; return to this when we
178 // have ASTs for such things.
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000179 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
180 return false;
181
182 if (InitEntity)
183 return Diag(InitLoc, diag::err_cannot_initialize_decl)
184 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
185 << Init->getType() << Init->getSourceRange();
186 else
187 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
188 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
189 << Init->getType() << Init->getSourceRange();
190 }
191
192 // C99 6.7.8p16.
193 if (DeclType->isArrayType())
194 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
195 << Init->getSourceRange();
196
Chris Lattner95e8d652009-02-24 22:46:58 +0000197 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000198 }
199
200 bool hadError = CheckInitList(InitList, DeclType);
201 Init = InitList;
202 return hadError;
203}
204
205//===----------------------------------------------------------------------===//
206// Semantic checking for initializer lists.
207//===----------------------------------------------------------------------===//
208
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209/// @brief Semantic checking for initializer lists.
210///
211/// The InitListChecker class contains a set of routines that each
212/// handle the initialization of a certain kind of entity, e.g.,
213/// arrays, vectors, struct/union types, scalars, etc. The
214/// InitListChecker itself performs a recursive walk of the subobject
215/// structure of the type to be initialized, while stepping through
216/// the initializer list one element at a time. The IList and Index
217/// parameters to each of the Check* routines contain the active
218/// (syntactic) initializer list and the index into that initializer
219/// list that represents the current initializer. Each routine is
220/// responsible for moving that Index forward as it consumes elements.
221///
222/// Each Check* routine also has a StructuredList/StructuredIndex
223/// arguments, which contains the current the "structured" (semantic)
224/// initializer list and the index into that initializer list where we
225/// are copying initializers as we map them over to the semantic
226/// list. Once we have completed our recursive walk of the subobject
227/// structure, we will have constructed a full semantic initializer
228/// list.
229///
230/// C99 designators cause changes in the initializer list traversal,
231/// because they make the initialization "jump" into a specific
232/// subobject and then continue the initialization from that
233/// point. CheckDesignatedInitializer() recursively steps into the
234/// designated subobject and manages backing out the recursion to
235/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000236namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000237class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000238 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000239 bool hadError;
240 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
241 InitListExpr *FullyStructuredList;
242
243 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000244 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000245 unsigned &StructuredIndex,
246 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000248 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000249 unsigned &StructuredIndex,
250 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000251 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
252 bool SubobjectIsDesignatorContext,
253 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000254 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000257 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
258 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000259 InitListExpr *StructuredList,
260 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000261 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000263 InitListExpr *StructuredList,
264 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000265 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
266 unsigned &Index,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000269 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000272 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
273 RecordDecl::field_iterator Field,
274 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000275 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000276 unsigned &StructuredIndex,
277 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000278 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
279 llvm::APSInt elementIndex,
280 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000283 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000284 unsigned DesigIdx,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000285 QualType &CurrentObjectType,
286 RecordDecl::field_iterator *NextField,
287 llvm::APSInt *NextElementIndex,
288 unsigned &Index,
289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000291 bool FinishSubobjectInit,
292 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000293 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
294 QualType CurrentObjectType,
295 InitListExpr *StructuredList,
296 unsigned StructuredIndex,
297 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000298 void UpdateStructuredListElement(InitListExpr *StructuredList,
299 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000300 Expr *expr);
301 int numArrayElements(QualType DeclType);
302 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000303
304 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000305public:
Chris Lattner08202542009-02-24 22:50:46 +0000306 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000307 bool HadError() { return hadError; }
308
309 // @brief Retrieves the fully-structured initializer list used for
310 // semantic analysis and code generation.
311 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
312};
Chris Lattner8b419b92009-02-24 22:48:58 +0000313} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000314
Douglas Gregor4c678342009-01-28 21:54:33 +0000315/// Recursively replaces NULL values within the given initializer list
316/// with expressions that perform value-initialization of the
317/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000318void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner08202542009-02-24 22:50:46 +0000319 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000320 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000321 SourceLocation Loc = ILE->getSourceRange().getBegin();
322 if (ILE->getSyntacticForm())
323 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
324
Douglas Gregor4c678342009-01-28 21:54:33 +0000325 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
326 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000327 for (RecordDecl::field_iterator
328 Field = RType->getDecl()->field_begin(SemaRef.Context),
329 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000330 Field != FieldEnd; ++Field) {
331 if (Field->isUnnamedBitfield())
332 continue;
333
Douglas Gregor87fd7032009-02-02 17:43:21 +0000334 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000335 if (Field->getType()->isReferenceType()) {
336 // C++ [dcl.init.aggr]p9:
337 // If an incomplete or empty initializer-list leaves a
338 // member of reference type uninitialized, the program is
339 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000340 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000341 << Field->getType()
342 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +0000343 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000344 diag::note_uninit_reference_member);
345 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000346 return;
Chris Lattner08202542009-02-24 22:50:46 +0000347 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000348 hadError = true;
349 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000350 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000351
Mike Stump390b4cc2009-05-16 07:39:55 +0000352 // FIXME: If value-initialization involves calling a constructor, should
353 // we make that call explicit in the representation (even when it means
354 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000355 if (Init < NumInits && !hadError)
356 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000357 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000359 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000360 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000361 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000362
363 // Only look at the first initialization of a union.
364 if (RType->getDecl()->isUnion())
365 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000366 }
367
368 return;
369 }
370
371 QualType ElementType;
372
Douglas Gregor87fd7032009-02-02 17:43:21 +0000373 unsigned NumInits = ILE->getNumInits();
374 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000375 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000376 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000377 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
378 NumElements = CAType->getSize().getZExtValue();
379 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000380 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000381 NumElements = VType->getNumElements();
382 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000383 ElementType = ILE->getType();
384
Douglas Gregor87fd7032009-02-02 17:43:21 +0000385 for (unsigned Init = 0; Init != NumElements; ++Init) {
386 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000387 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 hadError = true;
389 return;
390 }
391
Mike Stump390b4cc2009-05-16 07:39:55 +0000392 // FIXME: If value-initialization involves calling a constructor, should
393 // we make that call explicit in the representation (even when it means
394 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 if (Init < NumInits && !hadError)
396 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000397 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000398 }
Chris Lattner68355a52009-01-29 05:10:57 +0000399 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000400 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000401 }
402}
403
Chris Lattner68355a52009-01-29 05:10:57 +0000404
Chris Lattner08202542009-02-24 22:50:46 +0000405InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
406 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000407 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000408
Eli Friedmanb85f7072008-05-19 19:16:24 +0000409 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000410 unsigned newStructuredIndex = 0;
411 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000412 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000413 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
414 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000415
Douglas Gregor930d8b52009-01-30 22:09:00 +0000416 if (!hadError)
417 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000418}
419
420int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000421 // FIXME: use a proper constant
422 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000423 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000424 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000425 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
426 }
427 return maxElements;
428}
429
430int InitListChecker::numStructUnionElements(QualType DeclType) {
431 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000432 int InitializableMembers = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000433 for (RecordDecl::field_iterator
434 Field = structDecl->field_begin(SemaRef.Context),
435 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000436 Field != FieldEnd; ++Field) {
437 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
438 ++InitializableMembers;
439 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000440 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000441 return std::min(InitializableMembers, 1);
442 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000443}
444
445void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000446 QualType T, unsigned &Index,
447 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000448 unsigned &StructuredIndex,
449 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000450 int maxElements = 0;
451
452 if (T->isArrayType())
453 maxElements = numArrayElements(T);
454 else if (T->isStructureType() || T->isUnionType())
455 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000456 else if (T->isVectorType())
457 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000458 else
459 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000460
Eli Friedman402256f2008-05-25 13:49:22 +0000461 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000462 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000463 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000464 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000465 hadError = true;
466 return;
467 }
468
Douglas Gregor4c678342009-01-28 21:54:33 +0000469 // Build a structured initializer list corresponding to this subobject.
470 InitListExpr *StructuredSubobjectInitList
471 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
472 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000473 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
474 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000475 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000476
Douglas Gregor4c678342009-01-28 21:54:33 +0000477 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000478 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000479 CheckListElementTypes(ParentIList, T, false, Index,
480 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000481 StructuredSubobjectInitIndex,
482 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000483 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000484 StructuredSubobjectInitList->setType(T);
485
Douglas Gregored8a93d2009-03-01 17:12:46 +0000486 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000487 // range corresponds with the end of the last initializer it used.
488 if (EndIndex < ParentIList->getNumInits()) {
489 SourceLocation EndLoc
490 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
491 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
492 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000493}
494
Steve Naroffa647caa2008-05-06 00:23:44 +0000495void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000496 unsigned &Index,
497 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000498 unsigned &StructuredIndex,
499 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000500 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000501 SyntacticToSemantic[IList] = StructuredList;
502 StructuredList->setSyntacticForm(IList);
503 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000504 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000505 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000507 if (hadError)
508 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000509
Eli Friedman638e1442008-05-25 13:22:35 +0000510 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000511 // We have leftover initializers
512 if (IList->getNumInits() > 0 &&
Chris Lattner08202542009-02-24 22:50:46 +0000513 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000514 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Chris Lattner08202542009-02-24 22:50:46 +0000515 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000516 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000517 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000518 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000519 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000520 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000521 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000522 // Don't complain for incomplete types, since we'll get an error
523 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000524 QualType CurrentObjectType = StructuredList->getType();
525 int initKind =
526 CurrentObjectType->isArrayType()? 0 :
527 CurrentObjectType->isVectorType()? 1 :
528 CurrentObjectType->isScalarType()? 2 :
529 CurrentObjectType->isUnionType()? 3 :
530 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000531
532 unsigned DK = diag::warn_excess_initializers;
Chris Lattner08202542009-02-24 22:50:46 +0000533 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000534 DK = diag::err_excess_initializers;
535
Chris Lattner08202542009-02-24 22:50:46 +0000536 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000537 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000538 }
539 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000540
Eli Friedman759f2522009-05-16 11:45:48 +0000541 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000542 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000543 << IList->getSourceRange()
544 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
545 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroff0cca7492008-05-01 22:18:59 +0000546}
547
Eli Friedmanb85f7072008-05-19 19:16:24 +0000548void InitListChecker::CheckListElementTypes(InitListExpr *IList,
549 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000550 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000551 unsigned &Index,
552 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000553 unsigned &StructuredIndex,
554 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000555 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000556 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000557 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000558 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000559 } else if (DeclType->isAggregateType()) {
560 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000561 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000562 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregor4c678342009-01-28 21:54:33 +0000563 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000564 StructuredList, StructuredIndex,
565 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000566 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000567 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000568 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000569 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000570 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
571 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000572 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000573 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000574 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000575 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
576 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000577 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000578 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000579 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000580 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000581 } else if (DeclType->isRecordType()) {
582 // C++ [dcl.init]p14:
583 // [...] If the class is an aggregate (8.5.1), and the initializer
584 // is a brace-enclosed list, see 8.5.1.
585 //
586 // Note: 8.5.1 is handled below; here, we diagnose the case where
587 // we have an initializer list and a destination type that is not
588 // an aggregate.
589 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000590 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000591 << DeclType << IList->getSourceRange();
592 hadError = true;
593 } else if (DeclType->isReferenceType()) {
594 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000595 } else {
596 // In C, all types are either scalars or aggregates, but
597 // additional handling is needed here for C++ (and possibly others?).
598 assert(0 && "Unsupported initializer type");
599 }
600}
601
Eli Friedmanb85f7072008-05-19 19:16:24 +0000602void InitListChecker::CheckSubElementType(InitListExpr *IList,
603 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 unsigned &Index,
605 InitListExpr *StructuredList,
606 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000607 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000608 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
609 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000610 unsigned newStructuredIndex = 0;
611 InitListExpr *newStructuredList
612 = getStructuredSubobjectInit(IList, Index, ElemType,
613 StructuredList, StructuredIndex,
614 SubInitList->getSourceRange());
615 CheckExplicitInitList(SubInitList, ElemType, newIndex,
616 newStructuredList, newStructuredIndex);
617 ++StructuredIndex;
618 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000619 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
620 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000621 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000622 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000623 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000624 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000625 } else if (ElemType->isReferenceType()) {
626 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000627 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000628 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000629 // C++ [dcl.init.aggr]p12:
630 // All implicit type conversions (clause 4) are considered when
631 // initializing the aggregate member with an ini- tializer from
632 // an initializer-list. If the initializer can initialize a
633 // member, the member is initialized. [...]
634 ImplicitConversionSequence ICS
Chris Lattner08202542009-02-24 22:50:46 +0000635 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000636 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner08202542009-02-24 22:50:46 +0000637 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000638 "initializing"))
639 hadError = true;
640 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
641 ++Index;
642 return;
643 }
644
645 // Fall through for subaggregate initialization
646 } else {
647 // C99 6.7.8p13:
648 //
649 // The initializer for a structure or union object that has
650 // automatic storage duration shall be either an initializer
651 // list as described below, or a single expression that has
652 // compatible structure or union type. In the latter case, the
653 // initial value of the object, including unnamed members, is
654 // that of the expression.
Chris Lattner08202542009-02-24 22:50:46 +0000655 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
656 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
657 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000658 ElemTypeCanon.getUnqualifiedType())) {
659 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
660 ++Index;
661 return;
662 }
663
664 // Fall through for subaggregate initialization
665 }
666
667 // C++ [dcl.init.aggr]p12:
668 //
669 // [...] Otherwise, if the member is itself a non-empty
670 // subaggregate, brace elision is assumed and the initializer is
671 // considered for the initialization of the first member of
672 // the subaggregate.
673 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
674 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
675 StructuredIndex);
676 ++StructuredIndex;
677 } else {
678 // We cannot initialize this element, so let
679 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000680 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000681 hadError = true;
682 ++Index;
683 ++StructuredIndex;
684 }
685 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000686}
687
Douglas Gregor930d8b52009-01-30 22:09:00 +0000688void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000689 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000690 InitListExpr *StructuredList,
691 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000692 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000693 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000694 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000695 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000696 diag::err_many_braces_around_scalar_init)
697 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000698 hadError = true;
699 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000700 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000701 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000702 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000703 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000704 diag::err_designator_for_scalar_init)
705 << DeclType << expr->getSourceRange();
706 hadError = true;
707 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000708 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000709 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000710 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000711
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000712 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000713 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000714 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000715 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000716 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000717 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000718 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000719 if (hadError)
720 ++StructuredIndex;
721 else
722 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000723 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000724 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000725 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000726 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000727 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000728 ++Index;
729 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000730 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000731 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000732}
733
Douglas Gregor930d8b52009-01-30 22:09:00 +0000734void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
735 unsigned &Index,
736 InitListExpr *StructuredList,
737 unsigned &StructuredIndex) {
738 if (Index < IList->getNumInits()) {
739 Expr *expr = IList->getInit(Index);
740 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000741 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000742 << DeclType << IList->getSourceRange();
743 hadError = true;
744 ++Index;
745 ++StructuredIndex;
746 return;
747 }
748
749 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000750 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000751 hadError = true;
752 else if (savExpr != expr) {
753 // The type was promoted, update initializer list.
754 IList->setInit(Index, expr);
755 }
756 if (hadError)
757 ++StructuredIndex;
758 else
759 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
760 ++Index;
761 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000762 // FIXME: It would be wonderful if we could point at the actual member. In
763 // general, it would be useful to pass location information down the stack,
764 // so that we know the location (or decl) of the "current object" being
765 // initialized.
Chris Lattner08202542009-02-24 22:50:46 +0000766 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000767 diag::err_init_reference_member_uninitialized)
768 << DeclType
769 << IList->getSourceRange();
770 hadError = true;
771 ++Index;
772 ++StructuredIndex;
773 return;
774 }
775}
776
Steve Naroff0cca7492008-05-01 22:18:59 +0000777void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000778 unsigned &Index,
779 InitListExpr *StructuredList,
780 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000781 if (Index < IList->getNumInits()) {
782 const VectorType *VT = DeclType->getAsVectorType();
783 int maxElements = VT->getNumElements();
784 QualType elementType = VT->getElementType();
785
786 for (int i = 0; i < maxElements; ++i) {
787 // Don't attempt to go past the end of the init list
788 if (Index >= IList->getNumInits())
789 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000790 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000791 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000792 }
793 }
794}
795
796void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000797 llvm::APSInt elementIndex,
798 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000799 unsigned &Index,
800 InitListExpr *StructuredList,
801 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000802 // Check for the special-case of initializing an array with a string.
803 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000804 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
805 SemaRef.Context)) {
806 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000807 // We place the string literal directly into the resulting
808 // initializer list. This is the only place where the structure
809 // of the structured initializer list doesn't match exactly,
810 // because doing so would involve allocating one character
811 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000812 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000813 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000814 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000815 return;
816 }
817 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000818 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000819 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000820 // Check for VLAs; in standard C it would be possible to check this
821 // earlier, but I don't know where clang accepts VLAs (gcc accepts
822 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000823 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000824 diag::err_variable_object_no_init)
825 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000826 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000827 ++Index;
828 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000829 return;
830 }
831
Douglas Gregor05c13a32009-01-22 00:58:24 +0000832 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000833 llvm::APSInt maxElements(elementIndex.getBitWidth(),
834 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000835 bool maxElementsKnown = false;
836 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000837 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000838 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000839 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000840 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000841 maxElementsKnown = true;
842 }
843
Chris Lattner08202542009-02-24 22:50:46 +0000844 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000845 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000846 while (Index < IList->getNumInits()) {
847 Expr *Init = IList->getInit(Index);
848 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000849 // If we're not the subobject that matches up with the '{' for
850 // the designator, we shouldn't be handling the
851 // designator. Return immediately.
852 if (!SubobjectIsDesignatorContext)
853 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000854
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000855 // Handle this designated initializer. elementIndex will be
856 // updated to be the next array element we'll initialize.
Douglas Gregor71199712009-04-15 04:56:10 +0000857 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000858 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000859 StructuredList, StructuredIndex, true,
860 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000861 hadError = true;
862 continue;
863 }
864
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000865 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
866 maxElements.extend(elementIndex.getBitWidth());
867 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
868 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000869 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000870
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000871 // If the array is of incomplete type, keep track of the number of
872 // elements in the initializer.
873 if (!maxElementsKnown && elementIndex > maxElements)
874 maxElements = elementIndex;
875
Douglas Gregor05c13a32009-01-22 00:58:24 +0000876 continue;
877 }
878
879 // If we know the maximum number of elements, and we've already
880 // hit it, stop consuming elements in the initializer list.
881 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000882 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000883
884 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000885 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000886 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000887 ++elementIndex;
888
889 // If the array is of incomplete type, keep track of the number of
890 // elements in the initializer.
891 if (!maxElementsKnown && elementIndex > maxElements)
892 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000893 }
894 if (DeclType->isIncompleteArrayType()) {
895 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000896 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000897 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000898 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000899 // Sizing an array implicitly to zero is not allowed by ISO C,
900 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000901 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000902 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000903 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000904
Chris Lattner08202542009-02-24 22:50:46 +0000905 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000906 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000907 }
908}
909
910void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
911 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000912 RecordDecl::field_iterator Field,
913 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000914 unsigned &Index,
915 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000916 unsigned &StructuredIndex,
917 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000918 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000919
Eli Friedmanb85f7072008-05-19 19:16:24 +0000920 // If the record is invalid, some of it's members are invalid. To avoid
921 // confusion, we forgo checking the intializer for the entire record.
922 if (structDecl->isInvalidDecl()) {
923 hadError = true;
924 return;
925 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000926
927 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
928 // Value-initialize the first named member of the union.
929 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000930 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000931 Field != FieldEnd; ++Field) {
932 if (Field->getDeclName()) {
933 StructuredList->setInitializedFieldInUnion(*Field);
934 break;
935 }
936 }
937 return;
938 }
939
Douglas Gregor05c13a32009-01-22 00:58:24 +0000940 // If structDecl is a forward declaration, this loop won't do
941 // anything except look at designated initializers; That's okay,
942 // because an error should get printed out elsewhere. It might be
943 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000944 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000945 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000946 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000947 while (Index < IList->getNumInits()) {
948 Expr *Init = IList->getInit(Index);
949
950 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000951 // If we're not the subobject that matches up with the '{' for
952 // the designator, we shouldn't be handling the
953 // designator. Return immediately.
954 if (!SubobjectIsDesignatorContext)
955 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000956
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000957 // Handle this designated initializer. Field will be updated to
958 // the next field that we'll be initializing.
Douglas Gregor71199712009-04-15 04:56:10 +0000959 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000960 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000961 StructuredList, StructuredIndex,
962 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000963 hadError = true;
964
Douglas Gregordfb5e592009-02-12 19:00:39 +0000965 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000966 continue;
967 }
968
969 if (Field == FieldEnd) {
970 // We've run out of fields. We're done.
971 break;
972 }
973
Douglas Gregordfb5e592009-02-12 19:00:39 +0000974 // We've already initialized a member of a union. We're done.
975 if (InitializedSomething && DeclType->isUnionType())
976 break;
977
Douglas Gregor44b43212008-12-11 16:49:14 +0000978 // If we've hit the flexible array member at the end, we're done.
979 if (Field->getType()->isIncompleteArrayType())
980 break;
981
Douglas Gregor0bb76892009-01-29 16:53:55 +0000982 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000983 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000984 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000985 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000986 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000987
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000988 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000989 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000990 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000991
992 if (DeclType->isUnionType()) {
993 // Initialize the first field within the union.
994 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000995 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000996
997 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000998 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000999
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001000 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001001 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001002 return;
1003
1004 // Handle GNU flexible array initializers.
1005 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001006 (!isa<InitListExpr>(IList->getInit(Index)) ||
1007 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner08202542009-02-24 22:50:46 +00001008 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001009 diag::err_flexible_array_init_nonempty)
1010 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001011 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001012 << *Field;
1013 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001014 ++Index;
1015 return;
1016 } else {
1017 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1018 diag::ext_flexible_array_init)
1019 << IList->getInit(Index)->getSourceRange().getBegin();
1020 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1021 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001022 }
1023
Douglas Gregora6457962009-03-20 00:32:56 +00001024 if (isa<InitListExpr>(IList->getInit(Index)))
1025 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1026 StructuredIndex);
1027 else
1028 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1029 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001030}
Steve Naroff0cca7492008-05-01 22:18:59 +00001031
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001032/// \brief Expand a field designator that refers to a member of an
1033/// anonymous struct or union into a series of field designators that
1034/// refers to the field within the appropriate subobject.
1035///
1036/// Field/FieldIndex will be updated to point to the (new)
1037/// currently-designated field.
1038static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1039 DesignatedInitExpr *DIE,
1040 unsigned DesigIdx,
1041 FieldDecl *Field,
1042 RecordDecl::field_iterator &FieldIter,
1043 unsigned &FieldIndex) {
1044 typedef DesignatedInitExpr::Designator Designator;
1045
1046 // Build the path from the current object to the member of the
1047 // anonymous struct/union (backwards).
1048 llvm::SmallVector<FieldDecl *, 4> Path;
1049 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1050
1051 // Build the replacement designators.
1052 llvm::SmallVector<Designator, 4> Replacements;
1053 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1054 FI = Path.rbegin(), FIEnd = Path.rend();
1055 FI != FIEnd; ++FI) {
1056 if (FI + 1 == FIEnd)
1057 Replacements.push_back(Designator((IdentifierInfo *)0,
1058 DIE->getDesignator(DesigIdx)->getDotLoc(),
1059 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1060 else
1061 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1062 SourceLocation()));
1063 Replacements.back().setField(*FI);
1064 }
1065
1066 // Expand the current designator into the set of replacement
1067 // designators, so we have a full subobject path down to where the
1068 // member of the anonymous struct/union is actually stored.
1069 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1070 &Replacements[0] + Replacements.size());
1071
1072 // Update FieldIter/FieldIndex;
1073 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1074 FieldIter = Record->field_begin(SemaRef.Context);
1075 FieldIndex = 0;
1076 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1077 FieldIter != FEnd; ++FieldIter) {
1078 if (FieldIter->isUnnamedBitfield())
1079 continue;
1080
1081 if (*FieldIter == Path.back())
1082 return;
1083
1084 ++FieldIndex;
1085 }
1086
1087 assert(false && "Unable to find anonymous struct/union field");
1088}
1089
Douglas Gregor05c13a32009-01-22 00:58:24 +00001090/// @brief Check the well-formedness of a C99 designated initializer.
1091///
1092/// Determines whether the designated initializer @p DIE, which
1093/// resides at the given @p Index within the initializer list @p
1094/// IList, is well-formed for a current object of type @p DeclType
1095/// (C99 6.7.8). The actual subobject that this designator refers to
1096/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001097/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001098///
1099/// @param IList The initializer list in which this designated
1100/// initializer occurs.
1101///
Douglas Gregor71199712009-04-15 04:56:10 +00001102/// @param DIE The designated initializer expression.
1103///
1104/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001105///
1106/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1107/// into which the designation in @p DIE should refer.
1108///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001109/// @param NextField If non-NULL and the first designator in @p DIE is
1110/// a field, this will be set to the field declaration corresponding
1111/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001112///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001113/// @param NextElementIndex If non-NULL and the first designator in @p
1114/// DIE is an array designator or GNU array-range designator, this
1115/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001116///
1117/// @param Index Index into @p IList where the designated initializer
1118/// @p DIE occurs.
1119///
Douglas Gregor4c678342009-01-28 21:54:33 +00001120/// @param StructuredList The initializer list expression that
1121/// describes all of the subobject initializers in the order they'll
1122/// actually be initialized.
1123///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001124/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001125bool
1126InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1127 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001128 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001129 QualType &CurrentObjectType,
1130 RecordDecl::field_iterator *NextField,
1131 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001132 unsigned &Index,
1133 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001134 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001135 bool FinishSubobjectInit,
1136 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001137 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001138 // Check the actual initialization for the designated object type.
1139 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001140
1141 // Temporarily remove the designator expression from the
1142 // initializer list that the child calls see, so that we don't try
1143 // to re-process the designator.
1144 unsigned OldIndex = Index;
1145 IList->setInit(OldIndex, DIE->getInit());
1146
1147 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001148 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001149
1150 // Restore the designated initializer expression in the syntactic
1151 // form of the initializer list.
1152 if (IList->getInit(OldIndex) != DIE->getInit())
1153 DIE->setInit(IList->getInit(OldIndex));
1154 IList->setInit(OldIndex, DIE);
1155
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001156 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001157 }
1158
Douglas Gregor71199712009-04-15 04:56:10 +00001159 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001160 assert((IsFirstDesignator || StructuredList) &&
1161 "Need a non-designated initializer list to start from");
1162
Douglas Gregor71199712009-04-15 04:56:10 +00001163 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001164 // Determine the structural initializer list that corresponds to the
1165 // current subobject.
1166 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregored8a93d2009-03-01 17:12:46 +00001167 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1168 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001169 SourceRange(D->getStartLocation(),
1170 DIE->getSourceRange().getEnd()));
1171 assert(StructuredList && "Expected a structured initializer list");
1172
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001173 if (D->isFieldDesignator()) {
1174 // C99 6.7.8p7:
1175 //
1176 // If a designator has the form
1177 //
1178 // . identifier
1179 //
1180 // then the current object (defined below) shall have
1181 // structure or union type and the identifier shall be the
1182 // name of a member of that type.
1183 const RecordType *RT = CurrentObjectType->getAsRecordType();
1184 if (!RT) {
1185 SourceLocation Loc = D->getDotLoc();
1186 if (Loc.isInvalid())
1187 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001188 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1189 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001190 ++Index;
1191 return true;
1192 }
1193
Douglas Gregor4c678342009-01-28 21:54:33 +00001194 // Note: we perform a linear search of the fields here, despite
1195 // the fact that we have a faster lookup method, because we always
1196 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001197 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001198 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001199 unsigned FieldIndex = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001200 RecordDecl::field_iterator
1201 Field = RT->getDecl()->field_begin(SemaRef.Context),
1202 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +00001203 for (; Field != FieldEnd; ++Field) {
1204 if (Field->isUnnamedBitfield())
1205 continue;
1206
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001207 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001208 break;
1209
1210 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001211 }
1212
Douglas Gregor4c678342009-01-28 21:54:33 +00001213 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001214 // There was no normal field in the struct with the designated
1215 // name. Perform another lookup for this name, which may find
1216 // something that we can't designate (e.g., a member function),
1217 // may find nothing, or may find a member of an anonymous
1218 // struct/union.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001219 DeclContext::lookup_result Lookup
1220 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001221 if (Lookup.first == Lookup.second) {
1222 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001223 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001224 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001225 ++Index;
1226 return true;
1227 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1228 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1229 ->isAnonymousStructOrUnion()) {
1230 // Handle an field designator that refers to a member of an
1231 // anonymous struct or union.
1232 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1233 cast<FieldDecl>(*Lookup.first),
1234 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001235 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001236 } else {
1237 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001238 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001239 << FieldName;
Chris Lattner08202542009-02-24 22:50:46 +00001240 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001241 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001242 ++Index;
1243 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001244 }
1245 } else if (!KnownField &&
1246 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001247 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001248 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1249 Field, FieldIndex);
1250 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001251 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001252
1253 // All of the fields of a union are located at the same place in
1254 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001255 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001256 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001257 StructuredList->setInitializedFieldInUnion(*Field);
1258 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001259
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001260 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001261 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001262
Douglas Gregor4c678342009-01-28 21:54:33 +00001263 // Make sure that our non-designated initializer list has space
1264 // for a subobject corresponding to this field.
1265 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001266 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001267
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001268 // This designator names a flexible array member.
1269 if (Field->getType()->isIncompleteArrayType()) {
1270 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001271 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001272 // We can't designate an object within the flexible array
1273 // member (because GCC doesn't allow it).
Douglas Gregor71199712009-04-15 04:56:10 +00001274 DesignatedInitExpr::Designator *NextD
1275 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner08202542009-02-24 22:50:46 +00001276 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001277 diag::err_designator_into_flexible_array_member)
1278 << SourceRange(NextD->getStartLocation(),
1279 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001280 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001281 << *Field;
1282 Invalid = true;
1283 }
1284
1285 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1286 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001287 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001288 diag::err_flexible_array_init_needs_braces)
1289 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001290 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001291 << *Field;
1292 Invalid = true;
1293 }
1294
1295 // Handle GNU flexible array initializers.
1296 if (!Invalid && !TopLevelObject &&
1297 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner08202542009-02-24 22:50:46 +00001298 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001299 diag::err_flexible_array_init_nonempty)
1300 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001301 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001302 << *Field;
1303 Invalid = true;
1304 }
1305
1306 if (Invalid) {
1307 ++Index;
1308 return true;
1309 }
1310
1311 // Initialize the array.
1312 bool prevHadError = hadError;
1313 unsigned newStructuredIndex = FieldIndex;
1314 unsigned OldIndex = Index;
1315 IList->setInit(Index, DIE->getInit());
1316 CheckSubElementType(IList, Field->getType(), Index,
1317 StructuredList, newStructuredIndex);
1318 IList->setInit(OldIndex, DIE);
1319 if (hadError && !prevHadError) {
1320 ++Field;
1321 ++FieldIndex;
1322 if (NextField)
1323 *NextField = Field;
1324 StructuredIndex = FieldIndex;
1325 return true;
1326 }
1327 } else {
1328 // Recurse to check later designated subobjects.
1329 QualType FieldType = (*Field)->getType();
1330 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001331 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1332 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001333 true, false))
1334 return true;
1335 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001336
1337 // Find the position of the next field to be initialized in this
1338 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001339 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001340 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001341
1342 // If this the first designator, our caller will continue checking
1343 // the rest of this struct/class/union subobject.
1344 if (IsFirstDesignator) {
1345 if (NextField)
1346 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001347 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001348 return false;
1349 }
1350
Douglas Gregor34e79462009-01-28 23:36:17 +00001351 if (!FinishSubobjectInit)
1352 return false;
1353
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001354 // We've already initialized something in the union; we're done.
1355 if (RT->getDecl()->isUnion())
1356 return hadError;
1357
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001358 // Check the remaining fields within this class/struct/union subobject.
1359 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001360 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1361 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001362 return hadError && !prevHadError;
1363 }
1364
1365 // C99 6.7.8p6:
1366 //
1367 // If a designator has the form
1368 //
1369 // [ constant-expression ]
1370 //
1371 // then the current object (defined below) shall have array
1372 // type and the expression shall be an integer constant
1373 // expression. If the array is of unknown size, any
1374 // nonnegative value is valid.
1375 //
1376 // Additionally, cope with the GNU extension that permits
1377 // designators of the form
1378 //
1379 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001380 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001381 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001382 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001383 << CurrentObjectType;
1384 ++Index;
1385 return true;
1386 }
1387
1388 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001389 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1390 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001391 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001392 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001393 DesignatedEndIndex = DesignatedStartIndex;
1394 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001395 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001396
Douglas Gregor34e79462009-01-28 23:36:17 +00001397
Chris Lattner3bf68932009-04-25 21:59:05 +00001398 DesignatedStartIndex =
1399 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1400 DesignatedEndIndex =
1401 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001402 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001403
Chris Lattner3bf68932009-04-25 21:59:05 +00001404 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001405 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 }
1407
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001408 if (isa<ConstantArrayType>(AT)) {
1409 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001410 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1411 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1412 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1413 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1414 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001415 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001416 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001417 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001418 << IndexExpr->getSourceRange();
1419 ++Index;
1420 return true;
1421 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001422 } else {
1423 // Make sure the bit-widths and signedness match.
1424 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1425 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001426 else if (DesignatedStartIndex.getBitWidth() <
1427 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001428 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1429 DesignatedStartIndex.setIsUnsigned(true);
1430 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001431 }
1432
Douglas Gregor4c678342009-01-28 21:54:33 +00001433 // Make sure that our non-designated initializer list has space
1434 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001435 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001436 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001437 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001438
Douglas Gregor34e79462009-01-28 23:36:17 +00001439 // Repeatedly perform subobject initializations in the range
1440 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001441
Douglas Gregor34e79462009-01-28 23:36:17 +00001442 // Move to the next designator
1443 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1444 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001445 while (DesignatedStartIndex <= DesignatedEndIndex) {
1446 // Recurse to check later designated subobjects.
1447 QualType ElementType = AT->getElementType();
1448 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001449 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1450 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001451 (DesignatedStartIndex == DesignatedEndIndex),
1452 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001453 return true;
1454
1455 // Move to the next index in the array that we'll be initializing.
1456 ++DesignatedStartIndex;
1457 ElementIndex = DesignatedStartIndex.getZExtValue();
1458 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001459
1460 // If this the first designator, our caller will continue checking
1461 // the rest of this array subobject.
1462 if (IsFirstDesignator) {
1463 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001464 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001465 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001466 return false;
1467 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001468
1469 if (!FinishSubobjectInit)
1470 return false;
1471
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001472 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001473 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001474 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001475 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001476 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001477}
1478
Douglas Gregor4c678342009-01-28 21:54:33 +00001479// Get the structured initializer list for a subobject of type
1480// @p CurrentObjectType.
1481InitListExpr *
1482InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1483 QualType CurrentObjectType,
1484 InitListExpr *StructuredList,
1485 unsigned StructuredIndex,
1486 SourceRange InitRange) {
1487 Expr *ExistingInit = 0;
1488 if (!StructuredList)
1489 ExistingInit = SyntacticToSemantic[IList];
1490 else if (StructuredIndex < StructuredList->getNumInits())
1491 ExistingInit = StructuredList->getInit(StructuredIndex);
1492
1493 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1494 return Result;
1495
1496 if (ExistingInit) {
1497 // We are creating an initializer list that initializes the
1498 // subobjects of the current object, but there was already an
1499 // initialization that completely initialized the current
1500 // subobject, e.g., by a compound literal:
1501 //
1502 // struct X { int a, b; };
1503 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1504 //
1505 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1506 // designated initializer re-initializes the whole
1507 // subobject [0], overwriting previous initializers.
Douglas Gregored8a93d2009-03-01 17:12:46 +00001508 SemaRef.Diag(InitRange.getBegin(),
1509 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001510 << InitRange;
Chris Lattner08202542009-02-24 22:50:46 +00001511 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001512 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001513 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001514 << ExistingInit->getSourceRange();
1515 }
1516
1517 InitListExpr *Result
Douglas Gregored8a93d2009-03-01 17:12:46 +00001518 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1519 InitRange.getEnd());
1520
Douglas Gregor4c678342009-01-28 21:54:33 +00001521 Result->setType(CurrentObjectType);
1522
Douglas Gregorfa219202009-03-20 23:58:33 +00001523 // Pre-allocate storage for the structured initializer list.
1524 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001525 unsigned NumInits = 0;
1526 if (!StructuredList)
1527 NumInits = IList->getNumInits();
1528 else if (Index < IList->getNumInits()) {
1529 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1530 NumInits = SubList->getNumInits();
1531 }
1532
Douglas Gregorfa219202009-03-20 23:58:33 +00001533 if (const ArrayType *AType
1534 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1535 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1536 NumElements = CAType->getSize().getZExtValue();
1537 // Simple heuristic so that we don't allocate a very large
1538 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001539 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001540 NumElements = 0;
1541 }
1542 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1543 NumElements = VType->getNumElements();
1544 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1545 RecordDecl *RDecl = RType->getDecl();
1546 if (RDecl->isUnion())
1547 NumElements = 1;
1548 else
Douglas Gregor6ab35242009-04-09 21:40:53 +00001549 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1550 RDecl->field_end(SemaRef.Context));
Douglas Gregorfa219202009-03-20 23:58:33 +00001551 }
1552
Douglas Gregor08457732009-03-21 18:13:52 +00001553 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001554 NumElements = IList->getNumInits();
1555
1556 Result->reserveInits(NumElements);
1557
Douglas Gregor4c678342009-01-28 21:54:33 +00001558 // Link this new initializer list into the structured initializer
1559 // lists.
1560 if (StructuredList)
1561 StructuredList->updateInit(StructuredIndex, Result);
1562 else {
1563 Result->setSyntacticForm(IList);
1564 SyntacticToSemantic[IList] = Result;
1565 }
1566
1567 return Result;
1568}
1569
1570/// Update the initializer at index @p StructuredIndex within the
1571/// structured initializer list to the value @p expr.
1572void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1573 unsigned &StructuredIndex,
1574 Expr *expr) {
1575 // No structured initializer list to update
1576 if (!StructuredList)
1577 return;
1578
1579 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1580 // This initializer overwrites a previous initializer. Warn.
Chris Lattner08202542009-02-24 22:50:46 +00001581 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001582 diag::warn_initializer_overrides)
1583 << expr->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001584 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001585 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001586 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001587 << PrevInit->getSourceRange();
1588 }
1589
1590 ++StructuredIndex;
1591}
1592
Douglas Gregor05c13a32009-01-22 00:58:24 +00001593/// Check that the given Index expression is a valid array designator
1594/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001595/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001596/// and produces a reasonable diagnostic if there is a
1597/// failure. Returns true if there was an error, false otherwise. If
1598/// everything went okay, Value will receive the value of the constant
1599/// expression.
1600static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001601CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001602 SourceLocation Loc = Index->getSourceRange().getBegin();
1603
1604 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001605 if (S.VerifyIntegerConstantExpression(Index, &Value))
1606 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001607
Chris Lattner3bf68932009-04-25 21:59:05 +00001608 if (Value.isSigned() && Value.isNegative())
1609 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001610 << Value.toString(10) << Index->getSourceRange();
1611
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001612 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001613 return false;
1614}
1615
1616Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1617 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001618 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001619 OwningExprResult Init) {
1620 typedef DesignatedInitExpr::Designator ASTDesignator;
1621
1622 bool Invalid = false;
1623 llvm::SmallVector<ASTDesignator, 32> Designators;
1624 llvm::SmallVector<Expr *, 32> InitExpressions;
1625
1626 // Build designators and check array designator expressions.
1627 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1628 const Designator &D = Desig.getDesignator(Idx);
1629 switch (D.getKind()) {
1630 case Designator::FieldDesignator:
1631 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1632 D.getFieldLoc()));
1633 break;
1634
1635 case Designator::ArrayDesignator: {
1636 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1637 llvm::APSInt IndexValue;
1638 if (CheckArrayDesignatorExpr(*this, Index, IndexValue))
1639 Invalid = true;
1640 else {
1641 Designators.push_back(ASTDesignator(InitExpressions.size(),
1642 D.getLBracketLoc(),
1643 D.getRBracketLoc()));
1644 InitExpressions.push_back(Index);
1645 }
1646 break;
1647 }
1648
1649 case Designator::ArrayRangeDesignator: {
1650 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1651 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1652 llvm::APSInt StartValue;
1653 llvm::APSInt EndValue;
1654 if (CheckArrayDesignatorExpr(*this, StartIndex, StartValue) ||
1655 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))
1656 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001657 else {
1658 // Make sure we're comparing values with the same bit width.
1659 if (StartValue.getBitWidth() > EndValue.getBitWidth())
1660 EndValue.extend(StartValue.getBitWidth());
1661 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1662 StartValue.extend(EndValue.getBitWidth());
1663
1664 if (EndValue < StartValue) {
1665 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1666 << StartValue.toString(10) << EndValue.toString(10)
1667 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1668 Invalid = true;
1669 } else {
1670 Designators.push_back(ASTDesignator(InitExpressions.size(),
1671 D.getLBracketLoc(),
1672 D.getEllipsisLoc(),
1673 D.getRBracketLoc()));
1674 InitExpressions.push_back(StartIndex);
1675 InitExpressions.push_back(EndIndex);
1676 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001677 }
1678 break;
1679 }
1680 }
1681 }
1682
1683 if (Invalid || Init.isInvalid())
1684 return ExprError();
1685
1686 // Clear out the expressions within the designation.
1687 Desig.ClearExprs(*this);
1688
1689 DesignatedInitExpr *DIE
1690 = DesignatedInitExpr::Create(Context, &Designators[0], Designators.size(),
1691 &InitExpressions[0], InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001692 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001693 return Owned(DIE);
1694}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001695
1696bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001697 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001698 if (!CheckInitList.HadError())
1699 InitList = CheckInitList.getFullyStructuredList();
1700
1701 return CheckInitList.HadError();
1702}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001703
1704/// \brief Diagnose any semantic errors with value-initialization of
1705/// the given type.
1706///
1707/// Value-initialization effectively zero-initializes any types
1708/// without user-declared constructors, and calls the default
1709/// constructor for a for any type that has a user-declared
1710/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1711/// a type with a user-declared constructor does not have an
1712/// accessible, non-deleted default constructor. In C, everything can
1713/// be value-initialized, which corresponds to C's notion of
1714/// initializing objects with static storage duration when no
1715/// initializer is provided for that object.
1716///
1717/// \returns true if there was an error, false otherwise.
1718bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1719 // C++ [dcl.init]p5:
1720 //
1721 // To value-initialize an object of type T means:
1722
1723 // -- if T is an array type, then each element is value-initialized;
1724 if (const ArrayType *AT = Context.getAsArrayType(Type))
1725 return CheckValueInitialization(AT->getElementType(), Loc);
1726
1727 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001728 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001729 // -- if T is a class type (clause 9) with a user-declared
1730 // constructor (12.1), then the default constructor for T is
1731 // called (and the initialization is ill-formed if T has no
1732 // accessible default constructor);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001733 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stump390b4cc2009-05-16 07:39:55 +00001734 // FIXME: Eventually, we'll need to put the constructor decl into the
1735 // AST.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001736 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1737 SourceRange(Loc),
1738 DeclarationName(),
1739 IK_Direct);
1740 }
1741 }
1742
1743 if (Type->isReferenceType()) {
1744 // C++ [dcl.init]p5:
1745 // [...] A program that calls for default-initialization or
1746 // value-initialization of an entity of reference type is
1747 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001748 // FIXME: Once we have code that goes through this path, add an actual
1749 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001750 }
1751
1752 return false;
1753}