blob: 6b812e1968de2e0af5a2c1ac7b629f8f7b39e9c3 [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).
Chris Lattner45d6fd62009-02-24 22:41:04 +0000100 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
101 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000102 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000103 }
Chris Lattnerd20fac42009-02-24 23:01:39 +0000104
Eli Friedman95acf982009-05-29 18:22:49 +0000105 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
106
107 // C99 6.7.8p14. We have an array of character type with known size. However,
108 // the size may be smaller or larger than the string we are initializing.
109 // FIXME: Avoid truncation for 64-bit length strings.
110 if (StrLength-1 > CAT->getSize().getZExtValue())
111 S.Diag(Str->getSourceRange().getBegin(),
112 diag::warn_initializer_string_for_char_array_too_long)
113 << Str->getSourceRange();
114
115 // Set the type to the actual size that we are initializing. If we have
116 // something like:
117 // char x[1] = "foo";
118 // then this will set the string literal's type to char[1].
119 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000120}
121
122bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
123 SourceLocation InitLoc,
Anders Carlsson8cc1f0d2009-05-30 20:41:30 +0000124 DeclarationName InitEntity, bool DirectInit) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000125 if (DeclType->isDependentType() ||
126 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000127 return false;
128
129 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000130 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000131 // (8.3.2), shall be initialized by an object, or function, of
132 // type T or by an object that can be converted into a T.
133 if (DeclType->isReferenceType())
134 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
135
136 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
137 // of unknown size ("[]") or an object type that is not a variable array type.
138 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
139 return Diag(InitLoc, diag::err_variable_object_no_init)
140 << VAT->getSizeExpr()->getSourceRange();
141
142 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
143 if (!InitList) {
144 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000145 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
146 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000147 return false;
148 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000149
150 // C++ [dcl.init]p14:
151 // -- If the destination type is a (possibly cv-qualified) class
152 // type:
153 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
154 QualType DeclTypeC = Context.getCanonicalType(DeclType);
155 QualType InitTypeC = Context.getCanonicalType(Init->getType());
156
157 // -- If the initialization is direct-initialization, or if it is
158 // copy-initialization where the cv-unqualified version of the
159 // source type is the same class as, or a derived class of, the
160 // class of the destination, constructors are considered.
161 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
162 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000163 const CXXRecordDecl *RD =
164 cast<CXXRecordDecl>(DeclType->getAsRecordType()->getDecl());
165
166 // No need to make a CXXConstructExpr if both the ctor and dtor are
167 // trivial.
168 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
169 return false;
170
Chris Lattnerd3a00502009-02-24 22:27:37 +0000171 CXXConstructorDecl *Constructor
172 = PerformInitializationByConstructor(DeclType, &Init, 1,
173 InitLoc, Init->getSourceRange(),
174 InitEntity,
175 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000176 if (!Constructor)
177 return true;
178
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000179 Init = CXXConstructExpr::Create(Context, DeclType, Constructor, false,
180 &Init, 1);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000181 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000182 }
183
184 // -- Otherwise (i.e., for the remaining copy-initialization
185 // cases), user-defined conversion sequences that can
186 // convert from the source type to the destination type or
187 // (when a conversion function is used) to a derived class
188 // thereof are enumerated as described in 13.3.1.4, and the
189 // best one is chosen through overload resolution
190 // (13.3). If the conversion cannot be done or is
191 // ambiguous, the initialization is ill-formed. The
192 // function selected is called with the initializer
193 // expression as its argument; if the function is a
194 // constructor, the call initializes a temporary of the
195 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000196 // FIXME: We're pretending to do copy elision here; return to this when we
197 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000198 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
199 return false;
200
201 if (InitEntity)
202 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000203 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
204 << Init->getType() << Init->getSourceRange();
205 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000206 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
207 << Init->getType() << Init->getSourceRange();
208 }
209
210 // C99 6.7.8p16.
211 if (DeclType->isArrayType())
212 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000213 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000214
Chris Lattner160da072009-02-24 22:46:58 +0000215 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000216 }
217
218 bool hadError = CheckInitList(InitList, DeclType);
219 Init = InitList;
220 return hadError;
221}
222
223//===----------------------------------------------------------------------===//
224// Semantic checking for initializer lists.
225//===----------------------------------------------------------------------===//
226
Douglas Gregoraaa20962009-01-29 01:05:33 +0000227/// @brief Semantic checking for initializer lists.
228///
229/// The InitListChecker class contains a set of routines that each
230/// handle the initialization of a certain kind of entity, e.g.,
231/// arrays, vectors, struct/union types, scalars, etc. The
232/// InitListChecker itself performs a recursive walk of the subobject
233/// structure of the type to be initialized, while stepping through
234/// the initializer list one element at a time. The IList and Index
235/// parameters to each of the Check* routines contain the active
236/// (syntactic) initializer list and the index into that initializer
237/// list that represents the current initializer. Each routine is
238/// responsible for moving that Index forward as it consumes elements.
239///
240/// Each Check* routine also has a StructuredList/StructuredIndex
241/// arguments, which contains the current the "structured" (semantic)
242/// initializer list and the index into that initializer list where we
243/// are copying initializers as we map them over to the semantic
244/// list. Once we have completed our recursive walk of the subobject
245/// structure, we will have constructed a full semantic initializer
246/// list.
247///
248/// C99 designators cause changes in the initializer list traversal,
249/// because they make the initialization "jump" into a specific
250/// subobject and then continue the initialization from that
251/// point. CheckDesignatedInitializer() recursively steps into the
252/// designated subobject and manages backing out the recursion to
253/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000254namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000255class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000256 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000257 bool hadError;
258 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
259 InitListExpr *FullyStructuredList;
260
261 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000262 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000263 unsigned &StructuredIndex,
264 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000265 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000266 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000267 unsigned &StructuredIndex,
268 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000269 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
270 bool SubobjectIsDesignatorContext,
271 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000272 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000273 unsigned &StructuredIndex,
274 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000275 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
276 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000279 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000280 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000283 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
284 unsigned &Index,
285 InitListExpr *StructuredList,
286 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000287 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000290 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
291 RecordDecl::field_iterator Field,
292 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000293 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000294 unsigned &StructuredIndex,
295 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000296 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
297 llvm::APSInt elementIndex,
298 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000299 InitListExpr *StructuredList,
300 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000301 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000302 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000303 QualType &CurrentObjectType,
304 RecordDecl::field_iterator *NextField,
305 llvm::APSInt *NextElementIndex,
306 unsigned &Index,
307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000309 bool FinishSubobjectInit,
310 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000311 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
312 QualType CurrentObjectType,
313 InitListExpr *StructuredList,
314 unsigned StructuredIndex,
315 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000316 void UpdateStructuredListElement(InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000318 Expr *expr);
319 int numArrayElements(QualType DeclType);
320 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000321
322 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000323public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000324 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000325 bool HadError() { return hadError; }
326
327 // @brief Retrieves the fully-structured initializer list used for
328 // semantic analysis and code generation.
329 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
330};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000331} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000332
Douglas Gregorf603b472009-01-28 21:54:33 +0000333/// Recursively replaces NULL values within the given initializer list
334/// with expressions that perform value-initialization of the
335/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000336void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
342
Douglas Gregorf603b472009-01-28 21:54:33 +0000343 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
344 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000345 for (RecordDecl::field_iterator
346 Field = RType->getDecl()->field_begin(SemaRef.Context),
347 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000348 Field != FieldEnd; ++Field) {
349 if (Field->isUnnamedBitfield())
350 continue;
351
Douglas Gregor538a4c22009-02-02 17:43:21 +0000352 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000353 if (Field->getType()->isReferenceType()) {
354 // C++ [dcl.init.aggr]p9:
355 // If an incomplete or empty initializer-list leaves a
356 // member of reference type uninitialized, the program is
357 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000358 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000359 << Field->getType()
360 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000361 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000362 diag::note_uninit_reference_member);
363 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000364 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000365 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000366 hadError = true;
367 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000368 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000369
Mike Stumpe127ae32009-05-16 07:39:55 +0000370 // FIXME: If value-initialization involves calling a constructor, should
371 // we make that call explicit in the representation (even when it means
372 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000373 if (Init < NumInits && !hadError)
374 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000375 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000376 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000377 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000378 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000379 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000380
381 // Only look at the first initialization of a union.
382 if (RType->getDecl()->isUnion())
383 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000384 }
385
386 return;
387 }
388
389 QualType ElementType;
390
Douglas Gregor538a4c22009-02-02 17:43:21 +0000391 unsigned NumInits = ILE->getNumInits();
392 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000393 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000394 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000395 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
396 NumElements = CAType->getSize().getZExtValue();
397 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000398 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000399 NumElements = VType->getNumElements();
400 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000401 ElementType = ILE->getType();
402
Douglas Gregor538a4c22009-02-02 17:43:21 +0000403 for (unsigned Init = 0; Init != NumElements; ++Init) {
404 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000405 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000406 hadError = true;
407 return;
408 }
409
Mike Stumpe127ae32009-05-16 07:39:55 +0000410 // FIXME: If value-initialization involves calling a constructor, should
411 // we make that call explicit in the representation (even when it means
412 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000413 if (Init < NumInits && !hadError)
414 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000415 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000416 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000417 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000418 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000419 }
420}
421
Chris Lattner1aa25a72009-01-29 05:10:57 +0000422
Chris Lattner2e2766a2009-02-24 22:50:46 +0000423InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
424 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000425 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000426
Eli Friedman683cedf2008-05-19 19:16:24 +0000427 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000428 unsigned newStructuredIndex = 0;
429 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000430 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000431 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
432 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000433
Douglas Gregord45210d2009-01-30 22:09:00 +0000434 if (!hadError)
435 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000436}
437
438int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000439 // FIXME: use a proper constant
440 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000441 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000442 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000443 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
444 }
445 return maxElements;
446}
447
448int InitListChecker::numStructUnionElements(QualType DeclType) {
449 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000450 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000451 for (RecordDecl::field_iterator
452 Field = structDecl->field_begin(SemaRef.Context),
453 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000454 Field != FieldEnd; ++Field) {
455 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
456 ++InitializableMembers;
457 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000458 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000459 return std::min(InitializableMembers, 1);
460 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000461}
462
463void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000464 QualType T, unsigned &Index,
465 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000466 unsigned &StructuredIndex,
467 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000468 int maxElements = 0;
469
470 if (T->isArrayType())
471 maxElements = numArrayElements(T);
472 else if (T->isStructureType() || T->isUnionType())
473 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000474 else if (T->isVectorType())
475 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000476 else
477 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000478
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000479 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000480 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000481 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000482 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000483 hadError = true;
484 return;
485 }
486
Douglas Gregorf603b472009-01-28 21:54:33 +0000487 // Build a structured initializer list corresponding to this subobject.
488 InitListExpr *StructuredSubobjectInitList
489 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
490 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000491 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
492 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000493 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000494
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000496 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000497 CheckListElementTypes(ParentIList, T, false, Index,
498 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000499 StructuredSubobjectInitIndex,
500 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000501 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000502 StructuredSubobjectInitList->setType(T);
503
Douglas Gregorea765e12009-03-01 17:12:46 +0000504 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000505 // range corresponds with the end of the last initializer it used.
506 if (EndIndex < ParentIList->getNumInits()) {
507 SourceLocation EndLoc
508 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
509 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
510 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000511}
512
Steve Naroff56099522008-05-06 00:23:44 +0000513void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000514 unsigned &Index,
515 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000516 unsigned &StructuredIndex,
517 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000518 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000519 SyntacticToSemantic[IList] = StructuredList;
520 StructuredList->setSyntacticForm(IList);
521 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000522 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000523 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000524 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000525 if (hadError)
526 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000527
Eli Friedman46f81662008-05-25 13:22:35 +0000528 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000529 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000530 if (StructuredIndex == 1 &&
531 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000532 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000533 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000534 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000535 hadError = true;
536 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000537 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000538 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000539 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000540 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000541 // Don't complain for incomplete types, since we'll get an error
542 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000543 QualType CurrentObjectType = StructuredList->getType();
544 int initKind =
545 CurrentObjectType->isArrayType()? 0 :
546 CurrentObjectType->isVectorType()? 1 :
547 CurrentObjectType->isScalarType()? 2 :
548 CurrentObjectType->isUnionType()? 3 :
549 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000550
551 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000552 if (SemaRef.getLangOptions().CPlusPlus) {
553 DK = diag::err_excess_initializers;
554 hadError = true;
555 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000556
Chris Lattner2e2766a2009-02-24 22:50:46 +0000557 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000558 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000559 }
560 }
Eli Friedman455f7622008-05-19 20:20:43 +0000561
Eli Friedman90bcb892009-05-16 11:45:48 +0000562 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000563 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000564 << IList->getSourceRange()
565 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
566 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000567}
568
Eli Friedman683cedf2008-05-19 19:16:24 +0000569void InitListChecker::CheckListElementTypes(InitListExpr *IList,
570 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000571 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000572 unsigned &Index,
573 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000574 unsigned &StructuredIndex,
575 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000576 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000577 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000578 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000579 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000580 } else if (DeclType->isAggregateType()) {
581 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000582 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000583 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregorf603b472009-01-28 21:54:33 +0000584 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000585 StructuredList, StructuredIndex,
586 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000587 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000588 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000589 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000590 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000591 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
592 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000593 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000594 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000595 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000596 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
597 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000598 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000599 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000600 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000601 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000602 } else if (DeclType->isRecordType()) {
603 // C++ [dcl.init]p14:
604 // [...] If the class is an aggregate (8.5.1), and the initializer
605 // is a brace-enclosed list, see 8.5.1.
606 //
607 // Note: 8.5.1 is handled below; here, we diagnose the case where
608 // we have an initializer list and a destination type that is not
609 // an aggregate.
610 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000612 << DeclType << IList->getSourceRange();
613 hadError = true;
614 } else if (DeclType->isReferenceType()) {
615 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000616 } else {
617 // In C, all types are either scalars or aggregates, but
618 // additional handling is needed here for C++ (and possibly others?).
619 assert(0 && "Unsupported initializer type");
620 }
621}
622
Eli Friedman683cedf2008-05-19 19:16:24 +0000623void InitListChecker::CheckSubElementType(InitListExpr *IList,
624 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000625 unsigned &Index,
626 InitListExpr *StructuredList,
627 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000628 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000629 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
630 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000631 unsigned newStructuredIndex = 0;
632 InitListExpr *newStructuredList
633 = getStructuredSubobjectInit(IList, Index, ElemType,
634 StructuredList, StructuredIndex,
635 SubInitList->getSourceRange());
636 CheckExplicitInitList(SubInitList, ElemType, newIndex,
637 newStructuredList, newStructuredIndex);
638 ++StructuredIndex;
639 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000640 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
641 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000642 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000643 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000644 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000645 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000646 } else if (ElemType->isReferenceType()) {
647 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000648 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000649 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000650 // C++ [dcl.init.aggr]p12:
651 // All implicit type conversions (clause 4) are considered when
652 // initializing the aggregate member with an ini- tializer from
653 // an initializer-list. If the initializer can initialize a
654 // member, the member is initialized. [...]
655 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000656 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000657 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000658 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000659 "initializing"))
660 hadError = true;
661 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
662 ++Index;
663 return;
664 }
665
666 // Fall through for subaggregate initialization
667 } else {
668 // C99 6.7.8p13:
669 //
670 // The initializer for a structure or union object that has
671 // automatic storage duration shall be either an initializer
672 // list as described below, or a single expression that has
673 // compatible structure or union type. In the latter case, the
674 // initial value of the object, including unnamed members, is
675 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000676 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000677 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000678 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
679 ++Index;
680 return;
681 }
682
683 // Fall through for subaggregate initialization
684 }
685
686 // C++ [dcl.init.aggr]p12:
687 //
688 // [...] Otherwise, if the member is itself a non-empty
689 // subaggregate, brace elision is assumed and the initializer is
690 // considered for the initialization of the first member of
691 // the subaggregate.
692 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
693 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
694 StructuredIndex);
695 ++StructuredIndex;
696 } else {
697 // We cannot initialize this element, so let
698 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000699 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000700 hadError = true;
701 ++Index;
702 ++StructuredIndex;
703 }
704 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000705}
706
Douglas Gregord45210d2009-01-30 22:09:00 +0000707void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000708 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000709 InitListExpr *StructuredList,
710 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000711 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000712 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000713 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000714 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000715 diag::err_many_braces_around_scalar_init)
716 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000717 hadError = true;
718 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000719 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000720 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000721 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000722 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000723 diag::err_designator_for_scalar_init)
724 << DeclType << expr->getSourceRange();
725 hadError = true;
726 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000727 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000728 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000729 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000730
Eli Friedmand8535af2008-05-19 20:00:43 +0000731 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000732 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000733 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000734 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000735 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000736 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000737 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000738 if (hadError)
739 ++StructuredIndex;
740 else
741 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000742 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000743 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000744 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000745 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000746 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000747 ++Index;
748 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000749 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000750 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000751}
752
Douglas Gregord45210d2009-01-30 22:09:00 +0000753void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
754 unsigned &Index,
755 InitListExpr *StructuredList,
756 unsigned &StructuredIndex) {
757 if (Index < IList->getNumInits()) {
758 Expr *expr = IList->getInit(Index);
759 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000760 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000761 << DeclType << IList->getSourceRange();
762 hadError = true;
763 ++Index;
764 ++StructuredIndex;
765 return;
766 }
767
768 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000769 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000770 hadError = true;
771 else if (savExpr != expr) {
772 // The type was promoted, update initializer list.
773 IList->setInit(Index, expr);
774 }
775 if (hadError)
776 ++StructuredIndex;
777 else
778 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
779 ++Index;
780 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000781 // FIXME: It would be wonderful if we could point at the actual member. In
782 // general, it would be useful to pass location information down the stack,
783 // so that we know the location (or decl) of the "current object" being
784 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000785 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000786 diag::err_init_reference_member_uninitialized)
787 << DeclType
788 << IList->getSourceRange();
789 hadError = true;
790 ++Index;
791 ++StructuredIndex;
792 return;
793 }
794}
795
Steve Naroffc4d4a482008-05-01 22:18:59 +0000796void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000797 unsigned &Index,
798 InitListExpr *StructuredList,
799 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000800 if (Index < IList->getNumInits()) {
801 const VectorType *VT = DeclType->getAsVectorType();
802 int maxElements = VT->getNumElements();
803 QualType elementType = VT->getElementType();
804
805 for (int i = 0; i < maxElements; ++i) {
806 // Don't attempt to go past the end of the init list
807 if (Index >= IList->getNumInits())
808 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000809 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000810 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000811 }
812 }
813}
814
815void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000816 llvm::APSInt elementIndex,
817 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000818 unsigned &Index,
819 InitListExpr *StructuredList,
820 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000821 // Check for the special-case of initializing an array with a string.
822 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000823 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
824 SemaRef.Context)) {
825 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000826 // We place the string literal directly into the resulting
827 // initializer list. This is the only place where the structure
828 // of the structured initializer list doesn't match exactly,
829 // because doing so would involve allocating one character
830 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000831 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000832 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000833 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000834 return;
835 }
836 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000837 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000838 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000839 // Check for VLAs; in standard C it would be possible to check this
840 // earlier, but I don't know where clang accepts VLAs (gcc accepts
841 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000842 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000843 diag::err_variable_object_no_init)
844 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000845 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000846 ++Index;
847 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000848 return;
849 }
850
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000851 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000852 llvm::APSInt maxElements(elementIndex.getBitWidth(),
853 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000854 bool maxElementsKnown = false;
855 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000856 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000857 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000858 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000859 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000860 maxElementsKnown = true;
861 }
862
Chris Lattner2e2766a2009-02-24 22:50:46 +0000863 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000864 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000865 while (Index < IList->getNumInits()) {
866 Expr *Init = IList->getInit(Index);
867 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000868 // If we're not the subobject that matches up with the '{' for
869 // the designator, we shouldn't be handling the
870 // designator. Return immediately.
871 if (!SubobjectIsDesignatorContext)
872 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000873
Douglas Gregor710f6d42009-01-22 23:26:18 +0000874 // Handle this designated initializer. elementIndex will be
875 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000876 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000877 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000878 StructuredList, StructuredIndex, true,
879 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000880 hadError = true;
881 continue;
882 }
883
Douglas Gregor5a203a62009-01-23 16:54:12 +0000884 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
885 maxElements.extend(elementIndex.getBitWidth());
886 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
887 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000888 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000889
Douglas Gregor710f6d42009-01-22 23:26:18 +0000890 // If the array is of incomplete type, keep track of the number of
891 // elements in the initializer.
892 if (!maxElementsKnown && elementIndex > maxElements)
893 maxElements = elementIndex;
894
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000895 continue;
896 }
897
898 // If we know the maximum number of elements, and we've already
899 // hit it, stop consuming elements in the initializer list.
900 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000901 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000902
903 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000904 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000905 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000906 ++elementIndex;
907
908 // If the array is of incomplete type, keep track of the number of
909 // elements in the initializer.
910 if (!maxElementsKnown && elementIndex > maxElements)
911 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000912 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000913 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000914 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000915 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000916 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000917 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000918 // Sizing an array implicitly to zero is not allowed by ISO C,
919 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000920 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000921 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000922 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000923
Chris Lattner2e2766a2009-02-24 22:50:46 +0000924 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000925 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000926 }
927}
928
929void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
930 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000931 RecordDecl::field_iterator Field,
932 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000933 unsigned &Index,
934 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000935 unsigned &StructuredIndex,
936 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000937 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000938
Eli Friedman683cedf2008-05-19 19:16:24 +0000939 // If the record is invalid, some of it's members are invalid. To avoid
940 // confusion, we forgo checking the intializer for the entire record.
941 if (structDecl->isInvalidDecl()) {
942 hadError = true;
943 return;
944 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000945
946 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
947 // Value-initialize the first named member of the union.
948 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000949 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000950 Field != FieldEnd; ++Field) {
951 if (Field->getDeclName()) {
952 StructuredList->setInitializedFieldInUnion(*Field);
953 break;
954 }
955 }
956 return;
957 }
958
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000959 // If structDecl is a forward declaration, this loop won't do
960 // anything except look at designated initializers; That's okay,
961 // because an error should get printed out elsewhere. It might be
962 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000963 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000964 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000965 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000966 while (Index < IList->getNumInits()) {
967 Expr *Init = IList->getInit(Index);
968
969 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000970 // If we're not the subobject that matches up with the '{' for
971 // the designator, we shouldn't be handling the
972 // designator. Return immediately.
973 if (!SubobjectIsDesignatorContext)
974 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000975
Douglas Gregor710f6d42009-01-22 23:26:18 +0000976 // Handle this designated initializer. Field will be updated to
977 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +0000978 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000979 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000980 StructuredList, StructuredIndex,
981 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000982 hadError = true;
983
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000984 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000985 continue;
986 }
987
988 if (Field == FieldEnd) {
989 // We've run out of fields. We're done.
990 break;
991 }
992
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000993 // We've already initialized a member of a union. We're done.
994 if (InitializedSomething && DeclType->isUnionType())
995 break;
996
Douglas Gregor8acb7272008-12-11 16:49:14 +0000997 // If we've hit the flexible array member at the end, we're done.
998 if (Field->getType()->isIncompleteArrayType())
999 break;
1000
Douglas Gregor82462762009-01-29 16:53:55 +00001001 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001002 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001003 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001004 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001005 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001006
Douglas Gregor36859eb2009-01-29 00:39:20 +00001007 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001008 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001009 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001010
1011 if (DeclType->isUnionType()) {
1012 // Initialize the first field within the union.
1013 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001014 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001015
1016 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001017 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001018
Douglas Gregorbe69b162009-02-04 22:46:25 +00001019 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001020 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001021 return;
1022
1023 // Handle GNU flexible array initializers.
1024 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001025 (!isa<InitListExpr>(IList->getInit(Index)) ||
1026 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001027 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001028 diag::err_flexible_array_init_nonempty)
1029 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001030 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001031 << *Field;
1032 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001033 ++Index;
1034 return;
1035 } else {
1036 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1037 diag::ext_flexible_array_init)
1038 << IList->getInit(Index)->getSourceRange().getBegin();
1039 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1040 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001041 }
1042
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001043 if (isa<InitListExpr>(IList->getInit(Index)))
1044 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1045 StructuredIndex);
1046 else
1047 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1048 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001049}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001050
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001051/// \brief Expand a field designator that refers to a member of an
1052/// anonymous struct or union into a series of field designators that
1053/// refers to the field within the appropriate subobject.
1054///
1055/// Field/FieldIndex will be updated to point to the (new)
1056/// currently-designated field.
1057static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1058 DesignatedInitExpr *DIE,
1059 unsigned DesigIdx,
1060 FieldDecl *Field,
1061 RecordDecl::field_iterator &FieldIter,
1062 unsigned &FieldIndex) {
1063 typedef DesignatedInitExpr::Designator Designator;
1064
1065 // Build the path from the current object to the member of the
1066 // anonymous struct/union (backwards).
1067 llvm::SmallVector<FieldDecl *, 4> Path;
1068 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1069
1070 // Build the replacement designators.
1071 llvm::SmallVector<Designator, 4> Replacements;
1072 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1073 FI = Path.rbegin(), FIEnd = Path.rend();
1074 FI != FIEnd; ++FI) {
1075 if (FI + 1 == FIEnd)
1076 Replacements.push_back(Designator((IdentifierInfo *)0,
1077 DIE->getDesignator(DesigIdx)->getDotLoc(),
1078 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1079 else
1080 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1081 SourceLocation()));
1082 Replacements.back().setField(*FI);
1083 }
1084
1085 // Expand the current designator into the set of replacement
1086 // designators, so we have a full subobject path down to where the
1087 // member of the anonymous struct/union is actually stored.
1088 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1089 &Replacements[0] + Replacements.size());
1090
1091 // Update FieldIter/FieldIndex;
1092 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1093 FieldIter = Record->field_begin(SemaRef.Context);
1094 FieldIndex = 0;
1095 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1096 FieldIter != FEnd; ++FieldIter) {
1097 if (FieldIter->isUnnamedBitfield())
1098 continue;
1099
1100 if (*FieldIter == Path.back())
1101 return;
1102
1103 ++FieldIndex;
1104 }
1105
1106 assert(false && "Unable to find anonymous struct/union field");
1107}
1108
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001109/// @brief Check the well-formedness of a C99 designated initializer.
1110///
1111/// Determines whether the designated initializer @p DIE, which
1112/// resides at the given @p Index within the initializer list @p
1113/// IList, is well-formed for a current object of type @p DeclType
1114/// (C99 6.7.8). The actual subobject that this designator refers to
1115/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001116/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001117///
1118/// @param IList The initializer list in which this designated
1119/// initializer occurs.
1120///
Douglas Gregoraa357272009-04-15 04:56:10 +00001121/// @param DIE The designated initializer expression.
1122///
1123/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001124///
1125/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1126/// into which the designation in @p DIE should refer.
1127///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001128/// @param NextField If non-NULL and the first designator in @p DIE is
1129/// a field, this will be set to the field declaration corresponding
1130/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001131///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001132/// @param NextElementIndex If non-NULL and the first designator in @p
1133/// DIE is an array designator or GNU array-range designator, this
1134/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001135///
1136/// @param Index Index into @p IList where the designated initializer
1137/// @p DIE occurs.
1138///
Douglas Gregorf603b472009-01-28 21:54:33 +00001139/// @param StructuredList The initializer list expression that
1140/// describes all of the subobject initializers in the order they'll
1141/// actually be initialized.
1142///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001143/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001144bool
1145InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1146 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001147 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001148 QualType &CurrentObjectType,
1149 RecordDecl::field_iterator *NextField,
1150 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001151 unsigned &Index,
1152 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001153 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001154 bool FinishSubobjectInit,
1155 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001156 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001157 // Check the actual initialization for the designated object type.
1158 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001159
1160 // Temporarily remove the designator expression from the
1161 // initializer list that the child calls see, so that we don't try
1162 // to re-process the designator.
1163 unsigned OldIndex = Index;
1164 IList->setInit(OldIndex, DIE->getInit());
1165
1166 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001167 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001168
1169 // Restore the designated initializer expression in the syntactic
1170 // form of the initializer list.
1171 if (IList->getInit(OldIndex) != DIE->getInit())
1172 DIE->setInit(IList->getInit(OldIndex));
1173 IList->setInit(OldIndex, DIE);
1174
Douglas Gregor710f6d42009-01-22 23:26:18 +00001175 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001176 }
1177
Douglas Gregoraa357272009-04-15 04:56:10 +00001178 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001179 assert((IsFirstDesignator || StructuredList) &&
1180 "Need a non-designated initializer list to start from");
1181
Douglas Gregoraa357272009-04-15 04:56:10 +00001182 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001183 // Determine the structural initializer list that corresponds to the
1184 // current subobject.
1185 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001186 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1187 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001188 SourceRange(D->getStartLocation(),
1189 DIE->getSourceRange().getEnd()));
1190 assert(StructuredList && "Expected a structured initializer list");
1191
Douglas Gregor710f6d42009-01-22 23:26:18 +00001192 if (D->isFieldDesignator()) {
1193 // C99 6.7.8p7:
1194 //
1195 // If a designator has the form
1196 //
1197 // . identifier
1198 //
1199 // then the current object (defined below) shall have
1200 // structure or union type and the identifier shall be the
1201 // name of a member of that type.
1202 const RecordType *RT = CurrentObjectType->getAsRecordType();
1203 if (!RT) {
1204 SourceLocation Loc = D->getDotLoc();
1205 if (Loc.isInvalid())
1206 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001207 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1208 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001209 ++Index;
1210 return true;
1211 }
1212
Douglas Gregorf603b472009-01-28 21:54:33 +00001213 // Note: we perform a linear search of the fields here, despite
1214 // the fact that we have a faster lookup method, because we always
1215 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001216 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001217 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001218 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001219 RecordDecl::field_iterator
1220 Field = RT->getDecl()->field_begin(SemaRef.Context),
1221 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +00001222 for (; Field != FieldEnd; ++Field) {
1223 if (Field->isUnnamedBitfield())
1224 continue;
1225
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001226 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001227 break;
1228
1229 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001230 }
1231
Douglas Gregorf603b472009-01-28 21:54:33 +00001232 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001233 // There was no normal field in the struct with the designated
1234 // name. Perform another lookup for this name, which may find
1235 // something that we can't designate (e.g., a member function),
1236 // may find nothing, or may find a member of an anonymous
1237 // struct/union.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001238 DeclContext::lookup_result Lookup
1239 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001240 if (Lookup.first == Lookup.second) {
1241 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001242 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001243 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001244 ++Index;
1245 return true;
1246 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1247 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1248 ->isAnonymousStructOrUnion()) {
1249 // Handle an field designator that refers to a member of an
1250 // anonymous struct or union.
1251 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1252 cast<FieldDecl>(*Lookup.first),
1253 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001254 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001255 } else {
1256 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001257 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001258 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001259 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001260 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001261 ++Index;
1262 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001263 }
1264 } else if (!KnownField &&
1265 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001266 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001267 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1268 Field, FieldIndex);
1269 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001270 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001271
1272 // All of the fields of a union are located at the same place in
1273 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001274 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001275 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001276 StructuredList->setInitializedFieldInUnion(*Field);
1277 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001278
Douglas Gregor710f6d42009-01-22 23:26:18 +00001279 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001280 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001281
Douglas Gregorf603b472009-01-28 21:54:33 +00001282 // Make sure that our non-designated initializer list has space
1283 // for a subobject corresponding to this field.
1284 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001285 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001286
Douglas Gregorbe69b162009-02-04 22:46:25 +00001287 // This designator names a flexible array member.
1288 if (Field->getType()->isIncompleteArrayType()) {
1289 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001290 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001291 // We can't designate an object within the flexible array
1292 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001293 DesignatedInitExpr::Designator *NextD
1294 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001295 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001296 diag::err_designator_into_flexible_array_member)
1297 << SourceRange(NextD->getStartLocation(),
1298 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001299 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001300 << *Field;
1301 Invalid = true;
1302 }
1303
1304 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1305 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001306 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001307 diag::err_flexible_array_init_needs_braces)
1308 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001309 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001310 << *Field;
1311 Invalid = true;
1312 }
1313
1314 // Handle GNU flexible array initializers.
1315 if (!Invalid && !TopLevelObject &&
1316 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001317 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001318 diag::err_flexible_array_init_nonempty)
1319 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001320 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001321 << *Field;
1322 Invalid = true;
1323 }
1324
1325 if (Invalid) {
1326 ++Index;
1327 return true;
1328 }
1329
1330 // Initialize the array.
1331 bool prevHadError = hadError;
1332 unsigned newStructuredIndex = FieldIndex;
1333 unsigned OldIndex = Index;
1334 IList->setInit(Index, DIE->getInit());
1335 CheckSubElementType(IList, Field->getType(), Index,
1336 StructuredList, newStructuredIndex);
1337 IList->setInit(OldIndex, DIE);
1338 if (hadError && !prevHadError) {
1339 ++Field;
1340 ++FieldIndex;
1341 if (NextField)
1342 *NextField = Field;
1343 StructuredIndex = FieldIndex;
1344 return true;
1345 }
1346 } else {
1347 // Recurse to check later designated subobjects.
1348 QualType FieldType = (*Field)->getType();
1349 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001350 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1351 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001352 true, false))
1353 return true;
1354 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001355
1356 // Find the position of the next field to be initialized in this
1357 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001358 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001359 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001360
1361 // If this the first designator, our caller will continue checking
1362 // the rest of this struct/class/union subobject.
1363 if (IsFirstDesignator) {
1364 if (NextField)
1365 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001366 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001367 return false;
1368 }
1369
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001370 if (!FinishSubobjectInit)
1371 return false;
1372
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001373 // We've already initialized something in the union; we're done.
1374 if (RT->getDecl()->isUnion())
1375 return hadError;
1376
Douglas Gregor710f6d42009-01-22 23:26:18 +00001377 // Check the remaining fields within this class/struct/union subobject.
1378 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001379 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1380 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001381 return hadError && !prevHadError;
1382 }
1383
1384 // C99 6.7.8p6:
1385 //
1386 // If a designator has the form
1387 //
1388 // [ constant-expression ]
1389 //
1390 // then the current object (defined below) shall have array
1391 // type and the expression shall be an integer constant
1392 // expression. If the array is of unknown size, any
1393 // nonnegative value is valid.
1394 //
1395 // Additionally, cope with the GNU extension that permits
1396 // designators of the form
1397 //
1398 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001399 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001400 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001401 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001402 << CurrentObjectType;
1403 ++Index;
1404 return true;
1405 }
1406
1407 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001408 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1409 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001410 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001411 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001412 DesignatedEndIndex = DesignatedStartIndex;
1413 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001414 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001415
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001416
Chris Lattnereec8ae22009-04-25 21:59:05 +00001417 DesignatedStartIndex =
1418 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1419 DesignatedEndIndex =
1420 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001421 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001422
Chris Lattnereec8ae22009-04-25 21:59:05 +00001423 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001424 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001425 }
1426
Douglas Gregor710f6d42009-01-22 23:26:18 +00001427 if (isa<ConstantArrayType>(AT)) {
1428 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001429 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1430 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1431 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1432 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1433 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001434 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001435 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001436 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001437 << IndexExpr->getSourceRange();
1438 ++Index;
1439 return true;
1440 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001441 } else {
1442 // Make sure the bit-widths and signedness match.
1443 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1444 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001445 else if (DesignatedStartIndex.getBitWidth() <
1446 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001447 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1448 DesignatedStartIndex.setIsUnsigned(true);
1449 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001450 }
1451
Douglas Gregorf603b472009-01-28 21:54:33 +00001452 // Make sure that our non-designated initializer list has space
1453 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001454 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001455 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001456 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001457
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001458 // Repeatedly perform subobject initializations in the range
1459 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001460
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001461 // Move to the next designator
1462 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1463 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001464 while (DesignatedStartIndex <= DesignatedEndIndex) {
1465 // Recurse to check later designated subobjects.
1466 QualType ElementType = AT->getElementType();
1467 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001468 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1469 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001470 (DesignatedStartIndex == DesignatedEndIndex),
1471 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001472 return true;
1473
1474 // Move to the next index in the array that we'll be initializing.
1475 ++DesignatedStartIndex;
1476 ElementIndex = DesignatedStartIndex.getZExtValue();
1477 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001478
1479 // If this the first designator, our caller will continue checking
1480 // the rest of this array subobject.
1481 if (IsFirstDesignator) {
1482 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001483 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001484 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001485 return false;
1486 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001487
1488 if (!FinishSubobjectInit)
1489 return false;
1490
Douglas Gregor710f6d42009-01-22 23:26:18 +00001491 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001492 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001493 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001494 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001495 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001496}
1497
Douglas Gregorf603b472009-01-28 21:54:33 +00001498// Get the structured initializer list for a subobject of type
1499// @p CurrentObjectType.
1500InitListExpr *
1501InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1502 QualType CurrentObjectType,
1503 InitListExpr *StructuredList,
1504 unsigned StructuredIndex,
1505 SourceRange InitRange) {
1506 Expr *ExistingInit = 0;
1507 if (!StructuredList)
1508 ExistingInit = SyntacticToSemantic[IList];
1509 else if (StructuredIndex < StructuredList->getNumInits())
1510 ExistingInit = StructuredList->getInit(StructuredIndex);
1511
1512 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1513 return Result;
1514
1515 if (ExistingInit) {
1516 // We are creating an initializer list that initializes the
1517 // subobjects of the current object, but there was already an
1518 // initialization that completely initialized the current
1519 // subobject, e.g., by a compound literal:
1520 //
1521 // struct X { int a, b; };
1522 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1523 //
1524 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1525 // designated initializer re-initializes the whole
1526 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001527 SemaRef.Diag(InitRange.getBegin(),
1528 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001529 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001530 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001531 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001532 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001533 << ExistingInit->getSourceRange();
1534 }
1535
1536 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001537 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1538 InitRange.getEnd());
1539
Douglas Gregorf603b472009-01-28 21:54:33 +00001540 Result->setType(CurrentObjectType);
1541
Douglas Gregoree0792c2009-03-20 23:58:33 +00001542 // Pre-allocate storage for the structured initializer list.
1543 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001544 unsigned NumInits = 0;
1545 if (!StructuredList)
1546 NumInits = IList->getNumInits();
1547 else if (Index < IList->getNumInits()) {
1548 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1549 NumInits = SubList->getNumInits();
1550 }
1551
Douglas Gregoree0792c2009-03-20 23:58:33 +00001552 if (const ArrayType *AType
1553 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1554 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1555 NumElements = CAType->getSize().getZExtValue();
1556 // Simple heuristic so that we don't allocate a very large
1557 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001558 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001559 NumElements = 0;
1560 }
1561 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1562 NumElements = VType->getNumElements();
1563 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1564 RecordDecl *RDecl = RType->getDecl();
1565 if (RDecl->isUnion())
1566 NumElements = 1;
1567 else
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001568 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1569 RDecl->field_end(SemaRef.Context));
Douglas Gregoree0792c2009-03-20 23:58:33 +00001570 }
1571
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001572 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001573 NumElements = IList->getNumInits();
1574
1575 Result->reserveInits(NumElements);
1576
Douglas Gregorf603b472009-01-28 21:54:33 +00001577 // Link this new initializer list into the structured initializer
1578 // lists.
1579 if (StructuredList)
1580 StructuredList->updateInit(StructuredIndex, Result);
1581 else {
1582 Result->setSyntacticForm(IList);
1583 SyntacticToSemantic[IList] = Result;
1584 }
1585
1586 return Result;
1587}
1588
1589/// Update the initializer at index @p StructuredIndex within the
1590/// structured initializer list to the value @p expr.
1591void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1592 unsigned &StructuredIndex,
1593 Expr *expr) {
1594 // No structured initializer list to update
1595 if (!StructuredList)
1596 return;
1597
1598 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1599 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001600 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001601 diag::warn_initializer_overrides)
1602 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001603 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001604 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001605 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001606 << PrevInit->getSourceRange();
1607 }
1608
1609 ++StructuredIndex;
1610}
1611
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001612/// Check that the given Index expression is a valid array designator
1613/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001614/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001615/// and produces a reasonable diagnostic if there is a
1616/// failure. Returns true if there was an error, false otherwise. If
1617/// everything went okay, Value will receive the value of the constant
1618/// expression.
1619static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001620CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001621 SourceLocation Loc = Index->getSourceRange().getBegin();
1622
1623 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001624 if (S.VerifyIntegerConstantExpression(Index, &Value))
1625 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001626
Chris Lattnereec8ae22009-04-25 21:59:05 +00001627 if (Value.isSigned() && Value.isNegative())
1628 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001629 << Value.toString(10) << Index->getSourceRange();
1630
Douglas Gregore498e372009-01-23 21:04:18 +00001631 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001632 return false;
1633}
1634
1635Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1636 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001637 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001638 OwningExprResult Init) {
1639 typedef DesignatedInitExpr::Designator ASTDesignator;
1640
1641 bool Invalid = false;
1642 llvm::SmallVector<ASTDesignator, 32> Designators;
1643 llvm::SmallVector<Expr *, 32> InitExpressions;
1644
1645 // Build designators and check array designator expressions.
1646 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1647 const Designator &D = Desig.getDesignator(Idx);
1648 switch (D.getKind()) {
1649 case Designator::FieldDesignator:
1650 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1651 D.getFieldLoc()));
1652 break;
1653
1654 case Designator::ArrayDesignator: {
1655 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1656 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001657 if (!Index->isTypeDependent() &&
1658 !Index->isValueDependent() &&
1659 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001660 Invalid = true;
1661 else {
1662 Designators.push_back(ASTDesignator(InitExpressions.size(),
1663 D.getLBracketLoc(),
1664 D.getRBracketLoc()));
1665 InitExpressions.push_back(Index);
1666 }
1667 break;
1668 }
1669
1670 case Designator::ArrayRangeDesignator: {
1671 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1672 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1673 llvm::APSInt StartValue;
1674 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001675 bool StartDependent = StartIndex->isTypeDependent() ||
1676 StartIndex->isValueDependent();
1677 bool EndDependent = EndIndex->isTypeDependent() ||
1678 EndIndex->isValueDependent();
1679 if ((!StartDependent &&
1680 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1681 (!EndDependent &&
1682 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001683 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001684 else {
1685 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001686 if (StartDependent || EndDependent) {
1687 // Nothing to compute.
1688 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001689 EndValue.extend(StartValue.getBitWidth());
1690 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1691 StartValue.extend(EndValue.getBitWidth());
1692
Douglas Gregor1401c062009-05-21 23:30:39 +00001693 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001694 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1695 << StartValue.toString(10) << EndValue.toString(10)
1696 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1697 Invalid = true;
1698 } else {
1699 Designators.push_back(ASTDesignator(InitExpressions.size(),
1700 D.getLBracketLoc(),
1701 D.getEllipsisLoc(),
1702 D.getRBracketLoc()));
1703 InitExpressions.push_back(StartIndex);
1704 InitExpressions.push_back(EndIndex);
1705 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001706 }
1707 break;
1708 }
1709 }
1710 }
1711
1712 if (Invalid || Init.isInvalid())
1713 return ExprError();
1714
1715 // Clear out the expressions within the designation.
1716 Desig.ClearExprs(*this);
1717
1718 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001719 = DesignatedInitExpr::Create(Context,
1720 Designators.data(), Designators.size(),
1721 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001722 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001723 return Owned(DIE);
1724}
Douglas Gregor849afc32009-01-29 00:45:39 +00001725
1726bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001727 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001728 if (!CheckInitList.HadError())
1729 InitList = CheckInitList.getFullyStructuredList();
1730
1731 return CheckInitList.HadError();
1732}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001733
1734/// \brief Diagnose any semantic errors with value-initialization of
1735/// the given type.
1736///
1737/// Value-initialization effectively zero-initializes any types
1738/// without user-declared constructors, and calls the default
1739/// constructor for a for any type that has a user-declared
1740/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1741/// a type with a user-declared constructor does not have an
1742/// accessible, non-deleted default constructor. In C, everything can
1743/// be value-initialized, which corresponds to C's notion of
1744/// initializing objects with static storage duration when no
1745/// initializer is provided for that object.
1746///
1747/// \returns true if there was an error, false otherwise.
1748bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1749 // C++ [dcl.init]p5:
1750 //
1751 // To value-initialize an object of type T means:
1752
1753 // -- if T is an array type, then each element is value-initialized;
1754 if (const ArrayType *AT = Context.getAsArrayType(Type))
1755 return CheckValueInitialization(AT->getElementType(), Loc);
1756
1757 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001758 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001759 // -- if T is a class type (clause 9) with a user-declared
1760 // constructor (12.1), then the default constructor for T is
1761 // called (and the initialization is ill-formed if T has no
1762 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001763 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001764 // FIXME: Eventually, we'll need to put the constructor decl into the
1765 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001766 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1767 SourceRange(Loc),
1768 DeclarationName(),
1769 IK_Direct);
1770 }
1771 }
1772
1773 if (Type->isReferenceType()) {
1774 // C++ [dcl.init]p5:
1775 // [...] A program that calls for default-initialization or
1776 // value-initialization of an entity of reference type is
1777 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001778 // FIXME: Once we have code that goes through this path, add an actual
1779 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001780 }
1781
1782 return false;
1783}