blob: ce6a99acd9daff3970fc4a436c8a991675f816f9 [file] [log] [blame]
Steve Naroffc4d4a482008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd3a00502009-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 Lattnere76e9bf2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroffc4d4a482008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
Anders Carlsson73bb5e62009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner19ae2fc2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000023#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000024using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000025
Chris Lattnerd3a00502009-02-24 22:27:37 +000026//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
Chris Lattner19ae2fc2009-02-24 23:10:27 +000030static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner7a7c1452009-02-26 23:26:43 +000031 const ArrayType *AT = Context.getAsArrayType(DeclType);
32 if (!AT) return 0;
33
Eli Friedman95acf982009-05-29 18:22:49 +000034 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
35 return 0;
36
Chris Lattner7a7c1452009-02-26 23:26:43 +000037 // See if this is a string literal or @encode.
38 Init = Init->IgnoreParens();
39
40 // Handle @encode, which is a narrow string.
41 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
42 return Init;
43
44 // Otherwise we can only handle string literals.
45 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattnerff065f72009-02-26 23:42:47 +000046 if (SL == 0) return 0;
Eli Friedmand16b0892009-05-31 10:54:53 +000047
48 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner7a7c1452009-02-26 23:26:43 +000049 // char array can be initialized with a narrow string.
50 // Only allow char x[] = "foo"; not char x[] = L"foo";
51 if (!SL->isWide())
Eli Friedmand16b0892009-05-31 10:54:53 +000052 return ElemTy->isCharType() ? Init : 0;
Chris Lattner7a7c1452009-02-26 23:26:43 +000053
Eli Friedmand16b0892009-05-31 10:54:53 +000054 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
55 // correction from DR343): "An array with element type compatible with a
56 // qualified or unqualified version of wchar_t may be initialized by a wide
57 // string literal, optionally enclosed in braces."
58 if (Context.typesAreCompatible(Context.getWCharType(),
59 ElemTy.getUnqualifiedType()))
Chris Lattner7a7c1452009-02-26 23:26:43 +000060 return Init;
61
Chris Lattnerd3a00502009-02-24 22:27:37 +000062 return 0;
63}
64
Chris Lattner160da072009-02-24 22:46:58 +000065static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
66 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000067 // Get the type before calling CheckSingleAssignmentConstraints(), since
68 // it can promote the expression.
69 QualType InitType = Init->getType();
70
Chris Lattner160da072009-02-24 22:46:58 +000071 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000072 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000073 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
74 return S.Diag(Init->getSourceRange().getBegin(),
75 diag::err_typecheck_convert_incompatible)
76 << DeclType << Init->getType() << "initializing"
77 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000078 return false;
79 }
80
Chris Lattner160da072009-02-24 22:46:58 +000081 Sema::AssignConvertType ConvTy =
82 S.CheckSingleAssignmentConstraints(DeclType, Init);
83 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000084 InitType, Init, "initializing");
85}
86
Chris Lattner19ae2fc2009-02-24 23:10:27 +000087static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
88 // Get the length of the string as parsed.
89 uint64_t StrLength =
90 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
91
Chris Lattnerd3a00502009-02-24 22:27:37 +000092
Chris Lattner19ae2fc2009-02-24 23:10:27 +000093 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000094 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
95 // C99 6.7.8p14. We have an array of character type with unknown size
96 // being initialized to a string literal.
97 llvm::APSInt ConstVal(32);
Chris Lattnerd20fac42009-02-24 23:01:39 +000098 ConstVal = StrLength;
Chris Lattnerd3a00502009-02-24 22:27:37 +000099 // Return a new array type (C99 6.7.8p22).
Douglas Gregor1d381132009-07-06 15:59:29 +0000100 DeclT = S.Context.getConstantArrayWithoutExprType(IAT->getElementType(),
101 ConstVal,
102 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000103 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000104 }
Chris Lattnerd20fac42009-02-24 23:01:39 +0000105
Eli Friedman95acf982009-05-29 18:22:49 +0000106 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
107
108 // C99 6.7.8p14. We have an array of character type with known size. However,
109 // the size may be smaller or larger than the string we are initializing.
110 // FIXME: Avoid truncation for 64-bit length strings.
111 if (StrLength-1 > CAT->getSize().getZExtValue())
112 S.Diag(Str->getSourceRange().getBegin(),
113 diag::warn_initializer_string_for_char_array_too_long)
114 << Str->getSourceRange();
115
116 // Set the type to the actual size that we are initializing. If we have
117 // something like:
118 // char x[1] = "foo";
119 // then this will set the string literal's type to char[1].
120 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000121}
122
123bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
124 SourceLocation InitLoc,
Anders Carlsson8cc1f0d2009-05-30 20:41:30 +0000125 DeclarationName InitEntity, bool DirectInit) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000126 if (DeclType->isDependentType() ||
127 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000128 return false;
129
130 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000131 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000132 // (8.3.2), shall be initialized by an object, or function, of
133 // type T or by an object that can be converted into a T.
134 if (DeclType->isReferenceType())
135 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
136
137 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
138 // of unknown size ("[]") or an object type that is not a variable array type.
139 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
140 return Diag(InitLoc, diag::err_variable_object_no_init)
141 << VAT->getSizeExpr()->getSourceRange();
142
143 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
144 if (!InitList) {
145 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000146 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
147 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000148 return false;
149 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000150
151 // C++ [dcl.init]p14:
152 // -- If the destination type is a (possibly cv-qualified) class
153 // type:
154 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
155 QualType DeclTypeC = Context.getCanonicalType(DeclType);
156 QualType InitTypeC = Context.getCanonicalType(Init->getType());
157
158 // -- If the initialization is direct-initialization, or if it is
159 // copy-initialization where the cv-unqualified version of the
160 // source type is the same class as, or a derived class of, the
161 // class of the destination, constructors are considered.
162 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
163 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000164 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000165 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000166
167 // No need to make a CXXConstructExpr if both the ctor and dtor are
168 // trivial.
169 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
170 return false;
171
Chris Lattnerd3a00502009-02-24 22:27:37 +0000172 CXXConstructorDecl *Constructor
173 = PerformInitializationByConstructor(DeclType, &Init, 1,
174 InitLoc, Init->getSourceRange(),
175 InitEntity,
176 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000177 if (!Constructor)
178 return true;
Anders Carlssonbd9f51a2009-08-16 05:13:48 +0000179 Init = BuildCXXConstructExpr(DeclType, Constructor, &Init, 1);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000180 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000181 }
182
183 // -- Otherwise (i.e., for the remaining copy-initialization
184 // cases), user-defined conversion sequences that can
185 // convert from the source type to the destination type or
186 // (when a conversion function is used) to a derived class
187 // thereof are enumerated as described in 13.3.1.4, and the
188 // best one is chosen through overload resolution
189 // (13.3). If the conversion cannot be done or is
190 // ambiguous, the initialization is ill-formed. The
191 // function selected is called with the initializer
192 // expression as its argument; if the function is a
193 // constructor, the call initializes a temporary of the
194 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000195 // FIXME: We're pretending to do copy elision here; return to this when we
196 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000197 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
198 return false;
199
200 if (InitEntity)
201 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000202 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
203 << Init->getType() << Init->getSourceRange();
204 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000205 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
206 << Init->getType() << Init->getSourceRange();
207 }
208
209 // C99 6.7.8p16.
210 if (DeclType->isArrayType())
211 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000212 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000213
Chris Lattner160da072009-02-24 22:46:58 +0000214 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000215 }
216
217 bool hadError = CheckInitList(InitList, DeclType);
218 Init = InitList;
219 return hadError;
220}
221
222//===----------------------------------------------------------------------===//
223// Semantic checking for initializer lists.
224//===----------------------------------------------------------------------===//
225
Douglas Gregoraaa20962009-01-29 01:05:33 +0000226/// @brief Semantic checking for initializer lists.
227///
228/// The InitListChecker class contains a set of routines that each
229/// handle the initialization of a certain kind of entity, e.g.,
230/// arrays, vectors, struct/union types, scalars, etc. The
231/// InitListChecker itself performs a recursive walk of the subobject
232/// structure of the type to be initialized, while stepping through
233/// the initializer list one element at a time. The IList and Index
234/// parameters to each of the Check* routines contain the active
235/// (syntactic) initializer list and the index into that initializer
236/// list that represents the current initializer. Each routine is
237/// responsible for moving that Index forward as it consumes elements.
238///
239/// Each Check* routine also has a StructuredList/StructuredIndex
240/// arguments, which contains the current the "structured" (semantic)
241/// initializer list and the index into that initializer list where we
242/// are copying initializers as we map them over to the semantic
243/// list. Once we have completed our recursive walk of the subobject
244/// structure, we will have constructed a full semantic initializer
245/// list.
246///
247/// C99 designators cause changes in the initializer list traversal,
248/// because they make the initialization "jump" into a specific
249/// subobject and then continue the initialization from that
250/// point. CheckDesignatedInitializer() recursively steps into the
251/// designated subobject and manages backing out the recursion to
252/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000253namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000254class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000255 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000256 bool hadError;
257 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
258 InitListExpr *FullyStructuredList;
259
260 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000261 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000262 unsigned &StructuredIndex,
263 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000264 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000265 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000266 unsigned &StructuredIndex,
267 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000268 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
269 bool SubobjectIsDesignatorContext,
270 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000271 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000272 unsigned &StructuredIndex,
273 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000274 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
275 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000276 InitListExpr *StructuredList,
277 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000278 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000279 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000280 InitListExpr *StructuredList,
281 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000282 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
283 unsigned &Index,
284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000286 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000287 InitListExpr *StructuredList,
288 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000289 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
290 RecordDecl::field_iterator Field,
291 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000292 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000293 unsigned &StructuredIndex,
294 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000295 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
296 llvm::APSInt elementIndex,
297 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
299 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000300 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000301 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000302 QualType &CurrentObjectType,
303 RecordDecl::field_iterator *NextField,
304 llvm::APSInt *NextElementIndex,
305 unsigned &Index,
306 InitListExpr *StructuredList,
307 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000308 bool FinishSubobjectInit,
309 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000310 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
311 QualType CurrentObjectType,
312 InitListExpr *StructuredList,
313 unsigned StructuredIndex,
314 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000315 void UpdateStructuredListElement(InitListExpr *StructuredList,
316 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000317 Expr *expr);
318 int numArrayElements(QualType DeclType);
319 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000320
321 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000322public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000323 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000324 bool HadError() { return hadError; }
325
326 // @brief Retrieves the fully-structured initializer list used for
327 // semantic analysis and code generation.
328 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
329};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000330} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000331
Douglas Gregorf603b472009-01-28 21:54:33 +0000332/// Recursively replaces NULL values within the given initializer list
333/// with expressions that perform value-initialization of the
334/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000335void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000336 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000337 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000338 SourceLocation Loc = ILE->getSourceRange().getBegin();
339 if (ILE->getSyntacticForm())
340 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
341
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000342 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000343 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000344 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000345 Field = RType->getDecl()->field_begin(),
346 FieldEnd = RType->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000347 Field != FieldEnd; ++Field) {
348 if (Field->isUnnamedBitfield())
349 continue;
350
Douglas Gregor538a4c22009-02-02 17:43:21 +0000351 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000352 if (Field->getType()->isReferenceType()) {
353 // C++ [dcl.init.aggr]p9:
354 // If an incomplete or empty initializer-list leaves a
355 // member of reference type uninitialized, the program is
356 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000357 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000358 << Field->getType()
359 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000360 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000361 diag::note_uninit_reference_member);
362 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000363 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000364 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000365 hadError = true;
366 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000367 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000368
Mike Stumpe127ae32009-05-16 07:39:55 +0000369 // FIXME: If value-initialization involves calling a constructor, should
370 // we make that call explicit in the representation (even when it means
371 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000372 if (Init < NumInits && !hadError)
373 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000374 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000375 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000376 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000377 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000378 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000379
380 // Only look at the first initialization of a union.
381 if (RType->getDecl()->isUnion())
382 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000383 }
384
385 return;
386 }
387
388 QualType ElementType;
389
Douglas Gregor538a4c22009-02-02 17:43:21 +0000390 unsigned NumInits = ILE->getNumInits();
391 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000392 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000393 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000394 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
395 NumElements = CAType->getSize().getZExtValue();
396 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000397 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000398 NumElements = VType->getNumElements();
399 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000400 ElementType = ILE->getType();
401
Douglas Gregor538a4c22009-02-02 17:43:21 +0000402 for (unsigned Init = 0; Init != NumElements; ++Init) {
403 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000404 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000405 hadError = true;
406 return;
407 }
408
Mike Stumpe127ae32009-05-16 07:39:55 +0000409 // FIXME: If value-initialization involves calling a constructor, should
410 // we make that call explicit in the representation (even when it means
411 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000412 if (Init < NumInits && !hadError)
413 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000414 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stump90fc78e2009-08-04 21:02:39 +0000415 } else if (InitListExpr *InnerILE
416 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000417 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000418 }
419}
420
Chris Lattner1aa25a72009-01-29 05:10:57 +0000421
Chris Lattner2e2766a2009-02-24 22:50:46 +0000422InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
423 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000424 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000425
Eli Friedman683cedf2008-05-19 19:16:24 +0000426 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000427 unsigned newStructuredIndex = 0;
428 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000429 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000430 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
431 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000432
Douglas Gregord45210d2009-01-30 22:09:00 +0000433 if (!hadError)
434 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000435}
436
437int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000438 // FIXME: use a proper constant
439 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000440 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000441 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000442 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
443 }
444 return maxElements;
445}
446
447int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000448 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000449 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000450 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000451 Field = structDecl->field_begin(),
452 FieldEnd = structDecl->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000453 Field != FieldEnd; ++Field) {
454 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
455 ++InitializableMembers;
456 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000457 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000458 return std::min(InitializableMembers, 1);
459 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000460}
461
462void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000463 QualType T, unsigned &Index,
464 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000465 unsigned &StructuredIndex,
466 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000467 int maxElements = 0;
468
469 if (T->isArrayType())
470 maxElements = numArrayElements(T);
471 else if (T->isStructureType() || T->isUnionType())
472 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000473 else if (T->isVectorType())
474 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000475 else
476 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000477
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000478 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000479 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000480 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000481 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000482 hadError = true;
483 return;
484 }
485
Douglas Gregorf603b472009-01-28 21:54:33 +0000486 // Build a structured initializer list corresponding to this subobject.
487 InitListExpr *StructuredSubobjectInitList
488 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
489 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000490 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
491 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000492 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000493
Douglas Gregorf603b472009-01-28 21:54:33 +0000494 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000495 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000496 CheckListElementTypes(ParentIList, T, false, Index,
497 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000498 StructuredSubobjectInitIndex,
499 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000500 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000501 StructuredSubobjectInitList->setType(T);
502
Douglas Gregorea765e12009-03-01 17:12:46 +0000503 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000504 // range corresponds with the end of the last initializer it used.
505 if (EndIndex < ParentIList->getNumInits()) {
506 SourceLocation EndLoc
507 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
508 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
509 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000510}
511
Steve Naroff56099522008-05-06 00:23:44 +0000512void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000513 unsigned &Index,
514 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000515 unsigned &StructuredIndex,
516 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000517 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000518 SyntacticToSemantic[IList] = StructuredList;
519 StructuredList->setSyntacticForm(IList);
520 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000521 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000522 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000523 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000524 if (hadError)
525 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000526
Eli Friedman46f81662008-05-25 13:22:35 +0000527 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000528 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000529 if (StructuredIndex == 1 &&
530 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000531 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000532 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000533 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000534 hadError = true;
535 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000536 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000537 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000538 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000539 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000540 // Don't complain for incomplete types, since we'll get an error
541 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000542 QualType CurrentObjectType = StructuredList->getType();
543 int initKind =
544 CurrentObjectType->isArrayType()? 0 :
545 CurrentObjectType->isVectorType()? 1 :
546 CurrentObjectType->isScalarType()? 2 :
547 CurrentObjectType->isUnionType()? 3 :
548 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000549
550 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000551 if (SemaRef.getLangOptions().CPlusPlus) {
552 DK = diag::err_excess_initializers;
553 hadError = true;
554 }
Nate Begeman48fd8c92009-07-07 21:53:06 +0000555 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000559
Chris Lattner2e2766a2009-02-24 22:50:46 +0000560 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000561 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000562 }
563 }
Eli Friedman455f7622008-05-19 20:20:43 +0000564
Eli Friedman90bcb892009-05-16 11:45:48 +0000565 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000566 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000567 << IList->getSourceRange()
568 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
569 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000570}
571
Eli Friedman683cedf2008-05-19 19:16:24 +0000572void InitListChecker::CheckListElementTypes(InitListExpr *IList,
573 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000574 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000575 unsigned &Index,
576 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000577 unsigned &StructuredIndex,
578 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000579 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000580 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000581 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000582 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000583 } else if (DeclType->isAggregateType()) {
584 if (DeclType->isRecordType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000585 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000586 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000587 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000588 StructuredList, StructuredIndex,
589 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000590 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000591 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000592 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000593 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000594 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
595 StructuredList, StructuredIndex);
Mike Stump90fc78e2009-08-04 21:02:39 +0000596 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000597 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000598 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
599 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000600 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000601 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000602 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000603 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000604 } else if (DeclType->isRecordType()) {
605 // C++ [dcl.init]p14:
606 // [...] If the class is an aggregate (8.5.1), and the initializer
607 // is a brace-enclosed list, see 8.5.1.
608 //
609 // Note: 8.5.1 is handled below; here, we diagnose the case where
610 // we have an initializer list and a destination type that is not
611 // an aggregate.
612 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000613 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000614 << DeclType << IList->getSourceRange();
615 hadError = true;
616 } else if (DeclType->isReferenceType()) {
617 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000618 } else {
619 // In C, all types are either scalars or aggregates, but
620 // additional handling is needed here for C++ (and possibly others?).
621 assert(0 && "Unsupported initializer type");
622 }
623}
624
Eli Friedman683cedf2008-05-19 19:16:24 +0000625void InitListChecker::CheckSubElementType(InitListExpr *IList,
626 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000627 unsigned &Index,
628 InitListExpr *StructuredList,
629 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000630 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000631 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
632 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000633 unsigned newStructuredIndex = 0;
634 InitListExpr *newStructuredList
635 = getStructuredSubobjectInit(IList, Index, ElemType,
636 StructuredList, StructuredIndex,
637 SubInitList->getSourceRange());
638 CheckExplicitInitList(SubInitList, ElemType, newIndex,
639 newStructuredList, newStructuredIndex);
640 ++StructuredIndex;
641 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000642 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
643 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000644 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000645 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000646 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000647 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000648 } else if (ElemType->isReferenceType()) {
649 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000650 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000651 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000652 // C++ [dcl.init.aggr]p12:
653 // All implicit type conversions (clause 4) are considered when
654 // initializing the aggregate member with an ini- tializer from
655 // an initializer-list. If the initializer can initialize a
656 // member, the member is initialized. [...]
657 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000658 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000659 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000660 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000661 "initializing"))
662 hadError = true;
663 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
664 ++Index;
665 return;
666 }
667
668 // Fall through for subaggregate initialization
669 } else {
670 // C99 6.7.8p13:
671 //
672 // The initializer for a structure or union object that has
673 // automatic storage duration shall be either an initializer
674 // list as described below, or a single expression that has
675 // compatible structure or union type. In the latter case, the
676 // initial value of the object, including unnamed members, is
677 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000678 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000679 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000680 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
681 ++Index;
682 return;
683 }
684
685 // Fall through for subaggregate initialization
686 }
687
688 // C++ [dcl.init.aggr]p12:
689 //
690 // [...] Otherwise, if the member is itself a non-empty
691 // subaggregate, brace elision is assumed and the initializer is
692 // considered for the initialization of the first member of
693 // the subaggregate.
694 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
695 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
696 StructuredIndex);
697 ++StructuredIndex;
698 } else {
699 // We cannot initialize this element, so let
700 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000701 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000702 hadError = true;
703 ++Index;
704 ++StructuredIndex;
705 }
706 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000707}
708
Douglas Gregord45210d2009-01-30 22:09:00 +0000709void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000710 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000711 InitListExpr *StructuredList,
712 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000713 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000714 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000715 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000716 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000717 diag::err_many_braces_around_scalar_init)
718 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000719 hadError = true;
720 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000721 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000722 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000723 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000724 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000725 diag::err_designator_for_scalar_init)
726 << DeclType << expr->getSourceRange();
727 hadError = true;
728 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000729 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000730 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000731 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000732
Eli Friedmand8535af2008-05-19 20:00:43 +0000733 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000734 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000735 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000736 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000737 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000738 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000739 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000740 if (hadError)
741 ++StructuredIndex;
742 else
743 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000744 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000745 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000747 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000748 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000749 ++Index;
750 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000751 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000752 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000753}
754
Douglas Gregord45210d2009-01-30 22:09:00 +0000755void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
756 unsigned &Index,
757 InitListExpr *StructuredList,
758 unsigned &StructuredIndex) {
759 if (Index < IList->getNumInits()) {
760 Expr *expr = IList->getInit(Index);
761 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000762 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000763 << DeclType << IList->getSourceRange();
764 hadError = true;
765 ++Index;
766 ++StructuredIndex;
767 return;
768 }
769
770 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000771 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000772 hadError = true;
773 else if (savExpr != expr) {
774 // The type was promoted, update initializer list.
775 IList->setInit(Index, expr);
776 }
777 if (hadError)
778 ++StructuredIndex;
779 else
780 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
781 ++Index;
782 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000783 // FIXME: It would be wonderful if we could point at the actual member. In
784 // general, it would be useful to pass location information down the stack,
785 // so that we know the location (or decl) of the "current object" being
786 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000787 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000788 diag::err_init_reference_member_uninitialized)
789 << DeclType
790 << IList->getSourceRange();
791 hadError = true;
792 ++Index;
793 ++StructuredIndex;
794 return;
795 }
796}
797
Steve Naroffc4d4a482008-05-01 22:18:59 +0000798void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000799 unsigned &Index,
800 InitListExpr *StructuredList,
801 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000802 if (Index < IList->getNumInits()) {
803 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000804 unsigned maxElements = VT->getNumElements();
805 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000806 QualType elementType = VT->getElementType();
807
Nate Begemane85f43d2009-08-10 23:49:36 +0000808 if (!SemaRef.getLangOptions().OpenCL) {
809 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
810 // Don't attempt to go past the end of the init list
811 if (Index >= IList->getNumInits())
812 break;
813 CheckSubElementType(IList, elementType, Index,
814 StructuredList, StructuredIndex);
815 }
816 } else {
817 // OpenCL initializers allows vectors to be constructed from vectors.
818 for (unsigned i = 0; i < maxElements; ++i) {
819 // Don't attempt to go past the end of the init list
820 if (Index >= IList->getNumInits())
821 break;
822 QualType IType = IList->getInit(Index)->getType();
823 if (!IType->isVectorType()) {
824 CheckSubElementType(IList, elementType, Index,
825 StructuredList, StructuredIndex);
826 ++numEltsInit;
827 } else {
828 const VectorType *IVT = IType->getAsVectorType();
829 unsigned numIElts = IVT->getNumElements();
830 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
831 numIElts);
832 CheckSubElementType(IList, VecType, Index,
833 StructuredList, StructuredIndex);
834 numEltsInit += numIElts;
835 }
836 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000837 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000838
839 // OpenCL & AltiVec require all elements to be initialized.
840 if (numEltsInit != maxElements)
841 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
842 SemaRef.Diag(IList->getSourceRange().getBegin(),
843 diag::err_vector_incorrect_num_initializers)
844 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000845 }
846}
847
848void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000849 llvm::APSInt elementIndex,
850 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000851 unsigned &Index,
852 InitListExpr *StructuredList,
853 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000854 // Check for the special-case of initializing an array with a string.
855 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000856 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
857 SemaRef.Context)) {
858 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000859 // We place the string literal directly into the resulting
860 // initializer list. This is the only place where the structure
861 // of the structured initializer list doesn't match exactly,
862 // because doing so would involve allocating one character
863 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000864 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000865 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000866 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000867 return;
868 }
869 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000870 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000871 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000872 // Check for VLAs; in standard C it would be possible to check this
873 // earlier, but I don't know where clang accepts VLAs (gcc accepts
874 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000875 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000876 diag::err_variable_object_no_init)
877 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000878 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000879 ++Index;
880 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000881 return;
882 }
883
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000884 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000885 llvm::APSInt maxElements(elementIndex.getBitWidth(),
886 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000887 bool maxElementsKnown = false;
888 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000889 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000890 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000891 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000892 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000893 maxElementsKnown = true;
894 }
895
Chris Lattner2e2766a2009-02-24 22:50:46 +0000896 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000897 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000898 while (Index < IList->getNumInits()) {
899 Expr *Init = IList->getInit(Index);
900 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000901 // If we're not the subobject that matches up with the '{' for
902 // the designator, we shouldn't be handling the
903 // designator. Return immediately.
904 if (!SubobjectIsDesignatorContext)
905 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000906
Douglas Gregor710f6d42009-01-22 23:26:18 +0000907 // Handle this designated initializer. elementIndex will be
908 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000909 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000910 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000911 StructuredList, StructuredIndex, true,
912 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000913 hadError = true;
914 continue;
915 }
916
Douglas Gregor5a203a62009-01-23 16:54:12 +0000917 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
918 maxElements.extend(elementIndex.getBitWidth());
919 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
920 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000921 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000922
Douglas Gregor710f6d42009-01-22 23:26:18 +0000923 // If the array is of incomplete type, keep track of the number of
924 // elements in the initializer.
925 if (!maxElementsKnown && elementIndex > maxElements)
926 maxElements = elementIndex;
927
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000928 continue;
929 }
930
931 // If we know the maximum number of elements, and we've already
932 // hit it, stop consuming elements in the initializer list.
933 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000934 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000935
936 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000937 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000938 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000939 ++elementIndex;
940
941 // If the array is of incomplete type, keep track of the number of
942 // elements in the initializer.
943 if (!maxElementsKnown && elementIndex > maxElements)
944 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000945 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000946 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000947 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000948 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000949 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000950 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000951 // Sizing an array implicitly to zero is not allowed by ISO C,
952 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000953 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000954 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000955 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000956
Chris Lattner2e2766a2009-02-24 22:50:46 +0000957 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000958 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000959 }
960}
961
962void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
963 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000964 RecordDecl::field_iterator Field,
965 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000966 unsigned &Index,
967 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000968 unsigned &StructuredIndex,
969 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000970 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000971
Eli Friedman683cedf2008-05-19 19:16:24 +0000972 // If the record is invalid, some of it's members are invalid. To avoid
973 // confusion, we forgo checking the intializer for the entire record.
974 if (structDecl->isInvalidDecl()) {
975 hadError = true;
976 return;
977 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000978
979 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
980 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000981 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000982 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000983 Field != FieldEnd; ++Field) {
984 if (Field->getDeclName()) {
985 StructuredList->setInitializedFieldInUnion(*Field);
986 break;
987 }
988 }
989 return;
990 }
991
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000992 // If structDecl is a forward declaration, this loop won't do
993 // anything except look at designated initializers; That's okay,
994 // because an error should get printed out elsewhere. It might be
995 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000996 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000997 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000998 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000999 while (Index < IList->getNumInits()) {
1000 Expr *Init = IList->getInit(Index);
1001
1002 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001003 // If we're not the subobject that matches up with the '{' for
1004 // the designator, we shouldn't be handling the
1005 // designator. Return immediately.
1006 if (!SubobjectIsDesignatorContext)
1007 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001008
Douglas Gregor710f6d42009-01-22 23:26:18 +00001009 // Handle this designated initializer. Field will be updated to
1010 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001011 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001012 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001013 StructuredList, StructuredIndex,
1014 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001015 hadError = true;
1016
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001017 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001018 continue;
1019 }
1020
1021 if (Field == FieldEnd) {
1022 // We've run out of fields. We're done.
1023 break;
1024 }
1025
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001026 // We've already initialized a member of a union. We're done.
1027 if (InitializedSomething && DeclType->isUnionType())
1028 break;
1029
Douglas Gregor8acb7272008-12-11 16:49:14 +00001030 // If we've hit the flexible array member at the end, we're done.
1031 if (Field->getType()->isIncompleteArrayType())
1032 break;
1033
Douglas Gregor82462762009-01-29 16:53:55 +00001034 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001035 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001036 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001037 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001038 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001039
Douglas Gregor36859eb2009-01-29 00:39:20 +00001040 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001041 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001042 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001043
1044 if (DeclType->isUnionType()) {
1045 // Initialize the first field within the union.
1046 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001047 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001048
1049 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001050 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001051
Douglas Gregorbe69b162009-02-04 22:46:25 +00001052 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001053 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001054 return;
1055
1056 // Handle GNU flexible array initializers.
1057 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001058 (!isa<InitListExpr>(IList->getInit(Index)) ||
1059 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001060 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001061 diag::err_flexible_array_init_nonempty)
1062 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001063 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001064 << *Field;
1065 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001066 ++Index;
1067 return;
1068 } else {
1069 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1070 diag::ext_flexible_array_init)
1071 << IList->getInit(Index)->getSourceRange().getBegin();
1072 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1073 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001074 }
1075
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001076 if (isa<InitListExpr>(IList->getInit(Index)))
1077 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1078 StructuredIndex);
1079 else
1080 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1081 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001082}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001083
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001084/// \brief Expand a field designator that refers to a member of an
1085/// anonymous struct or union into a series of field designators that
1086/// refers to the field within the appropriate subobject.
1087///
1088/// Field/FieldIndex will be updated to point to the (new)
1089/// currently-designated field.
1090static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1091 DesignatedInitExpr *DIE,
1092 unsigned DesigIdx,
1093 FieldDecl *Field,
1094 RecordDecl::field_iterator &FieldIter,
1095 unsigned &FieldIndex) {
1096 typedef DesignatedInitExpr::Designator Designator;
1097
1098 // Build the path from the current object to the member of the
1099 // anonymous struct/union (backwards).
1100 llvm::SmallVector<FieldDecl *, 4> Path;
1101 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1102
1103 // Build the replacement designators.
1104 llvm::SmallVector<Designator, 4> Replacements;
1105 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1106 FI = Path.rbegin(), FIEnd = Path.rend();
1107 FI != FIEnd; ++FI) {
1108 if (FI + 1 == FIEnd)
1109 Replacements.push_back(Designator((IdentifierInfo *)0,
1110 DIE->getDesignator(DesigIdx)->getDotLoc(),
1111 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1112 else
1113 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1114 SourceLocation()));
1115 Replacements.back().setField(*FI);
1116 }
1117
1118 // Expand the current designator into the set of replacement
1119 // designators, so we have a full subobject path down to where the
1120 // member of the anonymous struct/union is actually stored.
1121 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1122 &Replacements[0] + Replacements.size());
1123
1124 // Update FieldIter/FieldIndex;
1125 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001126 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001127 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001128 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001129 FieldIter != FEnd; ++FieldIter) {
1130 if (FieldIter->isUnnamedBitfield())
1131 continue;
1132
1133 if (*FieldIter == Path.back())
1134 return;
1135
1136 ++FieldIndex;
1137 }
1138
1139 assert(false && "Unable to find anonymous struct/union field");
1140}
1141
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001142/// @brief Check the well-formedness of a C99 designated initializer.
1143///
1144/// Determines whether the designated initializer @p DIE, which
1145/// resides at the given @p Index within the initializer list @p
1146/// IList, is well-formed for a current object of type @p DeclType
1147/// (C99 6.7.8). The actual subobject that this designator refers to
1148/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001149/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001150///
1151/// @param IList The initializer list in which this designated
1152/// initializer occurs.
1153///
Douglas Gregoraa357272009-04-15 04:56:10 +00001154/// @param DIE The designated initializer expression.
1155///
1156/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001157///
1158/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1159/// into which the designation in @p DIE should refer.
1160///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001161/// @param NextField If non-NULL and the first designator in @p DIE is
1162/// a field, this will be set to the field declaration corresponding
1163/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001164///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001165/// @param NextElementIndex If non-NULL and the first designator in @p
1166/// DIE is an array designator or GNU array-range designator, this
1167/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001168///
1169/// @param Index Index into @p IList where the designated initializer
1170/// @p DIE occurs.
1171///
Douglas Gregorf603b472009-01-28 21:54:33 +00001172/// @param StructuredList The initializer list expression that
1173/// describes all of the subobject initializers in the order they'll
1174/// actually be initialized.
1175///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001176/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001177bool
1178InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1179 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001180 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001181 QualType &CurrentObjectType,
1182 RecordDecl::field_iterator *NextField,
1183 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001184 unsigned &Index,
1185 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001186 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001187 bool FinishSubobjectInit,
1188 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001189 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001190 // Check the actual initialization for the designated object type.
1191 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001192
1193 // Temporarily remove the designator expression from the
1194 // initializer list that the child calls see, so that we don't try
1195 // to re-process the designator.
1196 unsigned OldIndex = Index;
1197 IList->setInit(OldIndex, DIE->getInit());
1198
1199 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001200 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001201
1202 // Restore the designated initializer expression in the syntactic
1203 // form of the initializer list.
1204 if (IList->getInit(OldIndex) != DIE->getInit())
1205 DIE->setInit(IList->getInit(OldIndex));
1206 IList->setInit(OldIndex, DIE);
1207
Douglas Gregor710f6d42009-01-22 23:26:18 +00001208 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001209 }
1210
Douglas Gregoraa357272009-04-15 04:56:10 +00001211 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001212 assert((IsFirstDesignator || StructuredList) &&
1213 "Need a non-designated initializer list to start from");
1214
Douglas Gregoraa357272009-04-15 04:56:10 +00001215 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001216 // Determine the structural initializer list that corresponds to the
1217 // current subobject.
1218 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001219 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1220 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001221 SourceRange(D->getStartLocation(),
1222 DIE->getSourceRange().getEnd()));
1223 assert(StructuredList && "Expected a structured initializer list");
1224
Douglas Gregor710f6d42009-01-22 23:26:18 +00001225 if (D->isFieldDesignator()) {
1226 // C99 6.7.8p7:
1227 //
1228 // If a designator has the form
1229 //
1230 // . identifier
1231 //
1232 // then the current object (defined below) shall have
1233 // structure or union type and the identifier shall be the
1234 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001235 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001236 if (!RT) {
1237 SourceLocation Loc = D->getDotLoc();
1238 if (Loc.isInvalid())
1239 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001240 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1241 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001242 ++Index;
1243 return true;
1244 }
1245
Douglas Gregorf603b472009-01-28 21:54:33 +00001246 // Note: we perform a linear search of the fields here, despite
1247 // the fact that we have a faster lookup method, because we always
1248 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001249 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001250 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001251 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001252 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001253 Field = RT->getDecl()->field_begin(),
1254 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001255 for (; Field != FieldEnd; ++Field) {
1256 if (Field->isUnnamedBitfield())
1257 continue;
1258
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001259 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001260 break;
1261
1262 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001263 }
1264
Douglas Gregorf603b472009-01-28 21:54:33 +00001265 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001266 // There was no normal field in the struct with the designated
1267 // name. Perform another lookup for this name, which may find
1268 // something that we can't designate (e.g., a member function),
1269 // may find nothing, or may find a member of an anonymous
1270 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001271 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001272 if (Lookup.first == Lookup.second) {
1273 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001274 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001275 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001276 ++Index;
1277 return true;
1278 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1279 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1280 ->isAnonymousStructOrUnion()) {
1281 // Handle an field designator that refers to a member of an
1282 // anonymous struct or union.
1283 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1284 cast<FieldDecl>(*Lookup.first),
1285 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001286 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001287 } else {
1288 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001289 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001290 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001291 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001292 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001293 ++Index;
1294 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001295 }
1296 } else if (!KnownField &&
1297 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001298 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001299 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1300 Field, FieldIndex);
1301 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001302 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001303
1304 // All of the fields of a union are located at the same place in
1305 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001306 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001307 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001308 StructuredList->setInitializedFieldInUnion(*Field);
1309 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001310
Douglas Gregor710f6d42009-01-22 23:26:18 +00001311 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001312 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001313
Douglas Gregorf603b472009-01-28 21:54:33 +00001314 // Make sure that our non-designated initializer list has space
1315 // for a subobject corresponding to this field.
1316 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001317 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001318
Douglas Gregorbe69b162009-02-04 22:46:25 +00001319 // This designator names a flexible array member.
1320 if (Field->getType()->isIncompleteArrayType()) {
1321 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001322 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001323 // We can't designate an object within the flexible array
1324 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001325 DesignatedInitExpr::Designator *NextD
1326 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001327 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001328 diag::err_designator_into_flexible_array_member)
1329 << SourceRange(NextD->getStartLocation(),
1330 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001331 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001332 << *Field;
1333 Invalid = true;
1334 }
1335
1336 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1337 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001338 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001339 diag::err_flexible_array_init_needs_braces)
1340 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001341 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001342 << *Field;
1343 Invalid = true;
1344 }
1345
1346 // Handle GNU flexible array initializers.
1347 if (!Invalid && !TopLevelObject &&
1348 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001349 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001350 diag::err_flexible_array_init_nonempty)
1351 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001352 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001353 << *Field;
1354 Invalid = true;
1355 }
1356
1357 if (Invalid) {
1358 ++Index;
1359 return true;
1360 }
1361
1362 // Initialize the array.
1363 bool prevHadError = hadError;
1364 unsigned newStructuredIndex = FieldIndex;
1365 unsigned OldIndex = Index;
1366 IList->setInit(Index, DIE->getInit());
1367 CheckSubElementType(IList, Field->getType(), Index,
1368 StructuredList, newStructuredIndex);
1369 IList->setInit(OldIndex, DIE);
1370 if (hadError && !prevHadError) {
1371 ++Field;
1372 ++FieldIndex;
1373 if (NextField)
1374 *NextField = Field;
1375 StructuredIndex = FieldIndex;
1376 return true;
1377 }
1378 } else {
1379 // Recurse to check later designated subobjects.
1380 QualType FieldType = (*Field)->getType();
1381 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001382 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1383 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001384 true, false))
1385 return true;
1386 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001387
1388 // Find the position of the next field to be initialized in this
1389 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001390 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001391 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001392
1393 // If this the first designator, our caller will continue checking
1394 // the rest of this struct/class/union subobject.
1395 if (IsFirstDesignator) {
1396 if (NextField)
1397 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001398 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001399 return false;
1400 }
1401
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001402 if (!FinishSubobjectInit)
1403 return false;
1404
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001405 // We've already initialized something in the union; we're done.
1406 if (RT->getDecl()->isUnion())
1407 return hadError;
1408
Douglas Gregor710f6d42009-01-22 23:26:18 +00001409 // Check the remaining fields within this class/struct/union subobject.
1410 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001411 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1412 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001413 return hadError && !prevHadError;
1414 }
1415
1416 // C99 6.7.8p6:
1417 //
1418 // If a designator has the form
1419 //
1420 // [ constant-expression ]
1421 //
1422 // then the current object (defined below) shall have array
1423 // type and the expression shall be an integer constant
1424 // expression. If the array is of unknown size, any
1425 // nonnegative value is valid.
1426 //
1427 // Additionally, cope with the GNU extension that permits
1428 // designators of the form
1429 //
1430 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001431 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001432 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001433 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001434 << CurrentObjectType;
1435 ++Index;
1436 return true;
1437 }
1438
1439 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001440 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1441 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001442 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001443 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001444 DesignatedEndIndex = DesignatedStartIndex;
1445 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001446 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001447
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001448
Chris Lattnereec8ae22009-04-25 21:59:05 +00001449 DesignatedStartIndex =
1450 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1451 DesignatedEndIndex =
1452 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001453 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001454
Chris Lattnereec8ae22009-04-25 21:59:05 +00001455 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001456 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001457 }
1458
Douglas Gregor710f6d42009-01-22 23:26:18 +00001459 if (isa<ConstantArrayType>(AT)) {
1460 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001461 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1462 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1463 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1464 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1465 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001466 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001467 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001468 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001469 << IndexExpr->getSourceRange();
1470 ++Index;
1471 return true;
1472 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001473 } else {
1474 // Make sure the bit-widths and signedness match.
1475 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1476 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001477 else if (DesignatedStartIndex.getBitWidth() <
1478 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001479 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1480 DesignatedStartIndex.setIsUnsigned(true);
1481 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001482 }
1483
Douglas Gregorf603b472009-01-28 21:54:33 +00001484 // Make sure that our non-designated initializer list has space
1485 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001486 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001487 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001488 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001489
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001490 // Repeatedly perform subobject initializations in the range
1491 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001492
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001493 // Move to the next designator
1494 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1495 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001496 while (DesignatedStartIndex <= DesignatedEndIndex) {
1497 // Recurse to check later designated subobjects.
1498 QualType ElementType = AT->getElementType();
1499 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001500 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1501 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001502 (DesignatedStartIndex == DesignatedEndIndex),
1503 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001504 return true;
1505
1506 // Move to the next index in the array that we'll be initializing.
1507 ++DesignatedStartIndex;
1508 ElementIndex = DesignatedStartIndex.getZExtValue();
1509 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001510
1511 // If this the first designator, our caller will continue checking
1512 // the rest of this array subobject.
1513 if (IsFirstDesignator) {
1514 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001515 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001516 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001517 return false;
1518 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001519
1520 if (!FinishSubobjectInit)
1521 return false;
1522
Douglas Gregor710f6d42009-01-22 23:26:18 +00001523 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001524 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001525 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001526 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001527 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001528}
1529
Douglas Gregorf603b472009-01-28 21:54:33 +00001530// Get the structured initializer list for a subobject of type
1531// @p CurrentObjectType.
1532InitListExpr *
1533InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1534 QualType CurrentObjectType,
1535 InitListExpr *StructuredList,
1536 unsigned StructuredIndex,
1537 SourceRange InitRange) {
1538 Expr *ExistingInit = 0;
1539 if (!StructuredList)
1540 ExistingInit = SyntacticToSemantic[IList];
1541 else if (StructuredIndex < StructuredList->getNumInits())
1542 ExistingInit = StructuredList->getInit(StructuredIndex);
1543
1544 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1545 return Result;
1546
1547 if (ExistingInit) {
1548 // We are creating an initializer list that initializes the
1549 // subobjects of the current object, but there was already an
1550 // initialization that completely initialized the current
1551 // subobject, e.g., by a compound literal:
1552 //
1553 // struct X { int a, b; };
1554 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1555 //
1556 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1557 // designated initializer re-initializes the whole
1558 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001559 SemaRef.Diag(InitRange.getBegin(),
1560 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001561 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001562 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001563 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001564 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001565 << ExistingInit->getSourceRange();
1566 }
1567
1568 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001569 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1570 InitRange.getEnd());
1571
Douglas Gregorf603b472009-01-28 21:54:33 +00001572 Result->setType(CurrentObjectType);
1573
Douglas Gregoree0792c2009-03-20 23:58:33 +00001574 // Pre-allocate storage for the structured initializer list.
1575 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001576 unsigned NumInits = 0;
1577 if (!StructuredList)
1578 NumInits = IList->getNumInits();
1579 else if (Index < IList->getNumInits()) {
1580 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1581 NumInits = SubList->getNumInits();
1582 }
1583
Douglas Gregoree0792c2009-03-20 23:58:33 +00001584 if (const ArrayType *AType
1585 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1586 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1587 NumElements = CAType->getSize().getZExtValue();
1588 // Simple heuristic so that we don't allocate a very large
1589 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001590 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001591 NumElements = 0;
1592 }
1593 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1594 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001595 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001596 RecordDecl *RDecl = RType->getDecl();
1597 if (RDecl->isUnion())
1598 NumElements = 1;
1599 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001600 NumElements = std::distance(RDecl->field_begin(),
1601 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001602 }
1603
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001604 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001605 NumElements = IList->getNumInits();
1606
1607 Result->reserveInits(NumElements);
1608
Douglas Gregorf603b472009-01-28 21:54:33 +00001609 // Link this new initializer list into the structured initializer
1610 // lists.
1611 if (StructuredList)
1612 StructuredList->updateInit(StructuredIndex, Result);
1613 else {
1614 Result->setSyntacticForm(IList);
1615 SyntacticToSemantic[IList] = Result;
1616 }
1617
1618 return Result;
1619}
1620
1621/// Update the initializer at index @p StructuredIndex within the
1622/// structured initializer list to the value @p expr.
1623void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1624 unsigned &StructuredIndex,
1625 Expr *expr) {
1626 // No structured initializer list to update
1627 if (!StructuredList)
1628 return;
1629
1630 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1631 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001632 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001633 diag::warn_initializer_overrides)
1634 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001635 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001636 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001637 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001638 << PrevInit->getSourceRange();
1639 }
1640
1641 ++StructuredIndex;
1642}
1643
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001644/// Check that the given Index expression is a valid array designator
1645/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001646/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001647/// and produces a reasonable diagnostic if there is a
1648/// failure. Returns true if there was an error, false otherwise. If
1649/// everything went okay, Value will receive the value of the constant
1650/// expression.
1651static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001652CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001653 SourceLocation Loc = Index->getSourceRange().getBegin();
1654
1655 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001656 if (S.VerifyIntegerConstantExpression(Index, &Value))
1657 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001658
Chris Lattnereec8ae22009-04-25 21:59:05 +00001659 if (Value.isSigned() && Value.isNegative())
1660 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001661 << Value.toString(10) << Index->getSourceRange();
1662
Douglas Gregore498e372009-01-23 21:04:18 +00001663 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001664 return false;
1665}
1666
1667Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1668 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001669 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001670 OwningExprResult Init) {
1671 typedef DesignatedInitExpr::Designator ASTDesignator;
1672
1673 bool Invalid = false;
1674 llvm::SmallVector<ASTDesignator, 32> Designators;
1675 llvm::SmallVector<Expr *, 32> InitExpressions;
1676
1677 // Build designators and check array designator expressions.
1678 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1679 const Designator &D = Desig.getDesignator(Idx);
1680 switch (D.getKind()) {
1681 case Designator::FieldDesignator:
1682 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1683 D.getFieldLoc()));
1684 break;
1685
1686 case Designator::ArrayDesignator: {
1687 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1688 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001689 if (!Index->isTypeDependent() &&
1690 !Index->isValueDependent() &&
1691 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001692 Invalid = true;
1693 else {
1694 Designators.push_back(ASTDesignator(InitExpressions.size(),
1695 D.getLBracketLoc(),
1696 D.getRBracketLoc()));
1697 InitExpressions.push_back(Index);
1698 }
1699 break;
1700 }
1701
1702 case Designator::ArrayRangeDesignator: {
1703 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1704 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1705 llvm::APSInt StartValue;
1706 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001707 bool StartDependent = StartIndex->isTypeDependent() ||
1708 StartIndex->isValueDependent();
1709 bool EndDependent = EndIndex->isTypeDependent() ||
1710 EndIndex->isValueDependent();
1711 if ((!StartDependent &&
1712 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1713 (!EndDependent &&
1714 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001715 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001716 else {
1717 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001718 if (StartDependent || EndDependent) {
1719 // Nothing to compute.
1720 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001721 EndValue.extend(StartValue.getBitWidth());
1722 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1723 StartValue.extend(EndValue.getBitWidth());
1724
Douglas Gregor1401c062009-05-21 23:30:39 +00001725 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001726 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1727 << StartValue.toString(10) << EndValue.toString(10)
1728 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1729 Invalid = true;
1730 } else {
1731 Designators.push_back(ASTDesignator(InitExpressions.size(),
1732 D.getLBracketLoc(),
1733 D.getEllipsisLoc(),
1734 D.getRBracketLoc()));
1735 InitExpressions.push_back(StartIndex);
1736 InitExpressions.push_back(EndIndex);
1737 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001738 }
1739 break;
1740 }
1741 }
1742 }
1743
1744 if (Invalid || Init.isInvalid())
1745 return ExprError();
1746
1747 // Clear out the expressions within the designation.
1748 Desig.ClearExprs(*this);
1749
1750 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001751 = DesignatedInitExpr::Create(Context,
1752 Designators.data(), Designators.size(),
1753 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001754 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001755 return Owned(DIE);
1756}
Douglas Gregor849afc32009-01-29 00:45:39 +00001757
1758bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001759 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001760 if (!CheckInitList.HadError())
1761 InitList = CheckInitList.getFullyStructuredList();
1762
1763 return CheckInitList.HadError();
1764}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001765
1766/// \brief Diagnose any semantic errors with value-initialization of
1767/// the given type.
1768///
1769/// Value-initialization effectively zero-initializes any types
1770/// without user-declared constructors, and calls the default
1771/// constructor for a for any type that has a user-declared
1772/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1773/// a type with a user-declared constructor does not have an
1774/// accessible, non-deleted default constructor. In C, everything can
1775/// be value-initialized, which corresponds to C's notion of
1776/// initializing objects with static storage duration when no
1777/// initializer is provided for that object.
1778///
1779/// \returns true if there was an error, false otherwise.
1780bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1781 // C++ [dcl.init]p5:
1782 //
1783 // To value-initialize an object of type T means:
1784
1785 // -- if T is an array type, then each element is value-initialized;
1786 if (const ArrayType *AT = Context.getAsArrayType(Type))
1787 return CheckValueInitialization(AT->getElementType(), Loc);
1788
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001789 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001790 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001791 // -- if T is a class type (clause 9) with a user-declared
1792 // constructor (12.1), then the default constructor for T is
1793 // called (and the initialization is ill-formed if T has no
1794 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001795 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001796 // FIXME: Eventually, we'll need to put the constructor decl into the
1797 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001798 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1799 SourceRange(Loc),
1800 DeclarationName(),
1801 IK_Direct);
1802 }
1803 }
1804
1805 if (Type->isReferenceType()) {
1806 // C++ [dcl.init]p5:
1807 // [...] A program that calls for default-initialization or
1808 // value-initialization of an entity of reference type is
1809 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001810 // FIXME: Once we have code that goes through this path, add an actual
1811 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001812 }
1813
1814 return false;
1815}