blob: f734d9347ace5a1bfe7be4f3cbb8615152e67711 [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())
135 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
136
137 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
138 // of unknown size ("[]") or an object type that is not a variable array type.
139 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
140 return Diag(InitLoc, diag::err_variable_object_no_init)
141 << VAT->getSizeExpr()->getSourceRange();
142
143 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
144 if (!InitList) {
145 // FIXME: Handle wide strings
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000146 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
147 CheckStringInit(Str, DeclType, *this);
Chris Lattnerd20fac42009-02-24 23:01:39 +0000148 return false;
149 }
Chris Lattnerd3a00502009-02-24 22:27:37 +0000150
151 // C++ [dcl.init]p14:
152 // -- If the destination type is a (possibly cv-qualified) class
153 // type:
154 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
155 QualType DeclTypeC = Context.getCanonicalType(DeclType);
156 QualType InitTypeC = Context.getCanonicalType(Init->getType());
157
158 // -- If the initialization is direct-initialization, or if it is
159 // copy-initialization where the cv-unqualified version of the
160 // source type is the same class as, or a derived class of, the
161 // class of the destination, constructors are considered.
162 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
163 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000164 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000165 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Anders Carlsson5868dfc2009-05-27 16:38:58 +0000166
167 // No need to make a CXXConstructExpr if both the ctor and dtor are
168 // trivial.
169 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
170 return false;
171
Chris Lattnerd3a00502009-02-24 22:27:37 +0000172 CXXConstructorDecl *Constructor
173 = PerformInitializationByConstructor(DeclType, &Init, 1,
174 InitLoc, Init->getSourceRange(),
175 InitEntity,
176 DirectInit? IK_Direct : IK_Copy);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000177 if (!Constructor)
178 return true;
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000179 bool Elidable = (isa<CallExpr>(Init) ||
180 isa<CXXTemporaryObjectExpr>(Init));
Anders Carlsson1bfe1c42009-08-15 23:41:35 +0000181 Init = BuildCXXConstructExpr(DeclType, Constructor, Elidable, &Init, 1);
Fariborz Jahanian88e09cc2009-08-05 18:17:32 +0000182 Init = MaybeCreateCXXExprWithTemporaries(Init, /*DestroyTemps=*/true);
Anders Carlsson73bb5e62009-05-27 16:10:08 +0000183 return false;
Chris Lattnerd3a00502009-02-24 22:27:37 +0000184 }
185
186 // -- Otherwise (i.e., for the remaining copy-initialization
187 // cases), user-defined conversion sequences that can
188 // convert from the source type to the destination type or
189 // (when a conversion function is used) to a derived class
190 // thereof are enumerated as described in 13.3.1.4, and the
191 // best one is chosen through overload resolution
192 // (13.3). If the conversion cannot be done or is
193 // ambiguous, the initialization is ill-formed. The
194 // function selected is called with the initializer
195 // expression as its argument; if the function is a
196 // constructor, the call initializes a temporary of the
197 // destination type.
Mike Stumpe127ae32009-05-16 07:39:55 +0000198 // FIXME: We're pretending to do copy elision here; return to this when we
199 // have ASTs for such things.
Chris Lattnerd3a00502009-02-24 22:27:37 +0000200 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
201 return false;
202
203 if (InitEntity)
204 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000205 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
206 << Init->getType() << Init->getSourceRange();
207 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerd3a00502009-02-24 22:27:37 +0000208 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
209 << Init->getType() << Init->getSourceRange();
210 }
211
212 // C99 6.7.8p16.
213 if (DeclType->isArrayType())
214 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattner6434a1b2009-06-26 04:45:06 +0000215 << Init->getSourceRange();
Chris Lattnerd3a00502009-02-24 22:27:37 +0000216
Chris Lattner160da072009-02-24 22:46:58 +0000217 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerd3a00502009-02-24 22:27:37 +0000218 }
219
220 bool hadError = CheckInitList(InitList, DeclType);
221 Init = InitList;
222 return hadError;
223}
224
225//===----------------------------------------------------------------------===//
226// Semantic checking for initializer lists.
227//===----------------------------------------------------------------------===//
228
Douglas Gregoraaa20962009-01-29 01:05:33 +0000229/// @brief Semantic checking for initializer lists.
230///
231/// The InitListChecker class contains a set of routines that each
232/// handle the initialization of a certain kind of entity, e.g.,
233/// arrays, vectors, struct/union types, scalars, etc. The
234/// InitListChecker itself performs a recursive walk of the subobject
235/// structure of the type to be initialized, while stepping through
236/// the initializer list one element at a time. The IList and Index
237/// parameters to each of the Check* routines contain the active
238/// (syntactic) initializer list and the index into that initializer
239/// list that represents the current initializer. Each routine is
240/// responsible for moving that Index forward as it consumes elements.
241///
242/// Each Check* routine also has a StructuredList/StructuredIndex
243/// arguments, which contains the current the "structured" (semantic)
244/// initializer list and the index into that initializer list where we
245/// are copying initializers as we map them over to the semantic
246/// list. Once we have completed our recursive walk of the subobject
247/// structure, we will have constructed a full semantic initializer
248/// list.
249///
250/// C99 designators cause changes in the initializer list traversal,
251/// because they make the initialization "jump" into a specific
252/// subobject and then continue the initialization from that
253/// point. CheckDesignatedInitializer() recursively steps into the
254/// designated subobject and manages backing out the recursion to
255/// initialize the subobjects after the one designated.
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000256namespace {
Douglas Gregor849afc32009-01-29 00:45:39 +0000257class InitListChecker {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000258 Sema &SemaRef;
Douglas Gregor849afc32009-01-29 00:45:39 +0000259 bool hadError;
260 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
261 InitListExpr *FullyStructuredList;
262
263 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000264 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000265 unsigned &StructuredIndex,
266 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000267 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000268 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000269 unsigned &StructuredIndex,
270 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000271 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
272 bool SubobjectIsDesignatorContext,
273 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000274 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000275 unsigned &StructuredIndex,
276 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000277 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
278 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000279 InitListExpr *StructuredList,
280 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000281 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor849afc32009-01-29 00:45:39 +0000282 unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000283 InitListExpr *StructuredList,
284 unsigned &StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000285 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
286 unsigned &Index,
287 InitListExpr *StructuredList,
288 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000289 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000290 InitListExpr *StructuredList,
291 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000292 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
293 RecordDecl::field_iterator Field,
294 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000295 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000296 unsigned &StructuredIndex,
297 bool TopLevelObject = false);
Douglas Gregor849afc32009-01-29 00:45:39 +0000298 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
299 llvm::APSInt elementIndex,
300 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregoraaa20962009-01-29 01:05:33 +0000301 InitListExpr *StructuredList,
302 unsigned &StructuredIndex);
Douglas Gregor849afc32009-01-29 00:45:39 +0000303 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +0000304 unsigned DesigIdx,
Douglas Gregor849afc32009-01-29 00:45:39 +0000305 QualType &CurrentObjectType,
306 RecordDecl::field_iterator *NextField,
307 llvm::APSInt *NextElementIndex,
308 unsigned &Index,
309 InitListExpr *StructuredList,
310 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000311 bool FinishSubobjectInit,
312 bool TopLevelObject);
Douglas Gregor849afc32009-01-29 00:45:39 +0000313 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
314 QualType CurrentObjectType,
315 InitListExpr *StructuredList,
316 unsigned StructuredIndex,
317 SourceRange InitRange);
Douglas Gregoraaa20962009-01-29 01:05:33 +0000318 void UpdateStructuredListElement(InitListExpr *StructuredList,
319 unsigned &StructuredIndex,
Douglas Gregor849afc32009-01-29 00:45:39 +0000320 Expr *expr);
321 int numArrayElements(QualType DeclType);
322 int numStructUnionElements(QualType DeclType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000323
324 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregor849afc32009-01-29 00:45:39 +0000325public:
Chris Lattner2e2766a2009-02-24 22:50:46 +0000326 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregor849afc32009-01-29 00:45:39 +0000327 bool HadError() { return hadError; }
328
329 // @brief Retrieves the fully-structured initializer list used for
330 // semantic analysis and code generation.
331 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
332};
Chris Lattnere76e9bf2009-02-24 22:48:58 +0000333} // end anonymous namespace
Chris Lattner1aa25a72009-01-29 05:10:57 +0000334
Douglas Gregorf603b472009-01-28 21:54:33 +0000335/// Recursively replaces NULL values within the given initializer list
336/// with expressions that perform value-initialization of the
337/// appropriate type.
Douglas Gregord45210d2009-01-30 22:09:00 +0000338void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000339 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord45210d2009-01-30 22:09:00 +0000340 "Should not have void type");
Douglas Gregor538a4c22009-02-02 17:43:21 +0000341 SourceLocation Loc = ILE->getSourceRange().getBegin();
342 if (ILE->getSyntacticForm())
343 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
344
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000345 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000346 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000347 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000348 Field = RType->getDecl()->field_begin(),
349 FieldEnd = RType->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000350 Field != FieldEnd; ++Field) {
351 if (Field->isUnnamedBitfield())
352 continue;
353
Douglas Gregor538a4c22009-02-02 17:43:21 +0000354 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000355 if (Field->getType()->isReferenceType()) {
356 // C++ [dcl.init.aggr]p9:
357 // If an incomplete or empty initializer-list leaves a
358 // member of reference type uninitialized, the program is
359 // ill-formed.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000360 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord45210d2009-01-30 22:09:00 +0000361 << Field->getType()
362 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +0000363 SemaRef.Diag(Field->getLocation(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000364 diag::note_uninit_reference_member);
365 hadError = true;
Douglas Gregor538a4c22009-02-02 17:43:21 +0000366 return;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000367 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000368 hadError = true;
369 return;
Douglas Gregord45210d2009-01-30 22:09:00 +0000370 }
Douglas Gregor538a4c22009-02-02 17:43:21 +0000371
Mike Stumpe127ae32009-05-16 07:39:55 +0000372 // FIXME: If value-initialization involves calling a constructor, should
373 // we make that call explicit in the representation (even when it means
374 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000375 if (Init < NumInits && !hadError)
376 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000377 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor538a4c22009-02-02 17:43:21 +0000378 } else if (InitListExpr *InnerILE
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000379 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000380 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000381 ++Init;
Douglas Gregord45210d2009-01-30 22:09:00 +0000382
383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
Douglas Gregorf603b472009-01-28 21:54:33 +0000386 }
387
388 return;
389 }
390
391 QualType ElementType;
392
Douglas Gregor538a4c22009-02-02 17:43:21 +0000393 unsigned NumInits = ILE->getNumInits();
394 unsigned NumElements = NumInits;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000395 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000396 ElementType = AType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000397 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
398 NumElements = CAType->getSize().getZExtValue();
399 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000400 ElementType = VType->getElementType();
Douglas Gregor538a4c22009-02-02 17:43:21 +0000401 NumElements = VType->getNumElements();
402 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000403 ElementType = ILE->getType();
404
Douglas Gregor538a4c22009-02-02 17:43:21 +0000405 for (unsigned Init = 0; Init != NumElements; ++Init) {
406 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000407 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor538a4c22009-02-02 17:43:21 +0000408 hadError = true;
409 return;
410 }
411
Mike Stumpe127ae32009-05-16 07:39:55 +0000412 // FIXME: If value-initialization involves calling a constructor, should
413 // we make that call explicit in the representation (even when it means
414 // extending the initializer list)?
Douglas Gregor538a4c22009-02-02 17:43:21 +0000415 if (Init < NumInits && !hadError)
416 ILE->setInit(Init,
Chris Lattner2e2766a2009-02-24 22:50:46 +0000417 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stump90fc78e2009-08-04 21:02:39 +0000418 } else if (InitListExpr *InnerILE
419 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregord45210d2009-01-30 22:09:00 +0000420 FillInValueInitializations(InnerILE);
Douglas Gregorf603b472009-01-28 21:54:33 +0000421 }
422}
423
Chris Lattner1aa25a72009-01-29 05:10:57 +0000424
Chris Lattner2e2766a2009-02-24 22:50:46 +0000425InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
426 : SemaRef(S) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000427 hadError = false;
Eli Friedmand8535af2008-05-19 20:00:43 +0000428
Eli Friedman683cedf2008-05-19 19:16:24 +0000429 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000430 unsigned newStructuredIndex = 0;
431 FullyStructuredList
Douglas Gregorea765e12009-03-01 17:12:46 +0000432 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorbe69b162009-02-04 22:46:25 +0000433 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
434 /*TopLevelObject=*/true);
Eli Friedmand8535af2008-05-19 20:00:43 +0000435
Douglas Gregord45210d2009-01-30 22:09:00 +0000436 if (!hadError)
437 FillInValueInitializations(FullyStructuredList);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000438}
439
440int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman46f81662008-05-25 13:22:35 +0000441 // FIXME: use a proper constant
442 int maxElements = 0x7FFFFFFF;
Chris Lattnera1923f62008-08-04 07:31:14 +0000443 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000444 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000445 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
446 }
447 return maxElements;
448}
449
450int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000451 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregorf603b472009-01-28 21:54:33 +0000452 int InitializableMembers = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000453 for (RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000454 Field = structDecl->field_begin(),
455 FieldEnd = structDecl->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +0000456 Field != FieldEnd; ++Field) {
457 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
458 ++InitializableMembers;
459 }
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000460 if (structDecl->isUnion())
Eli Friedman9f5250b2008-05-25 14:03:31 +0000461 return std::min(InitializableMembers, 1);
462 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000463}
464
465void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregorf603b472009-01-28 21:54:33 +0000466 QualType T, unsigned &Index,
467 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000468 unsigned &StructuredIndex,
469 bool TopLevelObject) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000470 int maxElements = 0;
471
472 if (T->isArrayType())
473 maxElements = numArrayElements(T);
474 else if (T->isStructureType() || T->isUnionType())
475 maxElements = numStructUnionElements(T);
Eli Friedman683cedf2008-05-19 19:16:24 +0000476 else if (T->isVectorType())
477 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000478 else
479 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman683cedf2008-05-19 19:16:24 +0000480
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000481 if (maxElements == 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000482 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000483 diag::err_implicit_empty_initializer);
Douglas Gregorf603b472009-01-28 21:54:33 +0000484 ++Index;
Eli Friedmanf8df28c2008-05-25 13:49:22 +0000485 hadError = true;
486 return;
487 }
488
Douglas Gregorf603b472009-01-28 21:54:33 +0000489 // Build a structured initializer list corresponding to this subobject.
490 InitListExpr *StructuredSubobjectInitList
491 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
492 StructuredIndex,
Douglas Gregorea765e12009-03-01 17:12:46 +0000493 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
494 ParentIList->getSourceRange().getEnd()));
Douglas Gregorf603b472009-01-28 21:54:33 +0000495 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman683cedf2008-05-19 19:16:24 +0000496
Douglas Gregorf603b472009-01-28 21:54:33 +0000497 // Check the element types and build the structural subobject.
Douglas Gregor538a4c22009-02-02 17:43:21 +0000498 unsigned StartIndex = Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000499 CheckListElementTypes(ParentIList, T, false, Index,
500 StructuredSubobjectInitList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000501 StructuredSubobjectInitIndex,
502 TopLevelObject);
Douglas Gregor538a4c22009-02-02 17:43:21 +0000503 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregorcd2c5272009-03-20 00:32:56 +0000504 StructuredSubobjectInitList->setType(T);
505
Douglas Gregorea765e12009-03-01 17:12:46 +0000506 // Update the structured sub-object initializer so that it's ending
Douglas Gregor538a4c22009-02-02 17:43:21 +0000507 // range corresponds with the end of the last initializer it used.
508 if (EndIndex < ParentIList->getNumInits()) {
509 SourceLocation EndLoc
510 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
511 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
512 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000513}
514
Steve Naroff56099522008-05-06 00:23:44 +0000515void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorf603b472009-01-28 21:54:33 +0000516 unsigned &Index,
517 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000518 unsigned &StructuredIndex,
519 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000520 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregorf603b472009-01-28 21:54:33 +0000521 SyntacticToSemantic[IList] = StructuredList;
522 StructuredList->setSyntacticForm(IList);
523 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000524 StructuredIndex, TopLevelObject);
Steve Naroff56099522008-05-06 00:23:44 +0000525 IList->setType(T);
Douglas Gregorf603b472009-01-28 21:54:33 +0000526 StructuredList->setType(T);
Eli Friedman46f81662008-05-25 13:22:35 +0000527 if (hadError)
528 return;
Eli Friedmand8535af2008-05-19 20:00:43 +0000529
Eli Friedman46f81662008-05-25 13:22:35 +0000530 if (Index < IList->getNumInits()) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000531 // We have leftover initializers
Eli Friedman579534a2009-05-29 20:20:05 +0000532 if (StructuredIndex == 1 &&
533 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000534 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000535 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000536 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedman579534a2009-05-29 20:20:05 +0000537 hadError = true;
538 }
Eli Friedman71de9eb2008-05-19 20:12:18 +0000539 // Special-case
Chris Lattner2e2766a2009-02-24 22:50:46 +0000540 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000541 << IList->getInit(Index)->getSourceRange();
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000542 } else if (!T->isIncompleteType()) {
Douglas Gregor09f078c2009-01-30 22:26:29 +0000543 // Don't complain for incomplete types, since we'll get an error
544 // elsewhere
Douglas Gregorbe69b162009-02-04 22:46:25 +0000545 QualType CurrentObjectType = StructuredList->getType();
546 int initKind =
547 CurrentObjectType->isArrayType()? 0 :
548 CurrentObjectType->isVectorType()? 1 :
549 CurrentObjectType->isScalarType()? 2 :
550 CurrentObjectType->isUnionType()? 3 :
551 4;
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000552
553 unsigned DK = diag::warn_excess_initializers;
Eli Friedman579534a2009-05-29 20:20:05 +0000554 if (SemaRef.getLangOptions().CPlusPlus) {
555 DK = diag::err_excess_initializers;
556 hadError = true;
557 }
Nate Begeman48fd8c92009-07-07 21:53:06 +0000558 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
559 DK = diag::err_excess_initializers;
560 hadError = true;
561 }
Douglas Gregorc25bf6d2009-02-18 22:23:55 +0000562
Chris Lattner2e2766a2009-02-24 22:50:46 +0000563 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorbe69b162009-02-04 22:46:25 +0000564 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmand8535af2008-05-19 20:00:43 +0000565 }
566 }
Eli Friedman455f7622008-05-19 20:20:43 +0000567
Eli Friedman90bcb892009-05-16 11:45:48 +0000568 if (T->isScalarType() && !TopLevelObject)
Chris Lattner2e2766a2009-02-24 22:50:46 +0000569 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor3faaa812009-04-01 23:51:29 +0000570 << IList->getSourceRange()
571 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
572 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroffc4d4a482008-05-01 22:18:59 +0000573}
574
Eli Friedman683cedf2008-05-19 19:16:24 +0000575void InitListChecker::CheckListElementTypes(InitListExpr *IList,
576 QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000577 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000578 unsigned &Index,
579 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000580 unsigned &StructuredIndex,
581 bool TopLevelObject) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000582 if (DeclType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000583 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmand8535af2008-05-19 20:00:43 +0000584 } else if (DeclType->isVectorType()) {
Douglas Gregorf603b472009-01-28 21:54:33 +0000585 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregore7ef5002009-01-30 17:31:00 +0000586 } else if (DeclType->isAggregateType()) {
587 if (DeclType->isRecordType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000588 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000589 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregorf603b472009-01-28 21:54:33 +0000590 SubobjectIsDesignatorContext, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000591 StructuredList, StructuredIndex,
592 TopLevelObject);
Douglas Gregor710f6d42009-01-22 23:26:18 +0000593 } else if (DeclType->isArrayType()) {
Douglas Gregor5a203a62009-01-23 16:54:12 +0000594 llvm::APSInt Zero(
Chris Lattner2e2766a2009-02-24 22:50:46 +0000595 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor5a203a62009-01-23 16:54:12 +0000596 false);
Douglas Gregorf603b472009-01-28 21:54:33 +0000597 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
598 StructuredList, StructuredIndex);
Mike Stump90fc78e2009-08-04 21:02:39 +0000599 } else
Douglas Gregorf603b472009-01-28 21:54:33 +0000600 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffff5b3a82008-08-10 16:05:48 +0000601 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
602 // This type is invalid, issue a diagnostic.
Douglas Gregorf603b472009-01-28 21:54:33 +0000603 ++Index;
Chris Lattner2e2766a2009-02-24 22:50:46 +0000604 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000605 << DeclType;
Eli Friedmanb9ea6bc2008-05-20 05:25:56 +0000606 hadError = true;
Douglas Gregord45210d2009-01-30 22:09:00 +0000607 } else if (DeclType->isRecordType()) {
608 // C++ [dcl.init]p14:
609 // [...] If the class is an aggregate (8.5.1), and the initializer
610 // is a brace-enclosed list, see 8.5.1.
611 //
612 // Note: 8.5.1 is handled below; here, we diagnose the case where
613 // we have an initializer list and a destination type that is not
614 // an aggregate.
615 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000616 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000617 << DeclType << IList->getSourceRange();
618 hadError = true;
619 } else if (DeclType->isReferenceType()) {
620 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000621 } else {
622 // In C, all types are either scalars or aggregates, but
623 // additional handling is needed here for C++ (and possibly others?).
624 assert(0 && "Unsupported initializer type");
625 }
626}
627
Eli Friedman683cedf2008-05-19 19:16:24 +0000628void InitListChecker::CheckSubElementType(InitListExpr *IList,
629 QualType ElemType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000630 unsigned &Index,
631 InitListExpr *StructuredList,
632 unsigned &StructuredIndex) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000633 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000634 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
635 unsigned newIndex = 0;
Douglas Gregorf603b472009-01-28 21:54:33 +0000636 unsigned newStructuredIndex = 0;
637 InitListExpr *newStructuredList
638 = getStructuredSubobjectInit(IList, Index, ElemType,
639 StructuredList, StructuredIndex,
640 SubInitList->getSourceRange());
641 CheckExplicitInitList(SubInitList, ElemType, newIndex,
642 newStructuredList, newStructuredIndex);
643 ++StructuredIndex;
644 ++Index;
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000645 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
646 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattner45d6fd62009-02-24 22:41:04 +0000647 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregorf603b472009-01-28 21:54:33 +0000648 ++Index;
Eli Friedmand8535af2008-05-19 20:00:43 +0000649 } else if (ElemType->isScalarType()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000650 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord45210d2009-01-30 22:09:00 +0000651 } else if (ElemType->isReferenceType()) {
652 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman683cedf2008-05-19 19:16:24 +0000653 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000654 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000655 // C++ [dcl.init.aggr]p12:
656 // All implicit type conversions (clause 4) are considered when
657 // initializing the aggregate member with an ini- tializer from
658 // an initializer-list. If the initializer can initialize a
659 // member, the member is initialized. [...]
660 ImplicitConversionSequence ICS
Chris Lattner2e2766a2009-02-24 22:50:46 +0000661 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregord45210d2009-01-30 22:09:00 +0000662 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000663 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregord45210d2009-01-30 22:09:00 +0000664 "initializing"))
665 hadError = true;
666 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
667 ++Index;
668 return;
669 }
670
671 // Fall through for subaggregate initialization
672 } else {
673 // C99 6.7.8p13:
674 //
675 // The initializer for a structure or union object that has
676 // automatic storage duration shall be either an initializer
677 // list as described below, or a single expression that has
678 // compatible structure or union type. In the latter case, the
679 // initial value of the object, including unnamed members, is
680 // that of the expression.
Eli Friedman2a553812009-06-13 10:38:46 +0000681 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman95acf982009-05-29 18:22:49 +0000682 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord45210d2009-01-30 22:09:00 +0000683 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
684 ++Index;
685 return;
686 }
687
688 // Fall through for subaggregate initialization
689 }
690
691 // C++ [dcl.init.aggr]p12:
692 //
693 // [...] Otherwise, if the member is itself a non-empty
694 // subaggregate, brace elision is assumed and the initializer is
695 // considered for the initialization of the first member of
696 // the subaggregate.
697 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
698 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
699 StructuredIndex);
700 ++StructuredIndex;
701 } else {
702 // We cannot initialize this element, so let
703 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000704 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregord45210d2009-01-30 22:09:00 +0000705 hadError = true;
706 ++Index;
707 ++StructuredIndex;
708 }
709 }
Eli Friedman683cedf2008-05-19 19:16:24 +0000710}
711
Douglas Gregord45210d2009-01-30 22:09:00 +0000712void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor36859eb2009-01-29 00:39:20 +0000713 unsigned &Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000714 InitListExpr *StructuredList,
715 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000716 if (Index < IList->getNumInits()) {
Douglas Gregor36859eb2009-01-29 00:39:20 +0000717 Expr *expr = IList->getInit(Index);
Eli Friedmand8535af2008-05-19 20:00:43 +0000718 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000719 SemaRef.Diag(IList->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000720 diag::err_many_braces_around_scalar_init)
721 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000722 hadError = true;
723 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000724 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000725 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000726 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000727 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000728 diag::err_designator_for_scalar_init)
729 << DeclType << expr->getSourceRange();
730 hadError = true;
731 ++Index;
Douglas Gregorf603b472009-01-28 21:54:33 +0000732 ++StructuredIndex;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000733 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000734 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000735
Eli Friedmand8535af2008-05-19 20:00:43 +0000736 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000737 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedman71de9eb2008-05-19 20:12:18 +0000738 hadError = true; // types weren't compatible.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000739 else if (savExpr != expr) {
Eli Friedmand8535af2008-05-19 20:00:43 +0000740 // The type was promoted, update initializer list.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000741 IList->setInit(Index, expr);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000742 }
Douglas Gregorf603b472009-01-28 21:54:33 +0000743 if (hadError)
744 ++StructuredIndex;
745 else
746 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000747 ++Index;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000748 } else {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000749 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattner9d2cf082008-11-19 05:27:50 +0000750 << IList->getSourceRange();
Eli Friedman71de9eb2008-05-19 20:12:18 +0000751 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000752 ++Index;
753 ++StructuredIndex;
Eli Friedman71de9eb2008-05-19 20:12:18 +0000754 return;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000755 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000756}
757
Douglas Gregord45210d2009-01-30 22:09:00 +0000758void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
759 unsigned &Index,
760 InitListExpr *StructuredList,
761 unsigned &StructuredIndex) {
762 if (Index < IList->getNumInits()) {
763 Expr *expr = IList->getInit(Index);
764 if (isa<InitListExpr>(expr)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +0000765 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord45210d2009-01-30 22:09:00 +0000766 << DeclType << IList->getSourceRange();
767 hadError = true;
768 ++Index;
769 ++StructuredIndex;
770 return;
771 }
772
773 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000774 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregord45210d2009-01-30 22:09:00 +0000775 hadError = true;
776 else if (savExpr != expr) {
777 // The type was promoted, update initializer list.
778 IList->setInit(Index, expr);
779 }
780 if (hadError)
781 ++StructuredIndex;
782 else
783 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
784 ++Index;
785 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +0000786 // FIXME: It would be wonderful if we could point at the actual member. In
787 // general, it would be useful to pass location information down the stack,
788 // so that we know the location (or decl) of the "current object" being
789 // initialized.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000790 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord45210d2009-01-30 22:09:00 +0000791 diag::err_init_reference_member_uninitialized)
792 << DeclType
793 << IList->getSourceRange();
794 hadError = true;
795 ++Index;
796 ++StructuredIndex;
797 return;
798 }
799}
800
Steve Naroffc4d4a482008-05-01 22:18:59 +0000801void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf603b472009-01-28 21:54:33 +0000802 unsigned &Index,
803 InitListExpr *StructuredList,
804 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000805 if (Index < IList->getNumInits()) {
806 const VectorType *VT = DeclType->getAsVectorType();
Nate Begemane85f43d2009-08-10 23:49:36 +0000807 unsigned maxElements = VT->getNumElements();
808 unsigned numEltsInit = 0;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000809 QualType elementType = VT->getElementType();
810
Nate Begemane85f43d2009-08-10 23:49:36 +0000811 if (!SemaRef.getLangOptions().OpenCL) {
812 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
813 // Don't attempt to go past the end of the init list
814 if (Index >= IList->getNumInits())
815 break;
816 CheckSubElementType(IList, elementType, Index,
817 StructuredList, StructuredIndex);
818 }
819 } else {
820 // OpenCL initializers allows vectors to be constructed from vectors.
821 for (unsigned i = 0; i < maxElements; ++i) {
822 // Don't attempt to go past the end of the init list
823 if (Index >= IList->getNumInits())
824 break;
825 QualType IType = IList->getInit(Index)->getType();
826 if (!IType->isVectorType()) {
827 CheckSubElementType(IList, elementType, Index,
828 StructuredList, StructuredIndex);
829 ++numEltsInit;
830 } else {
831 const VectorType *IVT = IType->getAsVectorType();
832 unsigned numIElts = IVT->getNumElements();
833 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
834 numIElts);
835 CheckSubElementType(IList, VecType, Index,
836 StructuredList, StructuredIndex);
837 numEltsInit += numIElts;
838 }
839 }
Steve Naroffc4d4a482008-05-01 22:18:59 +0000840 }
Nate Begemane85f43d2009-08-10 23:49:36 +0000841
842 // OpenCL & AltiVec require all elements to be initialized.
843 if (numEltsInit != maxElements)
844 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
845 SemaRef.Diag(IList->getSourceRange().getBegin(),
846 diag::err_vector_incorrect_num_initializers)
847 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000848 }
849}
850
851void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000852 llvm::APSInt elementIndex,
853 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000854 unsigned &Index,
855 InitListExpr *StructuredList,
856 unsigned &StructuredIndex) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000857 // Check for the special-case of initializing an array with a string.
858 if (Index < IList->getNumInits()) {
Chris Lattner19ae2fc2009-02-24 23:10:27 +0000859 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
860 SemaRef.Context)) {
861 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregorf603b472009-01-28 21:54:33 +0000862 // We place the string literal directly into the resulting
863 // initializer list. This is the only place where the structure
864 // of the structured initializer list doesn't match exactly,
865 // because doing so would involve allocating one character
866 // constant for each string.
Chris Lattner45d6fd62009-02-24 22:41:04 +0000867 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner2e2766a2009-02-24 22:50:46 +0000868 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000869 ++Index;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000870 return;
871 }
872 }
Chris Lattnera1923f62008-08-04 07:31:14 +0000873 if (const VariableArrayType *VAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000874 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman46f81662008-05-25 13:22:35 +0000875 // Check for VLAs; in standard C it would be possible to check this
876 // earlier, but I don't know where clang accepts VLAs (gcc accepts
877 // them in all sorts of strange places).
Chris Lattner2e2766a2009-02-24 22:50:46 +0000878 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000879 diag::err_variable_object_no_init)
880 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman46f81662008-05-25 13:22:35 +0000881 hadError = true;
Douglas Gregorf603b472009-01-28 21:54:33 +0000882 ++Index;
883 ++StructuredIndex;
Eli Friedman46f81662008-05-25 13:22:35 +0000884 return;
885 }
886
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000887 // We might know the maximum number of elements in advance.
Douglas Gregorf603b472009-01-28 21:54:33 +0000888 llvm::APSInt maxElements(elementIndex.getBitWidth(),
889 elementIndex.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000890 bool maxElementsKnown = false;
891 if (const ConstantArrayType *CAT =
Chris Lattner2e2766a2009-02-24 22:50:46 +0000892 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000893 maxElements = CAT->getSize();
Douglas Gregor5a203a62009-01-23 16:54:12 +0000894 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000895 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000896 maxElementsKnown = true;
897 }
898
Chris Lattner2e2766a2009-02-24 22:50:46 +0000899 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnera1923f62008-08-04 07:31:14 +0000900 ->getElementType();
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000901 while (Index < IList->getNumInits()) {
902 Expr *Init = IList->getInit(Index);
903 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000904 // If we're not the subobject that matches up with the '{' for
905 // the designator, we shouldn't be handling the
906 // designator. Return immediately.
907 if (!SubobjectIsDesignatorContext)
908 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000909
Douglas Gregor710f6d42009-01-22 23:26:18 +0000910 // Handle this designated initializer. elementIndex will be
911 // updated to be the next array element we'll initialize.
Douglas Gregoraa357272009-04-15 04:56:10 +0000912 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +0000913 DeclType, 0, &elementIndex, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000914 StructuredList, StructuredIndex, true,
915 false)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +0000916 hadError = true;
917 continue;
918 }
919
Douglas Gregor5a203a62009-01-23 16:54:12 +0000920 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
921 maxElements.extend(elementIndex.getBitWidth());
922 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
923 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor69722702009-01-23 18:58:42 +0000924 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor5a203a62009-01-23 16:54:12 +0000925
Douglas Gregor710f6d42009-01-22 23:26:18 +0000926 // If the array is of incomplete type, keep track of the number of
927 // elements in the initializer.
928 if (!maxElementsKnown && elementIndex > maxElements)
929 maxElements = elementIndex;
930
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000931 continue;
932 }
933
934 // If we know the maximum number of elements, and we've already
935 // hit it, stop consuming elements in the initializer list.
936 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroffc4d4a482008-05-01 22:18:59 +0000937 break;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000938
939 // Check this element.
Douglas Gregor36859eb2009-01-29 00:39:20 +0000940 CheckSubElementType(IList, elementType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +0000941 StructuredList, StructuredIndex);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000942 ++elementIndex;
943
944 // If the array is of incomplete type, keep track of the number of
945 // elements in the initializer.
946 if (!maxElementsKnown && elementIndex > maxElements)
947 maxElements = elementIndex;
Steve Naroffc4d4a482008-05-01 22:18:59 +0000948 }
Eli Friedmanb4c71b32009-05-29 20:17:55 +0000949 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroffc4d4a482008-05-01 22:18:59 +0000950 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000951 // be calculated here.
Douglas Gregor69722702009-01-23 18:58:42 +0000952 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000953 if (maxElements == Zero) {
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000954 // Sizing an array implicitly to zero is not allowed by ISO C,
955 // but is supported by GNU.
Chris Lattner2e2766a2009-02-24 22:50:46 +0000956 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000957 diag::ext_typecheck_zero_array_size);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000958 }
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000959
Chris Lattner2e2766a2009-02-24 22:50:46 +0000960 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar604dacf2008-08-18 20:28:46 +0000961 ArrayType::Normal, 0);
Steve Naroffc4d4a482008-05-01 22:18:59 +0000962 }
963}
964
965void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
966 QualType DeclType,
Douglas Gregor710f6d42009-01-22 23:26:18 +0000967 RecordDecl::field_iterator Field,
968 bool SubobjectIsDesignatorContext,
Douglas Gregorf603b472009-01-28 21:54:33 +0000969 unsigned &Index,
970 InitListExpr *StructuredList,
Douglas Gregorbe69b162009-02-04 22:46:25 +0000971 unsigned &StructuredIndex,
972 bool TopLevelObject) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000973 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroffc4d4a482008-05-01 22:18:59 +0000974
Eli Friedman683cedf2008-05-19 19:16:24 +0000975 // If the record is invalid, some of it's members are invalid. To avoid
976 // confusion, we forgo checking the intializer for the entire record.
977 if (structDecl->isInvalidDecl()) {
978 hadError = true;
979 return;
980 }
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000981
982 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
983 // Value-initialize the first named member of the union.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000984 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000985 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000986 Field != FieldEnd; ++Field) {
987 if (Field->getDeclName()) {
988 StructuredList->setInitializedFieldInUnion(*Field);
989 break;
990 }
991 }
992 return;
993 }
994
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000995 // If structDecl is a forward declaration, this loop won't do
996 // anything except look at designated initializers; That's okay,
997 // because an error should get printed out elsewhere. It might be
998 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000999 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001000 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001001 bool InitializedSomething = false;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001002 while (Index < IList->getNumInits()) {
1003 Expr *Init = IList->getInit(Index);
1004
1005 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001006 // If we're not the subobject that matches up with the '{' for
1007 // the designator, we shouldn't be handling the
1008 // designator. Return immediately.
1009 if (!SubobjectIsDesignatorContext)
1010 return;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001011
Douglas Gregor710f6d42009-01-22 23:26:18 +00001012 // Handle this designated initializer. Field will be updated to
1013 // the next field that we'll be initializing.
Douglas Gregoraa357272009-04-15 04:56:10 +00001014 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregorf603b472009-01-28 21:54:33 +00001015 DeclType, &Field, 0, Index,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001016 StructuredList, StructuredIndex,
1017 true, TopLevelObject))
Douglas Gregor710f6d42009-01-22 23:26:18 +00001018 hadError = true;
1019
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001020 InitializedSomething = true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001021 continue;
1022 }
1023
1024 if (Field == FieldEnd) {
1025 // We've run out of fields. We're done.
1026 break;
1027 }
1028
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001029 // We've already initialized a member of a union. We're done.
1030 if (InitializedSomething && DeclType->isUnionType())
1031 break;
1032
Douglas Gregor8acb7272008-12-11 16:49:14 +00001033 // If we've hit the flexible array member at the end, we're done.
1034 if (Field->getType()->isIncompleteArrayType())
1035 break;
1036
Douglas Gregor82462762009-01-29 16:53:55 +00001037 if (Field->isUnnamedBitfield()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001038 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001039 ++Field;
Eli Friedman683cedf2008-05-19 19:16:24 +00001040 continue;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001041 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001042
Douglas Gregor36859eb2009-01-29 00:39:20 +00001043 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001044 StructuredList, StructuredIndex);
Douglas Gregor0ecc9e92009-02-12 19:00:39 +00001045 InitializedSomething = true;
Douglas Gregor82462762009-01-29 16:53:55 +00001046
1047 if (DeclType->isUnionType()) {
1048 // Initialize the first field within the union.
1049 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor82462762009-01-29 16:53:55 +00001050 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001051
1052 ++Field;
Steve Naroffc4d4a482008-05-01 22:18:59 +00001053 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001054
Douglas Gregorbe69b162009-02-04 22:46:25 +00001055 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001056 Index >= IList->getNumInits())
Douglas Gregorbe69b162009-02-04 22:46:25 +00001057 return;
1058
1059 // Handle GNU flexible array initializers.
1060 if (!TopLevelObject &&
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001061 (!isa<InitListExpr>(IList->getInit(Index)) ||
1062 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001063 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001064 diag::err_flexible_array_init_nonempty)
1065 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001066 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001067 << *Field;
1068 hadError = true;
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001069 ++Index;
1070 return;
1071 } else {
1072 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1073 diag::ext_flexible_array_init)
1074 << IList->getInit(Index)->getSourceRange().getBegin();
1075 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1076 << *Field;
Douglas Gregorbe69b162009-02-04 22:46:25 +00001077 }
1078
Douglas Gregorcd2c5272009-03-20 00:32:56 +00001079 if (isa<InitListExpr>(IList->getInit(Index)))
1080 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1081 StructuredIndex);
1082 else
1083 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1084 StructuredIndex);
Steve Naroffc4d4a482008-05-01 22:18:59 +00001085}
Steve Naroffc4d4a482008-05-01 22:18:59 +00001086
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001087/// \brief Expand a field designator that refers to a member of an
1088/// anonymous struct or union into a series of field designators that
1089/// refers to the field within the appropriate subobject.
1090///
1091/// Field/FieldIndex will be updated to point to the (new)
1092/// currently-designated field.
1093static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1094 DesignatedInitExpr *DIE,
1095 unsigned DesigIdx,
1096 FieldDecl *Field,
1097 RecordDecl::field_iterator &FieldIter,
1098 unsigned &FieldIndex) {
1099 typedef DesignatedInitExpr::Designator Designator;
1100
1101 // Build the path from the current object to the member of the
1102 // anonymous struct/union (backwards).
1103 llvm::SmallVector<FieldDecl *, 4> Path;
1104 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1105
1106 // Build the replacement designators.
1107 llvm::SmallVector<Designator, 4> Replacements;
1108 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1109 FI = Path.rbegin(), FIEnd = Path.rend();
1110 FI != FIEnd; ++FI) {
1111 if (FI + 1 == FIEnd)
1112 Replacements.push_back(Designator((IdentifierInfo *)0,
1113 DIE->getDesignator(DesigIdx)->getDotLoc(),
1114 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1115 else
1116 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1117 SourceLocation()));
1118 Replacements.back().setField(*FI);
1119 }
1120
1121 // Expand the current designator into the set of replacement
1122 // designators, so we have a full subobject path down to where the
1123 // member of the anonymous struct/union is actually stored.
1124 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1125 &Replacements[0] + Replacements.size());
1126
1127 // Update FieldIter/FieldIndex;
1128 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001129 FieldIter = Record->field_begin();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001130 FieldIndex = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001131 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001132 FieldIter != FEnd; ++FieldIter) {
1133 if (FieldIter->isUnnamedBitfield())
1134 continue;
1135
1136 if (*FieldIter == Path.back())
1137 return;
1138
1139 ++FieldIndex;
1140 }
1141
1142 assert(false && "Unable to find anonymous struct/union field");
1143}
1144
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001145/// @brief Check the well-formedness of a C99 designated initializer.
1146///
1147/// Determines whether the designated initializer @p DIE, which
1148/// resides at the given @p Index within the initializer list @p
1149/// IList, is well-formed for a current object of type @p DeclType
1150/// (C99 6.7.8). The actual subobject that this designator refers to
1151/// within the current subobject is returned in either
Douglas Gregorf603b472009-01-28 21:54:33 +00001152/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001153///
1154/// @param IList The initializer list in which this designated
1155/// initializer occurs.
1156///
Douglas Gregoraa357272009-04-15 04:56:10 +00001157/// @param DIE The designated initializer expression.
1158///
1159/// @param DesigIdx The index of the current designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001160///
1161/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1162/// into which the designation in @p DIE should refer.
1163///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001164/// @param NextField If non-NULL and the first designator in @p DIE is
1165/// a field, this will be set to the field declaration corresponding
1166/// to the field named by the designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001167///
Douglas Gregor710f6d42009-01-22 23:26:18 +00001168/// @param NextElementIndex If non-NULL and the first designator in @p
1169/// DIE is an array designator or GNU array-range designator, this
1170/// will be set to the last index initialized by this designator.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001171///
1172/// @param Index Index into @p IList where the designated initializer
1173/// @p DIE occurs.
1174///
Douglas Gregorf603b472009-01-28 21:54:33 +00001175/// @param StructuredList The initializer list expression that
1176/// describes all of the subobject initializers in the order they'll
1177/// actually be initialized.
1178///
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001179/// @returns true if there was an error, false otherwise.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001180bool
1181InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1182 DesignatedInitExpr *DIE,
Douglas Gregoraa357272009-04-15 04:56:10 +00001183 unsigned DesigIdx,
Douglas Gregor710f6d42009-01-22 23:26:18 +00001184 QualType &CurrentObjectType,
1185 RecordDecl::field_iterator *NextField,
1186 llvm::APSInt *NextElementIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001187 unsigned &Index,
1188 InitListExpr *StructuredList,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001189 unsigned &StructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001190 bool FinishSubobjectInit,
1191 bool TopLevelObject) {
Douglas Gregoraa357272009-04-15 04:56:10 +00001192 if (DesigIdx == DIE->size()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001193 // Check the actual initialization for the designated object type.
1194 bool prevHadError = hadError;
Douglas Gregor36859eb2009-01-29 00:39:20 +00001195
1196 // Temporarily remove the designator expression from the
1197 // initializer list that the child calls see, so that we don't try
1198 // to re-process the designator.
1199 unsigned OldIndex = Index;
1200 IList->setInit(OldIndex, DIE->getInit());
1201
1202 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001203 StructuredList, StructuredIndex);
Douglas Gregor36859eb2009-01-29 00:39:20 +00001204
1205 // Restore the designated initializer expression in the syntactic
1206 // form of the initializer list.
1207 if (IList->getInit(OldIndex) != DIE->getInit())
1208 DIE->setInit(IList->getInit(OldIndex));
1209 IList->setInit(OldIndex, DIE);
1210
Douglas Gregor710f6d42009-01-22 23:26:18 +00001211 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001212 }
1213
Douglas Gregoraa357272009-04-15 04:56:10 +00001214 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregorf603b472009-01-28 21:54:33 +00001215 assert((IsFirstDesignator || StructuredList) &&
1216 "Need a non-designated initializer list to start from");
1217
Douglas Gregoraa357272009-04-15 04:56:10 +00001218 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001219 // Determine the structural initializer list that corresponds to the
1220 // current subobject.
1221 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregorea765e12009-03-01 17:12:46 +00001222 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1223 StructuredList, StructuredIndex,
Douglas Gregorf603b472009-01-28 21:54:33 +00001224 SourceRange(D->getStartLocation(),
1225 DIE->getSourceRange().getEnd()));
1226 assert(StructuredList && "Expected a structured initializer list");
1227
Douglas Gregor710f6d42009-01-22 23:26:18 +00001228 if (D->isFieldDesignator()) {
1229 // C99 6.7.8p7:
1230 //
1231 // If a designator has the form
1232 //
1233 // . identifier
1234 //
1235 // then the current object (defined below) shall have
1236 // structure or union type and the identifier shall be the
1237 // name of a member of that type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001238 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001239 if (!RT) {
1240 SourceLocation Loc = D->getDotLoc();
1241 if (Loc.isInvalid())
1242 Loc = D->getFieldLoc();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001243 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1244 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001245 ++Index;
1246 return true;
1247 }
1248
Douglas Gregorf603b472009-01-28 21:54:33 +00001249 // Note: we perform a linear search of the fields here, despite
1250 // the fact that we have a faster lookup method, because we always
1251 // need to compute the field's index.
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001252 FieldDecl *KnownField = D->getField();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001253 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregorf603b472009-01-28 21:54:33 +00001254 unsigned FieldIndex = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001255 RecordDecl::field_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001256 Field = RT->getDecl()->field_begin(),
1257 FieldEnd = RT->getDecl()->field_end();
Douglas Gregorf603b472009-01-28 21:54:33 +00001258 for (; Field != FieldEnd; ++Field) {
1259 if (Field->isUnnamedBitfield())
1260 continue;
1261
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001262 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregorf603b472009-01-28 21:54:33 +00001263 break;
1264
1265 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001266 }
1267
Douglas Gregorf603b472009-01-28 21:54:33 +00001268 if (Field == FieldEnd) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001269 // There was no normal field in the struct with the designated
1270 // name. Perform another lookup for this name, which may find
1271 // something that we can't designate (e.g., a member function),
1272 // may find nothing, or may find a member of an anonymous
1273 // struct/union.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001274 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorf603b472009-01-28 21:54:33 +00001275 if (Lookup.first == Lookup.second) {
1276 // Name lookup didn't find anything.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001277 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregorf603b472009-01-28 21:54:33 +00001278 << FieldName << CurrentObjectType;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001279 ++Index;
1280 return true;
1281 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1282 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1283 ->isAnonymousStructOrUnion()) {
1284 // Handle an field designator that refers to a member of an
1285 // anonymous struct or union.
1286 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1287 cast<FieldDecl>(*Lookup.first),
1288 Field, FieldIndex);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001289 D = DIE->getDesignator(DesigIdx);
Douglas Gregorf603b472009-01-28 21:54:33 +00001290 } else {
1291 // Name lookup found something, but it wasn't a field.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001292 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregorf603b472009-01-28 21:54:33 +00001293 << FieldName;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001294 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001295 diag::note_field_designator_found);
Eli Friedmanbd45b552009-04-16 17:49:48 +00001296 ++Index;
1297 return true;
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001298 }
1299 } else if (!KnownField &&
1300 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregorf603b472009-01-28 21:54:33 +00001301 ->isAnonymousStructOrUnion()) {
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001302 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1303 Field, FieldIndex);
1304 D = DIE->getDesignator(DesigIdx);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001305 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001306
1307 // All of the fields of a union are located at the same place in
1308 // the initializer list.
Douglas Gregor82462762009-01-29 16:53:55 +00001309 if (RT->getDecl()->isUnion()) {
Douglas Gregorf603b472009-01-28 21:54:33 +00001310 FieldIndex = 0;
Douglas Gregor82462762009-01-29 16:53:55 +00001311 StructuredList->setInitializedFieldInUnion(*Field);
1312 }
Douglas Gregorf603b472009-01-28 21:54:33 +00001313
Douglas Gregor710f6d42009-01-22 23:26:18 +00001314 // Update the designator with the field declaration.
Douglas Gregorf603b472009-01-28 21:54:33 +00001315 D->setField(*Field);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001316
Douglas Gregorf603b472009-01-28 21:54:33 +00001317 // Make sure that our non-designated initializer list has space
1318 // for a subobject corresponding to this field.
1319 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001320 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001321
Douglas Gregorbe69b162009-02-04 22:46:25 +00001322 // This designator names a flexible array member.
1323 if (Field->getType()->isIncompleteArrayType()) {
1324 bool Invalid = false;
Douglas Gregoraa357272009-04-15 04:56:10 +00001325 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorbe69b162009-02-04 22:46:25 +00001326 // We can't designate an object within the flexible array
1327 // member (because GCC doesn't allow it).
Douglas Gregoraa357272009-04-15 04:56:10 +00001328 DesignatedInitExpr::Designator *NextD
1329 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner2e2766a2009-02-24 22:50:46 +00001330 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001331 diag::err_designator_into_flexible_array_member)
1332 << SourceRange(NextD->getStartLocation(),
1333 DIE->getSourceRange().getEnd());
Chris Lattner2e2766a2009-02-24 22:50:46 +00001334 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001335 << *Field;
1336 Invalid = true;
1337 }
1338
1339 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1340 // The initializer is not an initializer list.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001341 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001342 diag::err_flexible_array_init_needs_braces)
1343 << DIE->getInit()->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001344 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001345 << *Field;
1346 Invalid = true;
1347 }
1348
1349 // Handle GNU flexible array initializers.
1350 if (!Invalid && !TopLevelObject &&
1351 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001352 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorbe69b162009-02-04 22:46:25 +00001353 diag::err_flexible_array_init_nonempty)
1354 << DIE->getSourceRange().getBegin();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001355 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorbe69b162009-02-04 22:46:25 +00001356 << *Field;
1357 Invalid = true;
1358 }
1359
1360 if (Invalid) {
1361 ++Index;
1362 return true;
1363 }
1364
1365 // Initialize the array.
1366 bool prevHadError = hadError;
1367 unsigned newStructuredIndex = FieldIndex;
1368 unsigned OldIndex = Index;
1369 IList->setInit(Index, DIE->getInit());
1370 CheckSubElementType(IList, Field->getType(), Index,
1371 StructuredList, newStructuredIndex);
1372 IList->setInit(OldIndex, DIE);
1373 if (hadError && !prevHadError) {
1374 ++Field;
1375 ++FieldIndex;
1376 if (NextField)
1377 *NextField = Field;
1378 StructuredIndex = FieldIndex;
1379 return true;
1380 }
1381 } else {
1382 // Recurse to check later designated subobjects.
1383 QualType FieldType = (*Field)->getType();
1384 unsigned newStructuredIndex = FieldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001385 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1386 Index, StructuredList, newStructuredIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001387 true, false))
1388 return true;
1389 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001390
1391 // Find the position of the next field to be initialized in this
1392 // subobject.
Douglas Gregor710f6d42009-01-22 23:26:18 +00001393 ++Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001394 ++FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001395
1396 // If this the first designator, our caller will continue checking
1397 // the rest of this struct/class/union subobject.
1398 if (IsFirstDesignator) {
1399 if (NextField)
1400 *NextField = Field;
Douglas Gregorf603b472009-01-28 21:54:33 +00001401 StructuredIndex = FieldIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001402 return false;
1403 }
1404
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001405 if (!FinishSubobjectInit)
1406 return false;
1407
Douglas Gregorcc94ab72009-04-15 06:41:24 +00001408 // We've already initialized something in the union; we're done.
1409 if (RT->getDecl()->isUnion())
1410 return hadError;
1411
Douglas Gregor710f6d42009-01-22 23:26:18 +00001412 // Check the remaining fields within this class/struct/union subobject.
1413 bool prevHadError = hadError;
Douglas Gregorf603b472009-01-28 21:54:33 +00001414 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1415 StructuredList, FieldIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001416 return hadError && !prevHadError;
1417 }
1418
1419 // C99 6.7.8p6:
1420 //
1421 // If a designator has the form
1422 //
1423 // [ constant-expression ]
1424 //
1425 // then the current object (defined below) shall have array
1426 // type and the expression shall be an integer constant
1427 // expression. If the array is of unknown size, any
1428 // nonnegative value is valid.
1429 //
1430 // Additionally, cope with the GNU extension that permits
1431 // designators of the form
1432 //
1433 // [ constant-expression ... constant-expression ]
Chris Lattner2e2766a2009-02-24 22:50:46 +00001434 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001435 if (!AT) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001436 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001437 << CurrentObjectType;
1438 ++Index;
1439 return true;
1440 }
1441
1442 Expr *IndexExpr = 0;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001443 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1444 if (D->isArrayDesignator()) {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001445 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnereec8ae22009-04-25 21:59:05 +00001446 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001447 DesignatedEndIndex = DesignatedStartIndex;
1448 } else {
Douglas Gregor710f6d42009-01-22 23:26:18 +00001449 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001450
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001451
Chris Lattnereec8ae22009-04-25 21:59:05 +00001452 DesignatedStartIndex =
1453 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1454 DesignatedEndIndex =
1455 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001456 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001457
Chris Lattnereec8ae22009-04-25 21:59:05 +00001458 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregor9fddded2009-01-29 19:42:23 +00001459 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor710f6d42009-01-22 23:26:18 +00001460 }
1461
Douglas Gregor710f6d42009-01-22 23:26:18 +00001462 if (isa<ConstantArrayType>(AT)) {
1463 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001464 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1465 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1466 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1467 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1468 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001469 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor710f6d42009-01-22 23:26:18 +00001470 diag::err_array_designator_too_large)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001471 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor710f6d42009-01-22 23:26:18 +00001472 << IndexExpr->getSourceRange();
1473 ++Index;
1474 return true;
1475 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001476 } else {
1477 // Make sure the bit-widths and signedness match.
1478 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1479 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnereec8ae22009-04-25 21:59:05 +00001480 else if (DesignatedStartIndex.getBitWidth() <
1481 DesignatedEndIndex.getBitWidth())
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001482 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1483 DesignatedStartIndex.setIsUnsigned(true);
1484 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001485 }
1486
Douglas Gregorf603b472009-01-28 21:54:33 +00001487 // Make sure that our non-designated initializer list has space
1488 // for a subobject corresponding to this array element.
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001489 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner2e2766a2009-02-24 22:50:46 +00001490 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001491 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregorf603b472009-01-28 21:54:33 +00001492
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001493 // Repeatedly perform subobject initializations in the range
1494 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor710f6d42009-01-22 23:26:18 +00001495
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001496 // Move to the next designator
1497 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1498 unsigned OldIndex = Index;
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001499 while (DesignatedStartIndex <= DesignatedEndIndex) {
1500 // Recurse to check later designated subobjects.
1501 QualType ElementType = AT->getElementType();
1502 Index = OldIndex;
Douglas Gregoraa357272009-04-15 04:56:10 +00001503 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1504 Index, StructuredList, ElementIndex,
Douglas Gregorbe69b162009-02-04 22:46:25 +00001505 (DesignatedStartIndex == DesignatedEndIndex),
1506 false))
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001507 return true;
1508
1509 // Move to the next index in the array that we'll be initializing.
1510 ++DesignatedStartIndex;
1511 ElementIndex = DesignatedStartIndex.getZExtValue();
1512 }
Douglas Gregor710f6d42009-01-22 23:26:18 +00001513
1514 // If this the first designator, our caller will continue checking
1515 // the rest of this array subobject.
1516 if (IsFirstDesignator) {
1517 if (NextElementIndex)
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001518 *NextElementIndex = DesignatedStartIndex;
Douglas Gregorf603b472009-01-28 21:54:33 +00001519 StructuredIndex = ElementIndex;
Douglas Gregor710f6d42009-01-22 23:26:18 +00001520 return false;
1521 }
Douglas Gregor36dd0c52009-01-28 23:36:17 +00001522
1523 if (!FinishSubobjectInit)
1524 return false;
1525
Douglas Gregor710f6d42009-01-22 23:26:18 +00001526 // Check the remaining elements within this array subobject.
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001527 bool prevHadError = hadError;
Douglas Gregord7e76c52009-02-09 19:45:19 +00001528 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregorf603b472009-01-28 21:54:33 +00001529 StructuredList, ElementIndex);
Douglas Gregor710f6d42009-01-22 23:26:18 +00001530 return hadError && !prevHadError;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001531}
1532
Douglas Gregorf603b472009-01-28 21:54:33 +00001533// Get the structured initializer list for a subobject of type
1534// @p CurrentObjectType.
1535InitListExpr *
1536InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1537 QualType CurrentObjectType,
1538 InitListExpr *StructuredList,
1539 unsigned StructuredIndex,
1540 SourceRange InitRange) {
1541 Expr *ExistingInit = 0;
1542 if (!StructuredList)
1543 ExistingInit = SyntacticToSemantic[IList];
1544 else if (StructuredIndex < StructuredList->getNumInits())
1545 ExistingInit = StructuredList->getInit(StructuredIndex);
1546
1547 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1548 return Result;
1549
1550 if (ExistingInit) {
1551 // We are creating an initializer list that initializes the
1552 // subobjects of the current object, but there was already an
1553 // initialization that completely initialized the current
1554 // subobject, e.g., by a compound literal:
1555 //
1556 // struct X { int a, b; };
1557 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1558 //
1559 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1560 // designated initializer re-initializes the whole
1561 // subobject [0], overwriting previous initializers.
Douglas Gregorea765e12009-03-01 17:12:46 +00001562 SemaRef.Diag(InitRange.getBegin(),
1563 diag::warn_subobject_initializer_overrides)
Douglas Gregorf603b472009-01-28 21:54:33 +00001564 << InitRange;
Chris Lattner2e2766a2009-02-24 22:50:46 +00001565 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001566 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001567 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001568 << ExistingInit->getSourceRange();
1569 }
1570
1571 InitListExpr *Result
Douglas Gregorea765e12009-03-01 17:12:46 +00001572 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1573 InitRange.getEnd());
1574
Douglas Gregorf603b472009-01-28 21:54:33 +00001575 Result->setType(CurrentObjectType);
1576
Douglas Gregoree0792c2009-03-20 23:58:33 +00001577 // Pre-allocate storage for the structured initializer list.
1578 unsigned NumElements = 0;
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001579 unsigned NumInits = 0;
1580 if (!StructuredList)
1581 NumInits = IList->getNumInits();
1582 else if (Index < IList->getNumInits()) {
1583 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1584 NumInits = SubList->getNumInits();
1585 }
1586
Douglas Gregoree0792c2009-03-20 23:58:33 +00001587 if (const ArrayType *AType
1588 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1589 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1590 NumElements = CAType->getSize().getZExtValue();
1591 // Simple heuristic so that we don't allocate a very large
1592 // initializer with many empty entries at the end.
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001593 if (NumInits && NumElements > NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001594 NumElements = 0;
1595 }
1596 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1597 NumElements = VType->getNumElements();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001598 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregoree0792c2009-03-20 23:58:33 +00001599 RecordDecl *RDecl = RType->getDecl();
1600 if (RDecl->isUnion())
1601 NumElements = 1;
1602 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001603 NumElements = std::distance(RDecl->field_begin(),
1604 RDecl->field_end());
Douglas Gregoree0792c2009-03-20 23:58:33 +00001605 }
1606
Douglas Gregor1e5c7762009-03-21 18:13:52 +00001607 if (NumElements < NumInits)
Douglas Gregoree0792c2009-03-20 23:58:33 +00001608 NumElements = IList->getNumInits();
1609
1610 Result->reserveInits(NumElements);
1611
Douglas Gregorf603b472009-01-28 21:54:33 +00001612 // Link this new initializer list into the structured initializer
1613 // lists.
1614 if (StructuredList)
1615 StructuredList->updateInit(StructuredIndex, Result);
1616 else {
1617 Result->setSyntacticForm(IList);
1618 SyntacticToSemantic[IList] = Result;
1619 }
1620
1621 return Result;
1622}
1623
1624/// Update the initializer at index @p StructuredIndex within the
1625/// structured initializer list to the value @p expr.
1626void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1627 unsigned &StructuredIndex,
1628 Expr *expr) {
1629 // No structured initializer list to update
1630 if (!StructuredList)
1631 return;
1632
1633 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1634 // This initializer overwrites a previous initializer. Warn.
Chris Lattner2e2766a2009-02-24 22:50:46 +00001635 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001636 diag::warn_initializer_overrides)
1637 << expr->getSourceRange();
Chris Lattner2e2766a2009-02-24 22:50:46 +00001638 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregorf603b472009-01-28 21:54:33 +00001639 diag::note_previous_initializer)
Douglas Gregor756283b2009-01-28 23:43:32 +00001640 << /*FIXME:has side effects=*/0
Douglas Gregorf603b472009-01-28 21:54:33 +00001641 << PrevInit->getSourceRange();
1642 }
1643
1644 ++StructuredIndex;
1645}
1646
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001647/// Check that the given Index expression is a valid array designator
1648/// value. This is essentailly just a wrapper around
Chris Lattnereec8ae22009-04-25 21:59:05 +00001649/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001650/// and produces a reasonable diagnostic if there is a
1651/// failure. Returns true if there was an error, false otherwise. If
1652/// everything went okay, Value will receive the value of the constant
1653/// expression.
1654static bool
Chris Lattnereec8ae22009-04-25 21:59:05 +00001655CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001656 SourceLocation Loc = Index->getSourceRange().getBegin();
1657
1658 // Make sure this is an integer constant expression.
Chris Lattnereec8ae22009-04-25 21:59:05 +00001659 if (S.VerifyIntegerConstantExpression(Index, &Value))
1660 return true;
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001661
Chris Lattnereec8ae22009-04-25 21:59:05 +00001662 if (Value.isSigned() && Value.isNegative())
1663 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001664 << Value.toString(10) << Index->getSourceRange();
1665
Douglas Gregore498e372009-01-23 21:04:18 +00001666 Value.setIsUnsigned(true);
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001667 return false;
1668}
1669
1670Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1671 SourceLocation Loc,
Douglas Gregor5f34f0e2009-03-28 00:41:23 +00001672 bool GNUSyntax,
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001673 OwningExprResult Init) {
1674 typedef DesignatedInitExpr::Designator ASTDesignator;
1675
1676 bool Invalid = false;
1677 llvm::SmallVector<ASTDesignator, 32> Designators;
1678 llvm::SmallVector<Expr *, 32> InitExpressions;
1679
1680 // Build designators and check array designator expressions.
1681 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1682 const Designator &D = Desig.getDesignator(Idx);
1683 switch (D.getKind()) {
1684 case Designator::FieldDesignator:
1685 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1686 D.getFieldLoc()));
1687 break;
1688
1689 case Designator::ArrayDesignator: {
1690 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1691 llvm::APSInt IndexValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001692 if (!Index->isTypeDependent() &&
1693 !Index->isValueDependent() &&
1694 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001695 Invalid = true;
1696 else {
1697 Designators.push_back(ASTDesignator(InitExpressions.size(),
1698 D.getLBracketLoc(),
1699 D.getRBracketLoc()));
1700 InitExpressions.push_back(Index);
1701 }
1702 break;
1703 }
1704
1705 case Designator::ArrayRangeDesignator: {
1706 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1707 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1708 llvm::APSInt StartValue;
1709 llvm::APSInt EndValue;
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001710 bool StartDependent = StartIndex->isTypeDependent() ||
1711 StartIndex->isValueDependent();
1712 bool EndDependent = EndIndex->isTypeDependent() ||
1713 EndIndex->isValueDependent();
1714 if ((!StartDependent &&
1715 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1716 (!EndDependent &&
1717 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001718 Invalid = true;
Douglas Gregorea0528d2009-01-23 22:22:29 +00001719 else {
1720 // Make sure we're comparing values with the same bit width.
Douglas Gregor3a7a06e2009-05-21 23:17:49 +00001721 if (StartDependent || EndDependent) {
1722 // Nothing to compute.
1723 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregorea0528d2009-01-23 22:22:29 +00001724 EndValue.extend(StartValue.getBitWidth());
1725 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1726 StartValue.extend(EndValue.getBitWidth());
1727
Douglas Gregor1401c062009-05-21 23:30:39 +00001728 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregorea0528d2009-01-23 22:22:29 +00001729 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1730 << StartValue.toString(10) << EndValue.toString(10)
1731 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1732 Invalid = true;
1733 } else {
1734 Designators.push_back(ASTDesignator(InitExpressions.size(),
1735 D.getLBracketLoc(),
1736 D.getEllipsisLoc(),
1737 D.getRBracketLoc()));
1738 InitExpressions.push_back(StartIndex);
1739 InitExpressions.push_back(EndIndex);
1740 }
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001741 }
1742 break;
1743 }
1744 }
1745 }
1746
1747 if (Invalid || Init.isInvalid())
1748 return ExprError();
1749
1750 // Clear out the expressions within the designation.
1751 Desig.ClearExprs(*this);
1752
1753 DesignatedInitExpr *DIE
Jay Foad9e6bef42009-05-21 09:52:38 +00001754 = DesignatedInitExpr::Create(Context,
1755 Designators.data(), Designators.size(),
1756 InitExpressions.data(), InitExpressions.size(),
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001757 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00001758 return Owned(DIE);
1759}
Douglas Gregor849afc32009-01-29 00:45:39 +00001760
1761bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner2e2766a2009-02-24 22:50:46 +00001762 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregor849afc32009-01-29 00:45:39 +00001763 if (!CheckInitList.HadError())
1764 InitList = CheckInitList.getFullyStructuredList();
1765
1766 return CheckInitList.HadError();
1767}
Douglas Gregor538a4c22009-02-02 17:43:21 +00001768
1769/// \brief Diagnose any semantic errors with value-initialization of
1770/// the given type.
1771///
1772/// Value-initialization effectively zero-initializes any types
1773/// without user-declared constructors, and calls the default
1774/// constructor for a for any type that has a user-declared
1775/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1776/// a type with a user-declared constructor does not have an
1777/// accessible, non-deleted default constructor. In C, everything can
1778/// be value-initialized, which corresponds to C's notion of
1779/// initializing objects with static storage duration when no
1780/// initializer is provided for that object.
1781///
1782/// \returns true if there was an error, false otherwise.
1783bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1784 // C++ [dcl.init]p5:
1785 //
1786 // To value-initialize an object of type T means:
1787
1788 // -- if T is an array type, then each element is value-initialized;
1789 if (const ArrayType *AT = Context.getAsArrayType(Type))
1790 return CheckValueInitialization(AT->getElementType(), Loc);
1791
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001792 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001793 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor538a4c22009-02-02 17:43:21 +00001794 // -- if T is a class type (clause 9) with a user-declared
1795 // constructor (12.1), then the default constructor for T is
1796 // called (and the initialization is ill-formed if T has no
1797 // accessible default constructor);
Douglas Gregor2e047592009-02-28 01:32:25 +00001798 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stumpe127ae32009-05-16 07:39:55 +00001799 // FIXME: Eventually, we'll need to put the constructor decl into the
1800 // AST.
Douglas Gregor538a4c22009-02-02 17:43:21 +00001801 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1802 SourceRange(Loc),
1803 DeclarationName(),
1804 IK_Direct);
1805 }
1806 }
1807
1808 if (Type->isReferenceType()) {
1809 // C++ [dcl.init]p5:
1810 // [...] A program that calls for default-initialization or
1811 // value-initialization of an entity of reference type is
1812 // ill-formed. [...]
Mike Stumpe127ae32009-05-16 07:39:55 +00001813 // FIXME: Once we have code that goes through this path, add an actual
1814 // diagnostic :)
Douglas Gregor538a4c22009-02-02 17:43:21 +00001815 }
1816
1817 return false;
1818}