blob: 1e564ce45fbbab04fffc0d576f23a384740a792d [file] [log] [blame]
Steve Naroff0cca7492008-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 Lattnerdd8e0062009-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 Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000019#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000023#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000024using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000025
Chris Lattnerdd8e0062009-02-24 22:27:37 +000026//===----------------------------------------------------------------------===//
27// Sema Initialization Checking
28//===----------------------------------------------------------------------===//
29
Chris Lattner79e079d2009-02-24 23:10:27 +000030static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000031 const ArrayType *AT = Context.getAsArrayType(DeclType);
32 if (!AT) return 0;
33
Eli Friedman8718a6a2009-05-29 18:22:49 +000034 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
35 return 0;
36
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000046 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000047
48 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-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 Friedmanbb6415c2009-05-31 10:54:53 +000052 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000053
Eli Friedmanbb6415c2009-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 Lattner8879e3b2009-02-26 23:26:43 +000060 return Init;
61
Chris Lattnerdd8e0062009-02-24 22:27:37 +000062 return 0;
63}
64
Chris Lattner95e8d652009-02-24 22:46:58 +000065static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
66 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-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 Lattner95e8d652009-02-24 22:46:58 +000071 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000072 // FIXME: I dislike this error message. A lot.
Chris Lattner95e8d652009-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 Lattnerdd8e0062009-02-24 22:27:37 +000078 return false;
79 }
80
Chris Lattner95e8d652009-02-24 22:46:58 +000081 Sema::AssignConvertType ConvTy =
82 S.CheckSingleAssignmentConstraints(DeclType, Init);
83 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000084 InitType, Init, "initializing");
85}
86
Chris Lattner79e079d2009-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 Lattnerdd8e0062009-02-24 22:27:37 +000092
Chris Lattner79e079d2009-02-24 23:10:27 +000093 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-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 Lattner19da8cd2009-02-24 23:01:39 +000098 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000099 // Return a new array type (C99 6.7.8p22).
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000100 DeclT = S.Context.getConstantArrayWithoutExprType(IAT->getElementType(),
101 ConstVal,
102 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000103 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000104 }
Chris Lattner19da8cd2009-02-24 23:01:39 +0000105
Eli Friedman8718a6a2009-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 Lattnerdd8e0062009-02-24 22:27:37 +0000121}
122
123bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
124 SourceLocation InitLoc,
Anders Carlsson0f5f2c62009-05-30 20:41:30 +0000125 DeclarationName InitEntity, bool DirectInit) {
Douglas Gregor9ea62762009-05-21 23:17:49 +0000126 if (DeclType->isDependentType() ||
127 Init->isTypeDependent() || Init->isValueDependent())
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000128 return false;
129
130 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000131 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-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 Lattner79e079d2009-02-24 23:10:27 +0000146 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
147 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000148 return false;
149 }
Chris Lattnerdd8e0062009-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 Carlssonbffed8a2009-05-27 16:38:58 +0000164 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000165 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Anders Carlssonbffed8a2009-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 Lattnerdd8e0062009-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 Carlsson2078bb92009-05-27 16:10:08 +0000177 if (!Constructor)
178 return true;
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000179 bool Elidable = (isa<CallExpr>(Init) ||
180 isa<CXXTemporaryObjectExpr>(Init));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +0000181 Init = BuildCXXConstructExpr(Context,
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000182 DeclType, Constructor, Elidable, &Init, 1);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +0000183 Init = MaybeCreateCXXExprWithTemporaries(Init, /*DestroyTemps=*/true);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000184 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000185 }
186
187 // -- Otherwise (i.e., for the remaining copy-initialization
188 // cases), user-defined conversion sequences that can
189 // convert from the source type to the destination type or
190 // (when a conversion function is used) to a derived class
191 // thereof are enumerated as described in 13.3.1.4, and the
192 // best one is chosen through overload resolution
193 // (13.3). If the conversion cannot be done or is
194 // ambiguous, the initialization is ill-formed. The
195 // function selected is called with the initializer
196 // expression as its argument; if the function is a
197 // constructor, the call initializes a temporary of the
198 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000199 // FIXME: We're pretending to do copy elision here; return to this when we
200 // have ASTs for such things.
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000201 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
202 return false;
203
204 if (InitEntity)
205 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000206 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
207 << Init->getType() << Init->getSourceRange();
208 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000209 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
210 << Init->getType() << Init->getSourceRange();
211 }
212
213 // C99 6.7.8p16.
214 if (DeclType->isArrayType())
215 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000216 << Init->getSourceRange();
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000217
Chris Lattner95e8d652009-02-24 22:46:58 +0000218 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000219 }
220
221 bool hadError = CheckInitList(InitList, DeclType);
222 Init = InitList;
223 return hadError;
224}
225
226//===----------------------------------------------------------------------===//
227// Semantic checking for initializer lists.
228//===----------------------------------------------------------------------===//
229
Douglas Gregor9e80f722009-01-29 01:05:33 +0000230/// @brief Semantic checking for initializer lists.
231///
232/// The InitListChecker class contains a set of routines that each
233/// handle the initialization of a certain kind of entity, e.g.,
234/// arrays, vectors, struct/union types, scalars, etc. The
235/// InitListChecker itself performs a recursive walk of the subobject
236/// structure of the type to be initialized, while stepping through
237/// the initializer list one element at a time. The IList and Index
238/// parameters to each of the Check* routines contain the active
239/// (syntactic) initializer list and the index into that initializer
240/// list that represents the current initializer. Each routine is
241/// responsible for moving that Index forward as it consumes elements.
242///
243/// Each Check* routine also has a StructuredList/StructuredIndex
244/// arguments, which contains the current the "structured" (semantic)
245/// initializer list and the index into that initializer list where we
246/// are copying initializers as we map them over to the semantic
247/// list. Once we have completed our recursive walk of the subobject
248/// structure, we will have constructed a full semantic initializer
249/// list.
250///
251/// C99 designators cause changes in the initializer list traversal,
252/// because they make the initialization "jump" into a specific
253/// subobject and then continue the initialization from that
254/// point. CheckDesignatedInitializer() recursively steps into the
255/// designated subobject and manages backing out the recursion to
256/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000257namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000258class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000259 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000260 bool hadError;
261 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
262 InitListExpr *FullyStructuredList;
263
264 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000265 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000266 unsigned &StructuredIndex,
267 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000268 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000269 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000270 unsigned &StructuredIndex,
271 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000272 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
273 bool SubobjectIsDesignatorContext,
274 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000275 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000276 unsigned &StructuredIndex,
277 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000278 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
279 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000280 InitListExpr *StructuredList,
281 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000282 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000283 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000284 InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000286 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
287 unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000290 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000291 InitListExpr *StructuredList,
292 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000293 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
294 RecordDecl::field_iterator Field,
295 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000296 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000297 unsigned &StructuredIndex,
298 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000299 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
300 llvm::APSInt elementIndex,
301 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000302 InitListExpr *StructuredList,
303 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000304 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000305 unsigned DesigIdx,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000306 QualType &CurrentObjectType,
307 RecordDecl::field_iterator *NextField,
308 llvm::APSInt *NextElementIndex,
309 unsigned &Index,
310 InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000312 bool FinishSubobjectInit,
313 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000314 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
315 QualType CurrentObjectType,
316 InitListExpr *StructuredList,
317 unsigned StructuredIndex,
318 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000319 void UpdateStructuredListElement(InitListExpr *StructuredList,
320 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000321 Expr *expr);
322 int numArrayElements(QualType DeclType);
323 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000324
325 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000326public:
Chris Lattner08202542009-02-24 22:50:46 +0000327 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000328 bool HadError() { return hadError; }
329
330 // @brief Retrieves the fully-structured initializer list used for
331 // semantic analysis and code generation.
332 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
333};
Chris Lattner8b419b92009-02-24 22:48:58 +0000334} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000335
Douglas Gregor4c678342009-01-28 21:54:33 +0000336/// Recursively replaces NULL values within the given initializer list
337/// with expressions that perform value-initialization of the
338/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000339void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Chris Lattner08202542009-02-24 22:50:46 +0000340 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000341 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000342 SourceLocation Loc = ILE->getSourceRange().getBegin();
343 if (ILE->getSyntacticForm())
344 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
345
Ted Kremenek6217b802009-07-29 21:53:49 +0000346 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000347 unsigned Init = 0, NumInits = ILE->getNumInits();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000348 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000349 Field = RType->getDecl()->field_begin(),
350 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000351 Field != FieldEnd; ++Field) {
352 if (Field->isUnnamedBitfield())
353 continue;
354
Douglas Gregor87fd7032009-02-02 17:43:21 +0000355 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000356 if (Field->getType()->isReferenceType()) {
357 // C++ [dcl.init.aggr]p9:
358 // If an incomplete or empty initializer-list leaves a
359 // member of reference type uninitialized, the program is
360 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000361 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000362 << Field->getType()
363 << ILE->getSyntacticForm()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +0000364 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000365 diag::note_uninit_reference_member);
366 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000367 return;
Chris Lattner08202542009-02-24 22:50:46 +0000368 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000369 hadError = true;
370 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000371 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372
Mike Stump390b4cc2009-05-16 07:39:55 +0000373 // FIXME: If value-initialization involves calling a constructor, should
374 // we make that call explicit in the representation (even when it means
375 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 if (Init < NumInits && !hadError)
377 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000378 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000380 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000381 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000382 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000383
384 // Only look at the first initialization of a union.
385 if (RType->getDecl()->isUnion())
386 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 }
388
389 return;
390 }
391
392 QualType ElementType;
393
Douglas Gregor87fd7032009-02-02 17:43:21 +0000394 unsigned NumInits = ILE->getNumInits();
395 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000396 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000397 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000398 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
399 NumElements = CAType->getSize().getZExtValue();
400 } else if (const VectorType *VType = ILE->getType()->getAsVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000401 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000402 NumElements = VType->getNumElements();
403 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000404 ElementType = ILE->getType();
405
Douglas Gregor87fd7032009-02-02 17:43:21 +0000406 for (unsigned Init = 0; Init != NumElements; ++Init) {
407 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000408 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000409 hadError = true;
410 return;
411 }
412
Mike Stump390b4cc2009-05-16 07:39:55 +0000413 // FIXME: If value-initialization involves calling a constructor, should
414 // we make that call explicit in the representation (even when it means
415 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000416 if (Init < NumInits && !hadError)
417 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000418 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000419 } else if (InitListExpr *InnerILE
420 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000421 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000422 }
423}
424
Chris Lattner68355a52009-01-29 05:10:57 +0000425
Chris Lattner08202542009-02-24 22:50:46 +0000426InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
427 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000428 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000429
Eli Friedmanb85f7072008-05-19 19:16:24 +0000430 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000431 unsigned newStructuredIndex = 0;
432 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000433 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000434 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
435 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000436
Douglas Gregor930d8b52009-01-30 22:09:00 +0000437 if (!hadError)
438 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000439}
440
441int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000442 // FIXME: use a proper constant
443 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000444 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000445 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000446 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
447 }
448 return maxElements;
449}
450
451int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000452 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000453 int InitializableMembers = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000454 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000455 Field = structDecl->field_begin(),
456 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000457 Field != FieldEnd; ++Field) {
458 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
459 ++InitializableMembers;
460 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000461 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000462 return std::min(InitializableMembers, 1);
463 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000464}
465
466void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000467 QualType T, unsigned &Index,
468 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000469 unsigned &StructuredIndex,
470 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000471 int maxElements = 0;
472
473 if (T->isArrayType())
474 maxElements = numArrayElements(T);
475 else if (T->isStructureType() || T->isUnionType())
476 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000477 else if (T->isVectorType())
478 maxElements = T->getAsVectorType()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000479 else
480 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000481
Eli Friedman402256f2008-05-25 13:49:22 +0000482 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000483 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000484 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000485 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000486 hadError = true;
487 return;
488 }
489
Douglas Gregor4c678342009-01-28 21:54:33 +0000490 // Build a structured initializer list corresponding to this subobject.
491 InitListExpr *StructuredSubobjectInitList
492 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
493 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000494 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
495 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000496 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000497
Douglas Gregor4c678342009-01-28 21:54:33 +0000498 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000499 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000500 CheckListElementTypes(ParentIList, T, false, Index,
501 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000502 StructuredSubobjectInitIndex,
503 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000504 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000505 StructuredSubobjectInitList->setType(T);
506
Douglas Gregored8a93d2009-03-01 17:12:46 +0000507 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000508 // range corresponds with the end of the last initializer it used.
509 if (EndIndex < ParentIList->getNumInits()) {
510 SourceLocation EndLoc
511 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
512 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
513 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000514}
515
Steve Naroffa647caa2008-05-06 00:23:44 +0000516void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 unsigned &Index,
518 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000519 unsigned &StructuredIndex,
520 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000521 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 SyntacticToSemantic[IList] = StructuredList;
523 StructuredList->setSyntacticForm(IList);
524 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000525 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000526 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000527 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000528 if (hadError)
529 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000530
Eli Friedman638e1442008-05-25 13:22:35 +0000531 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000532 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000533 if (StructuredIndex == 1 &&
534 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000535 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000536 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000537 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000538 hadError = true;
539 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000540 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000541 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000542 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000543 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000544 // Don't complain for incomplete types, since we'll get an error
545 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000546 QualType CurrentObjectType = StructuredList->getType();
547 int initKind =
548 CurrentObjectType->isArrayType()? 0 :
549 CurrentObjectType->isVectorType()? 1 :
550 CurrentObjectType->isScalarType()? 2 :
551 CurrentObjectType->isUnionType()? 3 :
552 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000553
554 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
556 DK = diag::err_excess_initializers;
557 hadError = true;
558 }
Nate Begeman08634522009-07-07 21:53:06 +0000559 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560 DK = diag::err_excess_initializers;
561 hadError = true;
562 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000563
Chris Lattner08202542009-02-24 22:50:46 +0000564 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000566 }
567 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000568
Eli Friedman759f2522009-05-16 11:45:48 +0000569 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000571 << IList->getSourceRange()
572 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocStart()))
573 << CodeModificationHint::CreateRemoval(SourceRange(IList->getLocEnd()));
Steve Naroff0cca7492008-05-01 22:18:59 +0000574}
575
Eli Friedmanb85f7072008-05-19 19:16:24 +0000576void InitListChecker::CheckListElementTypes(InitListExpr *IList,
577 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000578 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000579 unsigned &Index,
580 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000581 unsigned &StructuredIndex,
582 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000583 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000584 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000586 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000587 } else if (DeclType->isAggregateType()) {
588 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000589 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000590 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000591 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000592 StructuredList, StructuredIndex,
593 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000594 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000595 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000596 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000597 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000598 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
599 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000600 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000602 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
603 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000605 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000606 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000607 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000608 } else if (DeclType->isRecordType()) {
609 // C++ [dcl.init]p14:
610 // [...] If the class is an aggregate (8.5.1), and the initializer
611 // is a brace-enclosed list, see 8.5.1.
612 //
613 // Note: 8.5.1 is handled below; here, we diagnose the case where
614 // we have an initializer list and a destination type that is not
615 // an aggregate.
616 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000617 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000618 << DeclType << IList->getSourceRange();
619 hadError = true;
620 } else if (DeclType->isReferenceType()) {
621 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000622 } else {
623 // In C, all types are either scalars or aggregates, but
624 // additional handling is needed here for C++ (and possibly others?).
625 assert(0 && "Unsupported initializer type");
626 }
627}
628
Eli Friedmanb85f7072008-05-19 19:16:24 +0000629void InitListChecker::CheckSubElementType(InitListExpr *IList,
630 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000631 unsigned &Index,
632 InitListExpr *StructuredList,
633 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000634 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000635 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
636 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000637 unsigned newStructuredIndex = 0;
638 InitListExpr *newStructuredList
639 = getStructuredSubobjectInit(IList, Index, ElemType,
640 StructuredList, StructuredIndex,
641 SubInitList->getSourceRange());
642 CheckExplicitInitList(SubInitList, ElemType, newIndex,
643 newStructuredList, newStructuredIndex);
644 ++StructuredIndex;
645 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000646 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
647 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000648 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000650 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000651 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000652 } else if (ElemType->isReferenceType()) {
653 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000654 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000655 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 // C++ [dcl.init.aggr]p12:
657 // All implicit type conversions (clause 4) are considered when
658 // initializing the aggregate member with an ini- tializer from
659 // an initializer-list. If the initializer can initialize a
660 // member, the member is initialized. [...]
661 ImplicitConversionSequence ICS
Chris Lattner08202542009-02-24 22:50:46 +0000662 = SemaRef.TryCopyInitialization(expr, ElemType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000663 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Chris Lattner08202542009-02-24 22:50:46 +0000664 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000665 "initializing"))
666 hadError = true;
667 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
668 ++Index;
669 return;
670 }
671
672 // Fall through for subaggregate initialization
673 } else {
674 // C99 6.7.8p13:
675 //
676 // The initializer for a structure or union object that has
677 // automatic storage duration shall be either an initializer
678 // list as described below, or a single expression that has
679 // compatible structure or union type. In the latter case, the
680 // initial value of the object, including unnamed members, is
681 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000682 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000683 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000684 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
685 ++Index;
686 return;
687 }
688
689 // Fall through for subaggregate initialization
690 }
691
692 // C++ [dcl.init.aggr]p12:
693 //
694 // [...] Otherwise, if the member is itself a non-empty
695 // subaggregate, brace elision is assumed and the initializer is
696 // considered for the initialization of the first member of
697 // the subaggregate.
698 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
699 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
700 StructuredIndex);
701 ++StructuredIndex;
702 } else {
703 // We cannot initialize this element, so let
704 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000705 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000706 hadError = true;
707 ++Index;
708 ++StructuredIndex;
709 }
710 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000711}
712
Douglas Gregor930d8b52009-01-30 22:09:00 +0000713void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000714 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000715 InitListExpr *StructuredList,
716 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000717 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000718 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000719 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000720 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000721 diag::err_many_braces_around_scalar_init)
722 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000723 hadError = true;
724 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000725 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000726 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000727 } else if (isa<DesignatedInitExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000728 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000729 diag::err_designator_for_scalar_init)
730 << DeclType << expr->getSourceRange();
731 hadError = true;
732 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000733 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000734 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000735 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000736
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000737 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000738 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000739 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000740 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000741 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000742 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000743 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000744 if (hadError)
745 ++StructuredIndex;
746 else
747 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000748 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000749 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000750 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000751 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000752 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000753 ++Index;
754 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000755 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000756 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000757}
758
Douglas Gregor930d8b52009-01-30 22:09:00 +0000759void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
760 unsigned &Index,
761 InitListExpr *StructuredList,
762 unsigned &StructuredIndex) {
763 if (Index < IList->getNumInits()) {
764 Expr *expr = IList->getInit(Index);
765 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000766 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000767 << DeclType << IList->getSourceRange();
768 hadError = true;
769 ++Index;
770 ++StructuredIndex;
771 return;
772 }
773
774 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000775 if (SemaRef.CheckReferenceInit(expr, DeclType))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000776 hadError = true;
777 else if (savExpr != expr) {
778 // The type was promoted, update initializer list.
779 IList->setInit(Index, expr);
780 }
781 if (hadError)
782 ++StructuredIndex;
783 else
784 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
785 ++Index;
786 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000787 // FIXME: It would be wonderful if we could point at the actual member. In
788 // general, it would be useful to pass location information down the stack,
789 // so that we know the location (or decl) of the "current object" being
790 // initialized.
Chris Lattner08202542009-02-24 22:50:46 +0000791 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000792 diag::err_init_reference_member_uninitialized)
793 << DeclType
794 << IList->getSourceRange();
795 hadError = true;
796 ++Index;
797 ++StructuredIndex;
798 return;
799 }
800}
801
Steve Naroff0cca7492008-05-01 22:18:59 +0000802void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000803 unsigned &Index,
804 InitListExpr *StructuredList,
805 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000806 if (Index < IList->getNumInits()) {
807 const VectorType *VT = DeclType->getAsVectorType();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000808 unsigned maxElements = VT->getNumElements();
809 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000810 QualType elementType = VT->getElementType();
811
Nate Begeman2ef13e52009-08-10 23:49:36 +0000812 if (!SemaRef.getLangOptions().OpenCL) {
813 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
814 // Don't attempt to go past the end of the init list
815 if (Index >= IList->getNumInits())
816 break;
817 CheckSubElementType(IList, elementType, Index,
818 StructuredList, StructuredIndex);
819 }
820 } else {
821 // OpenCL initializers allows vectors to be constructed from vectors.
822 for (unsigned i = 0; i < maxElements; ++i) {
823 // Don't attempt to go past the end of the init list
824 if (Index >= IList->getNumInits())
825 break;
826 QualType IType = IList->getInit(Index)->getType();
827 if (!IType->isVectorType()) {
828 CheckSubElementType(IList, elementType, Index,
829 StructuredList, StructuredIndex);
830 ++numEltsInit;
831 } else {
832 const VectorType *IVT = IType->getAsVectorType();
833 unsigned numIElts = IVT->getNumElements();
834 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
835 numIElts);
836 CheckSubElementType(IList, VecType, Index,
837 StructuredList, StructuredIndex);
838 numEltsInit += numIElts;
839 }
840 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000841 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000842
843 // OpenCL & AltiVec require all elements to be initialized.
844 if (numEltsInit != maxElements)
845 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
846 SemaRef.Diag(IList->getSourceRange().getBegin(),
847 diag::err_vector_incorrect_num_initializers)
848 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000849 }
850}
851
852void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000853 llvm::APSInt elementIndex,
854 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000855 unsigned &Index,
856 InitListExpr *StructuredList,
857 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000858 // Check for the special-case of initializing an array with a string.
859 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000860 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
861 SemaRef.Context)) {
862 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000863 // We place the string literal directly into the resulting
864 // initializer list. This is the only place where the structure
865 // of the structured initializer list doesn't match exactly,
866 // because doing so would involve allocating one character
867 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000868 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000869 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000870 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000871 return;
872 }
873 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000874 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000875 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000876 // Check for VLAs; in standard C it would be possible to check this
877 // earlier, but I don't know where clang accepts VLAs (gcc accepts
878 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000879 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000880 diag::err_variable_object_no_init)
881 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000882 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000883 ++Index;
884 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000885 return;
886 }
887
Douglas Gregor05c13a32009-01-22 00:58:24 +0000888 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000889 llvm::APSInt maxElements(elementIndex.getBitWidth(),
890 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000891 bool maxElementsKnown = false;
892 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000893 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000894 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000895 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000896 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000897 maxElementsKnown = true;
898 }
899
Chris Lattner08202542009-02-24 22:50:46 +0000900 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000901 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000902 while (Index < IList->getNumInits()) {
903 Expr *Init = IList->getInit(Index);
904 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000905 // If we're not the subobject that matches up with the '{' for
906 // the designator, we shouldn't be handling the
907 // designator. Return immediately.
908 if (!SubobjectIsDesignatorContext)
909 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000910
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000911 // Handle this designated initializer. elementIndex will be
912 // updated to be the next array element we'll initialize.
Douglas Gregor71199712009-04-15 04:56:10 +0000913 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000914 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000915 StructuredList, StructuredIndex, true,
916 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000917 hadError = true;
918 continue;
919 }
920
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000921 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
922 maxElements.extend(elementIndex.getBitWidth());
923 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
924 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000925 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000926
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000927 // If the array is of incomplete type, keep track of the number of
928 // elements in the initializer.
929 if (!maxElementsKnown && elementIndex > maxElements)
930 maxElements = elementIndex;
931
Douglas Gregor05c13a32009-01-22 00:58:24 +0000932 continue;
933 }
934
935 // If we know the maximum number of elements, and we've already
936 // hit it, stop consuming elements in the initializer list.
937 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000938 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000939
940 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000941 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000942 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000943 ++elementIndex;
944
945 // If the array is of incomplete type, keep track of the number of
946 // elements in the initializer.
947 if (!maxElementsKnown && elementIndex > maxElements)
948 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000949 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000950 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000951 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000952 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000953 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000954 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000955 // Sizing an array implicitly to zero is not allowed by ISO C,
956 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000957 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000958 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000959 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000960
Chris Lattner08202542009-02-24 22:50:46 +0000961 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000962 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000963 }
964}
965
966void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
967 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000968 RecordDecl::field_iterator Field,
969 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000970 unsigned &Index,
971 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000972 unsigned &StructuredIndex,
973 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000974 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Steve Naroff0cca7492008-05-01 22:18:59 +0000975
Eli Friedmanb85f7072008-05-19 19:16:24 +0000976 // If the record is invalid, some of it's members are invalid. To avoid
977 // confusion, we forgo checking the intializer for the entire record.
978 if (structDecl->isInvalidDecl()) {
979 hadError = true;
980 return;
981 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000982
983 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
984 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +0000985 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000986 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000987 Field != FieldEnd; ++Field) {
988 if (Field->getDeclName()) {
989 StructuredList->setInitializedFieldInUnion(*Field);
990 break;
991 }
992 }
993 return;
994 }
995
Douglas Gregor05c13a32009-01-22 00:58:24 +0000996 // If structDecl is a forward declaration, this loop won't do
997 // anything except look at designated initializers; That's okay,
998 // because an error should get printed out elsewhere. It might be
999 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001000 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001001 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001002 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001003 while (Index < IList->getNumInits()) {
1004 Expr *Init = IList->getInit(Index);
1005
1006 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001007 // If we're not the subobject that matches up with the '{' for
1008 // the designator, we shouldn't be handling the
1009 // designator. Return immediately.
1010 if (!SubobjectIsDesignatorContext)
1011 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001012
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001013 // Handle this designated initializer. Field will be updated to
1014 // the next field that we'll be initializing.
Douglas Gregor71199712009-04-15 04:56:10 +00001015 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001016 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001017 StructuredList, StructuredIndex,
1018 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001019 hadError = true;
1020
Douglas Gregordfb5e592009-02-12 19:00:39 +00001021 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001022 continue;
1023 }
1024
1025 if (Field == FieldEnd) {
1026 // We've run out of fields. We're done.
1027 break;
1028 }
1029
Douglas Gregordfb5e592009-02-12 19:00:39 +00001030 // We've already initialized a member of a union. We're done.
1031 if (InitializedSomething && DeclType->isUnionType())
1032 break;
1033
Douglas Gregor44b43212008-12-11 16:49:14 +00001034 // If we've hit the flexible array member at the end, we're done.
1035 if (Field->getType()->isIncompleteArrayType())
1036 break;
1037
Douglas Gregor0bb76892009-01-29 16:53:55 +00001038 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001039 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001040 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001041 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001042 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001043
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001044 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001045 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001046 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001047
1048 if (DeclType->isUnionType()) {
1049 // Initialize the first field within the union.
1050 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001051 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052
1053 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001054 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001055
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001056 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001057 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001058 return;
1059
1060 // Handle GNU flexible array initializers.
1061 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001062 (!isa<InitListExpr>(IList->getInit(Index)) ||
1063 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Chris Lattner08202542009-02-24 22:50:46 +00001064 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001065 diag::err_flexible_array_init_nonempty)
1066 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001067 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001068 << *Field;
1069 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001070 ++Index;
1071 return;
1072 } else {
1073 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1074 diag::ext_flexible_array_init)
1075 << IList->getInit(Index)->getSourceRange().getBegin();
1076 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1077 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001078 }
1079
Douglas Gregora6457962009-03-20 00:32:56 +00001080 if (isa<InitListExpr>(IList->getInit(Index)))
1081 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1082 StructuredIndex);
1083 else
1084 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1085 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001086}
Steve Naroff0cca7492008-05-01 22:18:59 +00001087
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001088/// \brief Expand a field designator that refers to a member of an
1089/// anonymous struct or union into a series of field designators that
1090/// refers to the field within the appropriate subobject.
1091///
1092/// Field/FieldIndex will be updated to point to the (new)
1093/// currently-designated field.
1094static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1095 DesignatedInitExpr *DIE,
1096 unsigned DesigIdx,
1097 FieldDecl *Field,
1098 RecordDecl::field_iterator &FieldIter,
1099 unsigned &FieldIndex) {
1100 typedef DesignatedInitExpr::Designator Designator;
1101
1102 // Build the path from the current object to the member of the
1103 // anonymous struct/union (backwards).
1104 llvm::SmallVector<FieldDecl *, 4> Path;
1105 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1106
1107 // Build the replacement designators.
1108 llvm::SmallVector<Designator, 4> Replacements;
1109 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1110 FI = Path.rbegin(), FIEnd = Path.rend();
1111 FI != FIEnd; ++FI) {
1112 if (FI + 1 == FIEnd)
1113 Replacements.push_back(Designator((IdentifierInfo *)0,
1114 DIE->getDesignator(DesigIdx)->getDotLoc(),
1115 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1116 else
1117 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1118 SourceLocation()));
1119 Replacements.back().setField(*FI);
1120 }
1121
1122 // Expand the current designator into the set of replacement
1123 // designators, so we have a full subobject path down to where the
1124 // member of the anonymous struct/union is actually stored.
1125 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
1126 &Replacements[0] + Replacements.size());
1127
1128 // Update FieldIter/FieldIndex;
1129 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001130 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001131 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001132 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001133 FieldIter != FEnd; ++FieldIter) {
1134 if (FieldIter->isUnnamedBitfield())
1135 continue;
1136
1137 if (*FieldIter == Path.back())
1138 return;
1139
1140 ++FieldIndex;
1141 }
1142
1143 assert(false && "Unable to find anonymous struct/union field");
1144}
1145
Douglas Gregor05c13a32009-01-22 00:58:24 +00001146/// @brief Check the well-formedness of a C99 designated initializer.
1147///
1148/// Determines whether the designated initializer @p DIE, which
1149/// resides at the given @p Index within the initializer list @p
1150/// IList, is well-formed for a current object of type @p DeclType
1151/// (C99 6.7.8). The actual subobject that this designator refers to
1152/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001153/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001154///
1155/// @param IList The initializer list in which this designated
1156/// initializer occurs.
1157///
Douglas Gregor71199712009-04-15 04:56:10 +00001158/// @param DIE The designated initializer expression.
1159///
1160/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001161///
1162/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1163/// into which the designation in @p DIE should refer.
1164///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001165/// @param NextField If non-NULL and the first designator in @p DIE is
1166/// a field, this will be set to the field declaration corresponding
1167/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001168///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001169/// @param NextElementIndex If non-NULL and the first designator in @p
1170/// DIE is an array designator or GNU array-range designator, this
1171/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001172///
1173/// @param Index Index into @p IList where the designated initializer
1174/// @p DIE occurs.
1175///
Douglas Gregor4c678342009-01-28 21:54:33 +00001176/// @param StructuredList The initializer list expression that
1177/// describes all of the subobject initializers in the order they'll
1178/// actually be initialized.
1179///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001180/// @returns true if there was an error, false otherwise.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001181bool
1182InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
1183 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001184 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001185 QualType &CurrentObjectType,
1186 RecordDecl::field_iterator *NextField,
1187 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001188 unsigned &Index,
1189 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001190 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001191 bool FinishSubobjectInit,
1192 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001193 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001194 // Check the actual initialization for the designated object type.
1195 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001196
1197 // Temporarily remove the designator expression from the
1198 // initializer list that the child calls see, so that we don't try
1199 // to re-process the designator.
1200 unsigned OldIndex = Index;
1201 IList->setInit(OldIndex, DIE->getInit());
1202
1203 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001204 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001205
1206 // Restore the designated initializer expression in the syntactic
1207 // form of the initializer list.
1208 if (IList->getInit(OldIndex) != DIE->getInit())
1209 DIE->setInit(IList->getInit(OldIndex));
1210 IList->setInit(OldIndex, DIE);
1211
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001212 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001213 }
1214
Douglas Gregor71199712009-04-15 04:56:10 +00001215 bool IsFirstDesignator = (DesigIdx == 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001216 assert((IsFirstDesignator || StructuredList) &&
1217 "Need a non-designated initializer list to start from");
1218
Douglas Gregor71199712009-04-15 04:56:10 +00001219 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001220 // Determine the structural initializer list that corresponds to the
1221 // current subobject.
1222 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Douglas Gregored8a93d2009-03-01 17:12:46 +00001223 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1224 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001225 SourceRange(D->getStartLocation(),
1226 DIE->getSourceRange().getEnd()));
1227 assert(StructuredList && "Expected a structured initializer list");
1228
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001229 if (D->isFieldDesignator()) {
1230 // C99 6.7.8p7:
1231 //
1232 // If a designator has the form
1233 //
1234 // . identifier
1235 //
1236 // then the current object (defined below) shall have
1237 // structure or union type and the identifier shall be the
1238 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001239 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001240 if (!RT) {
1241 SourceLocation Loc = D->getDotLoc();
1242 if (Loc.isInvalid())
1243 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001244 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1245 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001246 ++Index;
1247 return true;
1248 }
1249
Douglas Gregor4c678342009-01-28 21:54:33 +00001250 // Note: we perform a linear search of the fields here, despite
1251 // the fact that we have a faster lookup method, because we always
1252 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001253 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001254 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001255 unsigned FieldIndex = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001256 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001257 Field = RT->getDecl()->field_begin(),
1258 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001259 for (; Field != FieldEnd; ++Field) {
1260 if (Field->isUnnamedBitfield())
1261 continue;
1262
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001263 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001264 break;
1265
1266 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001267 }
1268
Douglas Gregor4c678342009-01-28 21:54:33 +00001269 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001270 // There was no normal field in the struct with the designated
1271 // name. Perform another lookup for this name, which may find
1272 // something that we can't designate (e.g., a member function),
1273 // may find nothing, or may find a member of an anonymous
1274 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001275 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001276 if (Lookup.first == Lookup.second) {
1277 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001278 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001279 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001280 ++Index;
1281 return true;
1282 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1283 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1284 ->isAnonymousStructOrUnion()) {
1285 // Handle an field designator that refers to a member of an
1286 // anonymous struct or union.
1287 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1288 cast<FieldDecl>(*Lookup.first),
1289 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001290 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001291 } else {
1292 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001293 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001294 << FieldName;
Chris Lattner08202542009-02-24 22:50:46 +00001295 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001297 ++Index;
1298 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001299 }
1300 } else if (!KnownField &&
1301 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001302 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001303 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1304 Field, FieldIndex);
1305 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001306 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001307
1308 // All of the fields of a union are located at the same place in
1309 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001310 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001311 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001312 StructuredList->setInitializedFieldInUnion(*Field);
1313 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001314
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001315 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001316 D->setField(*Field);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001317
Douglas Gregor4c678342009-01-28 21:54:33 +00001318 // Make sure that our non-designated initializer list has space
1319 // for a subobject corresponding to this field.
1320 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001321 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001322
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001323 // This designator names a flexible array member.
1324 if (Field->getType()->isIncompleteArrayType()) {
1325 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001326 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001327 // We can't designate an object within the flexible array
1328 // member (because GCC doesn't allow it).
Douglas Gregor71199712009-04-15 04:56:10 +00001329 DesignatedInitExpr::Designator *NextD
1330 = DIE->getDesignator(DesigIdx + 1);
Chris Lattner08202542009-02-24 22:50:46 +00001331 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001332 diag::err_designator_into_flexible_array_member)
1333 << SourceRange(NextD->getStartLocation(),
1334 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001335 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001336 << *Field;
1337 Invalid = true;
1338 }
1339
1340 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1341 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001342 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001343 diag::err_flexible_array_init_needs_braces)
1344 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001345 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001346 << *Field;
1347 Invalid = true;
1348 }
1349
1350 // Handle GNU flexible array initializers.
1351 if (!Invalid && !TopLevelObject &&
1352 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Chris Lattner08202542009-02-24 22:50:46 +00001353 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001354 diag::err_flexible_array_init_nonempty)
1355 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001356 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001357 << *Field;
1358 Invalid = true;
1359 }
1360
1361 if (Invalid) {
1362 ++Index;
1363 return true;
1364 }
1365
1366 // Initialize the array.
1367 bool prevHadError = hadError;
1368 unsigned newStructuredIndex = FieldIndex;
1369 unsigned OldIndex = Index;
1370 IList->setInit(Index, DIE->getInit());
1371 CheckSubElementType(IList, Field->getType(), Index,
1372 StructuredList, newStructuredIndex);
1373 IList->setInit(OldIndex, DIE);
1374 if (hadError && !prevHadError) {
1375 ++Field;
1376 ++FieldIndex;
1377 if (NextField)
1378 *NextField = Field;
1379 StructuredIndex = FieldIndex;
1380 return true;
1381 }
1382 } else {
1383 // Recurse to check later designated subobjects.
1384 QualType FieldType = (*Field)->getType();
1385 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001386 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1387 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001388 true, false))
1389 return true;
1390 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001391
1392 // Find the position of the next field to be initialized in this
1393 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001394 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001395 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396
1397 // If this the first designator, our caller will continue checking
1398 // the rest of this struct/class/union subobject.
1399 if (IsFirstDesignator) {
1400 if (NextField)
1401 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001403 return false;
1404 }
1405
Douglas Gregor34e79462009-01-28 23:36:17 +00001406 if (!FinishSubobjectInit)
1407 return false;
1408
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001409 // We've already initialized something in the union; we're done.
1410 if (RT->getDecl()->isUnion())
1411 return hadError;
1412
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001413 // Check the remaining fields within this class/struct/union subobject.
1414 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001415 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1416 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001417 return hadError && !prevHadError;
1418 }
1419
1420 // C99 6.7.8p6:
1421 //
1422 // If a designator has the form
1423 //
1424 // [ constant-expression ]
1425 //
1426 // then the current object (defined below) shall have array
1427 // type and the expression shall be an integer constant
1428 // expression. If the array is of unknown size, any
1429 // nonnegative value is valid.
1430 //
1431 // Additionally, cope with the GNU extension that permits
1432 // designators of the form
1433 //
1434 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001435 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001436 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001437 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001438 << CurrentObjectType;
1439 ++Index;
1440 return true;
1441 }
1442
1443 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001444 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1445 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001446 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001447 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001448 DesignatedEndIndex = DesignatedStartIndex;
1449 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001450 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001451
Douglas Gregor34e79462009-01-28 23:36:17 +00001452
Chris Lattner3bf68932009-04-25 21:59:05 +00001453 DesignatedStartIndex =
1454 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1455 DesignatedEndIndex =
1456 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001457 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001458
Chris Lattner3bf68932009-04-25 21:59:05 +00001459 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001460 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001461 }
1462
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001463 if (isa<ConstantArrayType>(AT)) {
1464 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001465 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1466 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1467 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1468 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1469 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001470 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001471 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001472 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001473 << IndexExpr->getSourceRange();
1474 ++Index;
1475 return true;
1476 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001477 } else {
1478 // Make sure the bit-widths and signedness match.
1479 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1480 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001481 else if (DesignatedStartIndex.getBitWidth() <
1482 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001483 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1484 DesignatedStartIndex.setIsUnsigned(true);
1485 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001486 }
1487
Douglas Gregor4c678342009-01-28 21:54:33 +00001488 // Make sure that our non-designated initializer list has space
1489 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001490 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001491 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001492 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001493
Douglas Gregor34e79462009-01-28 23:36:17 +00001494 // Repeatedly perform subobject initializations in the range
1495 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001496
Douglas Gregor34e79462009-01-28 23:36:17 +00001497 // Move to the next designator
1498 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1499 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001500 while (DesignatedStartIndex <= DesignatedEndIndex) {
1501 // Recurse to check later designated subobjects.
1502 QualType ElementType = AT->getElementType();
1503 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001504 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1505 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001506 (DesignatedStartIndex == DesignatedEndIndex),
1507 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001508 return true;
1509
1510 // Move to the next index in the array that we'll be initializing.
1511 ++DesignatedStartIndex;
1512 ElementIndex = DesignatedStartIndex.getZExtValue();
1513 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001514
1515 // If this the first designator, our caller will continue checking
1516 // the rest of this array subobject.
1517 if (IsFirstDesignator) {
1518 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001519 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001520 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001521 return false;
1522 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001523
1524 if (!FinishSubobjectInit)
1525 return false;
1526
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001528 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001529 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001530 StructuredList, ElementIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001531 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001532}
1533
Douglas Gregor4c678342009-01-28 21:54:33 +00001534// Get the structured initializer list for a subobject of type
1535// @p CurrentObjectType.
1536InitListExpr *
1537InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1538 QualType CurrentObjectType,
1539 InitListExpr *StructuredList,
1540 unsigned StructuredIndex,
1541 SourceRange InitRange) {
1542 Expr *ExistingInit = 0;
1543 if (!StructuredList)
1544 ExistingInit = SyntacticToSemantic[IList];
1545 else if (StructuredIndex < StructuredList->getNumInits())
1546 ExistingInit = StructuredList->getInit(StructuredIndex);
1547
1548 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1549 return Result;
1550
1551 if (ExistingInit) {
1552 // We are creating an initializer list that initializes the
1553 // subobjects of the current object, but there was already an
1554 // initialization that completely initialized the current
1555 // subobject, e.g., by a compound literal:
1556 //
1557 // struct X { int a, b; };
1558 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1559 //
1560 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1561 // designated initializer re-initializes the whole
1562 // subobject [0], overwriting previous initializers.
Douglas Gregored8a93d2009-03-01 17:12:46 +00001563 SemaRef.Diag(InitRange.getBegin(),
1564 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001565 << InitRange;
Chris Lattner08202542009-02-24 22:50:46 +00001566 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001567 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001568 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001569 << ExistingInit->getSourceRange();
1570 }
1571
1572 InitListExpr *Result
Douglas Gregored8a93d2009-03-01 17:12:46 +00001573 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
1574 InitRange.getEnd());
1575
Douglas Gregor4c678342009-01-28 21:54:33 +00001576 Result->setType(CurrentObjectType);
1577
Douglas Gregorfa219202009-03-20 23:58:33 +00001578 // Pre-allocate storage for the structured initializer list.
1579 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001580 unsigned NumInits = 0;
1581 if (!StructuredList)
1582 NumInits = IList->getNumInits();
1583 else if (Index < IList->getNumInits()) {
1584 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1585 NumInits = SubList->getNumInits();
1586 }
1587
Douglas Gregorfa219202009-03-20 23:58:33 +00001588 if (const ArrayType *AType
1589 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1590 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1591 NumElements = CAType->getSize().getZExtValue();
1592 // Simple heuristic so that we don't allocate a very large
1593 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001594 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001595 NumElements = 0;
1596 }
1597 } else if (const VectorType *VType = CurrentObjectType->getAsVectorType())
1598 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001599 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001600 RecordDecl *RDecl = RType->getDecl();
1601 if (RDecl->isUnion())
1602 NumElements = 1;
1603 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001604 NumElements = std::distance(RDecl->field_begin(),
1605 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001606 }
1607
Douglas Gregor08457732009-03-21 18:13:52 +00001608 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001609 NumElements = IList->getNumInits();
1610
1611 Result->reserveInits(NumElements);
1612
Douglas Gregor4c678342009-01-28 21:54:33 +00001613 // Link this new initializer list into the structured initializer
1614 // lists.
1615 if (StructuredList)
1616 StructuredList->updateInit(StructuredIndex, Result);
1617 else {
1618 Result->setSyntacticForm(IList);
1619 SyntacticToSemantic[IList] = Result;
1620 }
1621
1622 return Result;
1623}
1624
1625/// Update the initializer at index @p StructuredIndex within the
1626/// structured initializer list to the value @p expr.
1627void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1628 unsigned &StructuredIndex,
1629 Expr *expr) {
1630 // No structured initializer list to update
1631 if (!StructuredList)
1632 return;
1633
1634 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1635 // This initializer overwrites a previous initializer. Warn.
Chris Lattner08202542009-02-24 22:50:46 +00001636 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001637 diag::warn_initializer_overrides)
1638 << expr->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001639 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001640 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001641 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001642 << PrevInit->getSourceRange();
1643 }
1644
1645 ++StructuredIndex;
1646}
1647
Douglas Gregor05c13a32009-01-22 00:58:24 +00001648/// Check that the given Index expression is a valid array designator
1649/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001650/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001651/// and produces a reasonable diagnostic if there is a
1652/// failure. Returns true if there was an error, false otherwise. If
1653/// everything went okay, Value will receive the value of the constant
1654/// expression.
1655static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001656CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001657 SourceLocation Loc = Index->getSourceRange().getBegin();
1658
1659 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001660 if (S.VerifyIntegerConstantExpression(Index, &Value))
1661 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001662
Chris Lattner3bf68932009-04-25 21:59:05 +00001663 if (Value.isSigned() && Value.isNegative())
1664 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001665 << Value.toString(10) << Index->getSourceRange();
1666
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001667 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001668 return false;
1669}
1670
1671Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1672 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001673 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001674 OwningExprResult Init) {
1675 typedef DesignatedInitExpr::Designator ASTDesignator;
1676
1677 bool Invalid = false;
1678 llvm::SmallVector<ASTDesignator, 32> Designators;
1679 llvm::SmallVector<Expr *, 32> InitExpressions;
1680
1681 // Build designators and check array designator expressions.
1682 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1683 const Designator &D = Desig.getDesignator(Idx);
1684 switch (D.getKind()) {
1685 case Designator::FieldDesignator:
1686 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1687 D.getFieldLoc()));
1688 break;
1689
1690 case Designator::ArrayDesignator: {
1691 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1692 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001693 if (!Index->isTypeDependent() &&
1694 !Index->isValueDependent() &&
1695 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001696 Invalid = true;
1697 else {
1698 Designators.push_back(ASTDesignator(InitExpressions.size(),
1699 D.getLBracketLoc(),
1700 D.getRBracketLoc()));
1701 InitExpressions.push_back(Index);
1702 }
1703 break;
1704 }
1705
1706 case Designator::ArrayRangeDesignator: {
1707 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1708 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1709 llvm::APSInt StartValue;
1710 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001711 bool StartDependent = StartIndex->isTypeDependent() ||
1712 StartIndex->isValueDependent();
1713 bool EndDependent = EndIndex->isTypeDependent() ||
1714 EndIndex->isValueDependent();
1715 if ((!StartDependent &&
1716 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1717 (!EndDependent &&
1718 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001719 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001720 else {
1721 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001722 if (StartDependent || EndDependent) {
1723 // Nothing to compute.
1724 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001725 EndValue.extend(StartValue.getBitWidth());
1726 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1727 StartValue.extend(EndValue.getBitWidth());
1728
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001729 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001730 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1731 << StartValue.toString(10) << EndValue.toString(10)
1732 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1733 Invalid = true;
1734 } else {
1735 Designators.push_back(ASTDesignator(InitExpressions.size(),
1736 D.getLBracketLoc(),
1737 D.getEllipsisLoc(),
1738 D.getRBracketLoc()));
1739 InitExpressions.push_back(StartIndex);
1740 InitExpressions.push_back(EndIndex);
1741 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001742 }
1743 break;
1744 }
1745 }
1746 }
1747
1748 if (Invalid || Init.isInvalid())
1749 return ExprError();
1750
1751 // Clear out the expressions within the designation.
1752 Desig.ClearExprs(*this);
1753
1754 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001755 = DesignatedInitExpr::Create(Context,
1756 Designators.data(), Designators.size(),
1757 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001758 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001759 return Owned(DIE);
1760}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001761
1762bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001763 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001764 if (!CheckInitList.HadError())
1765 InitList = CheckInitList.getFullyStructuredList();
1766
1767 return CheckInitList.HadError();
1768}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001769
1770/// \brief Diagnose any semantic errors with value-initialization of
1771/// the given type.
1772///
1773/// Value-initialization effectively zero-initializes any types
1774/// without user-declared constructors, and calls the default
1775/// constructor for a for any type that has a user-declared
1776/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1777/// a type with a user-declared constructor does not have an
1778/// accessible, non-deleted default constructor. In C, everything can
1779/// be value-initialized, which corresponds to C's notion of
1780/// initializing objects with static storage duration when no
1781/// initializer is provided for that object.
1782///
1783/// \returns true if there was an error, false otherwise.
1784bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1785 // C++ [dcl.init]p5:
1786 //
1787 // To value-initialize an object of type T means:
1788
1789 // -- if T is an array type, then each element is value-initialized;
1790 if (const ArrayType *AT = Context.getAsArrayType(Type))
1791 return CheckValueInitialization(AT->getElementType(), Loc);
1792
Ted Kremenek6217b802009-07-29 21:53:49 +00001793 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001794 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001795 // -- if T is a class type (clause 9) with a user-declared
1796 // constructor (12.1), then the default constructor for T is
1797 // called (and the initialization is ill-formed if T has no
1798 // accessible default constructor);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001799 if (ClassDecl->hasUserDeclaredConstructor())
Mike Stump390b4cc2009-05-16 07:39:55 +00001800 // FIXME: Eventually, we'll need to put the constructor decl into the
1801 // AST.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001802 return PerformInitializationByConstructor(Type, 0, 0, Loc,
1803 SourceRange(Loc),
1804 DeclarationName(),
1805 IK_Direct);
1806 }
1807 }
1808
1809 if (Type->isReferenceType()) {
1810 // C++ [dcl.init]p5:
1811 // [...] A program that calls for default-initialization or
1812 // value-initialization of an entity of reference type is
1813 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001814 // FIXME: Once we have code that goes through this path, add an actual
1815 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001816 }
1817
1818 return false;
1819}