blob: d880c236d2dc35057c2b64afbac55a158cecc854 [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) {
Douglas Gregor9ea62762009-05-21 23:17:49 +0000120 if (DeclType->isDependentType() ||
121 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000122 return false;
123
124 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000125 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000126 // (8.3.2), shall be initialized by an object, or function, of
127 // type T or by an object that can be converted into a T.
128 if (DeclType->isReferenceType())
129 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
130
131 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
132 // of unknown size ("[]") or an object type that is not a variable array type.
133 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
134 return Diag(InitLoc, diag::err_variable_object_no_init)
135 << VAT->getSizeExpr()->getSourceRange();
136
137 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
138 if (!InitList) {
139 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000140 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
141 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000142 return false;
143 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000144
145 // C++ [dcl.init]p14:
146 // -- If the destination type is a (possibly cv-qualified) class
147 // type:
148 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
149 QualType DeclTypeC = Context.getCanonicalType(DeclType);
150 QualType InitTypeC = Context.getCanonicalType(Init->getType());
151
152 // -- If the initialization is direct-initialization, or if it is
153 // copy-initialization where the cv-unqualified version of the
154 // source type is the same class as, or a derived class of, the
155 // class of the destination, constructors are considered.
156 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
157 IsDerivedFrom(InitTypeC, DeclTypeC)) {
158 CXXConstructorDecl *Constructor
159 = PerformInitializationByConstructor(DeclType, &Init, 1,
160 InitLoc, Init->getSourceRange(),
161 InitEntity,
162 DirectInit? IK_Direct : IK_Copy);
163 return Constructor == 0;
164 }
165
166 // -- Otherwise (i.e., for the remaining copy-initialization
167 // cases), user-defined conversion sequences that can
168 // convert from the source type to the destination type or
169 // (when a conversion function is used) to a derived class
170 // thereof are enumerated as described in 13.3.1.4, and the
171 // best one is chosen through overload resolution
172 // (13.3). If the conversion cannot be done or is
173 // ambiguous, the initialization is ill-formed. The
174 // function selected is called with the initializer
175 // expression as its argument; if the function is a
176 // constructor, the call initializes a temporary of the
177 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000178 // FIXME: We're pretending to do copy elision here; return to this when we
179 // have ASTs for such things.
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000180 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
181 return false;
182
183 if (InitEntity)
184 return Diag(InitLoc, diag::err_cannot_initialize_decl)
185 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
186 << Init->getType() << Init->getSourceRange();
187 else
188 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
189 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
190 << Init->getType() << Init->getSourceRange();
191 }
192
193 // C99 6.7.8p16.
194 if (DeclType->isArrayType())
195 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
196 << Init->getSourceRange();
197
Chris Lattner95e8d652009-02-24 22:46:58 +0000198 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000199 }
200
201 bool hadError = CheckInitList(InitList, DeclType);
202 Init = InitList;
203 return hadError;
204}
205
206//===----------------------------------------------------------------------===//
207// Semantic checking for initializer lists.
208//===----------------------------------------------------------------------===//
209
Douglas Gregor9e80f722009-01-29 01:05:33 +0000210/// @brief Semantic checking for initializer lists.
211///
212/// The InitListChecker class contains a set of routines that each
213/// handle the initialization of a certain kind of entity, e.g.,
214/// arrays, vectors, struct/union types, scalars, etc. The
215/// InitListChecker itself performs a recursive walk of the subobject
216/// structure of the type to be initialized, while stepping through
217/// the initializer list one element at a time. The IList and Index
218/// parameters to each of the Check* routines contain the active
219/// (syntactic) initializer list and the index into that initializer
220/// list that represents the current initializer. Each routine is
221/// responsible for moving that Index forward as it consumes elements.
222///
223/// Each Check* routine also has a StructuredList/StructuredIndex
224/// arguments, which contains the current the "structured" (semantic)
225/// initializer list and the index into that initializer list where we
226/// are copying initializers as we map them over to the semantic
227/// list. Once we have completed our recursive walk of the subobject
228/// structure, we will have constructed a full semantic initializer
229/// list.
230///
231/// C99 designators cause changes in the initializer list traversal,
232/// because they make the initialization "jump" into a specific
233/// subobject and then continue the initialization from that
234/// point. CheckDesignatedInitializer() recursively steps into the
235/// designated subobject and manages backing out the recursion to
236/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000237namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000238class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000239 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 bool hadError;
241 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
242 InitListExpr *FullyStructuredList;
243
244 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000245 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000246 unsigned &StructuredIndex,
247 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000248 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000249 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000250 unsigned &StructuredIndex,
251 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000252 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
253 bool SubobjectIsDesignatorContext,
254 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000255 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000256 unsigned &StructuredIndex,
257 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000258 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
259 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000262 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000263 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000264 InitListExpr *StructuredList,
265 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000266 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
267 unsigned &Index,
268 InitListExpr *StructuredList,
269 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000270 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000271 InitListExpr *StructuredList,
272 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000273 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
274 RecordDecl::field_iterator Field,
275 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000276 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000277 unsigned &StructuredIndex,
278 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000279 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
280 llvm::APSInt elementIndex,
281 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000282 InitListExpr *StructuredList,
283 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000284 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000285 unsigned DesigIdx,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000286 QualType &CurrentObjectType,
287 RecordDecl::field_iterator *NextField,
288 llvm::APSInt *NextElementIndex,
289 unsigned &Index,
290 InitListExpr *StructuredList,
291 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000292 bool FinishSubobjectInit,
293 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000294 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
295 QualType CurrentObjectType,
296 InitListExpr *StructuredList,
297 unsigned StructuredIndex,
298 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000299 void UpdateStructuredListElement(InitListExpr *StructuredList,
300 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000301 Expr *expr);
302 int numArrayElements(QualType DeclType);
303 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000304
305 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000306public:
Chris Lattner08202542009-02-24 22:50:46 +0000307 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000308 bool HadError() { return hadError; }
309
310 // @brief Retrieves the fully-structured initializer list used for
311 // semantic analysis and code generation.
312 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
313};
Chris Lattner8b419b92009-02-24 22:48:58 +0000314} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000315
Douglas Gregor4c678342009-01-28 21:54:33 +0000316/// Recursively replaces NULL values within the given initializer list
317/// with expressions that perform value-initialization of the
318/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000319void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner08202542009-02-24 22:50:46 +0000320 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000321 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000322 SourceLocation Loc = ILE->getSourceRange().getBegin();
323 if (ILE->getSyntacticForm())
324 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
325
Douglas Gregor4c678342009-01-28 21:54:33 +0000326 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
327 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000328 for (RecordDecl::field_iterator
329 Field = RType->getDecl()->field_begin(SemaRef.Context),
330 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000331 Field != FieldEnd; ++Field) {
332 if (Field->isUnnamedBitfield())
333 continue;
334
Douglas Gregor87fd7032009-02-02 17:43:21 +0000335 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000336 if (Field->getType()->isReferenceType()) {
337 // C++ [dcl.init.aggr]p9:
338 // If an incomplete or empty initializer-list leaves a
339 // member of reference type uninitialized, the program is
340 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000341 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000342 << Field->getType()
343 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +0000344 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000345 diag::note_uninit_reference_member);
346 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000347 return;
Chris Lattner08202542009-02-24 22:50:46 +0000348 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000349 hadError = true;
350 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000351 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000352
Mike Stump390b4cc2009-05-16 07:39:55 +0000353 // FIXME: If value-initialization involves calling a constructor, should
354 // we make that call explicit in the representation (even when it means
355 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 if (Init < NumInits && !hadError)
357 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000358 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000359 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000360 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000361 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000362 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000363
364 // Only look at the first initialization of a union.
365 if (RType->getDecl()->isUnion())
366 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000367 }
368
369 return;
370 }
371
372 QualType ElementType;
373
Douglas Gregor87fd7032009-02-02 17:43:21 +0000374 unsigned NumInits = ILE->getNumInits();
375 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000376 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000377 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
379 NumElements = CAType->getSize().getZExtValue();
380 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 NumElements = VType->getNumElements();
383 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000384 ElementType = ILE->getType();
385
Douglas Gregor87fd7032009-02-02 17:43:21 +0000386 for (unsigned Init = 0; Init != NumElements; ++Init) {
387 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000388 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000389 hadError = true;
390 return;
391 }
392
Mike Stump390b4cc2009-05-16 07:39:55 +0000393 // FIXME: If value-initialization involves calling a constructor, should
394 // we make that call explicit in the representation (even when it means
395 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000396 if (Init < NumInits && !hadError)
397 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000398 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 }
Chris Lattner68355a52009-01-29 05:10:57 +0000400 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000401 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000402 }
403}
404
Chris Lattner68355a52009-01-29 05:10:57 +0000405
Chris Lattner08202542009-02-24 22:50:46 +0000406InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
407 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000408 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000409
Eli Friedmanb85f7072008-05-19 19:16:24 +0000410 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000411 unsigned newStructuredIndex = 0;
412 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000413 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000414 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
415 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000416
Douglas Gregor930d8b52009-01-30 22:09:00 +0000417 if (!hadError)
418 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000419}
420
421int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000422 // FIXME: use a proper constant
423 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000424 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000425 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000426 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
427 }
428 return maxElements;
429}
430
431int InitListChecker::numStructUnionElements(QualType DeclType) {
432 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000433 int InitializableMembers = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000434 for (RecordDecl::field_iterator
435 Field = structDecl->field_begin(SemaRef.Context),
436 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +0000437 Field != FieldEnd; ++Field) {
438 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
439 ++InitializableMembers;
440 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000441 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000442 return std::min(InitializableMembers, 1);
443 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000444}
445
446void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000447 QualType T, unsigned &Index,
448 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000449 unsigned &StructuredIndex,
450 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000451 int maxElements = 0;
452
453 if (T->isArrayType())
454 maxElements = numArrayElements(T);
455 else if (T->isStructureType() || T->isUnionType())
456 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000457 else if (T->isVectorType())
458 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000459 else
460 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000461
Eli Friedman402256f2008-05-25 13:49:22 +0000462 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000463 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000464 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000465 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000466 hadError = true;
467 return;
468 }
469
Douglas Gregor4c678342009-01-28 21:54:33 +0000470 // Build a structured initializer list corresponding to this subobject.
471 InitListExpr *StructuredSubobjectInitList
472 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
473 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000474 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
475 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000476 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000477
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000479 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000480 CheckListElementTypes(ParentIList, T, false, Index,
481 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000482 StructuredSubobjectInitIndex,
483 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000484 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000485 StructuredSubobjectInitList->setType(T);
486
Douglas Gregored8a93d2009-03-01 17:12:46 +0000487 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000488 // range corresponds with the end of the last initializer it used.
489 if (EndIndex < ParentIList->getNumInits()) {
490 SourceLocation EndLoc
491 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
492 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
493 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000494}
495
Steve Naroffa647caa2008-05-06 00:23:44 +0000496void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000497 unsigned &Index,
498 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000499 unsigned &StructuredIndex,
500 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000501 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000502 SyntacticToSemantic[IList] = StructuredList;
503 StructuredList->setSyntacticForm(IList);
504 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000505 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000506 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000507 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000508 if (hadError)
509 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000510
Eli Friedman638e1442008-05-25 13:22:35 +0000511 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000512 // We have leftover initializers
513 if (IList->getNumInits() > 0 &&
Chris Lattner08202542009-02-24 22:50:46 +0000514 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000515 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Chris Lattner08202542009-02-24 22:50:46 +0000516 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000517 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000518 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000519 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000520 << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 hadError = true;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000522 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000523 // Don't complain for incomplete types, since we'll get an error
524 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000525 QualType CurrentObjectType = StructuredList->getType();
526 int initKind =
527 CurrentObjectType->isArrayType()? 0 :
528 CurrentObjectType->isVectorType()? 1 :
529 CurrentObjectType->isScalarType()? 2 :
530 CurrentObjectType->isUnionType()? 3 :
531 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000532
533 unsigned DK = diag::warn_excess_initializers;
Chris Lattner08202542009-02-24 22:50:46 +0000534 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 DK = diag::err_excess_initializers;
536
Chris Lattner08202542009-02-24 22:50:46 +0000537 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000538 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000539 }
540 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000541
Eli Friedman759f2522009-05-16 11:45:48 +0000542 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000543 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000544 << IList->getSourceRange()
545 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
546 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroff0cca7492008-05-01 22:18:59 +0000547}
548
Eli Friedmanb85f7072008-05-19 19:16:24 +0000549void InitListChecker::CheckListElementTypes(InitListExpr *IList,
550 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000551 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 unsigned &Index,
553 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000554 unsigned &StructuredIndex,
555 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000556 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000557 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000558 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000559 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000560 } else if (DeclType->isAggregateType()) {
561 if (DeclType->isRecordType()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000562 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000563 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregor4c678342009-01-28 21:54:33 +0000564 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 StructuredList, StructuredIndex,
566 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000567 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000568 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000569 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000570 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000571 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
572 StructuredList, StructuredIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000573 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000574 else
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000576 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
577 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000578 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000579 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000580 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000581 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000582 } else if (DeclType->isRecordType()) {
583 // C++ [dcl.init]p14:
584 // [...] If the class is an aggregate (8.5.1), and the initializer
585 // is a brace-enclosed list, see 8.5.1.
586 //
587 // Note: 8.5.1 is handled below; here, we diagnose the case where
588 // we have an initializer list and a destination type that is not
589 // an aggregate.
590 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000591 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000592 << DeclType << IList->getSourceRange();
593 hadError = true;
594 } else if (DeclType->isReferenceType()) {
595 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000596 } else {
597 // In C, all types are either scalars or aggregates, but
598 // additional handling is needed here for C++ (and possibly others?).
599 assert(0 && "Unsupported initializer type");
600 }
601}
602
Eli Friedmanb85f7072008-05-19 19:16:24 +0000603void InitListChecker::CheckSubElementType(InitListExpr *IList,
604 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000605 unsigned &Index,
606 InitListExpr *StructuredList,
607 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000608 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000609 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
610 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000611 unsigned newStructuredIndex = 0;
612 InitListExpr *newStructuredList
613 = getStructuredSubobjectInit(IList, Index, ElemType,
614 StructuredList, StructuredIndex,
615 SubInitList->getSourceRange());
616 CheckExplicitInitList(SubInitList, ElemType, newIndex,
617 newStructuredList, newStructuredIndex);
618 ++StructuredIndex;
619 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000620 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
621 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000622 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000623 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000624 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000625 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000626 } else if (ElemType->isReferenceType()) {
627 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000628 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000629 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000630 // C++ [dcl.init.aggr]p12:
631 // All implicit type conversions (clause 4) are considered when
632 // initializing the aggregate member with an ini- tializer from
633 // an initializer-list. If the initializer can initialize a
634 // member, the member is initialized. [...]
635 ImplicitConversionSequence ICS
Chris Lattner08202542009-02-24 22:50:46 +0000636 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000637 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner08202542009-02-24 22:50:46 +0000638 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000639 "initializing"))
640 hadError = true;
641 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
642 ++Index;
643 return;
644 }
645
646 // Fall through for subaggregate initialization
647 } else {
648 // C99 6.7.8p13:
649 //
650 // The initializer for a structure or union object that has
651 // automatic storage duration shall be either an initializer
652 // list as described below, or a single expression that has
653 // compatible structure or union type. In the latter case, the
654 // initial value of the object, including unnamed members, is
655 // that of the expression.
Chris Lattner08202542009-02-24 22:50:46 +0000656 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
657 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
658 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000659 ElemTypeCanon.getUnqualifiedType())) {
660 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
661 ++Index;
662 return;
663 }
664
665 // Fall through for subaggregate initialization
666 }
667
668 // C++ [dcl.init.aggr]p12:
669 //
670 // [...] Otherwise, if the member is itself a non-empty
671 // subaggregate, brace elision is assumed and the initializer is
672 // considered for the initialization of the first member of
673 // the subaggregate.
674 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
675 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
676 StructuredIndex);
677 ++StructuredIndex;
678 } else {
679 // We cannot initialize this element, so let
680 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000681 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000682 hadError = true;
683 ++Index;
684 ++StructuredIndex;
685 }
686 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000687}
688
Douglas Gregor930d8b52009-01-30 22:09:00 +0000689void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000690 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 InitListExpr *StructuredList,
692 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000693 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000694 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000695 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000696 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000697 diag::err_many_braces_around_scalar_init)
698 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000699 hadError = true;
700 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000701 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000702 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000703 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000704 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000705 diag::err_designator_for_scalar_init)
706 << DeclType << expr->getSourceRange();
707 hadError = true;
708 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000709 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000710 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000711 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000712
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000713 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000714 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000715 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000716 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000717 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000718 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000719 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000720 if (hadError)
721 ++StructuredIndex;
722 else
723 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000724 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000725 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000726 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000727 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000728 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000729 ++Index;
730 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000731 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000732 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000733}
734
Douglas Gregor930d8b52009-01-30 22:09:00 +0000735void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
736 unsigned &Index,
737 InitListExpr *StructuredList,
738 unsigned &StructuredIndex) {
739 if (Index < IList->getNumInits()) {
740 Expr *expr = IList->getInit(Index);
741 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000742 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000743 << DeclType << IList->getSourceRange();
744 hadError = true;
745 ++Index;
746 ++StructuredIndex;
747 return;
748 }
749
750 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000751 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000752 hadError = true;
753 else if (savExpr != expr) {
754 // The type was promoted, update initializer list.
755 IList->setInit(Index, expr);
756 }
757 if (hadError)
758 ++StructuredIndex;
759 else
760 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
761 ++Index;
762 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000763 // FIXME: It would be wonderful if we could point at the actual member. In
764 // general, it would be useful to pass location information down the stack,
765 // so that we know the location (or decl) of the "current object" being
766 // initialized.
Chris Lattner08202542009-02-24 22:50:46 +0000767 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000768 diag::err_init_reference_member_uninitialized)
769 << DeclType
770 << IList->getSourceRange();
771 hadError = true;
772 ++Index;
773 ++StructuredIndex;
774 return;
775 }
776}
777
Steve Naroff0cca7492008-05-01 22:18:59 +0000778void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000779 unsigned &Index,
780 InitListExpr *StructuredList,
781 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000782 if (Index < IList->getNumInits()) {
783 const VectorType *VT = DeclType->getAsVectorType();
784 int maxElements = VT->getNumElements();
785 QualType elementType = VT->getElementType();
786
787 for (int i = 0; i < maxElements; ++i) {
788 // Don't attempt to go past the end of the init list
789 if (Index >= IList->getNumInits())
790 break;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000791 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000792 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000793 }
794 }
795}
796
797void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000798 llvm::APSInt elementIndex,
799 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000800 unsigned &Index,
801 InitListExpr *StructuredList,
802 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000803 // Check for the special-case of initializing an array with a string.
804 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000805 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
806 SemaRef.Context)) {
807 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000808 // We place the string literal directly into the resulting
809 // initializer list. This is the only place where the structure
810 // of the structured initializer list doesn't match exactly,
811 // because doing so would involve allocating one character
812 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000813 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000814 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000815 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000816 return;
817 }
818 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000819 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000820 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000821 // Check for VLAs; in standard C it would be possible to check this
822 // earlier, but I don't know where clang accepts VLAs (gcc accepts
823 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000824 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000825 diag::err_variable_object_no_init)
826 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000827 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000828 ++Index;
829 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000830 return;
831 }
832
Douglas Gregor05c13a32009-01-22 00:58:24 +0000833 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000834 llvm::APSInt maxElements(elementIndex.getBitWidth(),
835 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000836 bool maxElementsKnown = false;
837 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000838 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000839 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000840 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000841 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000842 maxElementsKnown = true;
843 }
844
Chris Lattner08202542009-02-24 22:50:46 +0000845 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000846 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000847 while (Index < IList->getNumInits()) {
848 Expr *Init = IList->getInit(Index);
849 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000850 // If we're not the subobject that matches up with the '{' for
851 // the designator, we shouldn't be handling the
852 // designator. Return immediately.
853 if (!SubobjectIsDesignatorContext)
854 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000855
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000856 // Handle this designated initializer. elementIndex will be
857 // updated to be the next array element we'll initialize.
Douglas Gregor71199712009-04-15 04:56:10 +0000858 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000859 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000860 StructuredList, StructuredIndex, true,
861 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000862 hadError = true;
863 continue;
864 }
865
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000866 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
867 maxElements.extend(elementIndex.getBitWidth());
868 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
869 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000870 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000871
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000872 // If the array is of incomplete type, keep track of the number of
873 // elements in the initializer.
874 if (!maxElementsKnown && elementIndex > maxElements)
875 maxElements = elementIndex;
876
Douglas Gregor05c13a32009-01-22 00:58:24 +0000877 continue;
878 }
879
880 // If we know the maximum number of elements, and we've already
881 // hit it, stop consuming elements in the initializer list.
882 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000883 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000884
885 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000886 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000887 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000888 ++elementIndex;
889
890 // If the array is of incomplete type, keep track of the number of
891 // elements in the initializer.
892 if (!maxElementsKnown && elementIndex > maxElements)
893 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000894 }
895 if (DeclType->isIncompleteArrayType()) {
896 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000897 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000898 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000899 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000900 // Sizing an array implicitly to zero is not allowed by ISO C,
901 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000902 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000903 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000904 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000905
Chris Lattner08202542009-02-24 22:50:46 +0000906 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000907 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000908 }
909}
910
911void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
912 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000913 RecordDecl::field_iterator Field,
914 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000915 unsigned &Index,
916 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000917 unsigned &StructuredIndex,
918 bool TopLevelObject) {
Eli Friedmanb85f7072008-05-19 19:16:24 +0000919 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000920
Eli Friedmanb85f7072008-05-19 19:16:24 +0000921 // If the record is invalid, some of it's members are invalid. To avoid
922 // confusion, we forgo checking the intializer for the entire record.
923 if (structDecl->isInvalidDecl()) {
924 hadError = true;
925 return;
926 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000927
928 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
929 // Value-initialize the first named member of the union.
930 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000931 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000932 Field != FieldEnd; ++Field) {
933 if (Field->getDeclName()) {
934 StructuredList->setInitializedFieldInUnion(*Field);
935 break;
936 }
937 }
938 return;
939 }
940
Douglas Gregor05c13a32009-01-22 00:58:24 +0000941 // If structDecl is a forward declaration, this loop won't do
942 // anything except look at designated initializers; That's okay,
943 // because an error should get printed out elsewhere. It might be
944 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor44b43212008-12-11 16:49:14 +0000945 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000946 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000947 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000948 while (Index < IList->getNumInits()) {
949 Expr *Init = IList->getInit(Index);
950
951 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000952 // If we're not the subobject that matches up with the '{' for
953 // the designator, we shouldn't be handling the
954 // designator. Return immediately.
955 if (!SubobjectIsDesignatorContext)
956 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000957
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000958 // Handle this designated initializer. Field will be updated to
959 // the next field that we'll be initializing.
Douglas Gregor71199712009-04-15 04:56:10 +0000960 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000961 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000962 StructuredList, StructuredIndex,
963 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000964 hadError = true;
965
Douglas Gregordfb5e592009-02-12 19:00:39 +0000966 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000967 continue;
968 }
969
970 if (Field == FieldEnd) {
971 // We've run out of fields. We're done.
972 break;
973 }
974
Douglas Gregordfb5e592009-02-12 19:00:39 +0000975 // We've already initialized a member of a union. We're done.
976 if (InitializedSomething && DeclType->isUnionType())
977 break;
978
Douglas Gregor44b43212008-12-11 16:49:14 +0000979 // If we've hit the flexible array member at the end, we're done.
980 if (Field->getType()->isIncompleteArrayType())
981 break;
982
Douglas Gregor0bb76892009-01-29 16:53:55 +0000983 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000984 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +0000985 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000986 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +0000987 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000988
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000989 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000990 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +0000991 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +0000992
993 if (DeclType->isUnionType()) {
994 // Initialize the first field within the union.
995 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000996 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000997
998 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +0000999 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001000
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001001 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001002 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001003 return;
1004
1005 // Handle GNU flexible array initializers.
1006 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001007 (!isa<InitListExpr>(IList->getInit(Index)) ||
1008 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner08202542009-02-24 22:50:46 +00001009 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001010 diag::err_flexible_array_init_nonempty)
1011 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001012 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001013 << *Field;
1014 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001015 ++Index;
1016 return;
1017 } else {
1018 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1019 diag::ext_flexible_array_init)
1020 << IList->getInit(Index)->getSourceRange().getBegin();
1021 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1022 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001023 }
1024
Douglas Gregora6457962009-03-20 00:32:56 +00001025 if (isa<InitListExpr>(IList->getInit(Index)))
1026 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1027 StructuredIndex);
1028 else
1029 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1030 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001031}
Steve Naroff0cca7492008-05-01 22:18:59 +00001032
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001033/// \brief Expand a field designator that refers to a member of an
1034/// anonymous struct or union into a series of field designators that
1035/// refers to the field within the appropriate subobject.
1036///
1037/// Field/FieldIndex will be updated to point to the (new)
1038/// currently-designated field.
1039static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1040 DesignatedInitExpr *DIE,
1041 unsigned DesigIdx,
1042 FieldDecl *Field,
1043 RecordDecl::field_iterator &FieldIter,
1044 unsigned &FieldIndex) {
1045 typedef DesignatedInitExpr::Designator Designator;
1046
1047 // Build the path from the current object to the member of the
1048 // anonymous struct/union (backwards).
1049 llvm::SmallVector<FieldDecl *, 4> Path;
1050 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1051
1052 // Build the replacement designators.
1053 llvm::SmallVector<Designator, 4> Replacements;
1054 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1055 FI = Path.rbegin(), FIEnd = Path.rend();
1056 FI != FIEnd; ++FI) {
1057 if (FI + 1 == FIEnd)
1058 Replacements.push_back(Designator((IdentifierInfo *)0,
1059 DIE->getDesignator(DesigIdx)->getDotLoc(),
1060 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1061 else
1062 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1063 SourceLocation()));
1064 Replacements.back().setField(*FI);
1065 }
1066
1067 // Expand the current designator into the set of replacement
1068 // designators, so we have a full subobject path down to where the
1069 // member of the anonymous struct/union is actually stored.
1070 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1071 &Replacements[0] + Replacements.size());
1072
1073 // Update FieldIter/FieldIndex;
1074 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1075 FieldIter = Record->field_begin(SemaRef.Context);
1076 FieldIndex = 0;
1077 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1078 FieldIter != FEnd; ++FieldIter) {
1079 if (FieldIter->isUnnamedBitfield())
1080 continue;
1081
1082 if (*FieldIter == Path.back())
1083 return;
1084
1085 ++FieldIndex;
1086 }
1087
1088 assert(false && "Unable to find anonymous struct/union field");
1089}
1090
Douglas Gregor05c13a32009-01-22 00:58:24 +00001091/// @brief Check the well-formedness of a C99 designated initializer.
1092///
1093/// Determines whether the designated initializer @p DIE, which
1094/// resides at the given @p Index within the initializer list @p
1095/// IList, is well-formed for a current object of type @p DeclType
1096/// (C99 6.7.8). The actual subobject that this designator refers to
1097/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001098/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001099///
1100/// @param IList The initializer list in which this designated
1101/// initializer occurs.
1102///
Douglas Gregor71199712009-04-15 04:56:10 +00001103/// @param DIE The designated initializer expression.
1104///
1105/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001106///
1107/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1108/// into which the designation in @p DIE should refer.
1109///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001110/// @param NextField If non-NULL and the first designator in @p DIE is
1111/// a field, this will be set to the field declaration corresponding
1112/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001113///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001114/// @param NextElementIndex If non-NULL and the first designator in @p
1115/// DIE is an array designator or GNU array-range designator, this
1116/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001117///
1118/// @param Index Index into @p IList where the designated initializer
1119/// @p DIE occurs.
1120///
Douglas Gregor4c678342009-01-28 21:54:33 +00001121/// @param StructuredList The initializer list expression that
1122/// describes all of the subobject initializers in the order they'll
1123/// actually be initialized.
1124///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001125/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001126bool
1127InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1128 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001129 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001130 QualType &CurrentObjectType,
1131 RecordDecl::field_iterator *NextField,
1132 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001133 unsigned &Index,
1134 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001135 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001136 bool FinishSubobjectInit,
1137 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001138 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001139 // Check the actual initialization for the designated object type.
1140 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001141
1142 // Temporarily remove the designator expression from the
1143 // initializer list that the child calls see, so that we don't try
1144 // to re-process the designator.
1145 unsigned OldIndex = Index;
1146 IList->setInit(OldIndex, DIE->getInit());
1147
1148 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001149 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001150
1151 // Restore the designated initializer expression in the syntactic
1152 // form of the initializer list.
1153 if (IList->getInit(OldIndex) != DIE->getInit())
1154 DIE->setInit(IList->getInit(OldIndex));
1155 IList->setInit(OldIndex, DIE);
1156
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001157 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001158 }
1159
Douglas Gregor71199712009-04-15 04:56:10 +00001160 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001161 assert((IsFirstDesignator || StructuredList) &&
1162 "Need a non-designated initializer list to start from");
1163
Douglas Gregor71199712009-04-15 04:56:10 +00001164 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001165 // Determine the structural initializer list that corresponds to the
1166 // current subobject.
1167 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregored8a93d2009-03-01 17:12:46 +00001168 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1169 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001170 SourceRange(D->getStartLocation(),
1171 DIE->getSourceRange().getEnd()));
1172 assert(StructuredList && "Expected a structured initializer list");
1173
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 if (D->isFieldDesignator()) {
1175 // C99 6.7.8p7:
1176 //
1177 // If a designator has the form
1178 //
1179 // . identifier
1180 //
1181 // then the current object (defined below) shall have
1182 // structure or union type and the identifier shall be the
1183 // name of a member of that type.
1184 const RecordType *RT = CurrentObjectType->getAsRecordType();
1185 if (!RT) {
1186 SourceLocation Loc = D->getDotLoc();
1187 if (Loc.isInvalid())
1188 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001189 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1190 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001191 ++Index;
1192 return true;
1193 }
1194
Douglas Gregor4c678342009-01-28 21:54:33 +00001195 // Note: we perform a linear search of the fields here, despite
1196 // the fact that we have a faster lookup method, because we always
1197 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001198 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001199 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001200 unsigned FieldIndex = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001201 RecordDecl::field_iterator
1202 Field = RT->getDecl()->field_begin(SemaRef.Context),
1203 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregor4c678342009-01-28 21:54:33 +00001204 for (; Field != FieldEnd; ++Field) {
1205 if (Field->isUnnamedBitfield())
1206 continue;
1207
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001208 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001209 break;
1210
1211 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001212 }
1213
Douglas Gregor4c678342009-01-28 21:54:33 +00001214 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001215 // There was no normal field in the struct with the designated
1216 // name. Perform another lookup for this name, which may find
1217 // something that we can't designate (e.g., a member function),
1218 // may find nothing, or may find a member of an anonymous
1219 // struct/union.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001220 DeclContext::lookup_result Lookup
1221 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001222 if (Lookup.first == Lookup.second) {
1223 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001224 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001225 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001226 ++Index;
1227 return true;
1228 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1229 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1230 ->isAnonymousStructOrUnion()) {
1231 // Handle an field designator that refers to a member of an
1232 // anonymous struct or union.
1233 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1234 cast<FieldDecl>(*Lookup.first),
1235 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001236 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001237 } else {
1238 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001239 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001240 << FieldName;
Chris Lattner08202542009-02-24 22:50:46 +00001241 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001242 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001243 ++Index;
1244 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001245 }
1246 } else if (!KnownField &&
1247 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001248 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001249 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1250 Field, FieldIndex);
1251 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001252 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001253
1254 // All of the fields of a union are located at the same place in
1255 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001256 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001257 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001258 StructuredList->setInitializedFieldInUnion(*Field);
1259 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001260
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001261 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001262 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001263
Douglas Gregor4c678342009-01-28 21:54:33 +00001264 // Make sure that our non-designated initializer list has space
1265 // for a subobject corresponding to this field.
1266 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001267 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001268
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001269 // This designator names a flexible array member.
1270 if (Field->getType()->isIncompleteArrayType()) {
1271 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001272 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001273 // We can't designate an object within the flexible array
1274 // member (because GCC doesn't allow it).
Douglas Gregor71199712009-04-15 04:56:10 +00001275 DesignatedInitExpr::Designator *NextD
1276 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner08202542009-02-24 22:50:46 +00001277 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001278 diag::err_designator_into_flexible_array_member)
1279 << SourceRange(NextD->getStartLocation(),
1280 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001281 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001282 << *Field;
1283 Invalid = true;
1284 }
1285
1286 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1287 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001288 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001289 diag::err_flexible_array_init_needs_braces)
1290 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001291 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001292 << *Field;
1293 Invalid = true;
1294 }
1295
1296 // Handle GNU flexible array initializers.
1297 if (!Invalid && !TopLevelObject &&
1298 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner08202542009-02-24 22:50:46 +00001299 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001300 diag::err_flexible_array_init_nonempty)
1301 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001302 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001303 << *Field;
1304 Invalid = true;
1305 }
1306
1307 if (Invalid) {
1308 ++Index;
1309 return true;
1310 }
1311
1312 // Initialize the array.
1313 bool prevHadError = hadError;
1314 unsigned newStructuredIndex = FieldIndex;
1315 unsigned OldIndex = Index;
1316 IList->setInit(Index, DIE->getInit());
1317 CheckSubElementType(IList, Field->getType(), Index,
1318 StructuredList, newStructuredIndex);
1319 IList->setInit(OldIndex, DIE);
1320 if (hadError && !prevHadError) {
1321 ++Field;
1322 ++FieldIndex;
1323 if (NextField)
1324 *NextField = Field;
1325 StructuredIndex = FieldIndex;
1326 return true;
1327 }
1328 } else {
1329 // Recurse to check later designated subobjects.
1330 QualType FieldType = (*Field)->getType();
1331 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001332 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1333 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001334 true, false))
1335 return true;
1336 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001337
1338 // Find the position of the next field to be initialized in this
1339 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001340 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001341 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001342
1343 // If this the first designator, our caller will continue checking
1344 // the rest of this struct/class/union subobject.
1345 if (IsFirstDesignator) {
1346 if (NextField)
1347 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001349 return false;
1350 }
1351
Douglas Gregor34e79462009-01-28 23:36:17 +00001352 if (!FinishSubobjectInit)
1353 return false;
1354
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001355 // We've already initialized something in the union; we're done.
1356 if (RT->getDecl()->isUnion())
1357 return hadError;
1358
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001359 // Check the remaining fields within this class/struct/union subobject.
1360 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001361 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1362 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001363 return hadError && !prevHadError;
1364 }
1365
1366 // C99 6.7.8p6:
1367 //
1368 // If a designator has the form
1369 //
1370 // [ constant-expression ]
1371 //
1372 // then the current object (defined below) shall have array
1373 // type and the expression shall be an integer constant
1374 // expression. If the array is of unknown size, any
1375 // nonnegative value is valid.
1376 //
1377 // Additionally, cope with the GNU extension that permits
1378 // designators of the form
1379 //
1380 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001381 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001382 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001383 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001384 << CurrentObjectType;
1385 ++Index;
1386 return true;
1387 }
1388
1389 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001390 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1391 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001392 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001393 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001394 DesignatedEndIndex = DesignatedStartIndex;
1395 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001397
Douglas Gregor34e79462009-01-28 23:36:17 +00001398
Chris Lattner3bf68932009-04-25 21:59:05 +00001399 DesignatedStartIndex =
1400 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1401 DesignatedEndIndex =
1402 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001403 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001404
Chris Lattner3bf68932009-04-25 21:59:05 +00001405 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001406 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001407 }
1408
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001409 if (isa<ConstantArrayType>(AT)) {
1410 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001411 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1412 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1413 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1414 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1415 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001416 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001417 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001418 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001419 << IndexExpr->getSourceRange();
1420 ++Index;
1421 return true;
1422 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001423 } else {
1424 // Make sure the bit-widths and signedness match.
1425 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1426 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001427 else if (DesignatedStartIndex.getBitWidth() <
1428 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001429 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1430 DesignatedStartIndex.setIsUnsigned(true);
1431 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001432 }
1433
Douglas Gregor4c678342009-01-28 21:54:33 +00001434 // Make sure that our non-designated initializer list has space
1435 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001436 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001437 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001438 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001439
Douglas Gregor34e79462009-01-28 23:36:17 +00001440 // Repeatedly perform subobject initializations in the range
1441 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001442
Douglas Gregor34e79462009-01-28 23:36:17 +00001443 // Move to the next designator
1444 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1445 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001446 while (DesignatedStartIndex <= DesignatedEndIndex) {
1447 // Recurse to check later designated subobjects.
1448 QualType ElementType = AT->getElementType();
1449 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001450 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1451 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001452 (DesignatedStartIndex == DesignatedEndIndex),
1453 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001454 return true;
1455
1456 // Move to the next index in the array that we'll be initializing.
1457 ++DesignatedStartIndex;
1458 ElementIndex = DesignatedStartIndex.getZExtValue();
1459 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001460
1461 // If this the first designator, our caller will continue checking
1462 // the rest of this array subobject.
1463 if (IsFirstDesignator) {
1464 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001465 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001466 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001467 return false;
1468 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001469
1470 if (!FinishSubobjectInit)
1471 return false;
1472
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001473 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001474 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001475 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001476 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001477 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001478}
1479
Douglas Gregor4c678342009-01-28 21:54:33 +00001480// Get the structured initializer list for a subobject of type
1481// @p CurrentObjectType.
1482InitListExpr *
1483InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1484 QualType CurrentObjectType,
1485 InitListExpr *StructuredList,
1486 unsigned StructuredIndex,
1487 SourceRange InitRange) {
1488 Expr *ExistingInit = 0;
1489 if (!StructuredList)
1490 ExistingInit = SyntacticToSemantic[IList];
1491 else if (StructuredIndex < StructuredList->getNumInits())
1492 ExistingInit = StructuredList->getInit(StructuredIndex);
1493
1494 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1495 return Result;
1496
1497 if (ExistingInit) {
1498 // We are creating an initializer list that initializes the
1499 // subobjects of the current object, but there was already an
1500 // initialization that completely initialized the current
1501 // subobject, e.g., by a compound literal:
1502 //
1503 // struct X { int a, b; };
1504 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1505 //
1506 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1507 // designated initializer re-initializes the whole
1508 // subobject [0], overwriting previous initializers.
Douglas Gregored8a93d2009-03-01 17:12:46 +00001509 SemaRef.Diag(InitRange.getBegin(),
1510 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001511 << InitRange;
Chris Lattner08202542009-02-24 22:50:46 +00001512 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001513 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001514 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001515 << ExistingInit->getSourceRange();
1516 }
1517
1518 InitListExpr *Result
Douglas Gregored8a93d2009-03-01 17:12:46 +00001519 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1520 InitRange.getEnd());
1521
Douglas Gregor4c678342009-01-28 21:54:33 +00001522 Result->setType(CurrentObjectType);
1523
Douglas Gregorfa219202009-03-20 23:58:33 +00001524 // Pre-allocate storage for the structured initializer list.
1525 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001526 unsigned NumInits = 0;
1527 if (!StructuredList)
1528 NumInits = IList->getNumInits();
1529 else if (Index < IList->getNumInits()) {
1530 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1531 NumInits = SubList->getNumInits();
1532 }
1533
Douglas Gregorfa219202009-03-20 23:58:33 +00001534 if (const ArrayType *AType
1535 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1536 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1537 NumElements = CAType->getSize().getZExtValue();
1538 // Simple heuristic so that we don't allocate a very large
1539 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001540 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001541 NumElements = 0;
1542 }
1543 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1544 NumElements = VType->getNumElements();
1545 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1546 RecordDecl *RDecl = RType->getDecl();
1547 if (RDecl->isUnion())
1548 NumElements = 1;
1549 else
Douglas Gregor6ab35242009-04-09 21:40:53 +00001550 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1551 RDecl->field_end(SemaRef.Context));
Douglas Gregorfa219202009-03-20 23:58:33 +00001552 }
1553
Douglas Gregor08457732009-03-21 18:13:52 +00001554 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001555 NumElements = IList->getNumInits();
1556
1557 Result->reserveInits(NumElements);
1558
Douglas Gregor4c678342009-01-28 21:54:33 +00001559 // Link this new initializer list into the structured initializer
1560 // lists.
1561 if (StructuredList)
1562 StructuredList->updateInit(StructuredIndex, Result);
1563 else {
1564 Result->setSyntacticForm(IList);
1565 SyntacticToSemantic[IList] = Result;
1566 }
1567
1568 return Result;
1569}
1570
1571/// Update the initializer at index @p StructuredIndex within the
1572/// structured initializer list to the value @p expr.
1573void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1574 unsigned &StructuredIndex,
1575 Expr *expr) {
1576 // No structured initializer list to update
1577 if (!StructuredList)
1578 return;
1579
1580 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1581 // This initializer overwrites a previous initializer. Warn.
Chris Lattner08202542009-02-24 22:50:46 +00001582 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001583 diag::warn_initializer_overrides)
1584 << expr->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001585 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001586 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001587 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001588 << PrevInit->getSourceRange();
1589 }
1590
1591 ++StructuredIndex;
1592}
1593
Douglas Gregor05c13a32009-01-22 00:58:24 +00001594/// Check that the given Index expression is a valid array designator
1595/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001596/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001597/// and produces a reasonable diagnostic if there is a
1598/// failure. Returns true if there was an error, false otherwise. If
1599/// everything went okay, Value will receive the value of the constant
1600/// expression.
1601static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001602CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001603 SourceLocation Loc = Index->getSourceRange().getBegin();
1604
1605 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001606 if (S.VerifyIntegerConstantExpression(Index, &Value))
1607 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001608
Chris Lattner3bf68932009-04-25 21:59:05 +00001609 if (Value.isSigned() && Value.isNegative())
1610 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001611 << Value.toString(10) << Index->getSourceRange();
1612
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001613 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001614 return false;
1615}
1616
1617Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1618 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001619 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001620 OwningExprResult Init) {
1621 typedef DesignatedInitExpr::Designator ASTDesignator;
1622
1623 bool Invalid = false;
1624 llvm::SmallVector<ASTDesignator, 32> Designators;
1625 llvm::SmallVector<Expr *, 32> InitExpressions;
1626
1627 // Build designators and check array designator expressions.
1628 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1629 const Designator &D = Desig.getDesignator(Idx);
1630 switch (D.getKind()) {
1631 case Designator::FieldDesignator:
1632 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1633 D.getFieldLoc()));
1634 break;
1635
1636 case Designator::ArrayDesignator: {
1637 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1638 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001639 if (!Index->isTypeDependent() &&
1640 !Index->isValueDependent() &&
1641 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001642 Invalid = true;
1643 else {
1644 Designators.push_back(ASTDesignator(InitExpressions.size(),
1645 D.getLBracketLoc(),
1646 D.getRBracketLoc()));
1647 InitExpressions.push_back(Index);
1648 }
1649 break;
1650 }
1651
1652 case Designator::ArrayRangeDesignator: {
1653 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1654 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1655 llvm::APSInt StartValue;
1656 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001657 bool StartDependent = StartIndex->isTypeDependent() ||
1658 StartIndex->isValueDependent();
1659 bool EndDependent = EndIndex->isTypeDependent() ||
1660 EndIndex->isValueDependent();
1661 if ((!StartDependent &&
1662 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1663 (!EndDependent &&
1664 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001665 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001666 else {
1667 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001668 if (StartDependent || EndDependent) {
1669 // Nothing to compute.
1670 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001671 EndValue.extend(StartValue.getBitWidth());
1672 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1673 StartValue.extend(EndValue.getBitWidth());
1674
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001675 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001676 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1677 << StartValue.toString(10) << EndValue.toString(10)
1678 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1679 Invalid = true;
1680 } else {
1681 Designators.push_back(ASTDesignator(InitExpressions.size(),
1682 D.getLBracketLoc(),
1683 D.getEllipsisLoc(),
1684 D.getRBracketLoc()));
1685 InitExpressions.push_back(StartIndex);
1686 InitExpressions.push_back(EndIndex);
1687 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001688 }
1689 break;
1690 }
1691 }
1692 }
1693
1694 if (Invalid || Init.isInvalid())
1695 return ExprError();
1696
1697 // Clear out the expressions within the designation.
1698 Desig.ClearExprs(*this);
1699
1700 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001701 = DesignatedInitExpr::Create(Context,
1702 Designators.data(), Designators.size(),
1703 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001704 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001705 return Owned(DIE);
1706}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001707
1708bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001709 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001710 if (!CheckInitList.HadError())
1711 InitList = CheckInitList.getFullyStructuredList();
1712
1713 return CheckInitList.HadError();
1714}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001715
1716/// \brief Diagnose any semantic errors with value-initialization of
1717/// the given type.
1718///
1719/// Value-initialization effectively zero-initializes any types
1720/// without user-declared constructors, and calls the default
1721/// constructor for a for any type that has a user-declared
1722/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1723/// a type with a user-declared constructor does not have an
1724/// accessible, non-deleted default constructor. In C, everything can
1725/// be value-initialized, which corresponds to C's notion of
1726/// initializing objects with static storage duration when no
1727/// initializer is provided for that object.
1728///
1729/// \returns true if there was an error, false otherwise.
1730bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1731 // C++ [dcl.init]p5:
1732 //
1733 // To value-initialize an object of type T means:
1734
1735 // -- if T is an array type, then each element is value-initialized;
1736 if (const ArrayType *AT = Context.getAsArrayType(Type))
1737 return CheckValueInitialization(AT->getElementType(), Loc);
1738
1739 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001740 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001741 // -- if T is a class type (clause 9) with a user-declared
1742 // constructor (12.1), then the default constructor for T is
1743 // called (and the initialization is ill-formed if T has no
1744 // accessible default constructor);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001745 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stump390b4cc2009-05-16 07:39:55 +00001746 // FIXME: Eventually, we'll need to put the constructor decl into the
1747 // AST.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001748 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1749 SourceRange(Loc),
1750 DeclarationName(),
1751 IK_Direct);
1752 }
1753 }
1754
1755 if (Type->isReferenceType()) {
1756 // C++ [dcl.init]p5:
1757 // [...] A program that calls for default-initialization or
1758 // value-initialization of an entity of reference type is
1759 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001760 // FIXME: Once we have code that goes through this path, add an actual
1761 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001762 }
1763
1764 return false;
1765}