blob: 951aaa3bc0f05b2ca07174c584101fd07248d865 [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
34 // See if this is a string literal or @encode.
35 Init = Init->IgnoreParens();
36
37 // Handle @encode, which is a narrow string.
38 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
39 return Init;
40
41 // Otherwise we can only handle string literals.
42 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattnerff065f72009-02-26 23:42:47 +000043 if (SL == 0) return 0;
Chris Lattner7a7c1452009-02-26 23:26:43 +000044
45 // char array can be initialized with a narrow string.
46 // Only allow char x[] = "foo"; not char x[] = L"foo";
47 if (!SL->isWide())
48 return AT->getElementType()->isCharType() ? Init : 0;
49
50 // wchar_t array can be initialized with a wide string: C99 6.7.8p15:
51 // "An array with element type compatible with wchar_t may be initialized by a
52 // wide string literal, optionally enclosed in braces."
Chris Lattnerb1fe0472009-02-26 23:36:02 +000053 if (Context.typesAreCompatible(Context.getWCharType(), AT->getElementType()))
Chris Lattner7a7c1452009-02-26 23:26:43 +000054 // Only allow wchar_t x[] = L"foo"; not wchar_t x[] = "foo";
55 return Init;
56
Chris Lattnerd3a00502009-02-24 22:27:37 +000057 return 0;
58}
59
Chris Lattner160da072009-02-24 22:46:58 +000060static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
61 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000062 // Get the type before calling CheckSingleAssignmentConstraints(), since
63 // it can promote the expression.
64 QualType InitType = Init->getType();
65
Chris Lattner160da072009-02-24 22:46:58 +000066 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000067 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000068 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
69 return S.Diag(Init->getSourceRange().getBegin(),
70 diag::err_typecheck_convert_incompatible)
71 << DeclType << Init->getType() << "initializing"
72 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000073 return false;
74 }
75
Chris Lattner160da072009-02-24 22:46:58 +000076 Sema::AssignConvertType ConvTy =
77 S.CheckSingleAssignmentConstraints(DeclType, Init);
78 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000079 InitType, Init, "initializing");
80}
81
Chris Lattner19ae2fc2009-02-24 23:10:27 +000082static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
83 // Get the length of the string as parsed.
84 uint64_t StrLength =
85 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
86
Chris Lattnerd3a00502009-02-24 22:27:37 +000087
Chris Lattner19ae2fc2009-02-24 23:10:27 +000088 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000089 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
90 // C99 6.7.8p14. We have an array of character type with unknown size
91 // being initialized to a string literal.
92 llvm::APSInt ConstVal(32);
Chris Lattnerd20fac42009-02-24 23:01:39 +000093 ConstVal = StrLength;
Chris Lattnerd3a00502009-02-24 22:27:37 +000094 // Return a new array type (C99 6.7.8p22).
Chris Lattner45d6fd62009-02-24 22:41:04 +000095 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), ConstVal,
96 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +000097 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +000098 }
Chris Lattnerd20fac42009-02-24 23:01:39 +000099
100 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
101
102 // C99 6.7.8p14. We have an array of character type with known size. However,
103 // the size may be smaller or larger than the string we are initializing.
104 // FIXME: Avoid truncation for 64-bit length strings.
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000105 if (StrLength-1 > CAT->getSize().getZExtValue())
Chris Lattnerd20fac42009-02-24 23:01:39 +0000106 S.Diag(Str->getSourceRange().getBegin(),
107 diag::warn_initializer_string_for_char_array_too_long)
108 << Str->getSourceRange();
109
110 // Set the type to the actual size that we are initializing. If we have
111 // something like:
112 // char x[1] = "foo";
113 // then this will set the string literal's type to char[1].
Chris Lattner45d6fd62009-02-24 22:41:04 +0000114 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000115}
116
117bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
118 SourceLocation InitLoc,
119 DeclarationName InitEntity,
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000120 bool DirectInit, VarDecl *VD) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000121 if (DeclType->isDependentType() ||
122 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000123 return false;
124
125 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000126 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000127 // (8.3.2), shall be initialized by an object, or function, of
128 // type T or by an object that can be converted into a T.
129 if (DeclType->isReferenceType())
130 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
131
132 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
133 // of unknown size ("[]") or an object type that is not a variable array type.
134 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
135 return Diag(InitLoc, diag::err_variable_object_no_init)
136 << VAT->getSizeExpr()->getSourceRange();
137
138 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
139 if (!InitList) {
140 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000141 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
142 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000143 return false;
144 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000145
146 // C++ [dcl.init]p14:
147 // -- If the destination type is a (possibly cv-qualified) class
148 // type:
149 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
150 QualType DeclTypeC = Context.getCanonicalType(DeclType);
151 QualType InitTypeC = Context.getCanonicalType(Init->getType());
152
153 // -- If the initialization is direct-initialization, or if it is
154 // copy-initialization where the cv-unqualified version of the
155 // source type is the same class as, or a derived class of, the
156 // class of the destination, constructors are considered.
157 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
158 IsDerivedFrom(InitTypeC, DeclTypeC)) {
159 CXXConstructorDecl *Constructor
160 = PerformInitializationByConstructor(DeclType, &Init, 1,
161 InitLoc, Init->getSourceRange(),
162 InitEntity,
163 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000164 if (!Constructor)
165 return true;
166
167 // FIXME: What do do if VD is null here?
Anders Carlsson6b0e7972009-05-27 16:28:34 +0000168 if (VD)
169 Init = CXXConstructExpr::Create(Context, VD, DeclType, Constructor,
170 false, &Init, 1);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000171 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000172 }
173
174 // -- Otherwise (i.e., for the remaining copy-initialization
175 // cases), user-defined conversion sequences that can
176 // convert from the source type to the destination type or
177 // (when a conversion function is used) to a derived class
178 // thereof are enumerated as described in 13.3.1.4, and the
179 // best one is chosen through overload resolution
180 // (13.3). If the conversion cannot be done or is
181 // ambiguous, the initialization is ill-formed. The
182 // function selected is called with the initializer
183 // expression as its argument; if the function is a
184 // constructor, the call initializes a temporary of the
185 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000186 // FIXME: We're pretending to do copy elision here; return to this when we
187 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000188 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
189 return false;
190
191 if (InitEntity)
192 return Diag(InitLoc, diag::err_cannot_initialize_decl)
193 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
194 << Init->getType() << Init->getSourceRange();
195 else
196 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
197 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
198 << Init->getType() << Init->getSourceRange();
199 }
200
201 // C99 6.7.8p16.
202 if (DeclType->isArrayType())
203 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
204 << Init->getSourceRange();
205
Chris Lattner160da072009-02-24 22:46:58 +0000206 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000207 }
208
209 bool hadError = CheckInitList(InitList, DeclType);
210 Init = InitList;
211 return hadError;
212}
213
214//===----------------------------------------------------------------------===//
215// Semantic checking for initializer lists.
216//===----------------------------------------------------------------------===//
217
Douglas Gregoraaa20962009-01-29 01:05:33 +0000218/// @brief Semantic checking for initializer lists.
219///
220/// The InitListChecker class contains a set of routines that each
221/// handle the initialization of a certain kind of entity, e.g.,
222/// arrays, vectors, struct/union types, scalars, etc. The
223/// InitListChecker itself performs a recursive walk of the subobject
224/// structure of the type to be initialized, while stepping through
225/// the initializer list one element at a time. The IList and Index
226/// parameters to each of the Check* routines contain the active
227/// (syntactic) initializer list and the index into that initializer
228/// list that represents the current initializer. Each routine is
229/// responsible for moving that Index forward as it consumes elements.
230///
231/// Each Check* routine also has a StructuredList/StructuredIndex
232/// arguments, which contains the current the "structured" (semantic)
233/// initializer list and the index into that initializer list where we
234/// are copying initializers as we map them over to the semantic
235/// list. Once we have completed our recursive walk of the subobject
236/// structure, we will have constructed a full semantic initializer
237/// list.
238///
239/// C99 designators cause changes in the initializer list traversal,
240/// because they make the initialization "jump" into a specific
241/// subobject and then continue the initialization from that
242/// point. CheckDesignatedInitializer() recursively steps into the
243/// designated subobject and manages backing out the recursion to
244/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000245namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000246class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000247 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000248 bool hadError;
249 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
250 InitListExpr *FullyStructuredList;
251
252 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000253 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000254 unsigned &StructuredIndex,
255 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000256 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000257 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000258 unsigned &StructuredIndex,
259 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000260 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
261 bool SubobjectIsDesignatorContext,
262 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000263 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000264 unsigned &StructuredIndex,
265 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000266 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
267 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000268 InitListExpr *StructuredList,
269 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000270 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000271 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000272 InitListExpr *StructuredList,
273 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000274 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
275 unsigned &Index,
276 InitListExpr *StructuredList,
277 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000278 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000281 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
282 RecordDecl::field_iterator Field,
283 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000285 unsigned &StructuredIndex,
286 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000287 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
288 llvm::APSInt elementIndex,
289 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000290 InitListExpr *StructuredList,
291 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000292 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000293 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000294 QualType &CurrentObjectType,
295 RecordDecl::field_iterator *NextField,
296 llvm::APSInt *NextElementIndex,
297 unsigned &Index,
298 InitListExpr *StructuredList,
299 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000300 bool FinishSubobjectInit,
301 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000302 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
303 QualType CurrentObjectType,
304 InitListExpr *StructuredList,
305 unsigned StructuredIndex,
306 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000307 void UpdateStructuredListElement(InitListExpr *StructuredList,
308 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000309 Expr *expr);
310 int numArrayElements(QualType DeclType);
311 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000312
313 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000314public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000315 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000316 bool HadError() { return hadError; }
317
318 // @brief Retrieves the fully-structured initializer list used for
319 // semantic analysis and code generation.
320 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
321};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000322} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000323
Douglas Gregorf603b472009-01-28 21:54:33 +0000324/// Recursively replaces NULL values within the given initializer list
325/// with expressions that perform value-initialization of the
326/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000327void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000328 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000329 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000330 SourceLocation Loc = ILE->getSourceRange().getBegin();
331 if (ILE->getSyntacticForm())
332 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
333
Douglas Gregorf603b472009-01-28 21:54:33 +0000334 if (const RecordType *RType = ILE->getType()->getAsRecordType()) {
335 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000336 for (RecordDecl::field_iterator
337 Field = RType->getDecl()->field_begin(SemaRef.Context),
338 FieldEnd = RType->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000339 Field != FieldEnd; ++Field) {
340 if (Field->isUnnamedBitfield())
341 continue;
342
Douglas Gregor538a4c22009-02-02 17:43:21 +0000343 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000344 if (Field->getType()->isReferenceType()) {
345 // C++ [dcl.init.aggr]p9:
346 // If an incomplete or empty initializer-list leaves a
347 // member of reference type uninitialized, the program is
348 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000349 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000350 << Field->getType()
351 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000352 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000353 diag::note_uninit_reference_member);
354 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000355 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000356 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000357 hadError = true;
358 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000359 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000360
Mike Stumpe127ae32009-05-16 07:39:55 +0000361 // FIXME: If value-initialization involves calling a constructor, should
362 // we make that call explicit in the representation (even when it means
363 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000364 if (Init < NumInits && !hadError)
365 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000366 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000367 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000368 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000369 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000370 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000371
372 // Only look at the first initialization of a union.
373 if (RType->getDecl()->isUnion())
374 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000375 }
376
377 return;
378 }
379
380 QualType ElementType;
381
Douglas Gregor538a4c22009-02-02 17:43:21 +0000382 unsigned NumInits = ILE->getNumInits();
383 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000384 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000385 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000386 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
387 NumElements = CAType->getSize().getZExtValue();
388 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000389 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000390 NumElements = VType->getNumElements();
391 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000392 ElementType = ILE->getType();
393
Douglas Gregor538a4c22009-02-02 17:43:21 +0000394 for (unsigned Init = 0; Init != NumElements; ++Init) {
395 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000396 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000397 hadError = true;
398 return;
399 }
400
Mike Stumpe127ae32009-05-16 07:39:55 +0000401 // FIXME: If value-initialization involves calling a constructor, should
402 // we make that call explicit in the representation (even when it means
403 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000404 if (Init < NumInits && !hadError)
405 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000406 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000407 }
Chris Lattner1aa25a72009-01-29 05:10:57 +0000408 else if (InitListExpr *InnerILE =dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000409 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000410 }
411}
412
Chris Lattner1aa25a72009-01-29 05:10:57 +0000413
Chris Lattner2e2766a2009-02-24 22:50:46 +0000414InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
415 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000416 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000417
Eli Friedman683cedf2008-05-19 19:16:24 +0000418 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000419 unsigned newStructuredIndex = 0;
420 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000421 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000422 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
423 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000424
Douglas Gregord45210d2009-01-30 22:09:00 +0000425 if (!hadError)
426 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000427}
428
429int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000430 // FIXME: use a proper constant
431 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000432 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000433 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000434 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
435 }
436 return maxElements;
437}
438
439int InitListChecker::numStructUnionElements(QualType DeclType) {
440 RecordDecl *structDecl = DeclType->getAsRecordType()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000441 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000442 for (RecordDecl::field_iterator
443 Field = structDecl->field_begin(SemaRef.Context),
444 FieldEnd = structDecl->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +0000445 Field != FieldEnd; ++Field) {
446 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
447 ++InitializableMembers;
448 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000449 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000450 return std::min(InitializableMembers, 1);
451 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000452}
453
454void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000455 QualType T, unsigned &Index,
456 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000457 unsigned &StructuredIndex,
458 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000459 int maxElements = 0;
460
461 if (T->isArrayType())
462 maxElements = numArrayElements(T);
463 else if (T->isStructureType() || T->isUnionType())
464 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000465 else if (T->isVectorType())
466 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000467 else
468 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000469
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000470 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000471 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000472 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000473 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000474 hadError = true;
475 return;
476 }
477
Douglas Gregorf603b472009-01-28 21:54:33 +0000478 // Build a structured initializer list corresponding to this subobject.
479 InitListExpr *StructuredSubobjectInitList
480 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
481 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000482 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
483 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000484 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000485
Douglas Gregorf603b472009-01-28 21:54:33 +0000486 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000487 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000488 CheckListElementTypes(ParentIList, T, false, Index,
489 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000490 StructuredSubobjectInitIndex,
491 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000492 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000493 StructuredSubobjectInitList->setType(T);
494
Douglas Gregorea765e12009-03-01 17:12:46 +0000495 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000496 // range corresponds with the end of the last initializer it used.
497 if (EndIndex < ParentIList->getNumInits()) {
498 SourceLocation EndLoc
499 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
500 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
501 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000502}
503
Steve Naroff56099522008-05-06 00:23:44 +0000504void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000505 unsigned &Index,
506 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000507 unsigned &StructuredIndex,
508 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000509 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000510 SyntacticToSemantic[IList] = StructuredList;
511 StructuredList->setSyntacticForm(IList);
512 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000513 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000514 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000515 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000516 if (hadError)
517 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000518
Eli Friedman46f81662008-05-25 13:22:35 +0000519 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000520 // We have leftover initializers
521 if (IList->getNumInits() > 0 &&
Chris Lattner2e2766a2009-02-24 22:50:46 +0000522 IsStringInit(IList->getInit(Index), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000523 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000524 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000525 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000526 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000527 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000528 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000529 hadError = true;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000530 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000531 // Don't complain for incomplete types, since we'll get an error
532 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000533 QualType CurrentObjectType = StructuredList->getType();
534 int initKind =
535 CurrentObjectType->isArrayType()? 0 :
536 CurrentObjectType->isVectorType()? 1 :
537 CurrentObjectType->isScalarType()? 2 :
538 CurrentObjectType->isUnionType()? 3 :
539 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000540
541 unsigned DK = diag::warn_excess_initializers;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000542 if (SemaRef.getLangOptions().CPlusPlus)
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000543 DK = diag::err_excess_initializers;
544
Chris Lattner2e2766a2009-02-24 22:50:46 +0000545 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000546 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000547 }
548 }
Eli Friedman455f7622008-05-19 20:20:43 +0000549
Eli Friedman90bcb892009-05-16 11:45:48 +0000550 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000551 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000552 << IList->getSourceRange()
553 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
554 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000555}
556
Eli Friedman683cedf2008-05-19 19:16:24 +0000557void InitListChecker::CheckListElementTypes(InitListExpr *IList,
558 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000559 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000560 unsigned &Index,
561 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000562 unsigned &StructuredIndex,
563 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000564 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000565 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000566 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000567 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000568 } else if (DeclType->isAggregateType()) {
569 if (DeclType->isRecordType()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000570 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000571 CheckStructUnionTypes(IList, DeclType, RD->field_begin(SemaRef.Context),
Douglas Gregorf603b472009-01-28 21:54:33 +0000572 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000573 StructuredList, StructuredIndex,
574 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000575 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000576 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000577 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000578 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000579 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
580 StructuredList, StructuredIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000581 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000582 else
Douglas Gregorf603b472009-01-28 21:54:33 +0000583 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000584 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
585 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000586 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000587 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000588 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000589 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000590 } else if (DeclType->isRecordType()) {
591 // C++ [dcl.init]p14:
592 // [...] If the class is an aggregate (8.5.1), and the initializer
593 // is a brace-enclosed list, see 8.5.1.
594 //
595 // Note: 8.5.1 is handled below; here, we diagnose the case where
596 // we have an initializer list and a destination type that is not
597 // an aggregate.
598 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000599 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000600 << DeclType << IList->getSourceRange();
601 hadError = true;
602 } else if (DeclType->isReferenceType()) {
603 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000604 } else {
605 // In C, all types are either scalars or aggregates, but
606 // additional handling is needed here for C++ (and possibly others?).
607 assert(0 && "Unsupported initializer type");
608 }
609}
610
Eli Friedman683cedf2008-05-19 19:16:24 +0000611void InitListChecker::CheckSubElementType(InitListExpr *IList,
612 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000613 unsigned &Index,
614 InitListExpr *StructuredList,
615 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000616 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000617 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
618 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000619 unsigned newStructuredIndex = 0;
620 InitListExpr *newStructuredList
621 = getStructuredSubobjectInit(IList, Index, ElemType,
622 StructuredList, StructuredIndex,
623 SubInitList->getSourceRange());
624 CheckExplicitInitList(SubInitList, ElemType, newIndex,
625 newStructuredList, newStructuredIndex);
626 ++StructuredIndex;
627 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000628 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
629 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000630 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000631 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000632 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000633 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000634 } else if (ElemType->isReferenceType()) {
635 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000636 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000637 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000638 // C++ [dcl.init.aggr]p12:
639 // All implicit type conversions (clause 4) are considered when
640 // initializing the aggregate member with an ini- tializer from
641 // an initializer-list. If the initializer can initialize a
642 // member, the member is initialized. [...]
643 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000644 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000645 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000646 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000647 "initializing"))
648 hadError = true;
649 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
650 ++Index;
651 return;
652 }
653
654 // Fall through for subaggregate initialization
655 } else {
656 // C99 6.7.8p13:
657 //
658 // The initializer for a structure or union object that has
659 // automatic storage duration shall be either an initializer
660 // list as described below, or a single expression that has
661 // compatible structure or union type. In the latter case, the
662 // initial value of the object, including unnamed members, is
663 // that of the expression.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000664 QualType ExprType = SemaRef.Context.getCanonicalType(expr->getType());
665 QualType ElemTypeCanon = SemaRef.Context.getCanonicalType(ElemType);
666 if (SemaRef.Context.typesAreCompatible(ExprType.getUnqualifiedType(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000667 ElemTypeCanon.getUnqualifiedType())) {
668 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
669 ++Index;
670 return;
671 }
672
673 // Fall through for subaggregate initialization
674 }
675
676 // C++ [dcl.init.aggr]p12:
677 //
678 // [...] Otherwise, if the member is itself a non-empty
679 // subaggregate, brace elision is assumed and the initializer is
680 // considered for the initialization of the first member of
681 // the subaggregate.
682 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
683 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
684 StructuredIndex);
685 ++StructuredIndex;
686 } else {
687 // We cannot initialize this element, so let
688 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000689 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000690 hadError = true;
691 ++Index;
692 ++StructuredIndex;
693 }
694 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000695}
696
Douglas Gregord45210d2009-01-30 22:09:00 +0000697void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000698 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000699 InitListExpr *StructuredList,
700 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000701 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000702 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000703 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000704 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000705 diag::err_many_braces_around_scalar_init)
706 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000707 hadError = true;
708 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000709 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000710 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000711 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000712 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000713 diag::err_designator_for_scalar_init)
714 << DeclType << expr->getSourceRange();
715 hadError = true;
716 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000717 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000718 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000719 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000720
Eli Friedmand8535af2008-05-19 20:00:43 +0000721 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000722 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000723 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000724 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000725 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000726 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000727 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000728 if (hadError)
729 ++StructuredIndex;
730 else
731 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000732 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000733 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000734 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000735 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000736 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000737 ++Index;
738 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000739 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000740 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000741}
742
Douglas Gregord45210d2009-01-30 22:09:00 +0000743void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
744 unsigned &Index,
745 InitListExpr *StructuredList,
746 unsigned &StructuredIndex) {
747 if (Index < IList->getNumInits()) {
748 Expr *expr = IList->getInit(Index);
749 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000750 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000751 << DeclType << IList->getSourceRange();
752 hadError = true;
753 ++Index;
754 ++StructuredIndex;
755 return;
756 }
757
758 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000759 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000760 hadError = true;
761 else if (savExpr != expr) {
762 // The type was promoted, update initializer list.
763 IList->setInit(Index, expr);
764 }
765 if (hadError)
766 ++StructuredIndex;
767 else
768 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
769 ++Index;
770 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000771 // FIXME: It would be wonderful if we could point at the actual member. In
772 // general, it would be useful to pass location information down the stack,
773 // so that we know the location (or decl) of the "current object" being
774 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000775 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000776 diag::err_init_reference_member_uninitialized)
777 << DeclType
778 << IList->getSourceRange();
779 hadError = true;
780 ++Index;
781 ++StructuredIndex;
782 return;
783 }
784}
785
Steve Naroffc4d4a482008-05-01 22:18:59 +0000786void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000787 unsigned &Index,
788 InitListExpr *StructuredList,
789 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000790 if (Index < IList->getNumInits()) {
791 const VectorType *VT = DeclType->getAsVectorType();
792 int maxElements = VT->getNumElements();
793 QualType elementType = VT->getElementType();
794
795 for (int i = 0; i < maxElements; ++i) {
796 // Don't attempt to go past the end of the init list
797 if (Index >= IList->getNumInits())
798 break;
Douglas Gregor36859eb2009-01-29 00:39:20 +0000799 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000800 StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000801 }
802 }
803}
804
805void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000806 llvm::APSInt elementIndex,
807 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000808 unsigned &Index,
809 InitListExpr *StructuredList,
810 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000811 // Check for the special-case of initializing an array with a string.
812 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000813 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
814 SemaRef.Context)) {
815 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000816 // We place the string literal directly into the resulting
817 // initializer list. This is the only place where the structure
818 // of the structured initializer list doesn't match exactly,
819 // because doing so would involve allocating one character
820 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000821 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000822 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000823 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000824 return;
825 }
826 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000827 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000828 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000829 // Check for VLAs; in standard C it would be possible to check this
830 // earlier, but I don't know where clang accepts VLAs (gcc accepts
831 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000832 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000833 diag::err_variable_object_no_init)
834 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000835 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000836 ++Index;
837 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000838 return;
839 }
840
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000841 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000842 llvm::APSInt maxElements(elementIndex.getBitWidth(),
843 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000844 bool maxElementsKnown = false;
845 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000846 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000847 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000848 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000849 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000850 maxElementsKnown = true;
851 }
852
Chris Lattner2e2766a2009-02-24 22:50:46 +0000853 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000854 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000855 while (Index < IList->getNumInits()) {
856 Expr *Init = IList->getInit(Index);
857 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000858 // If we're not the subobject that matches up with the '{' for
859 // the designator, we shouldn't be handling the
860 // designator. Return immediately.
861 if (!SubobjectIsDesignatorContext)
862 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000863
Douglas Gregor710f6d42009-01-22 23:26:18 +0000864 // Handle this designated initializer. elementIndex will be
865 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000866 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000867 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000868 StructuredList, StructuredIndex, true,
869 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000870 hadError = true;
871 continue;
872 }
873
Douglas Gregor5a203a62009-01-23 16:54:12 +0000874 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
875 maxElements.extend(elementIndex.getBitWidth());
876 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
877 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000878 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000879
Douglas Gregor710f6d42009-01-22 23:26:18 +0000880 // If the array is of incomplete type, keep track of the number of
881 // elements in the initializer.
882 if (!maxElementsKnown && elementIndex > maxElements)
883 maxElements = elementIndex;
884
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000885 continue;
886 }
887
888 // If we know the maximum number of elements, and we've already
889 // hit it, stop consuming elements in the initializer list.
890 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000891 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000892
893 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000894 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000895 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000896 ++elementIndex;
897
898 // If the array is of incomplete type, keep track of the number of
899 // elements in the initializer.
900 if (!maxElementsKnown && elementIndex > maxElements)
901 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000902 }
903 if (DeclType->isIncompleteArrayType()) {
904 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000905 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000906 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000907 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000908 // Sizing an array implicitly to zero is not allowed by ISO C,
909 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000910 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000911 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000912 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000913
Chris Lattner2e2766a2009-02-24 22:50:46 +0000914 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000915 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000916 }
917}
918
919void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
920 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000921 RecordDecl::field_iterator Field,
922 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000923 unsigned &Index,
924 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000925 unsigned &StructuredIndex,
926 bool TopLevelObject) {
Eli Friedman683cedf2008-05-19 19:16:24 +0000927 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000928
Eli Friedman683cedf2008-05-19 19:16:24 +0000929 // If the record is invalid, some of it's members are invalid. To avoid
930 // confusion, we forgo checking the intializer for the entire record.
931 if (structDecl->isInvalidDecl()) {
932 hadError = true;
933 return;
934 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000935
936 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
937 // Value-initialize the first named member of the union.
938 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000939 for (RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000940 Field != FieldEnd; ++Field) {
941 if (Field->getDeclName()) {
942 StructuredList->setInitializedFieldInUnion(*Field);
943 break;
944 }
945 }
946 return;
947 }
948
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000949 // If structDecl is a forward declaration, this loop won't do
950 // anything except look at designated initializers; That's okay,
951 // because an error should get printed out elsewhere. It might be
952 // worthwhile to skip over the rest of the initializer, though.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000953 RecordDecl *RD = DeclType->getAsRecordType()->getDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000954 RecordDecl::field_iterator FieldEnd = RD->field_end(SemaRef.Context);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000955 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000956 while (Index < IList->getNumInits()) {
957 Expr *Init = IList->getInit(Index);
958
959 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000960 // If we're not the subobject that matches up with the '{' for
961 // the designator, we shouldn't be handling the
962 // designator. Return immediately.
963 if (!SubobjectIsDesignatorContext)
964 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000965
Douglas Gregor710f6d42009-01-22 23:26:18 +0000966 // Handle this designated initializer. Field will be updated to
967 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +0000968 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000969 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000970 StructuredList, StructuredIndex,
971 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +0000972 hadError = true;
973
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000974 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000975 continue;
976 }
977
978 if (Field == FieldEnd) {
979 // We've run out of fields. We're done.
980 break;
981 }
982
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000983 // We've already initialized a member of a union. We're done.
984 if (InitializedSomething && DeclType->isUnionType())
985 break;
986
Douglas Gregor8acb7272008-12-11 16:49:14 +0000987 // If we've hit the flexible array member at the end, we're done.
988 if (Field->getType()->isIncompleteArrayType())
989 break;
990
Douglas Gregor82462762009-01-29 16:53:55 +0000991 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000992 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000993 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +0000994 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000995 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000996
Douglas Gregor36859eb2009-01-29 00:39:20 +0000997 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000998 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +0000999 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001000
1001 if (DeclType->isUnionType()) {
1002 // Initialize the first field within the union.
1003 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001004 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001005
1006 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001007 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001008
Douglas Gregorbe69b162009-02-04 22:46:25 +00001009 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001010 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001011 return;
1012
1013 // Handle GNU flexible array initializers.
1014 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001015 (!isa<InitListExpr>(IList->getInit(Index)) ||
1016 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001017 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001018 diag::err_flexible_array_init_nonempty)
1019 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001020 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001021 << *Field;
1022 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001023 ++Index;
1024 return;
1025 } else {
1026 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1027 diag::ext_flexible_array_init)
1028 << IList->getInit(Index)->getSourceRange().getBegin();
1029 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1030 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001031 }
1032
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001033 if (isa<InitListExpr>(IList->getInit(Index)))
1034 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1035 StructuredIndex);
1036 else
1037 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1038 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001039}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001040
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001041/// \brief Expand a field designator that refers to a member of an
1042/// anonymous struct or union into a series of field designators that
1043/// refers to the field within the appropriate subobject.
1044///
1045/// Field/FieldIndex will be updated to point to the (new)
1046/// currently-designated field.
1047static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1048 DesignatedInitExpr *DIE,
1049 unsigned DesigIdx,
1050 FieldDecl *Field,
1051 RecordDecl::field_iterator &FieldIter,
1052 unsigned &FieldIndex) {
1053 typedef DesignatedInitExpr::Designator Designator;
1054
1055 // Build the path from the current object to the member of the
1056 // anonymous struct/union (backwards).
1057 llvm::SmallVector<FieldDecl *, 4> Path;
1058 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1059
1060 // Build the replacement designators.
1061 llvm::SmallVector<Designator, 4> Replacements;
1062 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1063 FI = Path.rbegin(), FIEnd = Path.rend();
1064 FI != FIEnd; ++FI) {
1065 if (FI + 1 == FIEnd)
1066 Replacements.push_back(Designator((IdentifierInfo *)0,
1067 DIE->getDesignator(DesigIdx)->getDotLoc(),
1068 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1069 else
1070 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1071 SourceLocation()));
1072 Replacements.back().setField(*FI);
1073 }
1074
1075 // Expand the current designator into the set of replacement
1076 // designators, so we have a full subobject path down to where the
1077 // member of the anonymous struct/union is actually stored.
1078 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1079 &Replacements[0] + Replacements.size());
1080
1081 // Update FieldIter/FieldIndex;
1082 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1083 FieldIter = Record->field_begin(SemaRef.Context);
1084 FieldIndex = 0;
1085 for (RecordDecl::field_iterator FEnd = Record->field_end(SemaRef.Context);
1086 FieldIter != FEnd; ++FieldIter) {
1087 if (FieldIter->isUnnamedBitfield())
1088 continue;
1089
1090 if (*FieldIter == Path.back())
1091 return;
1092
1093 ++FieldIndex;
1094 }
1095
1096 assert(false && "Unable to find anonymous struct/union field");
1097}
1098
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001099/// @brief Check the well-formedness of a C99 designated initializer.
1100///
1101/// Determines whether the designated initializer @p DIE, which
1102/// resides at the given @p Index within the initializer list @p
1103/// IList, is well-formed for a current object of type @p DeclType
1104/// (C99 6.7.8). The actual subobject that this designator refers to
1105/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001106/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001107///
1108/// @param IList The initializer list in which this designated
1109/// initializer occurs.
1110///
Douglas Gregoraa357272009-04-15 04:56:10 +00001111/// @param DIE The designated initializer expression.
1112///
1113/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001114///
1115/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1116/// into which the designation in @p DIE should refer.
1117///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001118/// @param NextField If non-NULL and the first designator in @p DIE is
1119/// a field, this will be set to the field declaration corresponding
1120/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001121///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001122/// @param NextElementIndex If non-NULL and the first designator in @p
1123/// DIE is an array designator or GNU array-range designator, this
1124/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001125///
1126/// @param Index Index into @p IList where the designated initializer
1127/// @p DIE occurs.
1128///
Douglas Gregorf603b472009-01-28 21:54:33 +00001129/// @param StructuredList The initializer list expression that
1130/// describes all of the subobject initializers in the order they'll
1131/// actually be initialized.
1132///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001133/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001134bool
1135InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1136 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001137 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001138 QualType &CurrentObjectType,
1139 RecordDecl::field_iterator *NextField,
1140 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001141 unsigned &Index,
1142 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001143 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001144 bool FinishSubobjectInit,
1145 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001146 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001147 // Check the actual initialization for the designated object type.
1148 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001149
1150 // Temporarily remove the designator expression from the
1151 // initializer list that the child calls see, so that we don't try
1152 // to re-process the designator.
1153 unsigned OldIndex = Index;
1154 IList->setInit(OldIndex, DIE->getInit());
1155
1156 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001157 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001158
1159 // Restore the designated initializer expression in the syntactic
1160 // form of the initializer list.
1161 if (IList->getInit(OldIndex) != DIE->getInit())
1162 DIE->setInit(IList->getInit(OldIndex));
1163 IList->setInit(OldIndex, DIE);
1164
Douglas Gregor710f6d42009-01-22 23:26:18 +00001165 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001166 }
1167
Douglas Gregoraa357272009-04-15 04:56:10 +00001168 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001169 assert((IsFirstDesignator || StructuredList) &&
1170 "Need a non-designated initializer list to start from");
1171
Douglas Gregoraa357272009-04-15 04:56:10 +00001172 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001173 // Determine the structural initializer list that corresponds to the
1174 // current subobject.
1175 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001176 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1177 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001178 SourceRange(D->getStartLocation(),
1179 DIE->getSourceRange().getEnd()));
1180 assert(StructuredList && "Expected a structured initializer list");
1181
Douglas Gregor710f6d42009-01-22 23:26:18 +00001182 if (D->isFieldDesignator()) {
1183 // C99 6.7.8p7:
1184 //
1185 // If a designator has the form
1186 //
1187 // . identifier
1188 //
1189 // then the current object (defined below) shall have
1190 // structure or union type and the identifier shall be the
1191 // name of a member of that type.
1192 const RecordType *RT = CurrentObjectType->getAsRecordType();
1193 if (!RT) {
1194 SourceLocation Loc = D->getDotLoc();
1195 if (Loc.isInvalid())
1196 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001197 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1198 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001199 ++Index;
1200 return true;
1201 }
1202
Douglas Gregorf603b472009-01-28 21:54:33 +00001203 // Note: we perform a linear search of the fields here, despite
1204 // the fact that we have a faster lookup method, because we always
1205 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001206 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001207 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001208 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001209 RecordDecl::field_iterator
1210 Field = RT->getDecl()->field_begin(SemaRef.Context),
1211 FieldEnd = RT->getDecl()->field_end(SemaRef.Context);
Douglas Gregorf603b472009-01-28 21:54:33 +00001212 for (; Field != FieldEnd; ++Field) {
1213 if (Field->isUnnamedBitfield())
1214 continue;
1215
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001216 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001217 break;
1218
1219 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001220 }
1221
Douglas Gregorf603b472009-01-28 21:54:33 +00001222 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001223 // There was no normal field in the struct with the designated
1224 // name. Perform another lookup for this name, which may find
1225 // something that we can't designate (e.g., a member function),
1226 // may find nothing, or may find a member of an anonymous
1227 // struct/union.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001228 DeclContext::lookup_result Lookup
1229 = RT->getDecl()->lookup(SemaRef.Context, FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001230 if (Lookup.first == Lookup.second) {
1231 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001232 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001233 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001234 ++Index;
1235 return true;
1236 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1237 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1238 ->isAnonymousStructOrUnion()) {
1239 // Handle an field designator that refers to a member of an
1240 // anonymous struct or union.
1241 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1242 cast<FieldDecl>(*Lookup.first),
1243 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001244 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001245 } else {
1246 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001247 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001248 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001249 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001250 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001251 ++Index;
1252 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001253 }
1254 } else if (!KnownField &&
1255 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001256 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001257 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1258 Field, FieldIndex);
1259 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001260 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001261
1262 // All of the fields of a union are located at the same place in
1263 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001264 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001265 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001266 StructuredList->setInitializedFieldInUnion(*Field);
1267 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001268
Douglas Gregor710f6d42009-01-22 23:26:18 +00001269 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001270 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001271
Douglas Gregorf603b472009-01-28 21:54:33 +00001272 // Make sure that our non-designated initializer list has space
1273 // for a subobject corresponding to this field.
1274 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001275 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001276
Douglas Gregorbe69b162009-02-04 22:46:25 +00001277 // This designator names a flexible array member.
1278 if (Field->getType()->isIncompleteArrayType()) {
1279 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001280 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001281 // We can't designate an object within the flexible array
1282 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001283 DesignatedInitExpr::Designator *NextD
1284 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001285 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001286 diag::err_designator_into_flexible_array_member)
1287 << SourceRange(NextD->getStartLocation(),
1288 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001289 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001290 << *Field;
1291 Invalid = true;
1292 }
1293
1294 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1295 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001296 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001297 diag::err_flexible_array_init_needs_braces)
1298 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001299 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001300 << *Field;
1301 Invalid = true;
1302 }
1303
1304 // Handle GNU flexible array initializers.
1305 if (!Invalid && !TopLevelObject &&
1306 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001307 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001308 diag::err_flexible_array_init_nonempty)
1309 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001310 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001311 << *Field;
1312 Invalid = true;
1313 }
1314
1315 if (Invalid) {
1316 ++Index;
1317 return true;
1318 }
1319
1320 // Initialize the array.
1321 bool prevHadError = hadError;
1322 unsigned newStructuredIndex = FieldIndex;
1323 unsigned OldIndex = Index;
1324 IList->setInit(Index, DIE->getInit());
1325 CheckSubElementType(IList, Field->getType(), Index,
1326 StructuredList, newStructuredIndex);
1327 IList->setInit(OldIndex, DIE);
1328 if (hadError && !prevHadError) {
1329 ++Field;
1330 ++FieldIndex;
1331 if (NextField)
1332 *NextField = Field;
1333 StructuredIndex = FieldIndex;
1334 return true;
1335 }
1336 } else {
1337 // Recurse to check later designated subobjects.
1338 QualType FieldType = (*Field)->getType();
1339 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001340 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1341 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001342 true, false))
1343 return true;
1344 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001345
1346 // Find the position of the next field to be initialized in this
1347 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001348 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001349 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001350
1351 // If this the first designator, our caller will continue checking
1352 // the rest of this struct/class/union subobject.
1353 if (IsFirstDesignator) {
1354 if (NextField)
1355 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001356 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001357 return false;
1358 }
1359
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001360 if (!FinishSubobjectInit)
1361 return false;
1362
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001363 // We've already initialized something in the union; we're done.
1364 if (RT->getDecl()->isUnion())
1365 return hadError;
1366
Douglas Gregor710f6d42009-01-22 23:26:18 +00001367 // Check the remaining fields within this class/struct/union subobject.
1368 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001369 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1370 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001371 return hadError && !prevHadError;
1372 }
1373
1374 // C99 6.7.8p6:
1375 //
1376 // If a designator has the form
1377 //
1378 // [ constant-expression ]
1379 //
1380 // then the current object (defined below) shall have array
1381 // type and the expression shall be an integer constant
1382 // expression. If the array is of unknown size, any
1383 // nonnegative value is valid.
1384 //
1385 // Additionally, cope with the GNU extension that permits
1386 // designators of the form
1387 //
1388 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001389 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001390 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001391 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001392 << CurrentObjectType;
1393 ++Index;
1394 return true;
1395 }
1396
1397 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001398 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1399 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001400 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001401 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001402 DesignatedEndIndex = DesignatedStartIndex;
1403 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001404 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001405
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001406
Chris Lattnereec8ae22009-04-25 21:59:05 +00001407 DesignatedStartIndex =
1408 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1409 DesignatedEndIndex =
1410 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001411 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001412
Chris Lattnereec8ae22009-04-25 21:59:05 +00001413 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001414 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001415 }
1416
Douglas Gregor710f6d42009-01-22 23:26:18 +00001417 if (isa<ConstantArrayType>(AT)) {
1418 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001419 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1420 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1421 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1422 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1423 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001424 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001425 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001426 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001427 << IndexExpr->getSourceRange();
1428 ++Index;
1429 return true;
1430 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001431 } else {
1432 // Make sure the bit-widths and signedness match.
1433 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1434 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001435 else if (DesignatedStartIndex.getBitWidth() <
1436 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001437 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1438 DesignatedStartIndex.setIsUnsigned(true);
1439 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001440 }
1441
Douglas Gregorf603b472009-01-28 21:54:33 +00001442 // Make sure that our non-designated initializer list has space
1443 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001444 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001445 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001446 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001447
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001448 // Repeatedly perform subobject initializations in the range
1449 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001450
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001451 // Move to the next designator
1452 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1453 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001454 while (DesignatedStartIndex <= DesignatedEndIndex) {
1455 // Recurse to check later designated subobjects.
1456 QualType ElementType = AT->getElementType();
1457 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001458 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1459 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001460 (DesignatedStartIndex == DesignatedEndIndex),
1461 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001462 return true;
1463
1464 // Move to the next index in the array that we'll be initializing.
1465 ++DesignatedStartIndex;
1466 ElementIndex = DesignatedStartIndex.getZExtValue();
1467 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001468
1469 // If this the first designator, our caller will continue checking
1470 // the rest of this array subobject.
1471 if (IsFirstDesignator) {
1472 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001473 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001474 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001475 return false;
1476 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001477
1478 if (!FinishSubobjectInit)
1479 return false;
1480
Douglas Gregor710f6d42009-01-22 23:26:18 +00001481 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001482 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001483 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001484 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001485 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001486}
1487
Douglas Gregorf603b472009-01-28 21:54:33 +00001488// Get the structured initializer list for a subobject of type
1489// @p CurrentObjectType.
1490InitListExpr *
1491InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1492 QualType CurrentObjectType,
1493 InitListExpr *StructuredList,
1494 unsigned StructuredIndex,
1495 SourceRange InitRange) {
1496 Expr *ExistingInit = 0;
1497 if (!StructuredList)
1498 ExistingInit = SyntacticToSemantic[IList];
1499 else if (StructuredIndex < StructuredList->getNumInits())
1500 ExistingInit = StructuredList->getInit(StructuredIndex);
1501
1502 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1503 return Result;
1504
1505 if (ExistingInit) {
1506 // We are creating an initializer list that initializes the
1507 // subobjects of the current object, but there was already an
1508 // initialization that completely initialized the current
1509 // subobject, e.g., by a compound literal:
1510 //
1511 // struct X { int a, b; };
1512 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1513 //
1514 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1515 // designated initializer re-initializes the whole
1516 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001517 SemaRef.Diag(InitRange.getBegin(),
1518 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001519 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001520 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001521 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001522 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001523 << ExistingInit->getSourceRange();
1524 }
1525
1526 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001527 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1528 InitRange.getEnd());
1529
Douglas Gregorf603b472009-01-28 21:54:33 +00001530 Result->setType(CurrentObjectType);
1531
Douglas Gregoree0792c2009-03-20 23:58:33 +00001532 // Pre-allocate storage for the structured initializer list.
1533 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001534 unsigned NumInits = 0;
1535 if (!StructuredList)
1536 NumInits = IList->getNumInits();
1537 else if (Index < IList->getNumInits()) {
1538 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1539 NumInits = SubList->getNumInits();
1540 }
1541
Douglas Gregoree0792c2009-03-20 23:58:33 +00001542 if (const ArrayType *AType
1543 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1544 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1545 NumElements = CAType->getSize().getZExtValue();
1546 // Simple heuristic so that we don't allocate a very large
1547 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001548 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001549 NumElements = 0;
1550 }
1551 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1552 NumElements = VType->getNumElements();
1553 else if (const RecordType *RType = CurrentObjectType->getAsRecordType()) {
1554 RecordDecl *RDecl = RType->getDecl();
1555 if (RDecl->isUnion())
1556 NumElements = 1;
1557 else
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001558 NumElements = std::distance(RDecl->field_begin(SemaRef.Context),
1559 RDecl->field_end(SemaRef.Context));
Douglas Gregoree0792c2009-03-20 23:58:33 +00001560 }
1561
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001562 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001563 NumElements = IList->getNumInits();
1564
1565 Result->reserveInits(NumElements);
1566
Douglas Gregorf603b472009-01-28 21:54:33 +00001567 // Link this new initializer list into the structured initializer
1568 // lists.
1569 if (StructuredList)
1570 StructuredList->updateInit(StructuredIndex, Result);
1571 else {
1572 Result->setSyntacticForm(IList);
1573 SyntacticToSemantic[IList] = Result;
1574 }
1575
1576 return Result;
1577}
1578
1579/// Update the initializer at index @p StructuredIndex within the
1580/// structured initializer list to the value @p expr.
1581void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1582 unsigned &StructuredIndex,
1583 Expr *expr) {
1584 // No structured initializer list to update
1585 if (!StructuredList)
1586 return;
1587
1588 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1589 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001590 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001591 diag::warn_initializer_overrides)
1592 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001593 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001594 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001595 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001596 << PrevInit->getSourceRange();
1597 }
1598
1599 ++StructuredIndex;
1600}
1601
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001602/// Check that the given Index expression is a valid array designator
1603/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001604/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001605/// and produces a reasonable diagnostic if there is a
1606/// failure. Returns true if there was an error, false otherwise. If
1607/// everything went okay, Value will receive the value of the constant
1608/// expression.
1609static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001610CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001611 SourceLocation Loc = Index->getSourceRange().getBegin();
1612
1613 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001614 if (S.VerifyIntegerConstantExpression(Index, &Value))
1615 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001616
Chris Lattnereec8ae22009-04-25 21:59:05 +00001617 if (Value.isSigned() && Value.isNegative())
1618 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001619 << Value.toString(10) << Index->getSourceRange();
1620
Douglas Gregore498e372009-01-23 21:04:18 +00001621 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001622 return false;
1623}
1624
1625Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1626 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001627 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001628 OwningExprResult Init) {
1629 typedef DesignatedInitExpr::Designator ASTDesignator;
1630
1631 bool Invalid = false;
1632 llvm::SmallVector<ASTDesignator, 32> Designators;
1633 llvm::SmallVector<Expr *, 32> InitExpressions;
1634
1635 // Build designators and check array designator expressions.
1636 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1637 const Designator &D = Desig.getDesignator(Idx);
1638 switch (D.getKind()) {
1639 case Designator::FieldDesignator:
1640 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1641 D.getFieldLoc()));
1642 break;
1643
1644 case Designator::ArrayDesignator: {
1645 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1646 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001647 if (!Index->isTypeDependent() &&
1648 !Index->isValueDependent() &&
1649 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001650 Invalid = true;
1651 else {
1652 Designators.push_back(ASTDesignator(InitExpressions.size(),
1653 D.getLBracketLoc(),
1654 D.getRBracketLoc()));
1655 InitExpressions.push_back(Index);
1656 }
1657 break;
1658 }
1659
1660 case Designator::ArrayRangeDesignator: {
1661 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1662 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1663 llvm::APSInt StartValue;
1664 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001665 bool StartDependent = StartIndex->isTypeDependent() ||
1666 StartIndex->isValueDependent();
1667 bool EndDependent = EndIndex->isTypeDependent() ||
1668 EndIndex->isValueDependent();
1669 if ((!StartDependent &&
1670 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1671 (!EndDependent &&
1672 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001673 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001674 else {
1675 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001676 if (StartDependent || EndDependent) {
1677 // Nothing to compute.
1678 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001679 EndValue.extend(StartValue.getBitWidth());
1680 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1681 StartValue.extend(EndValue.getBitWidth());
1682
Douglas Gregor1401c062009-05-21 23:30:39 +00001683 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001684 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1685 << StartValue.toString(10) << EndValue.toString(10)
1686 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1687 Invalid = true;
1688 } else {
1689 Designators.push_back(ASTDesignator(InitExpressions.size(),
1690 D.getLBracketLoc(),
1691 D.getEllipsisLoc(),
1692 D.getRBracketLoc()));
1693 InitExpressions.push_back(StartIndex);
1694 InitExpressions.push_back(EndIndex);
1695 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001696 }
1697 break;
1698 }
1699 }
1700 }
1701
1702 if (Invalid || Init.isInvalid())
1703 return ExprError();
1704
1705 // Clear out the expressions within the designation.
1706 Desig.ClearExprs(*this);
1707
1708 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001709 = DesignatedInitExpr::Create(Context,
1710 Designators.data(), Designators.size(),
1711 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001712 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001713 return Owned(DIE);
1714}
Douglas Gregor849afc32009-01-29 00:45:39 +00001715
1716bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001717 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001718 if (!CheckInitList.HadError())
1719 InitList = CheckInitList.getFullyStructuredList();
1720
1721 return CheckInitList.HadError();
1722}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001723
1724/// \brief Diagnose any semantic errors with value-initialization of
1725/// the given type.
1726///
1727/// Value-initialization effectively zero-initializes any types
1728/// without user-declared constructors, and calls the default
1729/// constructor for a for any type that has a user-declared
1730/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1731/// a type with a user-declared constructor does not have an
1732/// accessible, non-deleted default constructor. In C, everything can
1733/// be value-initialized, which corresponds to C's notion of
1734/// initializing objects with static storage duration when no
1735/// initializer is provided for that object.
1736///
1737/// \returns true if there was an error, false otherwise.
1738bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1739 // C++ [dcl.init]p5:
1740 //
1741 // To value-initialize an object of type T means:
1742
1743 // -- if T is an array type, then each element is value-initialized;
1744 if (const ArrayType *AT = Context.getAsArrayType(Type))
1745 return CheckValueInitialization(AT->getElementType(), Loc);
1746
1747 if (const RecordType *RT = Type->getAsRecordType()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001748 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001749 // -- if T is a class type (clause 9) with a user-declared
1750 // constructor (12.1), then the default constructor for T is
1751 // called (and the initialization is ill-formed if T has no
1752 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001753 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001754 // FIXME: Eventually, we'll need to put the constructor decl into the
1755 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001756 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1757 SourceRange(Loc),
1758 DeclarationName(),
1759 IK_Direct);
1760 }
1761 }
1762
1763 if (Type->isReferenceType()) {
1764 // C++ [dcl.init]p5:
1765 // [...] A program that calls for default-initialization or
1766 // value-initialization of an entity of reference type is
1767 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001768 // FIXME: Once we have code that goes through this path, add an actual
1769 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001770 }
1771
1772 return false;
1773}