blob: f545db83f62271a8e44a7a830aea8af1025e5a54 [file] [log] [blame]
Steve Naroffc4d4a482008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd3a00502009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattnere76e9bf2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroffc4d4a482008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroffc4d4a482008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
Anders Carlsson73bb5e62009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner19ae2fc2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregor849afc32009-01-29 00:45:39 +000023#include <map>
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +000024using namespace clang;
Steve Naroffc4d4a482008-05-01 22:18:59 +000025
Chris Lattnerd3a00502009-02-24 22:27:37 +000026//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
Chris Lattner19ae2fc2009-02-24 23:10:27 +000030static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner7a7c1452009-02-26 23:26:43 +000031 const ArrayType *AT = Context.getAsArrayType(DeclType);
32 if (!AT) return 0;
33
Eli Friedman95acf982009-05-29 18:22:49 +000034 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
35 return 0;
36
Chris Lattner7a7c1452009-02-26 23:26:43 +000037 // See if this is a string literal or @encode.
38 Init = Init->IgnoreParens();
39
40 // Handle @encode, which is a narrow string.
41 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
42 return Init;
43
44 // Otherwise we can only handle string literals.
45 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattnerff065f72009-02-26 23:42:47 +000046 if (SL == 0) return 0;
Eli Friedmand16b0892009-05-31 10:54:53 +000047
48 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner7a7c1452009-02-26 23:26:43 +000049 // char array can be initialized with a narrow string.
50 // Only allow char x[] = "foo"; not char x[] = L"foo";
51 if (!SL->isWide())
Eli Friedmand16b0892009-05-31 10:54:53 +000052 return ElemTy->isCharType() ? Init : 0;
Chris Lattner7a7c1452009-02-26 23:26:43 +000053
Eli Friedmand16b0892009-05-31 10:54:53 +000054 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
55 // correction from DR343): "An array with element type compatible with a
56 // qualified or unqualified version of wchar_t may be initialized by a wide
57 // string literal, optionally enclosed in braces."
58 if (Context.typesAreCompatible(Context.getWCharType(),
59 ElemTy.getUnqualifiedType()))
Chris Lattner7a7c1452009-02-26 23:26:43 +000060 return Init;
61
Chris Lattnerd3a00502009-02-24 22:27:37 +000062 return 0;
63}
64
Chris Lattner160da072009-02-24 22:46:58 +000065static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
66 bool DirectInit, Sema &S) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000067 // Get the type before calling CheckSingleAssignmentConstraints(), since
68 // it can promote the expression.
69 QualType InitType = Init->getType();
70
Chris Lattner160da072009-02-24 22:46:58 +000071 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerd3a00502009-02-24 22:27:37 +000072 // FIXME: I dislike this error message. A lot.
Chris Lattner160da072009-02-24 22:46:58 +000073 if (S.PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
74 return S.Diag(Init->getSourceRange().getBegin(),
75 diag::err_typecheck_convert_incompatible)
76 << DeclType << Init->getType() << "initializing"
77 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +000078 return false;
79 }
80
Chris Lattner160da072009-02-24 22:46:58 +000081 Sema::AssignConvertType ConvTy =
82 S.CheckSingleAssignmentConstraints(DeclType, Init);
83 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerd3a00502009-02-24 22:27:37 +000084 InitType, Init, "initializing");
85}
86
Chris Lattner19ae2fc2009-02-24 23:10:27 +000087static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
88 // Get the length of the string as parsed.
89 uint64_t StrLength =
90 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
91
Chris Lattnerd3a00502009-02-24 22:27:37 +000092
Chris Lattner19ae2fc2009-02-24 23:10:27 +000093 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +000094 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
95 // C99 6.7.8p14. We have an array of character type with unknown size
96 // being initialized to a string literal.
97 llvm::APSInt ConstVal(32);
Chris Lattnerd20fac42009-02-24 23:01:39 +000098 ConstVal = StrLength;
Chris Lattnerd3a00502009-02-24 22:27:37 +000099 // Return a new array type (C99 6.7.8p22).
Douglas Gregor1d381132009-07-06 15:59:29 +0000100 DeclT = S.Context.getConstantArrayWithoutExprType(IAT->getElementType(),
101 ConstVal,
102 ArrayType::Normal, 0);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000103 return;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000104 }
Chris Lattnerd20fac42009-02-24 23:01:39 +0000105
Eli Friedman95acf982009-05-29 18:22:49 +0000106 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
107
108 // C99 6.7.8p14. We have an array of character type with known size. However,
109 // the size may be smaller or larger than the string we are initializing.
110 // FIXME: Avoid truncation for 64-bit length strings.
111 if (StrLength-1 > CAT->getSize().getZExtValue())
112 S.Diag(Str->getSourceRange().getBegin(),
113 diag::warn_initializer_string_for_char_array_too_long)
114 << Str->getSourceRange();
115
116 // Set the type to the actual size that we are initializing. If we have
117 // something like:
118 // char x[1] = "foo";
119 // then this will set the string literal's type to char[1].
120 Str->setType(DeclT);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000121}
122
123bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
124 SourceLocation InitLoc,
Anders Carlsson8cc1f0d2009-05-30 20:41:30 +0000125 DeclarationName InitEntity, bool DirectInit) {
Douglas Gregor3a7a06e2009-05-21 23:17:49 +0000126 if (DeclType->isDependentType() ||
127 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerd3a00502009-02-24 22:27:37 +0000128 return false;
129
130 // C++ [dcl.init.ref]p1:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000131 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerd3a00502009-02-24 22:27:37 +0000132 // (8.3.2), shall be initialized by an object, or function, of
133 // type T or by an object that can be converted into a T.
134 if (DeclType->isReferenceType())
Anders Carlsson8f809f92009-08-27 17:30:43 +0000135 return CheckReferenceInit(Init, DeclType,
136 /*SuppressUserConversions=*/false,
137 /*AllowExplicit=*/DirectInit,
138 /*ForceRValue=*/false);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000139
140 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
141 // of unknown size ("[]") or an object type that is not a variable array type.
142 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
143 return Diag(InitLoc, diag::err_variable_object_no_init)
144 << VAT->getSizeExpr()->getSourceRange();
145
146 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
147 if (!InitList) {
148 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000149 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
150 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000151 return false;
152 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000153
154 // C++ [dcl.init]p14:
155 // -- If the destination type is a (possibly cv-qualified) class
156 // type:
157 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
158 QualType DeclTypeC = Context.getCanonicalType(DeclType);
159 QualType InitTypeC = Context.getCanonicalType(Init->getType());
160
161 // -- If the initialization is direct-initialization, or if it is
162 // copy-initialization where the cv-unqualified version of the
163 // source type is the same class as, or a derived class of, the
164 // class of the destination, constructors are considered.
165 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
166 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000167 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000168 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000169
170 // No need to make a CXXConstructExpr if both the ctor and dtor are
171 // trivial.
172 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
173 return false;
174
Chris Lattnerd3a00502009-02-24 22:27:37 +0000175 CXXConstructorDecl *Constructor
176 = PerformInitializationByConstructor(DeclType, &Init, 1,
177 InitLoc, Init->getSourceRange(),
178 InitEntity,
179 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000180 if (!Constructor)
181 return true;
Anders Carlsson665e4692009-08-25 05:12:04 +0000182
183 OwningExprResult InitResult =
184 BuildCXXConstructExpr(DeclType, Constructor, &Init, 1);
185 if (InitResult.isInvalid())
186 return true;
187
188 Init = InitResult.takeAs<Expr>();
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000189 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000190 }
191
192 // -- Otherwise (i.e., for the remaining copy-initialization
193 // cases), user-defined conversion sequences that can
194 // convert from the source type to the destination type or
195 // (when a conversion function is used) to a derived class
196 // thereof are enumerated as described in 13.3.1.4, and the
197 // best one is chosen through overload resolution
198 // (13.3). If the conversion cannot be done or is
199 // ambiguous, the initialization is ill-formed. The
200 // function selected is called with the initializer
201 // expression as its argument; if the function is a
202 // constructor, the call initializes a temporary of the
203 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000204 // FIXME: We're pretending to do copy elision here; return to this when we
205 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000206 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
207 return false;
208
209 if (InitEntity)
210 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000211 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
212 << Init->getType() << Init->getSourceRange();
213 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000214 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
215 << Init->getType() << Init->getSourceRange();
216 }
217
218 // C99 6.7.8p16.
219 if (DeclType->isArrayType())
220 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000221 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000222
Chris Lattner160da072009-02-24 22:46:58 +0000223 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000224 }
225
226 bool hadError = CheckInitList(InitList, DeclType);
227 Init = InitList;
228 return hadError;
229}
230
231//===----------------------------------------------------------------------===//
232// Semantic checking for initializer lists.
233//===----------------------------------------------------------------------===//
234
Douglas Gregoraaa20962009-01-29 01:05:33 +0000235/// @brief Semantic checking for initializer lists.
236///
237/// The InitListChecker class contains a set of routines that each
238/// handle the initialization of a certain kind of entity, e.g.,
239/// arrays, vectors, struct/union types, scalars, etc. The
240/// InitListChecker itself performs a recursive walk of the subobject
241/// structure of the type to be initialized, while stepping through
242/// the initializer list one element at a time. The IList and Index
243/// parameters to each of the Check* routines contain the active
244/// (syntactic) initializer list and the index into that initializer
245/// list that represents the current initializer. Each routine is
246/// responsible for moving that Index forward as it consumes elements.
247///
248/// Each Check* routine also has a StructuredList/StructuredIndex
249/// arguments, which contains the current the "structured" (semantic)
250/// initializer list and the index into that initializer list where we
251/// are copying initializers as we map them over to the semantic
252/// list. Once we have completed our recursive walk of the subobject
253/// structure, we will have constructed a full semantic initializer
254/// list.
255///
256/// C99 designators cause changes in the initializer list traversal,
257/// because they make the initialization "jump" into a specific
258/// subobject and then continue the initialization from that
259/// point. CheckDesignatedInitializer() recursively steps into the
260/// designated subobject and manages backing out the recursion to
261/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000262namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000263class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000264 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000265 bool hadError;
266 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
267 InitListExpr *FullyStructuredList;
268
269 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000270 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000271 unsigned &StructuredIndex,
272 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000273 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000274 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000275 unsigned &StructuredIndex,
276 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000277 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
278 bool SubobjectIsDesignatorContext,
279 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000280 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000281 unsigned &StructuredIndex,
282 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000283 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
284 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000285 InitListExpr *StructuredList,
286 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000287 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000288 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000289 InitListExpr *StructuredList,
290 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000291 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
292 unsigned &Index,
293 InitListExpr *StructuredList,
294 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000295 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000296 InitListExpr *StructuredList,
297 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000298 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
299 RecordDecl::field_iterator Field,
300 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000301 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000302 unsigned &StructuredIndex,
303 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000304 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
305 llvm::APSInt elementIndex,
306 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000309 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000310 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000311 QualType &CurrentObjectType,
312 RecordDecl::field_iterator *NextField,
313 llvm::APSInt *NextElementIndex,
314 unsigned &Index,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000317 bool FinishSubobjectInit,
318 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000319 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
320 QualType CurrentObjectType,
321 InitListExpr *StructuredList,
322 unsigned StructuredIndex,
323 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000324 void UpdateStructuredListElement(InitListExpr *StructuredList,
325 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000326 Expr *expr);
327 int numArrayElements(QualType DeclType);
328 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000329
330 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000331public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000332 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000333 bool HadError() { return hadError; }
334
335 // @brief Retrieves the fully-structured initializer list used for
336 // semantic analysis and code generation.
337 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
338};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000339} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000340
Douglas Gregorf603b472009-01-28 21:54:33 +0000341/// Recursively replaces NULL values within the given initializer list
342/// with expressions that perform value-initialization of the
343/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000344void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000345 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000346 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000347 SourceLocation Loc = ILE->getSourceRange().getBegin();
348 if (ILE->getSyntacticForm())
349 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
350
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000351 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000352 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000353 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000354 Field = RType->getDecl()->field_begin(),
355 FieldEnd = RType->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000356 Field != FieldEnd; ++Field) {
357 if (Field->isUnnamedBitfield())
358 continue;
359
Douglas Gregor538a4c22009-02-02 17:43:21 +0000360 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000361 if (Field->getType()->isReferenceType()) {
362 // C++ [dcl.init.aggr]p9:
363 // If an incomplete or empty initializer-list leaves a
364 // member of reference type uninitialized, the program is
365 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000366 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000367 << Field->getType()
368 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000369 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000370 diag::note_uninit_reference_member);
371 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000372 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000373 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000374 hadError = true;
375 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000376 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000377
Mike Stumpe127ae32009-05-16 07:39:55 +0000378 // FIXME: If value-initialization involves calling a constructor, should
379 // we make that call explicit in the representation (even when it means
380 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000381 if (Init < NumInits && !hadError)
382 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000383 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000384 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000385 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000386 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000387 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000388
389 // Only look at the first initialization of a union.
390 if (RType->getDecl()->isUnion())
391 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000392 }
393
394 return;
395 }
396
397 QualType ElementType;
398
Douglas Gregor538a4c22009-02-02 17:43:21 +0000399 unsigned NumInits = ILE->getNumInits();
400 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000401 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000402 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000403 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
404 NumElements = CAType->getSize().getZExtValue();
405 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000406 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000407 NumElements = VType->getNumElements();
408 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000409 ElementType = ILE->getType();
410
Douglas Gregor538a4c22009-02-02 17:43:21 +0000411 for (unsigned Init = 0; Init != NumElements; ++Init) {
412 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000413 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000414 hadError = true;
415 return;
416 }
417
Mike Stumpe127ae32009-05-16 07:39:55 +0000418 // FIXME: If value-initialization involves calling a constructor, should
419 // we make that call explicit in the representation (even when it means
420 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000421 if (Init < NumInits && !hadError)
422 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000423 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stump90fc78e2009-08-04 21:02:39 +0000424 } else if (InitListExpr *InnerILE
425 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000426 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000427 }
428}
429
Chris Lattner1aa25a72009-01-29 05:10:57 +0000430
Chris Lattner2e2766a2009-02-24 22:50:46 +0000431InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
432 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000433 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000434
Eli Friedman683cedf2008-05-19 19:16:24 +0000435 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000436 unsigned newStructuredIndex = 0;
437 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000438 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000439 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
440 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000441
Douglas Gregord45210d2009-01-30 22:09:00 +0000442 if (!hadError)
443 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000444}
445
446int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000447 // FIXME: use a proper constant
448 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000449 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000450 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000451 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
452 }
453 return maxElements;
454}
455
456int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000457 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000458 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000459 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000460 Field = structDecl->field_begin(),
461 FieldEnd = structDecl->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000462 Field != FieldEnd; ++Field) {
463 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
464 ++InitializableMembers;
465 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000466 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000467 return std::min(InitializableMembers, 1);
468 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000469}
470
471void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000472 QualType T, unsigned &Index,
473 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000474 unsigned &StructuredIndex,
475 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000476 int maxElements = 0;
477
478 if (T->isArrayType())
479 maxElements = numArrayElements(T);
480 else if (T->isStructureType() || T->isUnionType())
481 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000482 else if (T->isVectorType())
483 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000484 else
485 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000486
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000487 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000488 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000489 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000490 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000491 hadError = true;
492 return;
493 }
494
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 // Build a structured initializer list corresponding to this subobject.
496 InitListExpr *StructuredSubobjectInitList
497 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
498 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000499 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
500 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000501 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000502
Douglas Gregorf603b472009-01-28 21:54:33 +0000503 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000504 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000505 CheckListElementTypes(ParentIList, T, false, Index,
506 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000507 StructuredSubobjectInitIndex,
508 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000509 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000510 StructuredSubobjectInitList->setType(T);
511
Douglas Gregorea765e12009-03-01 17:12:46 +0000512 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000513 // range corresponds with the end of the last initializer it used.
514 if (EndIndex < ParentIList->getNumInits()) {
515 SourceLocation EndLoc
516 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
517 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
518 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000519}
520
Steve Naroff56099522008-05-06 00:23:44 +0000521void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000522 unsigned &Index,
523 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000524 unsigned &StructuredIndex,
525 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000526 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000527 SyntacticToSemantic[IList] = StructuredList;
528 StructuredList->setSyntacticForm(IList);
529 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000530 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000531 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000532 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000533 if (hadError)
534 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000535
Eli Friedman46f81662008-05-25 13:22:35 +0000536 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000537 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000538 if (StructuredIndex == 1 &&
539 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000540 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000541 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000542 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000543 hadError = true;
544 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000545 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000546 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000547 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000548 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000549 // Don't complain for incomplete types, since we'll get an error
550 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000551 QualType CurrentObjectType = StructuredList->getType();
552 int initKind =
553 CurrentObjectType->isArrayType()? 0 :
554 CurrentObjectType->isVectorType()? 1 :
555 CurrentObjectType->isScalarType()? 2 :
556 CurrentObjectType->isUnionType()? 3 :
557 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000558
559 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000560 if (SemaRef.getLangOptions().CPlusPlus) {
561 DK = diag::err_excess_initializers;
562 hadError = true;
563 }
Nate Begeman48fd8c92009-07-07 21:53:06 +0000564 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
565 DK = diag::err_excess_initializers;
566 hadError = true;
567 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000568
Chris Lattner2e2766a2009-02-24 22:50:46 +0000569 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000570 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000571 }
572 }
Eli Friedman455f7622008-05-19 20:20:43 +0000573
Eli Friedman90bcb892009-05-16 11:45:48 +0000574 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000575 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000576 << IList->getSourceRange()
577 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
578 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000579}
580
Eli Friedman683cedf2008-05-19 19:16:24 +0000581void InitListChecker::CheckListElementTypes(InitListExpr *IList,
582 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000583 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000584 unsigned &Index,
585 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000586 unsigned &StructuredIndex,
587 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000588 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000589 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000590 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000591 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000595 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000602 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000603 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
604 StructuredList, StructuredIndex);
Mike Stump90fc78e2009-08-04 21:02:39 +0000605 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000606 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
608 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000609 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000611 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000612 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000613 } else if (DeclType->isRecordType()) {
614 // C++ [dcl.init]p14:
615 // [...] If the class is an aggregate (8.5.1), and the initializer
616 // is a brace-enclosed list, see 8.5.1.
617 //
618 // Note: 8.5.1 is handled below; here, we diagnose the case where
619 // we have an initializer list and a destination type that is not
620 // an aggregate.
621 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000623 << DeclType << IList->getSourceRange();
624 hadError = true;
625 } else if (DeclType->isReferenceType()) {
626 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000627 } else {
628 // In C, all types are either scalars or aggregates, but
629 // additional handling is needed here for C++ (and possibly others?).
630 assert(0 && "Unsupported initializer type");
631 }
632}
633
Eli Friedman683cedf2008-05-19 19:16:24 +0000634void InitListChecker::CheckSubElementType(InitListExpr *IList,
635 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000636 unsigned &Index,
637 InitListExpr *StructuredList,
638 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000639 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000640 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
641 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000642 unsigned newStructuredIndex = 0;
643 InitListExpr *newStructuredList
644 = getStructuredSubobjectInit(IList, Index, ElemType,
645 StructuredList, StructuredIndex,
646 SubInitList->getSourceRange());
647 CheckExplicitInitList(SubInitList, ElemType, newIndex,
648 newStructuredList, newStructuredIndex);
649 ++StructuredIndex;
650 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000651 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
652 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000653 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000654 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000655 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000656 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000657 } else if (ElemType->isReferenceType()) {
658 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000659 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000660 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000661 // C++ [dcl.init.aggr]p12:
662 // All implicit type conversions (clause 4) are considered when
663 // initializing the aggregate member with an ini- tializer from
664 // an initializer-list. If the initializer can initialize a
665 // member, the member is initialized. [...]
666 ImplicitConversionSequence ICS
Anders Carlsson06386552009-08-27 17:18:13 +0000667 = SemaRef.TryCopyInitialization(expr, ElemType,
668 /*SuppressUserConversions=*/false,
669 /*ForceRValue=*/false);
670
Douglas Gregord45210d2009-01-30 22:09:00 +0000671 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000672 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000673 "initializing"))
674 hadError = true;
675 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
676 ++Index;
677 return;
678 }
679
680 // Fall through for subaggregate initialization
681 } else {
682 // C99 6.7.8p13:
683 //
684 // The initializer for a structure or union object that has
685 // automatic storage duration shall be either an initializer
686 // list as described below, or a single expression that has
687 // compatible structure or union type. In the latter case, the
688 // initial value of the object, including unnamed members, is
689 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000690 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000691 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000692 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
693 ++Index;
694 return;
695 }
696
697 // Fall through for subaggregate initialization
698 }
699
700 // C++ [dcl.init.aggr]p12:
701 //
702 // [...] Otherwise, if the member is itself a non-empty
703 // subaggregate, brace elision is assumed and the initializer is
704 // considered for the initialization of the first member of
705 // the subaggregate.
706 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
707 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
708 StructuredIndex);
709 ++StructuredIndex;
710 } else {
711 // We cannot initialize this element, so let
712 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000713 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000714 hadError = true;
715 ++Index;
716 ++StructuredIndex;
717 }
718 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000719}
720
Douglas Gregord45210d2009-01-30 22:09:00 +0000721void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000722 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000723 InitListExpr *StructuredList,
724 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000725 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000726 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000727 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000728 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000729 diag::err_many_braces_around_scalar_init)
730 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000731 hadError = true;
732 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000733 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000734 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000735 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000736 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000737 diag::err_designator_for_scalar_init)
738 << DeclType << expr->getSourceRange();
739 hadError = true;
740 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000741 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000742 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000743 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000744
Eli Friedmand8535af2008-05-19 20:00:43 +0000745 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000746 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000747 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000748 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000749 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000750 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000751 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000752 if (hadError)
753 ++StructuredIndex;
754 else
755 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000756 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000757 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000758 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000759 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000760 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000761 ++Index;
762 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000763 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000764 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000765}
766
Douglas Gregord45210d2009-01-30 22:09:00 +0000767void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
768 unsigned &Index,
769 InitListExpr *StructuredList,
770 unsigned &StructuredIndex) {
771 if (Index < IList->getNumInits()) {
772 Expr *expr = IList->getInit(Index);
773 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000774 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000775 << DeclType << IList->getSourceRange();
776 hadError = true;
777 ++Index;
778 ++StructuredIndex;
779 return;
780 }
781
782 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson8f809f92009-08-27 17:30:43 +0000783 if (SemaRef.CheckReferenceInit(expr, DeclType,
784 /*SuppressUserConversions=*/false,
785 /*AllowExplicit=*/false,
786 /*ForceRValue=*/false))
Douglas Gregord45210d2009-01-30 22:09:00 +0000787 hadError = true;
788 else if (savExpr != expr) {
789 // The type was promoted, update initializer list.
790 IList->setInit(Index, expr);
791 }
792 if (hadError)
793 ++StructuredIndex;
794 else
795 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
796 ++Index;
797 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000798 // FIXME: It would be wonderful if we could point at the actual member. In
799 // general, it would be useful to pass location information down the stack,
800 // so that we know the location (or decl) of the "current object" being
801 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000802 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000803 diag::err_init_reference_member_uninitialized)
804 << DeclType
805 << IList->getSourceRange();
806 hadError = true;
807 ++Index;
808 ++StructuredIndex;
809 return;
810 }
811}
812
Steve Naroffc4d4a482008-05-01 22:18:59 +0000813void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000814 unsigned &Index,
815 InitListExpr *StructuredList,
816 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000817 if (Index < IList->getNumInits()) {
818 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000819 unsigned maxElements = VT->getNumElements();
820 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000821 QualType elementType = VT->getElementType();
822
Nate Begemane85f43d2009-08-10 23:49:36 +0000823 if (!SemaRef.getLangOptions().OpenCL) {
824 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
825 // Don't attempt to go past the end of the init list
826 if (Index >= IList->getNumInits())
827 break;
828 CheckSubElementType(IList, elementType, Index,
829 StructuredList, StructuredIndex);
830 }
831 } else {
832 // OpenCL initializers allows vectors to be constructed from vectors.
833 for (unsigned i = 0; i < maxElements; ++i) {
834 // Don't attempt to go past the end of the init list
835 if (Index >= IList->getNumInits())
836 break;
837 QualType IType = IList->getInit(Index)->getType();
838 if (!IType->isVectorType()) {
839 CheckSubElementType(IList, elementType, Index,
840 StructuredList, StructuredIndex);
841 ++numEltsInit;
842 } else {
843 const VectorType *IVT = IType->getAsVectorType();
844 unsigned numIElts = IVT->getNumElements();
845 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
846 numIElts);
847 CheckSubElementType(IList, VecType, Index,
848 StructuredList, StructuredIndex);
849 numEltsInit += numIElts;
850 }
851 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000852 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000853
854 // OpenCL & AltiVec require all elements to be initialized.
855 if (numEltsInit != maxElements)
856 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
857 SemaRef.Diag(IList->getSourceRange().getBegin(),
858 diag::err_vector_incorrect_num_initializers)
859 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000860 }
861}
862
863void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000864 llvm::APSInt elementIndex,
865 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000866 unsigned &Index,
867 InitListExpr *StructuredList,
868 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000869 // Check for the special-case of initializing an array with a string.
870 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000871 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
872 SemaRef.Context)) {
873 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000874 // We place the string literal directly into the resulting
875 // initializer list. This is the only place where the structure
876 // of the structured initializer list doesn't match exactly,
877 // because doing so would involve allocating one character
878 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000879 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000880 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000881 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000882 return;
883 }
884 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000885 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000886 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000887 // Check for VLAs; in standard C it would be possible to check this
888 // earlier, but I don't know where clang accepts VLAs (gcc accepts
889 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000890 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000891 diag::err_variable_object_no_init)
892 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000893 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000894 ++Index;
895 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000896 return;
897 }
898
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000899 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000900 llvm::APSInt maxElements(elementIndex.getBitWidth(),
901 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000902 bool maxElementsKnown = false;
903 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000904 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000905 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000906 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000907 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000908 maxElementsKnown = true;
909 }
910
Chris Lattner2e2766a2009-02-24 22:50:46 +0000911 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000912 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000913 while (Index < IList->getNumInits()) {
914 Expr *Init = IList->getInit(Index);
915 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000916 // If we're not the subobject that matches up with the '{' for
917 // the designator, we shouldn't be handling the
918 // designator. Return immediately.
919 if (!SubobjectIsDesignatorContext)
920 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000921
Douglas Gregor710f6d42009-01-22 23:26:18 +0000922 // Handle this designated initializer. elementIndex will be
923 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000924 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000925 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000926 StructuredList, StructuredIndex, true,
927 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000928 hadError = true;
929 continue;
930 }
931
Douglas Gregor5a203a62009-01-23 16:54:12 +0000932 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
933 maxElements.extend(elementIndex.getBitWidth());
934 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
935 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000936 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000937
Douglas Gregor710f6d42009-01-22 23:26:18 +0000938 // If the array is of incomplete type, keep track of the number of
939 // elements in the initializer.
940 if (!maxElementsKnown && elementIndex > maxElements)
941 maxElements = elementIndex;
942
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000943 continue;
944 }
945
946 // If we know the maximum number of elements, and we've already
947 // hit it, stop consuming elements in the initializer list.
948 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000949 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000950
951 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000952 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000953 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000954 ++elementIndex;
955
956 // If the array is of incomplete type, keep track of the number of
957 // elements in the initializer.
958 if (!maxElementsKnown && elementIndex > maxElements)
959 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000960 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000961 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000962 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000963 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000964 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000965 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000966 // Sizing an array implicitly to zero is not allowed by ISO C,
967 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000968 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000969 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000970 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000971
Chris Lattner2e2766a2009-02-24 22:50:46 +0000972 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000973 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000974 }
975}
976
977void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
978 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000979 RecordDecl::field_iterator Field,
980 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000981 unsigned &Index,
982 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000983 unsigned &StructuredIndex,
984 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000985 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000986
Eli Friedman683cedf2008-05-19 19:16:24 +0000987 // If the record is invalid, some of it's members are invalid. To avoid
988 // confusion, we forgo checking the intializer for the entire record.
989 if (structDecl->isInvalidDecl()) {
990 hadError = true;
991 return;
992 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000993
994 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
995 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000996 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000997 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000998 Field != FieldEnd; ++Field) {
999 if (Field->getDeclName()) {
1000 StructuredList->setInitializedFieldInUnion(*Field);
1001 break;
1002 }
1003 }
1004 return;
1005 }
1006
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001007 // If structDecl is a forward declaration, this loop won't do
1008 // anything except look at designated initializers; That's okay,
1009 // because an error should get printed out elsewhere. It might be
1010 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001011 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001012 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001013 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001014 while (Index < IList->getNumInits()) {
1015 Expr *Init = IList->getInit(Index);
1016
1017 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001018 // If we're not the subobject that matches up with the '{' for
1019 // the designator, we shouldn't be handling the
1020 // designator. Return immediately.
1021 if (!SubobjectIsDesignatorContext)
1022 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001023
Douglas Gregor710f6d42009-01-22 23:26:18 +00001024 // Handle this designated initializer. Field will be updated to
1025 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001026 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001027 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001028 StructuredList, StructuredIndex,
1029 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001030 hadError = true;
1031
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001032 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001033 continue;
1034 }
1035
1036 if (Field == FieldEnd) {
1037 // We've run out of fields. We're done.
1038 break;
1039 }
1040
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001041 // We've already initialized a member of a union. We're done.
1042 if (InitializedSomething && DeclType->isUnionType())
1043 break;
1044
Douglas Gregor8acb7272008-12-11 16:49:14 +00001045 // If we've hit the flexible array member at the end, we're done.
1046 if (Field->getType()->isIncompleteArrayType())
1047 break;
1048
Douglas Gregor82462762009-01-29 16:53:55 +00001049 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001050 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001051 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001052 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001053 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001054
Douglas Gregor36859eb2009-01-29 00:39:20 +00001055 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001056 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001057 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001058
1059 if (DeclType->isUnionType()) {
1060 // Initialize the first field within the union.
1061 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001062 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001063
1064 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001065 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001066
Douglas Gregorbe69b162009-02-04 22:46:25 +00001067 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001068 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001069 return;
1070
1071 // Handle GNU flexible array initializers.
1072 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001073 (!isa<InitListExpr>(IList->getInit(Index)) ||
1074 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001075 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001076 diag::err_flexible_array_init_nonempty)
1077 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001078 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001079 << *Field;
1080 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001081 ++Index;
1082 return;
1083 } else {
1084 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1085 diag::ext_flexible_array_init)
1086 << IList->getInit(Index)->getSourceRange().getBegin();
1087 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1088 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001089 }
1090
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001091 if (isa<InitListExpr>(IList->getInit(Index)))
1092 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1093 StructuredIndex);
1094 else
1095 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1096 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001097}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001098
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001099/// \brief Expand a field designator that refers to a member of an
1100/// anonymous struct or union into a series of field designators that
1101/// refers to the field within the appropriate subobject.
1102///
1103/// Field/FieldIndex will be updated to point to the (new)
1104/// currently-designated field.
1105static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1106 DesignatedInitExpr *DIE,
1107 unsigned DesigIdx,
1108 FieldDecl *Field,
1109 RecordDecl::field_iterator &FieldIter,
1110 unsigned &FieldIndex) {
1111 typedef DesignatedInitExpr::Designator Designator;
1112
1113 // Build the path from the current object to the member of the
1114 // anonymous struct/union (backwards).
1115 llvm::SmallVector<FieldDecl *, 4> Path;
1116 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1117
1118 // Build the replacement designators.
1119 llvm::SmallVector<Designator, 4> Replacements;
1120 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1121 FI = Path.rbegin(), FIEnd = Path.rend();
1122 FI != FIEnd; ++FI) {
1123 if (FI + 1 == FIEnd)
1124 Replacements.push_back(Designator((IdentifierInfo *)0,
1125 DIE->getDesignator(DesigIdx)->getDotLoc(),
1126 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1127 else
1128 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1129 SourceLocation()));
1130 Replacements.back().setField(*FI);
1131 }
1132
1133 // Expand the current designator into the set of replacement
1134 // designators, so we have a full subobject path down to where the
1135 // member of the anonymous struct/union is actually stored.
1136 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1137 &Replacements[0] + Replacements.size());
1138
1139 // Update FieldIter/FieldIndex;
1140 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001141 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001142 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001143 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001144 FieldIter != FEnd; ++FieldIter) {
1145 if (FieldIter->isUnnamedBitfield())
1146 continue;
1147
1148 if (*FieldIter == Path.back())
1149 return;
1150
1151 ++FieldIndex;
1152 }
1153
1154 assert(false && "Unable to find anonymous struct/union field");
1155}
1156
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001157/// @brief Check the well-formedness of a C99 designated initializer.
1158///
1159/// Determines whether the designated initializer @p DIE, which
1160/// resides at the given @p Index within the initializer list @p
1161/// IList, is well-formed for a current object of type @p DeclType
1162/// (C99 6.7.8). The actual subobject that this designator refers to
1163/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001164/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001165///
1166/// @param IList The initializer list in which this designated
1167/// initializer occurs.
1168///
Douglas Gregoraa357272009-04-15 04:56:10 +00001169/// @param DIE The designated initializer expression.
1170///
1171/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001172///
1173/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1174/// into which the designation in @p DIE should refer.
1175///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001176/// @param NextField If non-NULL and the first designator in @p DIE is
1177/// a field, this will be set to the field declaration corresponding
1178/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001179///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001180/// @param NextElementIndex If non-NULL and the first designator in @p
1181/// DIE is an array designator or GNU array-range designator, this
1182/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001183///
1184/// @param Index Index into @p IList where the designated initializer
1185/// @p DIE occurs.
1186///
Douglas Gregorf603b472009-01-28 21:54:33 +00001187/// @param StructuredList The initializer list expression that
1188/// describes all of the subobject initializers in the order they'll
1189/// actually be initialized.
1190///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001191/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001192bool
1193InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1194 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001195 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001196 QualType &CurrentObjectType,
1197 RecordDecl::field_iterator *NextField,
1198 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001199 unsigned &Index,
1200 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001201 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001202 bool FinishSubobjectInit,
1203 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001204 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001205 // Check the actual initialization for the designated object type.
1206 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001207
1208 // Temporarily remove the designator expression from the
1209 // initializer list that the child calls see, so that we don't try
1210 // to re-process the designator.
1211 unsigned OldIndex = Index;
1212 IList->setInit(OldIndex, DIE->getInit());
1213
1214 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001215 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001216
1217 // Restore the designated initializer expression in the syntactic
1218 // form of the initializer list.
1219 if (IList->getInit(OldIndex) != DIE->getInit())
1220 DIE->setInit(IList->getInit(OldIndex));
1221 IList->setInit(OldIndex, DIE);
1222
Douglas Gregor710f6d42009-01-22 23:26:18 +00001223 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001224 }
1225
Douglas Gregoraa357272009-04-15 04:56:10 +00001226 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001227 assert((IsFirstDesignator || StructuredList) &&
1228 "Need a non-designated initializer list to start from");
1229
Douglas Gregoraa357272009-04-15 04:56:10 +00001230 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001231 // Determine the structural initializer list that corresponds to the
1232 // current subobject.
1233 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001234 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1235 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001236 SourceRange(D->getStartLocation(),
1237 DIE->getSourceRange().getEnd()));
1238 assert(StructuredList && "Expected a structured initializer list");
1239
Douglas Gregor710f6d42009-01-22 23:26:18 +00001240 if (D->isFieldDesignator()) {
1241 // C99 6.7.8p7:
1242 //
1243 // If a designator has the form
1244 //
1245 // . identifier
1246 //
1247 // then the current object (defined below) shall have
1248 // structure or union type and the identifier shall be the
1249 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001250 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001251 if (!RT) {
1252 SourceLocation Loc = D->getDotLoc();
1253 if (Loc.isInvalid())
1254 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001255 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1256 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001257 ++Index;
1258 return true;
1259 }
1260
Douglas Gregorf603b472009-01-28 21:54:33 +00001261 // Note: we perform a linear search of the fields here, despite
1262 // the fact that we have a faster lookup method, because we always
1263 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001264 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001265 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001266 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001267 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001268 Field = RT->getDecl()->field_begin(),
1269 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001270 for (; Field != FieldEnd; ++Field) {
1271 if (Field->isUnnamedBitfield())
1272 continue;
1273
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001274 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001275 break;
1276
1277 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001278 }
1279
Douglas Gregorf603b472009-01-28 21:54:33 +00001280 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001281 // There was no normal field in the struct with the designated
1282 // name. Perform another lookup for this name, which may find
1283 // something that we can't designate (e.g., a member function),
1284 // may find nothing, or may find a member of an anonymous
1285 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001286 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001287 if (Lookup.first == Lookup.second) {
1288 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001289 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001290 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001291 ++Index;
1292 return true;
1293 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1294 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1295 ->isAnonymousStructOrUnion()) {
1296 // Handle an field designator that refers to a member of an
1297 // anonymous struct or union.
1298 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1299 cast<FieldDecl>(*Lookup.first),
1300 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001301 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001302 } else {
1303 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001304 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001305 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001306 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001307 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001308 ++Index;
1309 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001310 }
1311 } else if (!KnownField &&
1312 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001313 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001314 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1315 Field, FieldIndex);
1316 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001317 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001318
1319 // All of the fields of a union are located at the same place in
1320 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001321 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001322 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001323 StructuredList->setInitializedFieldInUnion(*Field);
1324 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001325
Douglas Gregor710f6d42009-01-22 23:26:18 +00001326 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001327 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001328
Douglas Gregorf603b472009-01-28 21:54:33 +00001329 // Make sure that our non-designated initializer list has space
1330 // for a subobject corresponding to this field.
1331 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001332 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001333
Douglas Gregorbe69b162009-02-04 22:46:25 +00001334 // This designator names a flexible array member.
1335 if (Field->getType()->isIncompleteArrayType()) {
1336 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001337 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001338 // We can't designate an object within the flexible array
1339 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001340 DesignatedInitExpr::Designator *NextD
1341 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001342 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001343 diag::err_designator_into_flexible_array_member)
1344 << SourceRange(NextD->getStartLocation(),
1345 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001346 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001347 << *Field;
1348 Invalid = true;
1349 }
1350
1351 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1352 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001353 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001354 diag::err_flexible_array_init_needs_braces)
1355 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001356 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001357 << *Field;
1358 Invalid = true;
1359 }
1360
1361 // Handle GNU flexible array initializers.
1362 if (!Invalid && !TopLevelObject &&
1363 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001364 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001365 diag::err_flexible_array_init_nonempty)
1366 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001367 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001368 << *Field;
1369 Invalid = true;
1370 }
1371
1372 if (Invalid) {
1373 ++Index;
1374 return true;
1375 }
1376
1377 // Initialize the array.
1378 bool prevHadError = hadError;
1379 unsigned newStructuredIndex = FieldIndex;
1380 unsigned OldIndex = Index;
1381 IList->setInit(Index, DIE->getInit());
1382 CheckSubElementType(IList, Field->getType(), Index,
1383 StructuredList, newStructuredIndex);
1384 IList->setInit(OldIndex, DIE);
1385 if (hadError && !prevHadError) {
1386 ++Field;
1387 ++FieldIndex;
1388 if (NextField)
1389 *NextField = Field;
1390 StructuredIndex = FieldIndex;
1391 return true;
1392 }
1393 } else {
1394 // Recurse to check later designated subobjects.
1395 QualType FieldType = (*Field)->getType();
1396 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001397 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1398 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001399 true, false))
1400 return true;
1401 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001402
1403 // Find the position of the next field to be initialized in this
1404 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001405 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001406 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001407
1408 // If this the first designator, our caller will continue checking
1409 // the rest of this struct/class/union subobject.
1410 if (IsFirstDesignator) {
1411 if (NextField)
1412 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001413 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001414 return false;
1415 }
1416
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001417 if (!FinishSubobjectInit)
1418 return false;
1419
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001420 // We've already initialized something in the union; we're done.
1421 if (RT->getDecl()->isUnion())
1422 return hadError;
1423
Douglas Gregor710f6d42009-01-22 23:26:18 +00001424 // Check the remaining fields within this class/struct/union subobject.
1425 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001426 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1427 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001428 return hadError && !prevHadError;
1429 }
1430
1431 // C99 6.7.8p6:
1432 //
1433 // If a designator has the form
1434 //
1435 // [ constant-expression ]
1436 //
1437 // then the current object (defined below) shall have array
1438 // type and the expression shall be an integer constant
1439 // expression. If the array is of unknown size, any
1440 // nonnegative value is valid.
1441 //
1442 // Additionally, cope with the GNU extension that permits
1443 // designators of the form
1444 //
1445 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001446 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001447 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001448 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001449 << CurrentObjectType;
1450 ++Index;
1451 return true;
1452 }
1453
1454 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001455 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1456 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001457 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001458 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001459 DesignatedEndIndex = DesignatedStartIndex;
1460 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001461 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001462
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001463
Chris Lattnereec8ae22009-04-25 21:59:05 +00001464 DesignatedStartIndex =
1465 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1466 DesignatedEndIndex =
1467 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001468 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001469
Chris Lattnereec8ae22009-04-25 21:59:05 +00001470 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001471 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001472 }
1473
Douglas Gregor710f6d42009-01-22 23:26:18 +00001474 if (isa<ConstantArrayType>(AT)) {
1475 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001476 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1477 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1478 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1479 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1480 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001481 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001482 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001483 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001484 << IndexExpr->getSourceRange();
1485 ++Index;
1486 return true;
1487 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001488 } else {
1489 // Make sure the bit-widths and signedness match.
1490 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1491 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001492 else if (DesignatedStartIndex.getBitWidth() <
1493 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001494 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1495 DesignatedStartIndex.setIsUnsigned(true);
1496 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001497 }
1498
Douglas Gregorf603b472009-01-28 21:54:33 +00001499 // Make sure that our non-designated initializer list has space
1500 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001501 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001502 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001503 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001504
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001505 // Repeatedly perform subobject initializations in the range
1506 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001507
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001508 // Move to the next designator
1509 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1510 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001511 while (DesignatedStartIndex <= DesignatedEndIndex) {
1512 // Recurse to check later designated subobjects.
1513 QualType ElementType = AT->getElementType();
1514 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001515 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1516 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001517 (DesignatedStartIndex == DesignatedEndIndex),
1518 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001519 return true;
1520
1521 // Move to the next index in the array that we'll be initializing.
1522 ++DesignatedStartIndex;
1523 ElementIndex = DesignatedStartIndex.getZExtValue();
1524 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001525
1526 // If this the first designator, our caller will continue checking
1527 // the rest of this array subobject.
1528 if (IsFirstDesignator) {
1529 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001530 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001531 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001532 return false;
1533 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001534
1535 if (!FinishSubobjectInit)
1536 return false;
1537
Douglas Gregor710f6d42009-01-22 23:26:18 +00001538 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001539 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001540 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001541 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001542 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001543}
1544
Douglas Gregorf603b472009-01-28 21:54:33 +00001545// Get the structured initializer list for a subobject of type
1546// @p CurrentObjectType.
1547InitListExpr *
1548InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1549 QualType CurrentObjectType,
1550 InitListExpr *StructuredList,
1551 unsigned StructuredIndex,
1552 SourceRange InitRange) {
1553 Expr *ExistingInit = 0;
1554 if (!StructuredList)
1555 ExistingInit = SyntacticToSemantic[IList];
1556 else if (StructuredIndex < StructuredList->getNumInits())
1557 ExistingInit = StructuredList->getInit(StructuredIndex);
1558
1559 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1560 return Result;
1561
1562 if (ExistingInit) {
1563 // We are creating an initializer list that initializes the
1564 // subobjects of the current object, but there was already an
1565 // initialization that completely initialized the current
1566 // subobject, e.g., by a compound literal:
1567 //
1568 // struct X { int a, b; };
1569 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1570 //
1571 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1572 // designated initializer re-initializes the whole
1573 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001574 SemaRef.Diag(InitRange.getBegin(),
1575 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001576 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001577 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001578 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001579 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001580 << ExistingInit->getSourceRange();
1581 }
1582
1583 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001584 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1585 InitRange.getEnd());
1586
Douglas Gregorf603b472009-01-28 21:54:33 +00001587 Result->setType(CurrentObjectType);
1588
Douglas Gregoree0792c2009-03-20 23:58:33 +00001589 // Pre-allocate storage for the structured initializer list.
1590 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001591 unsigned NumInits = 0;
1592 if (!StructuredList)
1593 NumInits = IList->getNumInits();
1594 else if (Index < IList->getNumInits()) {
1595 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1596 NumInits = SubList->getNumInits();
1597 }
1598
Douglas Gregoree0792c2009-03-20 23:58:33 +00001599 if (const ArrayType *AType
1600 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1601 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1602 NumElements = CAType->getSize().getZExtValue();
1603 // Simple heuristic so that we don't allocate a very large
1604 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001605 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001606 NumElements = 0;
1607 }
1608 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1609 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001610 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001611 RecordDecl *RDecl = RType->getDecl();
1612 if (RDecl->isUnion())
1613 NumElements = 1;
1614 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001615 NumElements = std::distance(RDecl->field_begin(),
1616 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001617 }
1618
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001619 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001620 NumElements = IList->getNumInits();
1621
1622 Result->reserveInits(NumElements);
1623
Douglas Gregorf603b472009-01-28 21:54:33 +00001624 // Link this new initializer list into the structured initializer
1625 // lists.
1626 if (StructuredList)
1627 StructuredList->updateInit(StructuredIndex, Result);
1628 else {
1629 Result->setSyntacticForm(IList);
1630 SyntacticToSemantic[IList] = Result;
1631 }
1632
1633 return Result;
1634}
1635
1636/// Update the initializer at index @p StructuredIndex within the
1637/// structured initializer list to the value @p expr.
1638void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1639 unsigned &StructuredIndex,
1640 Expr *expr) {
1641 // No structured initializer list to update
1642 if (!StructuredList)
1643 return;
1644
1645 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1646 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001647 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001648 diag::warn_initializer_overrides)
1649 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001650 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001651 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001652 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001653 << PrevInit->getSourceRange();
1654 }
1655
1656 ++StructuredIndex;
1657}
1658
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001659/// Check that the given Index expression is a valid array designator
1660/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001661/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001662/// and produces a reasonable diagnostic if there is a
1663/// failure. Returns true if there was an error, false otherwise. If
1664/// everything went okay, Value will receive the value of the constant
1665/// expression.
1666static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001667CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001668 SourceLocation Loc = Index->getSourceRange().getBegin();
1669
1670 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001671 if (S.VerifyIntegerConstantExpression(Index, &Value))
1672 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001673
Chris Lattnereec8ae22009-04-25 21:59:05 +00001674 if (Value.isSigned() && Value.isNegative())
1675 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001676 << Value.toString(10) << Index->getSourceRange();
1677
Douglas Gregore498e372009-01-23 21:04:18 +00001678 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001679 return false;
1680}
1681
1682Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1683 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001684 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001685 OwningExprResult Init) {
1686 typedef DesignatedInitExpr::Designator ASTDesignator;
1687
1688 bool Invalid = false;
1689 llvm::SmallVector<ASTDesignator, 32> Designators;
1690 llvm::SmallVector<Expr *, 32> InitExpressions;
1691
1692 // Build designators and check array designator expressions.
1693 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1694 const Designator &D = Desig.getDesignator(Idx);
1695 switch (D.getKind()) {
1696 case Designator::FieldDesignator:
1697 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1698 D.getFieldLoc()));
1699 break;
1700
1701 case Designator::ArrayDesignator: {
1702 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1703 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001704 if (!Index->isTypeDependent() &&
1705 !Index->isValueDependent() &&
1706 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001707 Invalid = true;
1708 else {
1709 Designators.push_back(ASTDesignator(InitExpressions.size(),
1710 D.getLBracketLoc(),
1711 D.getRBracketLoc()));
1712 InitExpressions.push_back(Index);
1713 }
1714 break;
1715 }
1716
1717 case Designator::ArrayRangeDesignator: {
1718 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1719 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1720 llvm::APSInt StartValue;
1721 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001722 bool StartDependent = StartIndex->isTypeDependent() ||
1723 StartIndex->isValueDependent();
1724 bool EndDependent = EndIndex->isTypeDependent() ||
1725 EndIndex->isValueDependent();
1726 if ((!StartDependent &&
1727 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1728 (!EndDependent &&
1729 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001730 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001731 else {
1732 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001733 if (StartDependent || EndDependent) {
1734 // Nothing to compute.
1735 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001736 EndValue.extend(StartValue.getBitWidth());
1737 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1738 StartValue.extend(EndValue.getBitWidth());
1739
Douglas Gregor1401c062009-05-21 23:30:39 +00001740 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001741 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1742 << StartValue.toString(10) << EndValue.toString(10)
1743 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1744 Invalid = true;
1745 } else {
1746 Designators.push_back(ASTDesignator(InitExpressions.size(),
1747 D.getLBracketLoc(),
1748 D.getEllipsisLoc(),
1749 D.getRBracketLoc()));
1750 InitExpressions.push_back(StartIndex);
1751 InitExpressions.push_back(EndIndex);
1752 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001753 }
1754 break;
1755 }
1756 }
1757 }
1758
1759 if (Invalid || Init.isInvalid())
1760 return ExprError();
1761
1762 // Clear out the expressions within the designation.
1763 Desig.ClearExprs(*this);
1764
1765 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001766 = DesignatedInitExpr::Create(Context,
1767 Designators.data(), Designators.size(),
1768 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001769 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001770 return Owned(DIE);
1771}
Douglas Gregor849afc32009-01-29 00:45:39 +00001772
1773bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001774 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001775 if (!CheckInitList.HadError())
1776 InitList = CheckInitList.getFullyStructuredList();
1777
1778 return CheckInitList.HadError();
1779}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001780
1781/// \brief Diagnose any semantic errors with value-initialization of
1782/// the given type.
1783///
1784/// Value-initialization effectively zero-initializes any types
1785/// without user-declared constructors, and calls the default
1786/// constructor for a for any type that has a user-declared
1787/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1788/// a type with a user-declared constructor does not have an
1789/// accessible, non-deleted default constructor. In C, everything can
1790/// be value-initialized, which corresponds to C's notion of
1791/// initializing objects with static storage duration when no
1792/// initializer is provided for that object.
1793///
1794/// \returns true if there was an error, false otherwise.
1795bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1796 // C++ [dcl.init]p5:
1797 //
1798 // To value-initialize an object of type T means:
1799
1800 // -- if T is an array type, then each element is value-initialized;
1801 if (const ArrayType *AT = Context.getAsArrayType(Type))
1802 return CheckValueInitialization(AT->getElementType(), Loc);
1803
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001804 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001805 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001806 // -- if T is a class type (clause 9) with a user-declared
1807 // constructor (12.1), then the default constructor for T is
1808 // called (and the initialization is ill-formed if T has no
1809 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001810 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001811 // FIXME: Eventually, we'll need to put the constructor decl into the
1812 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001813 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1814 SourceRange(Loc),
1815 DeclarationName(),
1816 IK_Direct);
1817 }
1818 }
1819
1820 if (Type->isReferenceType()) {
1821 // C++ [dcl.init]p5:
1822 // [...] A program that calls for default-initialization or
1823 // value-initialization of an entity of reference type is
1824 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001825 // FIXME: Once we have code that goes through this path, add an actual
1826 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001827 }
1828
1829 return false;
1830}