blob: 6f71e1b3f72e9a875d2ba778eb9671c2f52d6921 [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;
Chris Lattner7a7c1452009-02-26 23:26:43 +000047
48 // char array can be initialized with a narrow string.
49 // Only allow char x[] = "foo"; not char x[] = L"foo";
50 if (!SL->isWide())
51 return AT->getElementType()->isCharType() ? Init : 0;
52
53 // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
54 // "An array with element type compatible with wchar_t may be initialized by a
55 // wide string literal, optionally enclosed in braces."
Chris Lattnerb1fe0472009-02-26 23:36:02 +000056 if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
Chris Lattner7a7c1452009-02-26 23:26:43 +000057 // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo";
58 return Init;
59
Chris Lattnerd3a00502009-02-24 22:27:37 +000060 return 0;
61}
62
Chris Lattner160da072009-02-24 22:46:58 +000063static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
64 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000065 // Get the type before calling CheckSingleAssignmentConstraints(), since
66 // it can promote the expression.
67 QualType InitType = Init->getType();
68
Chris Lattner160da072009-02-24 22:46:58 +000069 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000070 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000071 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
72 return S.Diag(Init->getSourceRange().getBegin(),
73 diag::err_typecheck_convert_incompatible)
74 << DeclType << Init->getType() << "initializing"
75 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000076 return false;
77 }
78
Chris Lattner160da072009-02-24 22:46:58 +000079 Sema::AssignConvertType ConvTy =
80 S.CheckSingleAssignmentConstraints(DeclType, Init);
81 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000082 InitType, Init, "initializing");
83}
84
Chris Lattner19ae2fc2009-02-24 23:10:27 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
86 // Get the length of the string as parsed.
87 uint64_t StrLength =
88 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
89
Chris Lattnerd3a00502009-02-24 22:27:37 +000090
Chris Lattner19ae2fc2009-02-24 23:10:27 +000091 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
93 // C99 6.7.8p14. We have an array of character type with unknown size
94 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattnerd20fac42009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerd3a00502009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
Chris Lattner45d6fd62009-02-24 22:41:04 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
99 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000100 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000101 }
Chris Lattnerd20fac42009-02-24 23:01:39 +0000102
Eli Friedman95acf982009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
104
105 // C99 6.7.8p14. We have an array of character type with known size. However,
106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
108 if (StrLength-1 > CAT->getSize().getZExtValue())
109 S.Diag(Str->getSourceRange().getBegin(),
110 diag::warn_initializer_string_for_char_array_too_long)
111 << Str->getSourceRange();
112
113 // Set the type to the actual size that we are initializing. If we have
114 // something like:
115 // char x[1] = "foo";
116 // then this will set the string literal's type to char[1].
117 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000118}
119
120bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
121 SourceLocation InitLoc,
122 DeclarationName InitEntity,
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000123 bool DirectInit, VarDecl *VD) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000124 if (DeclType->isDependentType() ||
125 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000126 return false;
127
128 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000129 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000130 // (8.3.2), shall be initialized by an object, or function, of
131 // type T or by an object that can be converted into a T.
132 if (DeclType->isReferenceType())
133 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
134
135 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
136 // of unknown size ("[]") or an object type that is not a variable array type.
137 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
138 return Diag(InitLoc, diag::err_variable_object_no_init)
139 << VAT->getSizeExpr()->getSourceRange();
140
141 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
142 if (!InitList) {
143 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000144 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
145 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000146 return false;
147 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000148
149 // C++ [dcl.init]p14:
150 // -- If the destination type is a (possibly cv-qualified) class
151 // type:
152 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
153 QualType DeclTypeC = Context.getCanonicalType(DeclType);
154 QualType InitTypeC = Context.getCanonicalType(Init->getType());
155
156 // -- If the initialization is direct-initialization, or if it is
157 // copy-initialization where the cv-unqualified version of the
158 // source type is the same class as, or a derived class of, the
159 // class of the destination, constructors are considered.
160 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
161 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000162 const CXXRecordDecl *RD =
163 cast<CXXRecordDecl>(DeclType->getAsRecordType()->getDecl());
164
165 // No need to make a CXXConstructExpr if both the ctor and dtor are
166 // trivial.
167 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
168 return false;
169
Chris Lattnerd3a00502009-02-24 22:27:37 +0000170 CXXConstructorDecl *Constructor
171 = PerformInitializationByConstructor(DeclType, &Init, 1,
172 InitLoc, Init->getSourceRange(),
173 InitEntity,
174 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000175 if (!Constructor)
176 return true;
177
178 // FIXME: What do do if VD is null here?
Anders Carlsson6b0e7972009-05-27 16:28:34 +0000179 if (VD)
180 Init = CXXConstructExpr::Create(Context, VD, DeclType, Constructor,
181 false, &Init, 1);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000182 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000183 }
184
185 // -- Otherwise (i.e., for the remaining copy-initialization
186 // cases), user-defined conversion sequences that can
187 // convert from the source type to the destination type or
188 // (when a conversion function is used) to a derived class
189 // thereof are enumerated as described in 13.3.1.4, and the
190 // best one is chosen through overload resolution
191 // (13.3). If the conversion cannot be done or is
192 // ambiguous, the initialization is ill-formed. The
193 // function selected is called with the initializer
194 // expression as its argument; if the function is a
195 // constructor, the call initializes a temporary of the
196 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000197 // FIXME: We're pretending to do copy elision here; return to this when we
198 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000199 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
200 return false;
201
202 if (InitEntity)
203 return Diag(InitLoc, diag::err_cannot_initialize_decl)
204 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
205 << Init->getType() << Init->getSourceRange();
206 else
207 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
208 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
209 << Init->getType() << Init->getSourceRange();
210 }
211
212 // C99 6.7.8p16.
213 if (DeclType->isArrayType())
214 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
215 << Init->getSourceRange();
216
Chris Lattner160da072009-02-24 22:46:58 +0000217 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000218 }
219
220 bool hadError = CheckInitList(InitList, DeclType);
221 Init = InitList;
222 return hadError;
223}
224
225//===----------------------------------------------------------------------===//
226// Semantic checking for initializer lists.
227//===----------------------------------------------------------------------===//
228
Douglas Gregoraaa20962009-01-29 01:05:33 +0000229/// @brief Semantic checking for initializer lists.
230///
231/// The InitListChecker class contains a set of routines that each
232/// handle the initialization of a certain kind of entity, e.g.,
233/// arrays, vectors, struct/union types, scalars, etc. The
234/// InitListChecker itself performs a recursive walk of the subobject
235/// structure of the type to be initialized, while stepping through
236/// the initializer list one element at a time. The IList and Index
237/// parameters to each of the Check* routines contain the active
238/// (syntactic) initializer list and the index into that initializer
239/// list that represents the current initializer. Each routine is
240/// responsible for moving that Index forward as it consumes elements.
241///
242/// Each Check* routine also has a StructuredList/StructuredIndex
243/// arguments, which contains the current the "structured" (semantic)
244/// initializer list and the index into that initializer list where we
245/// are copying initializers as we map them over to the semantic
246/// list. Once we have completed our recursive walk of the subobject
247/// structure, we will have constructed a full semantic initializer
248/// list.
249///
250/// C99 designators cause changes in the initializer list traversal,
251/// because they make the initialization "jump" into a specific
252/// subobject and then continue the initialization from that
253/// point. CheckDesignatedInitializer() recursively steps into the
254/// designated subobject and manages backing out the recursion to
255/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000256namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000257class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000258 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000259 bool hadError;
260 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
261 InitListExpr *FullyStructuredList;
262
263 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000264 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000265 unsigned &StructuredIndex,
266 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000267 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000268 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000269 unsigned &StructuredIndex,
270 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000271 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
272 bool SubobjectIsDesignatorContext,
273 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000274 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000275 unsigned &StructuredIndex,
276 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000277 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
278 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000281 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000282 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000283 InitListExpr *StructuredList,
284 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000285 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
286 unsigned &Index,
287 InitListExpr *StructuredList,
288 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000289 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000290 InitListExpr *StructuredList,
291 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000292 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
293 RecordDecl::field_iterator Field,
294 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000295 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000296 unsigned &StructuredIndex,
297 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000298 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
299 llvm::APSInt elementIndex,
300 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000303 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000304 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000305 QualType &CurrentObjectType,
306 RecordDecl::field_iterator *NextField,
307 llvm::APSInt *NextElementIndex,
308 unsigned &Index,
309 InitListExpr *StructuredList,
310 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000311 bool FinishSubobjectInit,
312 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000313 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
314 QualType CurrentObjectType,
315 InitListExpr *StructuredList,
316 unsigned StructuredIndex,
317 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000318 void UpdateStructuredListElement(InitListExpr *StructuredList,
319 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000320 Expr *expr);
321 int numArrayElements(QualType DeclType);
322 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000323
324 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000325public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000326 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000327 bool HadError() { return hadError; }
328
329 // @brief Retrieves the fully-structured initializer list used for
330 // semantic analysis and code generation.
331 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
332};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000333} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000334
Douglas Gregorf603b472009-01-28 21:54:33 +0000335/// Recursively replaces NULL values within the given initializer list
336/// with expressions that perform value-initialization of the
337/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000338void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000339 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000340 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000341 SourceLocation Loc = ILE->getSourceRange().getBegin();
342 if (ILE->getSyntacticForm())
343 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
344
Douglas Gregorf603b472009-01-28 21:54:33 +0000345 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
346 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000347 for (RecordDecl::field_iterator
348 Field = RType->getDecl()->field_begin(SemaRef.Context),
349 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000350 Field != FieldEnd; ++Field) {
351 if (Field->isUnnamedBitfield())
352 continue;
353
Douglas Gregor538a4c22009-02-02 17:43:21 +0000354 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000355 if (Field->getType()->isReferenceType()) {
356 // C++ [dcl.init.aggr]p9:
357 // If an incomplete or empty initializer-list leaves a
358 // member of reference type uninitialized, the program is
359 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000360 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000361 << Field->getType()
362 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000363 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000364 diag::note_uninit_reference_member);
365 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000366 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000367 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000368 hadError = true;
369 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000370 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000371
Mike Stumpe127ae32009-05-16 07:39:55 +0000372 // FIXME: If value-initialization involves calling a constructor, should
373 // we make that call explicit in the representation (even when it means
374 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000375 if (Init < NumInits && !hadError)
376 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000377 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000378 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000379 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000380 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000381 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000382
383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000386 }
387
388 return;
389 }
390
391 QualType ElementType;
392
Douglas Gregor538a4c22009-02-02 17:43:21 +0000393 unsigned NumInits = ILE->getNumInits();
394 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000395 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000396 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000397 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
398 NumElements = CAType->getSize().getZExtValue();
399 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000400 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000401 NumElements = VType->getNumElements();
402 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000403 ElementType = ILE->getType();
404
Douglas Gregor538a4c22009-02-02 17:43:21 +0000405 for (unsigned Init = 0; Init != NumElements; ++Init) {
406 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000407 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000408 hadError = true;
409 return;
410 }
411
Mike Stumpe127ae32009-05-16 07:39:55 +0000412 // FIXME: If value-initialization involves calling a constructor, should
413 // we make that call explicit in the representation (even when it means
414 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000415 if (Init < NumInits && !hadError)
416 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000417 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000418 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000419 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000420 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000421 }
422}
423
Chris Lattner1aa25a72009-01-29 05:10:57 +0000424
Chris Lattner2e2766a2009-02-24 22:50:46 +0000425InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
426 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000427 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000428
Eli Friedman683cedf2008-05-19 19:16:24 +0000429 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000430 unsigned newStructuredIndex = 0;
431 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000432 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000433 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
434 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000435
Douglas Gregord45210d2009-01-30 22:09:00 +0000436 if (!hadError)
437 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000438}
439
440int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000441 // FIXME: use a proper constant
442 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000443 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000444 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000445 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
446 }
447 return maxElements;
448}
449
450int InitListChecker::numStructUnionElements(QualType DeclType) {
451 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000452 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000453 for (RecordDecl::field_iterator
454 Field = structDecl->field_begin(SemaRef.Context),
455 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000456 Field != FieldEnd; ++Field) {
457 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
458 ++InitializableMembers;
459 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000460 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000461 return std::min(InitializableMembers, 1);
462 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000463}
464
465void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000466 QualType T, unsigned &Index,
467 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000468 unsigned &StructuredIndex,
469 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000470 int maxElements = 0;
471
472 if (T->isArrayType())
473 maxElements = numArrayElements(T);
474 else if (T->isStructureType() || T->isUnionType())
475 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000476 else if (T->isVectorType())
477 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000478 else
479 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000480
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000481 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000482 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000483 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000484 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000485 hadError = true;
486 return;
487 }
488
Douglas Gregorf603b472009-01-28 21:54:33 +0000489 // Build a structured initializer list corresponding to this subobject.
490 InitListExpr *StructuredSubobjectInitList
491 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
492 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000493 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
494 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000496
Douglas Gregorf603b472009-01-28 21:54:33 +0000497 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000498 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000499 CheckListElementTypes(ParentIList, T, false, Index,
500 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000501 StructuredSubobjectInitIndex,
502 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000503 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000504 StructuredSubobjectInitList->setType(T);
505
Douglas Gregorea765e12009-03-01 17:12:46 +0000506 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000507 // range corresponds with the end of the last initializer it used.
508 if (EndIndex < ParentIList->getNumInits()) {
509 SourceLocation EndLoc
510 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
511 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
512 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000513}
514
Steve Naroff56099522008-05-06 00:23:44 +0000515void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000516 unsigned &Index,
517 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000518 unsigned &StructuredIndex,
519 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000520 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000521 SyntacticToSemantic[IList] = StructuredList;
522 StructuredList->setSyntacticForm(IList);
523 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000524 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000525 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000526 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000527 if (hadError)
528 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000529
Eli Friedman46f81662008-05-25 13:22:35 +0000530 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000531 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000532 if (StructuredIndex == 1 &&
533 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000534 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000535 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000536 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000537 hadError = true;
538 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000539 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000540 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000541 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000542 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000543 // Don't complain for incomplete types, since we'll get an error
544 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000545 QualType CurrentObjectType = StructuredList->getType();
546 int initKind =
547 CurrentObjectType->isArrayType()? 0 :
548 CurrentObjectType->isVectorType()? 1 :
549 CurrentObjectType->isScalarType()? 2 :
550 CurrentObjectType->isUnionType()? 3 :
551 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000552
553 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000554 if (SemaRef.getLangOptions().CPlusPlus) {
555 DK = diag::err_excess_initializers;
556 hadError = true;
557 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000558
Chris Lattner2e2766a2009-02-24 22:50:46 +0000559 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000560 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000561 }
562 }
Eli Friedman455f7622008-05-19 20:20:43 +0000563
Eli Friedman90bcb892009-05-16 11:45:48 +0000564 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000565 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000566 << IList->getSourceRange()
567 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
568 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000569}
570
Eli Friedman683cedf2008-05-19 19:16:24 +0000571void InitListChecker::CheckListElementTypes(InitListExpr *IList,
572 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000573 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000574 unsigned &Index,
575 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000576 unsigned &StructuredIndex,
577 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000578 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000579 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000580 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000581 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000582 } else if (DeclType->isAggregateType()) {
583 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000584 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000585 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregorf603b472009-01-28 21:54:33 +0000586 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000587 StructuredList, StructuredIndex,
588 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000589 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000590 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000591 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000592 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000593 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
594 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000595 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000596 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000597 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000598 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
599 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000600 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000601 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000602 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000603 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000604 } else if (DeclType->isRecordType()) {
605 // C++ [dcl.init]p14:
606 // [...] If the class is an aggregate (8.5.1), and the initializer
607 // is a brace-enclosed list, see 8.5.1.
608 //
609 // Note: 8.5.1 is handled below; here, we diagnose the case where
610 // we have an initializer list and a destination type that is not
611 // an aggregate.
612 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000613 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000614 << DeclType << IList->getSourceRange();
615 hadError = true;
616 } else if (DeclType->isReferenceType()) {
617 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000618 } else {
619 // In C, all types are either scalars or aggregates, but
620 // additional handling is needed here for C++ (and possibly others?).
621 assert(0 && "Unsupported initializer type");
622 }
623}
624
Eli Friedman683cedf2008-05-19 19:16:24 +0000625void InitListChecker::CheckSubElementType(InitListExpr *IList,
626 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000627 unsigned &Index,
628 InitListExpr *StructuredList,
629 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000630 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000631 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
632 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000633 unsigned newStructuredIndex = 0;
634 InitListExpr *newStructuredList
635 = getStructuredSubobjectInit(IList, Index, ElemType,
636 StructuredList, StructuredIndex,
637 SubInitList->getSourceRange());
638 CheckExplicitInitList(SubInitList, ElemType, newIndex,
639 newStructuredList, newStructuredIndex);
640 ++StructuredIndex;
641 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000642 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
643 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000644 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000645 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000646 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000647 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000648 } else if (ElemType->isReferenceType()) {
649 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000650 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000651 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000652 // C++ [dcl.init.aggr]p12:
653 // All implicit type conversions (clause 4) are considered when
654 // initializing the aggregate member with an ini- tializer from
655 // an initializer-list. If the initializer can initialize a
656 // member, the member is initialized. [...]
657 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000658 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000659 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000660 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000661 "initializing"))
662 hadError = true;
663 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
664 ++Index;
665 return;
666 }
667
668 // Fall through for subaggregate initialization
669 } else {
670 // C99 6.7.8p13:
671 //
672 // The initializer for a structure or union object that has
673 // automatic storage duration shall be either an initializer
674 // list as described below, or a single expression that has
675 // compatible structure or union type. In the latter case, the
676 // initial value of the object, including unnamed members, is
677 // that of the expression.
Eli Friedman95acf982009-05-29 18:22:49 +0000678 if (ElemType->isRecordType() &&
679 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000680 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
681 ++Index;
682 return;
683 }
684
685 // Fall through for subaggregate initialization
686 }
687
688 // C++ [dcl.init.aggr]p12:
689 //
690 // [...] Otherwise, if the member is itself a non-empty
691 // subaggregate, brace elision is assumed and the initializer is
692 // considered for the initialization of the first member of
693 // the subaggregate.
694 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
695 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
696 StructuredIndex);
697 ++StructuredIndex;
698 } else {
699 // We cannot initialize this element, so let
700 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000701 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000702 hadError = true;
703 ++Index;
704 ++StructuredIndex;
705 }
706 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000707}
708
Douglas Gregord45210d2009-01-30 22:09:00 +0000709void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000710 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000711 InitListExpr *StructuredList,
712 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000713 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000714 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000715 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000716 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000717 diag::err_many_braces_around_scalar_init)
718 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000719 hadError = true;
720 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000721 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000722 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000723 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000724 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000725 diag::err_designator_for_scalar_init)
726 << DeclType << expr->getSourceRange();
727 hadError = true;
728 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000729 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000730 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000731 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000732
Eli Friedmand8535af2008-05-19 20:00:43 +0000733 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000734 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000735 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000736 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000737 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000738 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000739 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000740 if (hadError)
741 ++StructuredIndex;
742 else
743 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000744 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000745 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000746 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000747 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000748 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000749 ++Index;
750 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000751 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000752 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000753}
754
Douglas Gregord45210d2009-01-30 22:09:00 +0000755void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
756 unsigned &Index,
757 InitListExpr *StructuredList,
758 unsigned &StructuredIndex) {
759 if (Index < IList->getNumInits()) {
760 Expr *expr = IList->getInit(Index);
761 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000762 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000763 << DeclType << IList->getSourceRange();
764 hadError = true;
765 ++Index;
766 ++StructuredIndex;
767 return;
768 }
769
770 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000771 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000772 hadError = true;
773 else if (savExpr != expr) {
774 // The type was promoted, update initializer list.
775 IList->setInit(Index, expr);
776 }
777 if (hadError)
778 ++StructuredIndex;
779 else
780 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
781 ++Index;
782 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000783 // FIXME: It would be wonderful if we could point at the actual member. In
784 // general, it would be useful to pass location information down the stack,
785 // so that we know the location (or decl) of the "current object" being
786 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000787 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000788 diag::err_init_reference_member_uninitialized)
789 << DeclType
790 << IList->getSourceRange();
791 hadError = true;
792 ++Index;
793 ++StructuredIndex;
794 return;
795 }
796}
797
Steve Naroffc4d4a482008-05-01 22:18:59 +0000798void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000799 unsigned &Index,
800 InitListExpr *StructuredList,
801 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000802 if (Index < IList->getNumInits()) {
803 const VectorType *VT = DeclType->getAsVectorType();
804 int maxElements = VT->getNumElements();
805 QualType elementType = VT->getElementType();
806
807 for (int i = 0; i < maxElements; ++i) {
808 // Don't attempt to go past the end of the init list
809 if (Index >= IList->getNumInits())
810 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000811 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000812 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000813 }
814 }
815}
816
817void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000818 llvm::APSInt elementIndex,
819 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000820 unsigned &Index,
821 InitListExpr *StructuredList,
822 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000823 // Check for the special-case of initializing an array with a string.
824 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000825 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
826 SemaRef.Context)) {
827 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000828 // We place the string literal directly into the resulting
829 // initializer list. This is the only place where the structure
830 // of the structured initializer list doesn't match exactly,
831 // because doing so would involve allocating one character
832 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000833 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000834 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000835 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000836 return;
837 }
838 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000839 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000840 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000841 // Check for VLAs; in standard C it would be possible to check this
842 // earlier, but I don't know where clang accepts VLAs (gcc accepts
843 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000844 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000845 diag::err_variable_object_no_init)
846 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000847 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000848 ++Index;
849 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000850 return;
851 }
852
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000853 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000854 llvm::APSInt maxElements(elementIndex.getBitWidth(),
855 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000856 bool maxElementsKnown = false;
857 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000858 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000859 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000860 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000861 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000862 maxElementsKnown = true;
863 }
864
Chris Lattner2e2766a2009-02-24 22:50:46 +0000865 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000866 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000867 while (Index < IList->getNumInits()) {
868 Expr *Init = IList->getInit(Index);
869 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000870 // If we're not the subobject that matches up with the '{' for
871 // the designator, we shouldn't be handling the
872 // designator. Return immediately.
873 if (!SubobjectIsDesignatorContext)
874 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000875
Douglas Gregor710f6d42009-01-22 23:26:18 +0000876 // Handle this designated initializer. elementIndex will be
877 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000878 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000879 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000880 StructuredList, StructuredIndex, true,
881 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000882 hadError = true;
883 continue;
884 }
885
Douglas Gregor5a203a62009-01-23 16:54:12 +0000886 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
887 maxElements.extend(elementIndex.getBitWidth());
888 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
889 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000890 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000891
Douglas Gregor710f6d42009-01-22 23:26:18 +0000892 // If the array is of incomplete type, keep track of the number of
893 // elements in the initializer.
894 if (!maxElementsKnown && elementIndex > maxElements)
895 maxElements = elementIndex;
896
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000897 continue;
898 }
899
900 // If we know the maximum number of elements, and we've already
901 // hit it, stop consuming elements in the initializer list.
902 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000903 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000904
905 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000906 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000907 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000908 ++elementIndex;
909
910 // If the array is of incomplete type, keep track of the number of
911 // elements in the initializer.
912 if (!maxElementsKnown && elementIndex > maxElements)
913 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000914 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000915 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000916 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000917 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000918 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000919 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000920 // Sizing an array implicitly to zero is not allowed by ISO C,
921 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000922 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000923 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000924 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000925
Chris Lattner2e2766a2009-02-24 22:50:46 +0000926 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000927 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000928 }
929}
930
931void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
932 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000933 RecordDecl::field_iterator Field,
934 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000935 unsigned &Index,
936 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000937 unsigned &StructuredIndex,
938 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000939 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000940
Eli Friedman683cedf2008-05-19 19:16:24 +0000941 // If the record is invalid, some of it's members are invalid. To avoid
942 // confusion, we forgo checking the intializer for the entire record.
943 if (structDecl->isInvalidDecl()) {
944 hadError = true;
945 return;
946 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000947
948 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
949 // Value-initialize the first named member of the union.
950 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000951 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000952 Field != FieldEnd; ++Field) {
953 if (Field->getDeclName()) {
954 StructuredList->setInitializedFieldInUnion(*Field);
955 break;
956 }
957 }
958 return;
959 }
960
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000961 // If structDecl is a forward declaration, this loop won't do
962 // anything except look at designated initializers; That's okay,
963 // because an error should get printed out elsewhere. It might be
964 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000965 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000966 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000967 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000968 while (Index < IList->getNumInits()) {
969 Expr *Init = IList->getInit(Index);
970
971 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000972 // If we're not the subobject that matches up with the '{' for
973 // the designator, we shouldn't be handling the
974 // designator. Return immediately.
975 if (!SubobjectIsDesignatorContext)
976 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000977
Douglas Gregor710f6d42009-01-22 23:26:18 +0000978 // Handle this designated initializer. Field will be updated to
979 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +0000980 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000981 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000982 StructuredList, StructuredIndex,
983 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000984 hadError = true;
985
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000986 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000987 continue;
988 }
989
990 if (Field == FieldEnd) {
991 // We've run out of fields. We're done.
992 break;
993 }
994
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000995 // We've already initialized a member of a union. We're done.
996 if (InitializedSomething && DeclType->isUnionType())
997 break;
998
Douglas Gregor8acb7272008-12-11 16:49:14 +0000999 // If we've hit the flexible array member at the end, we're done.
1000 if (Field->getType()->isIncompleteArrayType())
1001 break;
1002
Douglas Gregor82462762009-01-29 16:53:55 +00001003 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001004 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001005 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001006 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001007 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001008
Douglas Gregor36859eb2009-01-29 00:39:20 +00001009 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001010 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001011 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001012
1013 if (DeclType->isUnionType()) {
1014 // Initialize the first field within the union.
1015 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001016 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001017
1018 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001019 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001020
Douglas Gregorbe69b162009-02-04 22:46:25 +00001021 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001022 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001023 return;
1024
1025 // Handle GNU flexible array initializers.
1026 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001027 (!isa<InitListExpr>(IList->getInit(Index)) ||
1028 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001029 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001030 diag::err_flexible_array_init_nonempty)
1031 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001032 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001033 << *Field;
1034 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001035 ++Index;
1036 return;
1037 } else {
1038 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1039 diag::ext_flexible_array_init)
1040 << IList->getInit(Index)->getSourceRange().getBegin();
1041 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1042 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001043 }
1044
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001045 if (isa<InitListExpr>(IList->getInit(Index)))
1046 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1047 StructuredIndex);
1048 else
1049 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1050 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001051}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001052
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001053/// \brief Expand a field designator that refers to a member of an
1054/// anonymous struct or union into a series of field designators that
1055/// refers to the field within the appropriate subobject.
1056///
1057/// Field/FieldIndex will be updated to point to the (new)
1058/// currently-designated field.
1059static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1060 DesignatedInitExpr *DIE,
1061 unsigned DesigIdx,
1062 FieldDecl *Field,
1063 RecordDecl::field_iterator &FieldIter,
1064 unsigned &FieldIndex) {
1065 typedef DesignatedInitExpr::Designator Designator;
1066
1067 // Build the path from the current object to the member of the
1068 // anonymous struct/union (backwards).
1069 llvm::SmallVector<FieldDecl *, 4> Path;
1070 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1071
1072 // Build the replacement designators.
1073 llvm::SmallVector<Designator, 4> Replacements;
1074 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1075 FI = Path.rbegin(), FIEnd = Path.rend();
1076 FI != FIEnd; ++FI) {
1077 if (FI + 1 == FIEnd)
1078 Replacements.push_back(Designator((IdentifierInfo *)0,
1079 DIE->getDesignator(DesigIdx)->getDotLoc(),
1080 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1081 else
1082 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1083 SourceLocation()));
1084 Replacements.back().setField(*FI);
1085 }
1086
1087 // Expand the current designator into the set of replacement
1088 // designators, so we have a full subobject path down to where the
1089 // member of the anonymous struct/union is actually stored.
1090 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1091 &Replacements[0] + Replacements.size());
1092
1093 // Update FieldIter/FieldIndex;
1094 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1095 FieldIter = Record->field_begin(SemaRef.Context);
1096 FieldIndex = 0;
1097 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1098 FieldIter != FEnd; ++FieldIter) {
1099 if (FieldIter->isUnnamedBitfield())
1100 continue;
1101
1102 if (*FieldIter == Path.back())
1103 return;
1104
1105 ++FieldIndex;
1106 }
1107
1108 assert(false && "Unable to find anonymous struct/union field");
1109}
1110
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001111/// @brief Check the well-formedness of a C99 designated initializer.
1112///
1113/// Determines whether the designated initializer @p DIE, which
1114/// resides at the given @p Index within the initializer list @p
1115/// IList, is well-formed for a current object of type @p DeclType
1116/// (C99 6.7.8). The actual subobject that this designator refers to
1117/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001118/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001119///
1120/// @param IList The initializer list in which this designated
1121/// initializer occurs.
1122///
Douglas Gregoraa357272009-04-15 04:56:10 +00001123/// @param DIE The designated initializer expression.
1124///
1125/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001126///
1127/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1128/// into which the designation in @p DIE should refer.
1129///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001130/// @param NextField If non-NULL and the first designator in @p DIE is
1131/// a field, this will be set to the field declaration corresponding
1132/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001133///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001134/// @param NextElementIndex If non-NULL and the first designator in @p
1135/// DIE is an array designator or GNU array-range designator, this
1136/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001137///
1138/// @param Index Index into @p IList where the designated initializer
1139/// @p DIE occurs.
1140///
Douglas Gregorf603b472009-01-28 21:54:33 +00001141/// @param StructuredList The initializer list expression that
1142/// describes all of the subobject initializers in the order they'll
1143/// actually be initialized.
1144///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001145/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001146bool
1147InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1148 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001149 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001150 QualType &CurrentObjectType,
1151 RecordDecl::field_iterator *NextField,
1152 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001153 unsigned &Index,
1154 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001155 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001156 bool FinishSubobjectInit,
1157 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001158 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001159 // Check the actual initialization for the designated object type.
1160 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001161
1162 // Temporarily remove the designator expression from the
1163 // initializer list that the child calls see, so that we don't try
1164 // to re-process the designator.
1165 unsigned OldIndex = Index;
1166 IList->setInit(OldIndex, DIE->getInit());
1167
1168 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001169 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001170
1171 // Restore the designated initializer expression in the syntactic
1172 // form of the initializer list.
1173 if (IList->getInit(OldIndex) != DIE->getInit())
1174 DIE->setInit(IList->getInit(OldIndex));
1175 IList->setInit(OldIndex, DIE);
1176
Douglas Gregor710f6d42009-01-22 23:26:18 +00001177 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001178 }
1179
Douglas Gregoraa357272009-04-15 04:56:10 +00001180 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001181 assert((IsFirstDesignator || StructuredList) &&
1182 "Need a non-designated initializer list to start from");
1183
Douglas Gregoraa357272009-04-15 04:56:10 +00001184 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001185 // Determine the structural initializer list that corresponds to the
1186 // current subobject.
1187 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001188 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1189 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001190 SourceRange(D->getStartLocation(),
1191 DIE->getSourceRange().getEnd()));
1192 assert(StructuredList && "Expected a structured initializer list");
1193
Douglas Gregor710f6d42009-01-22 23:26:18 +00001194 if (D->isFieldDesignator()) {
1195 // C99 6.7.8p7:
1196 //
1197 // If a designator has the form
1198 //
1199 // . identifier
1200 //
1201 // then the current object (defined below) shall have
1202 // structure or union type and the identifier shall be the
1203 // name of a member of that type.
1204 const RecordType *RT = CurrentObjectType->getAsRecordType();
1205 if (!RT) {
1206 SourceLocation Loc = D->getDotLoc();
1207 if (Loc.isInvalid())
1208 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001209 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1210 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001211 ++Index;
1212 return true;
1213 }
1214
Douglas Gregorf603b472009-01-28 21:54:33 +00001215 // Note: we perform a linear search of the fields here, despite
1216 // the fact that we have a faster lookup method, because we always
1217 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001218 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001219 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001220 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001221 RecordDecl::field_iterator
1222 Field = RT->getDecl()->field_begin(SemaRef.Context),
1223 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +00001224 for (; Field != FieldEnd; ++Field) {
1225 if (Field->isUnnamedBitfield())
1226 continue;
1227
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001228 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001229 break;
1230
1231 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001232 }
1233
Douglas Gregorf603b472009-01-28 21:54:33 +00001234 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001235 // There was no normal field in the struct with the designated
1236 // name. Perform another lookup for this name, which may find
1237 // something that we can't designate (e.g., a member function),
1238 // may find nothing, or may find a member of an anonymous
1239 // struct/union.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001240 DeclContext::lookup_result Lookup
1241 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001242 if (Lookup.first == Lookup.second) {
1243 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001244 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001245 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001246 ++Index;
1247 return true;
1248 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1249 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1250 ->isAnonymousStructOrUnion()) {
1251 // Handle an field designator that refers to a member of an
1252 // anonymous struct or union.
1253 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1254 cast<FieldDecl>(*Lookup.first),
1255 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001256 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001257 } else {
1258 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001259 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001260 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001261 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001262 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001263 ++Index;
1264 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001265 }
1266 } else if (!KnownField &&
1267 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001268 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001269 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1270 Field, FieldIndex);
1271 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001272 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001273
1274 // All of the fields of a union are located at the same place in
1275 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001276 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001277 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001278 StructuredList->setInitializedFieldInUnion(*Field);
1279 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001280
Douglas Gregor710f6d42009-01-22 23:26:18 +00001281 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001282 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001283
Douglas Gregorf603b472009-01-28 21:54:33 +00001284 // Make sure that our non-designated initializer list has space
1285 // for a subobject corresponding to this field.
1286 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001287 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001288
Douglas Gregorbe69b162009-02-04 22:46:25 +00001289 // This designator names a flexible array member.
1290 if (Field->getType()->isIncompleteArrayType()) {
1291 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001292 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001293 // We can't designate an object within the flexible array
1294 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001295 DesignatedInitExpr::Designator *NextD
1296 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001297 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001298 diag::err_designator_into_flexible_array_member)
1299 << SourceRange(NextD->getStartLocation(),
1300 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001301 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001302 << *Field;
1303 Invalid = true;
1304 }
1305
1306 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1307 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001308 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001309 diag::err_flexible_array_init_needs_braces)
1310 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001311 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001312 << *Field;
1313 Invalid = true;
1314 }
1315
1316 // Handle GNU flexible array initializers.
1317 if (!Invalid && !TopLevelObject &&
1318 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001319 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001320 diag::err_flexible_array_init_nonempty)
1321 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001322 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001323 << *Field;
1324 Invalid = true;
1325 }
1326
1327 if (Invalid) {
1328 ++Index;
1329 return true;
1330 }
1331
1332 // Initialize the array.
1333 bool prevHadError = hadError;
1334 unsigned newStructuredIndex = FieldIndex;
1335 unsigned OldIndex = Index;
1336 IList->setInit(Index, DIE->getInit());
1337 CheckSubElementType(IList, Field->getType(), Index,
1338 StructuredList, newStructuredIndex);
1339 IList->setInit(OldIndex, DIE);
1340 if (hadError && !prevHadError) {
1341 ++Field;
1342 ++FieldIndex;
1343 if (NextField)
1344 *NextField = Field;
1345 StructuredIndex = FieldIndex;
1346 return true;
1347 }
1348 } else {
1349 // Recurse to check later designated subobjects.
1350 QualType FieldType = (*Field)->getType();
1351 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001352 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1353 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001354 true, false))
1355 return true;
1356 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001357
1358 // Find the position of the next field to be initialized in this
1359 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001360 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001361 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001362
1363 // If this the first designator, our caller will continue checking
1364 // the rest of this struct/class/union subobject.
1365 if (IsFirstDesignator) {
1366 if (NextField)
1367 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001368 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001369 return false;
1370 }
1371
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001372 if (!FinishSubobjectInit)
1373 return false;
1374
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001375 // We've already initialized something in the union; we're done.
1376 if (RT->getDecl()->isUnion())
1377 return hadError;
1378
Douglas Gregor710f6d42009-01-22 23:26:18 +00001379 // Check the remaining fields within this class/struct/union subobject.
1380 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001381 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1382 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001383 return hadError && !prevHadError;
1384 }
1385
1386 // C99 6.7.8p6:
1387 //
1388 // If a designator has the form
1389 //
1390 // [ constant-expression ]
1391 //
1392 // then the current object (defined below) shall have array
1393 // type and the expression shall be an integer constant
1394 // expression. If the array is of unknown size, any
1395 // nonnegative value is valid.
1396 //
1397 // Additionally, cope with the GNU extension that permits
1398 // designators of the form
1399 //
1400 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001401 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001402 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001403 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001404 << CurrentObjectType;
1405 ++Index;
1406 return true;
1407 }
1408
1409 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001410 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1411 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001412 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001413 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001414 DesignatedEndIndex = DesignatedStartIndex;
1415 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001416 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001417
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001418
Chris Lattnereec8ae22009-04-25 21:59:05 +00001419 DesignatedStartIndex =
1420 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1421 DesignatedEndIndex =
1422 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001423 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001424
Chris Lattnereec8ae22009-04-25 21:59:05 +00001425 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001426 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001427 }
1428
Douglas Gregor710f6d42009-01-22 23:26:18 +00001429 if (isa<ConstantArrayType>(AT)) {
1430 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001431 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1432 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1433 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1434 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1435 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001436 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001437 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001438 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001439 << IndexExpr->getSourceRange();
1440 ++Index;
1441 return true;
1442 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001443 } else {
1444 // Make sure the bit-widths and signedness match.
1445 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1446 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001447 else if (DesignatedStartIndex.getBitWidth() <
1448 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001449 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1450 DesignatedStartIndex.setIsUnsigned(true);
1451 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001452 }
1453
Douglas Gregorf603b472009-01-28 21:54:33 +00001454 // Make sure that our non-designated initializer list has space
1455 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001456 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001457 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001458 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001459
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001460 // Repeatedly perform subobject initializations in the range
1461 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001462
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001463 // Move to the next designator
1464 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1465 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001466 while (DesignatedStartIndex <= DesignatedEndIndex) {
1467 // Recurse to check later designated subobjects.
1468 QualType ElementType = AT->getElementType();
1469 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001470 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1471 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001472 (DesignatedStartIndex == DesignatedEndIndex),
1473 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001474 return true;
1475
1476 // Move to the next index in the array that we'll be initializing.
1477 ++DesignatedStartIndex;
1478 ElementIndex = DesignatedStartIndex.getZExtValue();
1479 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001480
1481 // If this the first designator, our caller will continue checking
1482 // the rest of this array subobject.
1483 if (IsFirstDesignator) {
1484 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001485 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001486 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001487 return false;
1488 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001489
1490 if (!FinishSubobjectInit)
1491 return false;
1492
Douglas Gregor710f6d42009-01-22 23:26:18 +00001493 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001494 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001495 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001496 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001497 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001498}
1499
Douglas Gregorf603b472009-01-28 21:54:33 +00001500// Get the structured initializer list for a subobject of type
1501// @p CurrentObjectType.
1502InitListExpr *
1503InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1504 QualType CurrentObjectType,
1505 InitListExpr *StructuredList,
1506 unsigned StructuredIndex,
1507 SourceRange InitRange) {
1508 Expr *ExistingInit = 0;
1509 if (!StructuredList)
1510 ExistingInit = SyntacticToSemantic[IList];
1511 else if (StructuredIndex < StructuredList->getNumInits())
1512 ExistingInit = StructuredList->getInit(StructuredIndex);
1513
1514 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1515 return Result;
1516
1517 if (ExistingInit) {
1518 // We are creating an initializer list that initializes the
1519 // subobjects of the current object, but there was already an
1520 // initialization that completely initialized the current
1521 // subobject, e.g., by a compound literal:
1522 //
1523 // struct X { int a, b; };
1524 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1525 //
1526 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1527 // designated initializer re-initializes the whole
1528 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001529 SemaRef.Diag(InitRange.getBegin(),
1530 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001531 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001532 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001533 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001534 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001535 << ExistingInit->getSourceRange();
1536 }
1537
1538 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001539 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1540 InitRange.getEnd());
1541
Douglas Gregorf603b472009-01-28 21:54:33 +00001542 Result->setType(CurrentObjectType);
1543
Douglas Gregoree0792c2009-03-20 23:58:33 +00001544 // Pre-allocate storage for the structured initializer list.
1545 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001546 unsigned NumInits = 0;
1547 if (!StructuredList)
1548 NumInits = IList->getNumInits();
1549 else if (Index < IList->getNumInits()) {
1550 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1551 NumInits = SubList->getNumInits();
1552 }
1553
Douglas Gregoree0792c2009-03-20 23:58:33 +00001554 if (const ArrayType *AType
1555 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1556 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1557 NumElements = CAType->getSize().getZExtValue();
1558 // Simple heuristic so that we don't allocate a very large
1559 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001560 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001561 NumElements = 0;
1562 }
1563 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1564 NumElements = VType->getNumElements();
1565 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1566 RecordDecl *RDecl = RType->getDecl();
1567 if (RDecl->isUnion())
1568 NumElements = 1;
1569 else
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001570 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1571 RDecl->field_end(SemaRef.Context));
Douglas Gregoree0792c2009-03-20 23:58:33 +00001572 }
1573
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001574 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001575 NumElements = IList->getNumInits();
1576
1577 Result->reserveInits(NumElements);
1578
Douglas Gregorf603b472009-01-28 21:54:33 +00001579 // Link this new initializer list into the structured initializer
1580 // lists.
1581 if (StructuredList)
1582 StructuredList->updateInit(StructuredIndex, Result);
1583 else {
1584 Result->setSyntacticForm(IList);
1585 SyntacticToSemantic[IList] = Result;
1586 }
1587
1588 return Result;
1589}
1590
1591/// Update the initializer at index @p StructuredIndex within the
1592/// structured initializer list to the value @p expr.
1593void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1594 unsigned &StructuredIndex,
1595 Expr *expr) {
1596 // No structured initializer list to update
1597 if (!StructuredList)
1598 return;
1599
1600 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1601 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001602 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001603 diag::warn_initializer_overrides)
1604 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001605 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001606 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001607 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001608 << PrevInit->getSourceRange();
1609 }
1610
1611 ++StructuredIndex;
1612}
1613
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001614/// Check that the given Index expression is a valid array designator
1615/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001616/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001617/// and produces a reasonable diagnostic if there is a
1618/// failure. Returns true if there was an error, false otherwise. If
1619/// everything went okay, Value will receive the value of the constant
1620/// expression.
1621static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001622CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001623 SourceLocation Loc = Index->getSourceRange().getBegin();
1624
1625 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001626 if (S.VerifyIntegerConstantExpression(Index, &Value))
1627 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001628
Chris Lattnereec8ae22009-04-25 21:59:05 +00001629 if (Value.isSigned() && Value.isNegative())
1630 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001631 << Value.toString(10) << Index->getSourceRange();
1632
Douglas Gregore498e372009-01-23 21:04:18 +00001633 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001634 return false;
1635}
1636
1637Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1638 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001639 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001640 OwningExprResult Init) {
1641 typedef DesignatedInitExpr::Designator ASTDesignator;
1642
1643 bool Invalid = false;
1644 llvm::SmallVector<ASTDesignator, 32> Designators;
1645 llvm::SmallVector<Expr *, 32> InitExpressions;
1646
1647 // Build designators and check array designator expressions.
1648 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1649 const Designator &D = Desig.getDesignator(Idx);
1650 switch (D.getKind()) {
1651 case Designator::FieldDesignator:
1652 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1653 D.getFieldLoc()));
1654 break;
1655
1656 case Designator::ArrayDesignator: {
1657 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1658 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001659 if (!Index->isTypeDependent() &&
1660 !Index->isValueDependent() &&
1661 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001662 Invalid = true;
1663 else {
1664 Designators.push_back(ASTDesignator(InitExpressions.size(),
1665 D.getLBracketLoc(),
1666 D.getRBracketLoc()));
1667 InitExpressions.push_back(Index);
1668 }
1669 break;
1670 }
1671
1672 case Designator::ArrayRangeDesignator: {
1673 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1674 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1675 llvm::APSInt StartValue;
1676 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001677 bool StartDependent = StartIndex->isTypeDependent() ||
1678 StartIndex->isValueDependent();
1679 bool EndDependent = EndIndex->isTypeDependent() ||
1680 EndIndex->isValueDependent();
1681 if ((!StartDependent &&
1682 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1683 (!EndDependent &&
1684 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001685 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001686 else {
1687 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001688 if (StartDependent || EndDependent) {
1689 // Nothing to compute.
1690 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001691 EndValue.extend(StartValue.getBitWidth());
1692 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1693 StartValue.extend(EndValue.getBitWidth());
1694
Douglas Gregor1401c062009-05-21 23:30:39 +00001695 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001696 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1697 << StartValue.toString(10) << EndValue.toString(10)
1698 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1699 Invalid = true;
1700 } else {
1701 Designators.push_back(ASTDesignator(InitExpressions.size(),
1702 D.getLBracketLoc(),
1703 D.getEllipsisLoc(),
1704 D.getRBracketLoc()));
1705 InitExpressions.push_back(StartIndex);
1706 InitExpressions.push_back(EndIndex);
1707 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001708 }
1709 break;
1710 }
1711 }
1712 }
1713
1714 if (Invalid || Init.isInvalid())
1715 return ExprError();
1716
1717 // Clear out the expressions within the designation.
1718 Desig.ClearExprs(*this);
1719
1720 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001721 = DesignatedInitExpr::Create(Context,
1722 Designators.data(), Designators.size(),
1723 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001724 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001725 return Owned(DIE);
1726}
Douglas Gregor849afc32009-01-29 00:45:39 +00001727
1728bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001729 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001730 if (!CheckInitList.HadError())
1731 InitList = CheckInitList.getFullyStructuredList();
1732
1733 return CheckInitList.HadError();
1734}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001735
1736/// \brief Diagnose any semantic errors with value-initialization of
1737/// the given type.
1738///
1739/// Value-initialization effectively zero-initializes any types
1740/// without user-declared constructors, and calls the default
1741/// constructor for a for any type that has a user-declared
1742/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1743/// a type with a user-declared constructor does not have an
1744/// accessible, non-deleted default constructor. In C, everything can
1745/// be value-initialized, which corresponds to C's notion of
1746/// initializing objects with static storage duration when no
1747/// initializer is provided for that object.
1748///
1749/// \returns true if there was an error, false otherwise.
1750bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1751 // C++ [dcl.init]p5:
1752 //
1753 // To value-initialize an object of type T means:
1754
1755 // -- if T is an array type, then each element is value-initialized;
1756 if (const ArrayType *AT = Context.getAsArrayType(Type))
1757 return CheckValueInitialization(AT->getElementType(), Loc);
1758
1759 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001760 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001761 // -- if T is a class type (clause 9) with a user-declared
1762 // constructor (12.1), then the default constructor for T is
1763 // called (and the initialization is ill-formed if T has no
1764 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001765 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001766 // FIXME: Eventually, we'll need to put the constructor decl into the
1767 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001768 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1769 SourceRange(Loc),
1770 DeclarationName(),
1771 IK_Direct);
1772 }
1773 }
1774
1775 if (Type->isReferenceType()) {
1776 // C++ [dcl.init]p5:
1777 // [...] A program that calls for default-initialization or
1778 // value-initialization of an entity of reference type is
1779 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001780 // FIXME: Once we have code that goes through this path, add an actual
1781 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001782 }
1783
1784 return false;
1785}