blob: fb75ff3cd6cc8f678bbad275e6b9865a7fbd6050 [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,
Anders Carlssone0f3ee62009-08-27 17:37:39 +0000669 /*ForceRValue=*/false,
670 /*InOverloadResolution=*/false);
Anders Carlsson06386552009-08-27 17:18:13 +0000671
Douglas Gregord45210d2009-01-30 22:09:00 +0000672 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000673 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000674 "initializing"))
675 hadError = true;
676 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
677 ++Index;
678 return;
679 }
680
681 // Fall through for subaggregate initialization
682 } else {
683 // C99 6.7.8p13:
684 //
685 // The initializer for a structure or union object that has
686 // automatic storage duration shall be either an initializer
687 // list as described below, or a single expression that has
688 // compatible structure or union type. In the latter case, the
689 // initial value of the object, including unnamed members, is
690 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000691 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000692 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000693 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
694 ++Index;
695 return;
696 }
697
698 // Fall through for subaggregate initialization
699 }
700
701 // C++ [dcl.init.aggr]p12:
702 //
703 // [...] Otherwise, if the member is itself a non-empty
704 // subaggregate, brace elision is assumed and the initializer is
705 // considered for the initialization of the first member of
706 // the subaggregate.
707 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
708 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
709 StructuredIndex);
710 ++StructuredIndex;
711 } else {
712 // We cannot initialize this element, so let
713 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000714 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000715 hadError = true;
716 ++Index;
717 ++StructuredIndex;
718 }
719 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000720}
721
Douglas Gregord45210d2009-01-30 22:09:00 +0000722void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000723 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000724 InitListExpr *StructuredList,
725 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000726 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000727 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000728 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000729 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000730 diag::err_many_braces_around_scalar_init)
731 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000732 hadError = true;
733 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000734 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000735 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000736 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000737 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000738 diag::err_designator_for_scalar_init)
739 << DeclType << expr->getSourceRange();
740 hadError = true;
741 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000742 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000743 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000744 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000745
Eli Friedmand8535af2008-05-19 20:00:43 +0000746 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000747 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000748 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000749 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000750 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000751 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000752 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000753 if (hadError)
754 ++StructuredIndex;
755 else
756 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000757 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000758 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000759 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000760 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000761 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000762 ++Index;
763 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000764 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000765 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000766}
767
Douglas Gregord45210d2009-01-30 22:09:00 +0000768void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
769 unsigned &Index,
770 InitListExpr *StructuredList,
771 unsigned &StructuredIndex) {
772 if (Index < IList->getNumInits()) {
773 Expr *expr = IList->getInit(Index);
774 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000775 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000776 << DeclType << IList->getSourceRange();
777 hadError = true;
778 ++Index;
779 ++StructuredIndex;
780 return;
781 }
782
783 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson8f809f92009-08-27 17:30:43 +0000784 if (SemaRef.CheckReferenceInit(expr, DeclType,
785 /*SuppressUserConversions=*/false,
786 /*AllowExplicit=*/false,
787 /*ForceRValue=*/false))
Douglas Gregord45210d2009-01-30 22:09:00 +0000788 hadError = true;
789 else if (savExpr != expr) {
790 // The type was promoted, update initializer list.
791 IList->setInit(Index, expr);
792 }
793 if (hadError)
794 ++StructuredIndex;
795 else
796 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
797 ++Index;
798 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000799 // FIXME: It would be wonderful if we could point at the actual member. In
800 // general, it would be useful to pass location information down the stack,
801 // so that we know the location (or decl) of the "current object" being
802 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000803 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000804 diag::err_init_reference_member_uninitialized)
805 << DeclType
806 << IList->getSourceRange();
807 hadError = true;
808 ++Index;
809 ++StructuredIndex;
810 return;
811 }
812}
813
Steve Naroffc4d4a482008-05-01 22:18:59 +0000814void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000815 unsigned &Index,
816 InitListExpr *StructuredList,
817 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000818 if (Index < IList->getNumInits()) {
819 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000820 unsigned maxElements = VT->getNumElements();
821 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000822 QualType elementType = VT->getElementType();
823
Nate Begemane85f43d2009-08-10 23:49:36 +0000824 if (!SemaRef.getLangOptions().OpenCL) {
825 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
826 // Don't attempt to go past the end of the init list
827 if (Index >= IList->getNumInits())
828 break;
829 CheckSubElementType(IList, elementType, Index,
830 StructuredList, StructuredIndex);
831 }
832 } else {
833 // OpenCL initializers allows vectors to be constructed from vectors.
834 for (unsigned i = 0; i < maxElements; ++i) {
835 // Don't attempt to go past the end of the init list
836 if (Index >= IList->getNumInits())
837 break;
838 QualType IType = IList->getInit(Index)->getType();
839 if (!IType->isVectorType()) {
840 CheckSubElementType(IList, elementType, Index,
841 StructuredList, StructuredIndex);
842 ++numEltsInit;
843 } else {
844 const VectorType *IVT = IType->getAsVectorType();
845 unsigned numIElts = IVT->getNumElements();
846 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
847 numIElts);
848 CheckSubElementType(IList, VecType, Index,
849 StructuredList, StructuredIndex);
850 numEltsInit += numIElts;
851 }
852 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000853 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000854
855 // OpenCL & AltiVec require all elements to be initialized.
856 if (numEltsInit != maxElements)
857 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
858 SemaRef.Diag(IList->getSourceRange().getBegin(),
859 diag::err_vector_incorrect_num_initializers)
860 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000861 }
862}
863
864void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000865 llvm::APSInt elementIndex,
866 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000867 unsigned &Index,
868 InitListExpr *StructuredList,
869 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000870 // Check for the special-case of initializing an array with a string.
871 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000872 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
873 SemaRef.Context)) {
874 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000875 // We place the string literal directly into the resulting
876 // initializer list. This is the only place where the structure
877 // of the structured initializer list doesn't match exactly,
878 // because doing so would involve allocating one character
879 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000880 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000881 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000882 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000883 return;
884 }
885 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000886 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000887 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000888 // Check for VLAs; in standard C it would be possible to check this
889 // earlier, but I don't know where clang accepts VLAs (gcc accepts
890 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000891 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000892 diag::err_variable_object_no_init)
893 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000894 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000895 ++Index;
896 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000897 return;
898 }
899
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000900 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000901 llvm::APSInt maxElements(elementIndex.getBitWidth(),
902 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000903 bool maxElementsKnown = false;
904 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000905 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000906 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000907 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000908 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000909 maxElementsKnown = true;
910 }
911
Chris Lattner2e2766a2009-02-24 22:50:46 +0000912 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000913 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000914 while (Index < IList->getNumInits()) {
915 Expr *Init = IList->getInit(Index);
916 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000917 // If we're not the subobject that matches up with the '{' for
918 // the designator, we shouldn't be handling the
919 // designator. Return immediately.
920 if (!SubobjectIsDesignatorContext)
921 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000922
Douglas Gregor710f6d42009-01-22 23:26:18 +0000923 // Handle this designated initializer. elementIndex will be
924 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000925 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000926 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000927 StructuredList, StructuredIndex, true,
928 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000929 hadError = true;
930 continue;
931 }
932
Douglas Gregor5a203a62009-01-23 16:54:12 +0000933 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
934 maxElements.extend(elementIndex.getBitWidth());
935 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
936 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000937 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000938
Douglas Gregor710f6d42009-01-22 23:26:18 +0000939 // If the array is of incomplete type, keep track of the number of
940 // elements in the initializer.
941 if (!maxElementsKnown && elementIndex > maxElements)
942 maxElements = elementIndex;
943
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000944 continue;
945 }
946
947 // If we know the maximum number of elements, and we've already
948 // hit it, stop consuming elements in the initializer list.
949 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000950 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000951
952 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000953 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000954 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000955 ++elementIndex;
956
957 // If the array is of incomplete type, keep track of the number of
958 // elements in the initializer.
959 if (!maxElementsKnown && elementIndex > maxElements)
960 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000961 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000962 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000963 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000964 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000965 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000966 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000967 // Sizing an array implicitly to zero is not allowed by ISO C,
968 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000969 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000970 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000971 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000972
Chris Lattner2e2766a2009-02-24 22:50:46 +0000973 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000974 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000975 }
976}
977
978void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
979 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000980 RecordDecl::field_iterator Field,
981 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000982 unsigned &Index,
983 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000984 unsigned &StructuredIndex,
985 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000986 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000987
Eli Friedman683cedf2008-05-19 19:16:24 +0000988 // If the record is invalid, some of it's members are invalid. To avoid
989 // confusion, we forgo checking the intializer for the entire record.
990 if (structDecl->isInvalidDecl()) {
991 hadError = true;
992 return;
993 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000994
995 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
996 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000997 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000998 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000999 Field != FieldEnd; ++Field) {
1000 if (Field->getDeclName()) {
1001 StructuredList->setInitializedFieldInUnion(*Field);
1002 break;
1003 }
1004 }
1005 return;
1006 }
1007
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001008 // If structDecl is a forward declaration, this loop won't do
1009 // anything except look at designated initializers; That's okay,
1010 // because an error should get printed out elsewhere. It might be
1011 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001012 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001013 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001014 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001015 while (Index < IList->getNumInits()) {
1016 Expr *Init = IList->getInit(Index);
1017
1018 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001019 // If we're not the subobject that matches up with the '{' for
1020 // the designator, we shouldn't be handling the
1021 // designator. Return immediately.
1022 if (!SubobjectIsDesignatorContext)
1023 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001024
Douglas Gregor710f6d42009-01-22 23:26:18 +00001025 // Handle this designated initializer. Field will be updated to
1026 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001027 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001028 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001029 StructuredList, StructuredIndex,
1030 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001031 hadError = true;
1032
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001033 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001034 continue;
1035 }
1036
1037 if (Field == FieldEnd) {
1038 // We've run out of fields. We're done.
1039 break;
1040 }
1041
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001042 // We've already initialized a member of a union. We're done.
1043 if (InitializedSomething && DeclType->isUnionType())
1044 break;
1045
Douglas Gregor8acb7272008-12-11 16:49:14 +00001046 // If we've hit the flexible array member at the end, we're done.
1047 if (Field->getType()->isIncompleteArrayType())
1048 break;
1049
Douglas Gregor82462762009-01-29 16:53:55 +00001050 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001051 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001052 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001053 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001054 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001055
Douglas Gregor36859eb2009-01-29 00:39:20 +00001056 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001057 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001058 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001059
1060 if (DeclType->isUnionType()) {
1061 // Initialize the first field within the union.
1062 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001063 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001064
1065 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001066 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001067
Douglas Gregorbe69b162009-02-04 22:46:25 +00001068 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001069 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001070 return;
1071
1072 // Handle GNU flexible array initializers.
1073 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001074 (!isa<InitListExpr>(IList->getInit(Index)) ||
1075 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001076 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001077 diag::err_flexible_array_init_nonempty)
1078 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001079 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001080 << *Field;
1081 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001082 ++Index;
1083 return;
1084 } else {
1085 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1086 diag::ext_flexible_array_init)
1087 << IList->getInit(Index)->getSourceRange().getBegin();
1088 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1089 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001090 }
1091
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001092 if (isa<InitListExpr>(IList->getInit(Index)))
1093 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1094 StructuredIndex);
1095 else
1096 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1097 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001098}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001099
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001100/// \brief Expand a field designator that refers to a member of an
1101/// anonymous struct or union into a series of field designators that
1102/// refers to the field within the appropriate subobject.
1103///
1104/// Field/FieldIndex will be updated to point to the (new)
1105/// currently-designated field.
1106static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1107 DesignatedInitExpr *DIE,
1108 unsigned DesigIdx,
1109 FieldDecl *Field,
1110 RecordDecl::field_iterator &FieldIter,
1111 unsigned &FieldIndex) {
1112 typedef DesignatedInitExpr::Designator Designator;
1113
1114 // Build the path from the current object to the member of the
1115 // anonymous struct/union (backwards).
1116 llvm::SmallVector<FieldDecl *, 4> Path;
1117 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1118
1119 // Build the replacement designators.
1120 llvm::SmallVector<Designator, 4> Replacements;
1121 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1122 FI = Path.rbegin(), FIEnd = Path.rend();
1123 FI != FIEnd; ++FI) {
1124 if (FI + 1 == FIEnd)
1125 Replacements.push_back(Designator((IdentifierInfo *)0,
1126 DIE->getDesignator(DesigIdx)->getDotLoc(),
1127 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1128 else
1129 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1130 SourceLocation()));
1131 Replacements.back().setField(*FI);
1132 }
1133
1134 // Expand the current designator into the set of replacement
1135 // designators, so we have a full subobject path down to where the
1136 // member of the anonymous struct/union is actually stored.
1137 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1138 &Replacements[0] + Replacements.size());
1139
1140 // Update FieldIter/FieldIndex;
1141 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001142 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001143 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001144 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001145 FieldIter != FEnd; ++FieldIter) {
1146 if (FieldIter->isUnnamedBitfield())
1147 continue;
1148
1149 if (*FieldIter == Path.back())
1150 return;
1151
1152 ++FieldIndex;
1153 }
1154
1155 assert(false && "Unable to find anonymous struct/union field");
1156}
1157
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001158/// @brief Check the well-formedness of a C99 designated initializer.
1159///
1160/// Determines whether the designated initializer @p DIE, which
1161/// resides at the given @p Index within the initializer list @p
1162/// IList, is well-formed for a current object of type @p DeclType
1163/// (C99 6.7.8). The actual subobject that this designator refers to
1164/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001165/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001166///
1167/// @param IList The initializer list in which this designated
1168/// initializer occurs.
1169///
Douglas Gregoraa357272009-04-15 04:56:10 +00001170/// @param DIE The designated initializer expression.
1171///
1172/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001173///
1174/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1175/// into which the designation in @p DIE should refer.
1176///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001177/// @param NextField If non-NULL and the first designator in @p DIE is
1178/// a field, this will be set to the field declaration corresponding
1179/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001180///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001181/// @param NextElementIndex If non-NULL and the first designator in @p
1182/// DIE is an array designator or GNU array-range designator, this
1183/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001184///
1185/// @param Index Index into @p IList where the designated initializer
1186/// @p DIE occurs.
1187///
Douglas Gregorf603b472009-01-28 21:54:33 +00001188/// @param StructuredList The initializer list expression that
1189/// describes all of the subobject initializers in the order they'll
1190/// actually be initialized.
1191///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001192/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001193bool
1194InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1195 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001196 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001197 QualType &CurrentObjectType,
1198 RecordDecl::field_iterator *NextField,
1199 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001200 unsigned &Index,
1201 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001202 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001203 bool FinishSubobjectInit,
1204 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001205 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001206 // Check the actual initialization for the designated object type.
1207 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001208
1209 // Temporarily remove the designator expression from the
1210 // initializer list that the child calls see, so that we don't try
1211 // to re-process the designator.
1212 unsigned OldIndex = Index;
1213 IList->setInit(OldIndex, DIE->getInit());
1214
1215 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001216 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001217
1218 // Restore the designated initializer expression in the syntactic
1219 // form of the initializer list.
1220 if (IList->getInit(OldIndex) != DIE->getInit())
1221 DIE->setInit(IList->getInit(OldIndex));
1222 IList->setInit(OldIndex, DIE);
1223
Douglas Gregor710f6d42009-01-22 23:26:18 +00001224 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001225 }
1226
Douglas Gregoraa357272009-04-15 04:56:10 +00001227 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001228 assert((IsFirstDesignator || StructuredList) &&
1229 "Need a non-designated initializer list to start from");
1230
Douglas Gregoraa357272009-04-15 04:56:10 +00001231 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001232 // Determine the structural initializer list that corresponds to the
1233 // current subobject.
1234 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001235 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1236 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001237 SourceRange(D->getStartLocation(),
1238 DIE->getSourceRange().getEnd()));
1239 assert(StructuredList && "Expected a structured initializer list");
1240
Douglas Gregor710f6d42009-01-22 23:26:18 +00001241 if (D->isFieldDesignator()) {
1242 // C99 6.7.8p7:
1243 //
1244 // If a designator has the form
1245 //
1246 // . identifier
1247 //
1248 // then the current object (defined below) shall have
1249 // structure or union type and the identifier shall be the
1250 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001251 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001252 if (!RT) {
1253 SourceLocation Loc = D->getDotLoc();
1254 if (Loc.isInvalid())
1255 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001256 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1257 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001258 ++Index;
1259 return true;
1260 }
1261
Douglas Gregorf603b472009-01-28 21:54:33 +00001262 // Note: we perform a linear search of the fields here, despite
1263 // the fact that we have a faster lookup method, because we always
1264 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001265 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001266 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001267 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001268 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001269 Field = RT->getDecl()->field_begin(),
1270 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001271 for (; Field != FieldEnd; ++Field) {
1272 if (Field->isUnnamedBitfield())
1273 continue;
1274
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001275 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001276 break;
1277
1278 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001279 }
1280
Douglas Gregorf603b472009-01-28 21:54:33 +00001281 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001282 // There was no normal field in the struct with the designated
1283 // name. Perform another lookup for this name, which may find
1284 // something that we can't designate (e.g., a member function),
1285 // may find nothing, or may find a member of an anonymous
1286 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001287 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001288 if (Lookup.first == Lookup.second) {
1289 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001290 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001291 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001292 ++Index;
1293 return true;
1294 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1295 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1296 ->isAnonymousStructOrUnion()) {
1297 // Handle an field designator that refers to a member of an
1298 // anonymous struct or union.
1299 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1300 cast<FieldDecl>(*Lookup.first),
1301 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001302 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001303 } else {
1304 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001305 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001306 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001307 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001308 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001309 ++Index;
1310 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001311 }
1312 } else if (!KnownField &&
1313 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001314 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001315 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1316 Field, FieldIndex);
1317 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001318 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001319
1320 // All of the fields of a union are located at the same place in
1321 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001322 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001323 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001324 StructuredList->setInitializedFieldInUnion(*Field);
1325 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001326
Douglas Gregor710f6d42009-01-22 23:26:18 +00001327 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001328 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001329
Douglas Gregorf603b472009-01-28 21:54:33 +00001330 // Make sure that our non-designated initializer list has space
1331 // for a subobject corresponding to this field.
1332 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001333 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001334
Douglas Gregorbe69b162009-02-04 22:46:25 +00001335 // This designator names a flexible array member.
1336 if (Field->getType()->isIncompleteArrayType()) {
1337 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001338 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001339 // We can't designate an object within the flexible array
1340 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001341 DesignatedInitExpr::Designator *NextD
1342 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001343 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001344 diag::err_designator_into_flexible_array_member)
1345 << SourceRange(NextD->getStartLocation(),
1346 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001347 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001348 << *Field;
1349 Invalid = true;
1350 }
1351
1352 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1353 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001354 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001355 diag::err_flexible_array_init_needs_braces)
1356 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001357 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001358 << *Field;
1359 Invalid = true;
1360 }
1361
1362 // Handle GNU flexible array initializers.
1363 if (!Invalid && !TopLevelObject &&
1364 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001365 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001366 diag::err_flexible_array_init_nonempty)
1367 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001368 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001369 << *Field;
1370 Invalid = true;
1371 }
1372
1373 if (Invalid) {
1374 ++Index;
1375 return true;
1376 }
1377
1378 // Initialize the array.
1379 bool prevHadError = hadError;
1380 unsigned newStructuredIndex = FieldIndex;
1381 unsigned OldIndex = Index;
1382 IList->setInit(Index, DIE->getInit());
1383 CheckSubElementType(IList, Field->getType(), Index,
1384 StructuredList, newStructuredIndex);
1385 IList->setInit(OldIndex, DIE);
1386 if (hadError && !prevHadError) {
1387 ++Field;
1388 ++FieldIndex;
1389 if (NextField)
1390 *NextField = Field;
1391 StructuredIndex = FieldIndex;
1392 return true;
1393 }
1394 } else {
1395 // Recurse to check later designated subobjects.
1396 QualType FieldType = (*Field)->getType();
1397 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001398 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1399 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001400 true, false))
1401 return true;
1402 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001403
1404 // Find the position of the next field to be initialized in this
1405 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001406 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001407 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001408
1409 // If this the first designator, our caller will continue checking
1410 // the rest of this struct/class/union subobject.
1411 if (IsFirstDesignator) {
1412 if (NextField)
1413 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001414 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001415 return false;
1416 }
1417
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001418 if (!FinishSubobjectInit)
1419 return false;
1420
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001421 // We've already initialized something in the union; we're done.
1422 if (RT->getDecl()->isUnion())
1423 return hadError;
1424
Douglas Gregor710f6d42009-01-22 23:26:18 +00001425 // Check the remaining fields within this class/struct/union subobject.
1426 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001427 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1428 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001429 return hadError && !prevHadError;
1430 }
1431
1432 // C99 6.7.8p6:
1433 //
1434 // If a designator has the form
1435 //
1436 // [ constant-expression ]
1437 //
1438 // then the current object (defined below) shall have array
1439 // type and the expression shall be an integer constant
1440 // expression. If the array is of unknown size, any
1441 // nonnegative value is valid.
1442 //
1443 // Additionally, cope with the GNU extension that permits
1444 // designators of the form
1445 //
1446 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001447 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001448 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001449 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001450 << CurrentObjectType;
1451 ++Index;
1452 return true;
1453 }
1454
1455 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001456 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1457 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001458 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001459 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001460 DesignatedEndIndex = DesignatedStartIndex;
1461 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001462 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001463
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001464
Chris Lattnereec8ae22009-04-25 21:59:05 +00001465 DesignatedStartIndex =
1466 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1467 DesignatedEndIndex =
1468 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001469 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001470
Chris Lattnereec8ae22009-04-25 21:59:05 +00001471 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001472 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001473 }
1474
Douglas Gregor710f6d42009-01-22 23:26:18 +00001475 if (isa<ConstantArrayType>(AT)) {
1476 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001477 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1478 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1479 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1480 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1481 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001482 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001483 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001484 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001485 << IndexExpr->getSourceRange();
1486 ++Index;
1487 return true;
1488 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001489 } else {
1490 // Make sure the bit-widths and signedness match.
1491 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1492 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001493 else if (DesignatedStartIndex.getBitWidth() <
1494 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001495 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1496 DesignatedStartIndex.setIsUnsigned(true);
1497 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001498 }
1499
Douglas Gregorf603b472009-01-28 21:54:33 +00001500 // Make sure that our non-designated initializer list has space
1501 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001502 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001503 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001504 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001505
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001506 // Repeatedly perform subobject initializations in the range
1507 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001508
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001509 // Move to the next designator
1510 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1511 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001512 while (DesignatedStartIndex <= DesignatedEndIndex) {
1513 // Recurse to check later designated subobjects.
1514 QualType ElementType = AT->getElementType();
1515 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001516 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1517 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001518 (DesignatedStartIndex == DesignatedEndIndex),
1519 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001520 return true;
1521
1522 // Move to the next index in the array that we'll be initializing.
1523 ++DesignatedStartIndex;
1524 ElementIndex = DesignatedStartIndex.getZExtValue();
1525 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001526
1527 // If this the first designator, our caller will continue checking
1528 // the rest of this array subobject.
1529 if (IsFirstDesignator) {
1530 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001531 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001532 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001533 return false;
1534 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001535
1536 if (!FinishSubobjectInit)
1537 return false;
1538
Douglas Gregor710f6d42009-01-22 23:26:18 +00001539 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001540 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001541 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001542 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001543 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001544}
1545
Douglas Gregorf603b472009-01-28 21:54:33 +00001546// Get the structured initializer list for a subobject of type
1547// @p CurrentObjectType.
1548InitListExpr *
1549InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1550 QualType CurrentObjectType,
1551 InitListExpr *StructuredList,
1552 unsigned StructuredIndex,
1553 SourceRange InitRange) {
1554 Expr *ExistingInit = 0;
1555 if (!StructuredList)
1556 ExistingInit = SyntacticToSemantic[IList];
1557 else if (StructuredIndex < StructuredList->getNumInits())
1558 ExistingInit = StructuredList->getInit(StructuredIndex);
1559
1560 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1561 return Result;
1562
1563 if (ExistingInit) {
1564 // We are creating an initializer list that initializes the
1565 // subobjects of the current object, but there was already an
1566 // initialization that completely initialized the current
1567 // subobject, e.g., by a compound literal:
1568 //
1569 // struct X { int a, b; };
1570 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1571 //
1572 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1573 // designated initializer re-initializes the whole
1574 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001575 SemaRef.Diag(InitRange.getBegin(),
1576 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001577 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001578 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001579 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001580 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001581 << ExistingInit->getSourceRange();
1582 }
1583
1584 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001585 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1586 InitRange.getEnd());
1587
Douglas Gregorf603b472009-01-28 21:54:33 +00001588 Result->setType(CurrentObjectType);
1589
Douglas Gregoree0792c2009-03-20 23:58:33 +00001590 // Pre-allocate storage for the structured initializer list.
1591 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001592 unsigned NumInits = 0;
1593 if (!StructuredList)
1594 NumInits = IList->getNumInits();
1595 else if (Index < IList->getNumInits()) {
1596 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1597 NumInits = SubList->getNumInits();
1598 }
1599
Douglas Gregoree0792c2009-03-20 23:58:33 +00001600 if (const ArrayType *AType
1601 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1602 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1603 NumElements = CAType->getSize().getZExtValue();
1604 // Simple heuristic so that we don't allocate a very large
1605 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001606 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001607 NumElements = 0;
1608 }
1609 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1610 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001611 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001612 RecordDecl *RDecl = RType->getDecl();
1613 if (RDecl->isUnion())
1614 NumElements = 1;
1615 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001616 NumElements = std::distance(RDecl->field_begin(),
1617 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001618 }
1619
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001620 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001621 NumElements = IList->getNumInits();
1622
1623 Result->reserveInits(NumElements);
1624
Douglas Gregorf603b472009-01-28 21:54:33 +00001625 // Link this new initializer list into the structured initializer
1626 // lists.
1627 if (StructuredList)
1628 StructuredList->updateInit(StructuredIndex, Result);
1629 else {
1630 Result->setSyntacticForm(IList);
1631 SyntacticToSemantic[IList] = Result;
1632 }
1633
1634 return Result;
1635}
1636
1637/// Update the initializer at index @p StructuredIndex within the
1638/// structured initializer list to the value @p expr.
1639void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1640 unsigned &StructuredIndex,
1641 Expr *expr) {
1642 // No structured initializer list to update
1643 if (!StructuredList)
1644 return;
1645
1646 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1647 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001648 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001649 diag::warn_initializer_overrides)
1650 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001651 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001652 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001653 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001654 << PrevInit->getSourceRange();
1655 }
1656
1657 ++StructuredIndex;
1658}
1659
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001660/// Check that the given Index expression is a valid array designator
1661/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001662/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001663/// and produces a reasonable diagnostic if there is a
1664/// failure. Returns true if there was an error, false otherwise. If
1665/// everything went okay, Value will receive the value of the constant
1666/// expression.
1667static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001668CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001669 SourceLocation Loc = Index->getSourceRange().getBegin();
1670
1671 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001672 if (S.VerifyIntegerConstantExpression(Index, &Value))
1673 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001674
Chris Lattnereec8ae22009-04-25 21:59:05 +00001675 if (Value.isSigned() && Value.isNegative())
1676 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001677 << Value.toString(10) << Index->getSourceRange();
1678
Douglas Gregore498e372009-01-23 21:04:18 +00001679 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001680 return false;
1681}
1682
1683Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1684 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001685 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001686 OwningExprResult Init) {
1687 typedef DesignatedInitExpr::Designator ASTDesignator;
1688
1689 bool Invalid = false;
1690 llvm::SmallVector<ASTDesignator, 32> Designators;
1691 llvm::SmallVector<Expr *, 32> InitExpressions;
1692
1693 // Build designators and check array designator expressions.
1694 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1695 const Designator &D = Desig.getDesignator(Idx);
1696 switch (D.getKind()) {
1697 case Designator::FieldDesignator:
1698 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1699 D.getFieldLoc()));
1700 break;
1701
1702 case Designator::ArrayDesignator: {
1703 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1704 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001705 if (!Index->isTypeDependent() &&
1706 !Index->isValueDependent() &&
1707 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001708 Invalid = true;
1709 else {
1710 Designators.push_back(ASTDesignator(InitExpressions.size(),
1711 D.getLBracketLoc(),
1712 D.getRBracketLoc()));
1713 InitExpressions.push_back(Index);
1714 }
1715 break;
1716 }
1717
1718 case Designator::ArrayRangeDesignator: {
1719 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1720 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1721 llvm::APSInt StartValue;
1722 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001723 bool StartDependent = StartIndex->isTypeDependent() ||
1724 StartIndex->isValueDependent();
1725 bool EndDependent = EndIndex->isTypeDependent() ||
1726 EndIndex->isValueDependent();
1727 if ((!StartDependent &&
1728 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1729 (!EndDependent &&
1730 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001731 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001732 else {
1733 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001734 if (StartDependent || EndDependent) {
1735 // Nothing to compute.
1736 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001737 EndValue.extend(StartValue.getBitWidth());
1738 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1739 StartValue.extend(EndValue.getBitWidth());
1740
Douglas Gregor1401c062009-05-21 23:30:39 +00001741 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001742 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1743 << StartValue.toString(10) << EndValue.toString(10)
1744 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1745 Invalid = true;
1746 } else {
1747 Designators.push_back(ASTDesignator(InitExpressions.size(),
1748 D.getLBracketLoc(),
1749 D.getEllipsisLoc(),
1750 D.getRBracketLoc()));
1751 InitExpressions.push_back(StartIndex);
1752 InitExpressions.push_back(EndIndex);
1753 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001754 }
1755 break;
1756 }
1757 }
1758 }
1759
1760 if (Invalid || Init.isInvalid())
1761 return ExprError();
1762
1763 // Clear out the expressions within the designation.
1764 Desig.ClearExprs(*this);
1765
1766 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001767 = DesignatedInitExpr::Create(Context,
1768 Designators.data(), Designators.size(),
1769 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001770 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001771 return Owned(DIE);
1772}
Douglas Gregor849afc32009-01-29 00:45:39 +00001773
1774bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001775 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001776 if (!CheckInitList.HadError())
1777 InitList = CheckInitList.getFullyStructuredList();
1778
1779 return CheckInitList.HadError();
1780}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001781
1782/// \brief Diagnose any semantic errors with value-initialization of
1783/// the given type.
1784///
1785/// Value-initialization effectively zero-initializes any types
1786/// without user-declared constructors, and calls the default
1787/// constructor for a for any type that has a user-declared
1788/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1789/// a type with a user-declared constructor does not have an
1790/// accessible, non-deleted default constructor. In C, everything can
1791/// be value-initialized, which corresponds to C's notion of
1792/// initializing objects with static storage duration when no
1793/// initializer is provided for that object.
1794///
1795/// \returns true if there was an error, false otherwise.
1796bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1797 // C++ [dcl.init]p5:
1798 //
1799 // To value-initialize an object of type T means:
1800
1801 // -- if T is an array type, then each element is value-initialized;
1802 if (const ArrayType *AT = Context.getAsArrayType(Type))
1803 return CheckValueInitialization(AT->getElementType(), Loc);
1804
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001805 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001806 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001807 // -- if T is a class type (clause 9) with a user-declared
1808 // constructor (12.1), then the default constructor for T is
1809 // called (and the initialization is ill-formed if T has no
1810 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001811 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001812 // FIXME: Eventually, we'll need to put the constructor decl into the
1813 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001814 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1815 SourceRange(Loc),
1816 DeclarationName(),
1817 IK_Direct);
1818 }
1819 }
1820
1821 if (Type->isReferenceType()) {
1822 // C++ [dcl.init]p5:
1823 // [...] A program that calls for default-initialization or
1824 // value-initialization of an entity of reference type is
1825 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001826 // FIXME: Once we have code that goes through this path, add an actual
1827 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001828 }
1829
1830 return false;
1831}