blob: 4b0fc84b301ee99d19606491319df4d87897ce35 [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();
Mike Stump1eb44332009-09-09 15:08:12 +000039
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // 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;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattnerdd8e0062009-02-24 22:27:37 +000062 return 0;
63}
64
Mike Stump1eb44332009-09-09 15:08:12 +000065static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner95e8d652009-02-24 22:46:58 +000066 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.
Mike Stump1eb44332009-09-09 15:08:12 +000069 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.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000073 if (S.PerformImplicitConversion(Init, DeclType,
74 "initializing", DirectInit)) {
75 ImplicitConversionSequence ICS;
76 OverloadCandidateSet CandidateSet;
77 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
78 CandidateSet,
79 true, false, false) != S.OR_Ambiguous)
80 return S.Diag(Init->getSourceRange().getBegin(),
81 diag::err_typecheck_convert_incompatible)
82 << DeclType << Init->getType() << "initializing"
83 << Init->getSourceRange();
84 S.Diag(Init->getSourceRange().getBegin(),
85 diag::err_typecheck_convert_ambiguous)
86 << DeclType << Init->getType() << Init->getSourceRange();
87 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
88 return true;
89 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +000090 return false;
91 }
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattner95e8d652009-02-24 22:46:58 +000093 Sema::AssignConvertType ConvTy =
94 S.CheckSingleAssignmentConstraints(DeclType, Init);
95 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 InitType, Init, "initializing");
97}
98
Chris Lattner79e079d2009-02-24 23:10:27 +000099static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
100 // Get the length of the string as parsed.
101 uint64_t StrLength =
102 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
103
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Chris Lattner79e079d2009-02-24 23:10:27 +0000105 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000106 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000107 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108 // being initialized to a string literal.
109 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000110 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000111 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000112 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
113 ConstVal,
114 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000115 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000116 }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Eli Friedman8718a6a2009-05-29 18:22:49 +0000118 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Eli Friedman8718a6a2009-05-29 18:22:49 +0000120 // C99 6.7.8p14. We have an array of character type with known size. However,
121 // the size may be smaller or larger than the string we are initializing.
122 // FIXME: Avoid truncation for 64-bit length strings.
123 if (StrLength-1 > CAT->getSize().getZExtValue())
124 S.Diag(Str->getSourceRange().getBegin(),
125 diag::warn_initializer_string_for_char_array_too_long)
126 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Eli Friedman8718a6a2009-05-29 18:22:49 +0000128 // Set the type to the actual size that we are initializing. If we have
129 // something like:
130 // char x[1] = "foo";
131 // then this will set the string literal's type to char[1].
132 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000133}
134
135bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
136 SourceLocation InitLoc,
Anders Carlsson0f5f2c62009-05-30 20:41:30 +0000137 DeclarationName InitEntity, bool DirectInit) {
Mike Stump1eb44332009-09-09 15:08:12 +0000138 if (DeclType->isDependentType() ||
Douglas Gregorcb78d882009-11-19 18:03:26 +0000139 Init->isTypeDependent() || Init->isValueDependent()) {
140 // We have either a dependent type or a type- or value-dependent
141 // initializer, so we don't perform any additional checking at
142 // this point.
143
144 // If the declaration is a non-dependent, incomplete array type
145 // that has an initializer, then its type will be completed once
Douglas Gregor73460a32009-11-19 23:25:22 +0000146 // the initializer is instantiated.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000147 if (!DeclType->isDependentType()) {
148 if (const IncompleteArrayType *ArrayT
149 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregor73460a32009-11-19 23:25:22 +0000150 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
151 if (!ILE->isTypeDependent()) {
152 // Compute the constant array type from the length of the
153 // initializer list.
154 // FIXME: This will be wrong if there are designated
155 // initializations. Good thing they don't exist in C++!
156 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
157 ILE->getNumInits());
158 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
159 if (NumElements == Zero) {
160 // Sizing an array implicitly to zero is not allowed by ISO C,
161 // but is supported by GNU.
162 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
163 }
164
165 DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
166 NumElements,
167 ArrayT->getSizeModifier(),
168 ArrayT->getIndexTypeCVRQualifiers());
169 return false;
170 }
171 }
172
173 // Make the array type-dependent by making it dependently-sized.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000174 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
175 /*NumElts=*/0,
176 ArrayT->getSizeModifier(),
177 ArrayT->getIndexTypeCVRQualifiers(),
178 SourceRange());
179 }
180 }
181
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000182 return false;
Douglas Gregorcb78d882009-11-19 18:03:26 +0000183 }
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000185 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000186 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000187 // (8.3.2), shall be initialized by an object, or function, of
188 // type T or by an object that can be converted into a T.
189 if (DeclType->isReferenceType())
Douglas Gregor739d8282009-09-23 23:04:10 +0000190 return CheckReferenceInit(Init, DeclType, InitLoc,
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000191 /*SuppressUserConversions=*/false,
192 /*AllowExplicit=*/DirectInit,
193 /*ForceRValue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000195 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
196 // of unknown size ("[]") or an object type that is not a variable array type.
197 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
198 return Diag(InitLoc, diag::err_variable_object_no_init)
199 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000201 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
202 if (!InitList) {
203 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000204 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
205 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000206 return false;
207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000209 // C++ [dcl.init]p14:
210 // -- If the destination type is a (possibly cv-qualified) class
211 // type:
212 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
213 QualType DeclTypeC = Context.getCanonicalType(DeclType);
214 QualType InitTypeC = Context.getCanonicalType(Init->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000216 // -- If the initialization is direct-initialization, or if it is
217 // copy-initialization where the cv-unqualified version of the
218 // source type is the same class as, or a derived class of, the
219 // class of the destination, constructors are considered.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000220 if ((DeclTypeC.getLocalUnqualifiedType()
221 == InitTypeC.getLocalUnqualifiedType()) ||
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000222 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000223 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000224 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000226 // No need to make a CXXConstructExpr if both the ctor and dtor are
227 // trivial.
228 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Douglas Gregor39da0b82009-09-09 23:08:42 +0000231 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000234 = PerformInitializationByConstructor(DeclType,
235 MultiExprArg(*this,
236 (void **)&Init, 1),
237 InitLoc, Init->getSourceRange(),
238 InitEntity,
239 DirectInit? IK_Direct : IK_Copy,
240 ConstructorArgs);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000241 if (!Constructor)
242 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
244 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000245 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000246 DeclType, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000247 move_arg(ConstructorArgs));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000248 if (InitResult.isInvalid())
249 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000251 Init = InitResult.takeAs<Expr>();
Anders Carlsson2078bb92009-05-27 16:10:08 +0000252 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000255 // -- Otherwise (i.e., for the remaining copy-initialization
256 // cases), user-defined conversion sequences that can
257 // convert from the source type to the destination type or
258 // (when a conversion function is used) to a derived class
259 // thereof are enumerated as described in 13.3.1.4, and the
260 // best one is chosen through overload resolution
261 // (13.3). If the conversion cannot be done or is
262 // ambiguous, the initialization is ill-formed. The
263 // function selected is called with the initializer
264 // expression as its argument; if the function is a
265 // constructor, the call initializes a temporary of the
266 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000267 // FIXME: We're pretending to do copy elision here; return to this when we
268 // have ASTs for such things.
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000269 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
270 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000272 if (InitEntity)
273 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000274 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
275 << Init->getType() << Init->getSourceRange();
276 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000277 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
278 << Init->getType() << Init->getSourceRange();
279 }
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000281 // C99 6.7.8p16.
282 if (DeclType->isArrayType())
283 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000284 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattner95e8d652009-02-24 22:46:58 +0000286 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000287 }
288
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000289 bool hadError = CheckInitList(InitList, DeclType);
290 Init = InitList;
291 return hadError;
292}
293
294//===----------------------------------------------------------------------===//
295// Semantic checking for initializer lists.
296//===----------------------------------------------------------------------===//
297
Douglas Gregor9e80f722009-01-29 01:05:33 +0000298/// @brief Semantic checking for initializer lists.
299///
300/// The InitListChecker class contains a set of routines that each
301/// handle the initialization of a certain kind of entity, e.g.,
302/// arrays, vectors, struct/union types, scalars, etc. The
303/// InitListChecker itself performs a recursive walk of the subobject
304/// structure of the type to be initialized, while stepping through
305/// the initializer list one element at a time. The IList and Index
306/// parameters to each of the Check* routines contain the active
307/// (syntactic) initializer list and the index into that initializer
308/// list that represents the current initializer. Each routine is
309/// responsible for moving that Index forward as it consumes elements.
310///
311/// Each Check* routine also has a StructuredList/StructuredIndex
312/// arguments, which contains the current the "structured" (semantic)
313/// initializer list and the index into that initializer list where we
314/// are copying initializers as we map them over to the semantic
315/// list. Once we have completed our recursive walk of the subobject
316/// structure, we will have constructed a full semantic initializer
317/// list.
318///
319/// C99 designators cause changes in the initializer list traversal,
320/// because they make the initialization "jump" into a specific
321/// subobject and then continue the initialization from that
322/// point. CheckDesignatedInitializer() recursively steps into the
323/// designated subobject and manages backing out the recursion to
324/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000325namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000326class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000327 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000328 bool hadError;
329 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
330 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
332 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000333 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000334 unsigned &StructuredIndex,
335 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000336 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000337 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000338 unsigned &StructuredIndex,
339 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000340 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
341 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000342 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000343 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000344 unsigned &StructuredIndex,
345 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000346 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000347 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000348 InitListExpr *StructuredList,
349 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000350 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000351 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000352 InitListExpr *StructuredList,
353 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000354 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000355 unsigned &Index,
356 InitListExpr *StructuredList,
357 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000358 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000359 InitListExpr *StructuredList,
360 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000361 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
362 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000363 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000364 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000365 unsigned &StructuredIndex,
366 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
368 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000369 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000370 InitListExpr *StructuredList,
371 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000372 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000373 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000374 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000375 RecordDecl::field_iterator *NextField,
376 llvm::APSInt *NextElementIndex,
377 unsigned &Index,
378 InitListExpr *StructuredList,
379 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000380 bool FinishSubobjectInit,
381 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000382 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
383 QualType CurrentObjectType,
384 InitListExpr *StructuredList,
385 unsigned StructuredIndex,
386 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000387 void UpdateStructuredListElement(InitListExpr *StructuredList,
388 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000389 Expr *expr);
390 int numArrayElements(QualType DeclType);
391 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000392
393 void FillInValueInitializations(InitListExpr *ILE);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000394public:
Chris Lattner08202542009-02-24 22:50:46 +0000395 InitListChecker(Sema &S, InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000396 bool HadError() { return hadError; }
397
398 // @brief Retrieves the fully-structured initializer list used for
399 // semantic analysis and code generation.
400 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
401};
Chris Lattner8b419b92009-02-24 22:48:58 +0000402} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000403
Douglas Gregor4c678342009-01-28 21:54:33 +0000404/// Recursively replaces NULL values within the given initializer list
405/// with expressions that perform value-initialization of the
406/// appropriate type.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000407void InitListChecker::FillInValueInitializations(InitListExpr *ILE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000408 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000409 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000410 SourceLocation Loc = ILE->getSourceRange().getBegin();
411 if (ILE->getSyntacticForm())
412 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek6217b802009-07-29 21:53:49 +0000414 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000415 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000416 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000417 Field = RType->getDecl()->field_begin(),
418 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000419 Field != FieldEnd; ++Field) {
420 if (Field->isUnnamedBitfield())
421 continue;
422
Douglas Gregor87fd7032009-02-02 17:43:21 +0000423 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000424 if (Field->getType()->isReferenceType()) {
425 // C++ [dcl.init.aggr]p9:
426 // If an incomplete or empty initializer-list leaves a
427 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000428 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000429 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000430 << Field->getType()
431 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000432 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 diag::note_uninit_reference_member);
434 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000435 return;
Chris Lattner08202542009-02-24 22:50:46 +0000436 } else if (SemaRef.CheckValueInitialization(Field->getType(), Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000437 hadError = true;
438 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000439 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000440
Mike Stump390b4cc2009-05-16 07:39:55 +0000441 // FIXME: If value-initialization involves calling a constructor, should
442 // we make that call explicit in the representation (even when it means
443 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000444 if (Init < NumInits && !hadError)
Mike Stump1eb44332009-09-09 15:08:12 +0000445 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000446 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000447 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000448 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000449 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000450 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000451
452 // Only look at the first initialization of a union.
453 if (RType->getDecl()->isUnion())
454 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000455 }
456
457 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000458 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000459
460 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregor87fd7032009-02-02 17:43:21 +0000462 unsigned NumInits = ILE->getNumInits();
463 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000464 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000465 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000466 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
467 NumElements = CAType->getSize().getZExtValue();
John McCall183700f2009-09-21 23:43:11 +0000468 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000469 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000470 NumElements = VType->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000471 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000472 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Douglas Gregor87fd7032009-02-02 17:43:21 +0000474 for (unsigned Init = 0; Init != NumElements; ++Init) {
475 if (Init >= NumInits || !ILE->getInit(Init)) {
Chris Lattner08202542009-02-24 22:50:46 +0000476 if (SemaRef.CheckValueInitialization(ElementType, Loc)) {
Douglas Gregor87fd7032009-02-02 17:43:21 +0000477 hadError = true;
478 return;
479 }
480
Mike Stump390b4cc2009-05-16 07:39:55 +0000481 // FIXME: If value-initialization involves calling a constructor, should
482 // we make that call explicit in the representation (even when it means
483 // extending the initializer list)?
Douglas Gregor87fd7032009-02-02 17:43:21 +0000484 if (Init < NumInits && !hadError)
Mike Stump1eb44332009-09-09 15:08:12 +0000485 ILE->setInit(Init,
Chris Lattner08202542009-02-24 22:50:46 +0000486 new (SemaRef.Context) ImplicitValueInitExpr(ElementType));
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000487 } else if (InitListExpr *InnerILE
488 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000489 FillInValueInitializations(InnerILE);
Douglas Gregor4c678342009-01-28 21:54:33 +0000490 }
491}
492
Chris Lattner68355a52009-01-29 05:10:57 +0000493
Chris Lattner08202542009-02-24 22:50:46 +0000494InitListChecker::InitListChecker(Sema &S, InitListExpr *IL, QualType &T)
495 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000496 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000497
Eli Friedmanb85f7072008-05-19 19:16:24 +0000498 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000499 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000500 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000501 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000502 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
503 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000504
Douglas Gregor930d8b52009-01-30 22:09:00 +0000505 if (!hadError)
506 FillInValueInitializations(FullyStructuredList);
Steve Naroff0cca7492008-05-01 22:18:59 +0000507}
508
509int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000510 // FIXME: use a proper constant
511 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000512 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000513 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000514 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
515 }
516 return maxElements;
517}
518
519int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000520 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000522 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000523 Field = structDecl->field_begin(),
524 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000525 Field != FieldEnd; ++Field) {
526 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
527 ++InitializableMembers;
528 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000529 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000530 return std::min(InitializableMembers, 1);
531 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000532}
533
Mike Stump1eb44332009-09-09 15:08:12 +0000534void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000535 QualType T, unsigned &Index,
536 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000537 unsigned &StructuredIndex,
538 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000539 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Steve Naroff0cca7492008-05-01 22:18:59 +0000541 if (T->isArrayType())
542 maxElements = numArrayElements(T);
543 else if (T->isStructureType() || T->isUnionType())
544 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000545 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000546 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000547 else
548 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000549
Eli Friedman402256f2008-05-25 13:49:22 +0000550 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000551 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000552 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000553 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000554 hadError = true;
555 return;
556 }
557
Douglas Gregor4c678342009-01-28 21:54:33 +0000558 // Build a structured initializer list corresponding to this subobject.
559 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000560 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
561 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000562 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
563 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000564 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000565
Douglas Gregor4c678342009-01-28 21:54:33 +0000566 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000567 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000568 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000569 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000570 StructuredSubobjectInitIndex,
571 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000572 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000573 StructuredSubobjectInitList->setType(T);
574
Douglas Gregored8a93d2009-03-01 17:12:46 +0000575 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000576 // range corresponds with the end of the last initializer it used.
577 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000578 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000579 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
580 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
581 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000582}
583
Steve Naroffa647caa2008-05-06 00:23:44 +0000584void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000585 unsigned &Index,
586 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000587 unsigned &StructuredIndex,
588 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000589 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000590 SyntacticToSemantic[IList] = StructuredList;
591 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000592 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000593 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000594 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000595 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000596 if (hadError)
597 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000598
Eli Friedman638e1442008-05-25 13:22:35 +0000599 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000600 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000601 if (StructuredIndex == 1 &&
602 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000603 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000604 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000605 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000606 hadError = true;
607 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000608 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000609 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000610 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000611 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000612 // Don't complain for incomplete types, since we'll get an error
613 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000614 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000615 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000616 CurrentObjectType->isArrayType()? 0 :
617 CurrentObjectType->isVectorType()? 1 :
618 CurrentObjectType->isScalarType()? 2 :
619 CurrentObjectType->isUnionType()? 3 :
620 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000621
622 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000623 if (SemaRef.getLangOptions().CPlusPlus) {
624 DK = diag::err_excess_initializers;
625 hadError = true;
626 }
Nate Begeman08634522009-07-07 21:53:06 +0000627 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
628 DK = diag::err_excess_initializers;
629 hadError = true;
630 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000631
Chris Lattner08202542009-02-24 22:50:46 +0000632 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000633 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000634 }
635 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000636
Eli Friedman759f2522009-05-16 11:45:48 +0000637 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000638 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000639 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000640 << CodeModificationHint::CreateRemoval(IList->getLocStart())
641 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000642}
643
Eli Friedmanb85f7072008-05-19 19:16:24 +0000644void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000646 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned &Index,
648 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000649 unsigned &StructuredIndex,
650 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000651 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000652 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000653 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000654 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000655 } else if (DeclType->isAggregateType()) {
656 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000657 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000658 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000659 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000660 StructuredList, StructuredIndex,
661 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000662 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000663 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000664 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000665 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000666 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
667 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000668 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000669 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000670 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
671 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000673 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000674 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000675 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000676 } else if (DeclType->isRecordType()) {
677 // C++ [dcl.init]p14:
678 // [...] If the class is an aggregate (8.5.1), and the initializer
679 // is a brace-enclosed list, see 8.5.1.
680 //
681 // Note: 8.5.1 is handled below; here, we diagnose the case where
682 // we have an initializer list and a destination type that is not
683 // an aggregate.
684 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000685 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000686 << DeclType << IList->getSourceRange();
687 hadError = true;
688 } else if (DeclType->isReferenceType()) {
689 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000690 } else {
691 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000692 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000693 assert(0 && "Unsupported initializer type");
694 }
695}
696
Eli Friedmanb85f7072008-05-19 19:16:24 +0000697void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000698 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000699 unsigned &Index,
700 InitListExpr *StructuredList,
701 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000702 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000703 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
704 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000705 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000706 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000707 = getStructuredSubobjectInit(IList, Index, ElemType,
708 StructuredList, StructuredIndex,
709 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000710 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000711 newStructuredList, newStructuredIndex);
712 ++StructuredIndex;
713 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000714 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
715 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000716 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000718 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000719 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000720 } else if (ElemType->isReferenceType()) {
721 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000722 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000723 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000724 // C++ [dcl.init.aggr]p12:
725 // All implicit type conversions (clause 4) are considered when
726 // initializing the aggregate member with an ini- tializer from
727 // an initializer-list. If the initializer can initialize a
728 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000729 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000730 = SemaRef.TryCopyInitialization(expr, ElemType,
731 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000732 /*ForceRValue=*/false,
733 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000734
Douglas Gregor930d8b52009-01-30 22:09:00 +0000735 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000736 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000737 "initializing"))
738 hadError = true;
739 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
740 ++Index;
741 return;
742 }
743
744 // Fall through for subaggregate initialization
745 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000746 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000747 //
748 // The initializer for a structure or union object that has
749 // automatic storage duration shall be either an initializer
750 // list as described below, or a single expression that has
751 // compatible structure or union type. In the latter case, the
752 // initial value of the object, including unnamed members, is
753 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000754 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000755 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000756 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
757 ++Index;
758 return;
759 }
760
761 // Fall through for subaggregate initialization
762 }
763
764 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000765 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000766 // [...] Otherwise, if the member is itself a non-empty
767 // subaggregate, brace elision is assumed and the initializer is
768 // considered for the initialization of the first member of
769 // the subaggregate.
770 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000771 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000772 StructuredIndex);
773 ++StructuredIndex;
774 } else {
775 // We cannot initialize this element, so let
776 // PerformCopyInitialization produce the appropriate diagnostic.
Chris Lattner08202542009-02-24 22:50:46 +0000777 SemaRef.PerformCopyInitialization(expr, ElemType, "initializing");
Douglas Gregor930d8b52009-01-30 22:09:00 +0000778 hadError = true;
779 ++Index;
780 ++StructuredIndex;
781 }
782 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000783}
784
Douglas Gregor930d8b52009-01-30 22:09:00 +0000785void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000786 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000787 InitListExpr *StructuredList,
788 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000789 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000790 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000791 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000792 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000793 diag::err_many_braces_around_scalar_init)
794 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000795 hadError = true;
796 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000797 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000798 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000799 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000800 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000801 diag::err_designator_for_scalar_init)
802 << DeclType << expr->getSourceRange();
803 hadError = true;
804 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000805 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000806 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000807 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000808
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000809 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000810 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000811 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000812 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000813 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000814 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000815 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000816 if (hadError)
817 ++StructuredIndex;
818 else
819 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000820 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000821 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000822 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000823 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000824 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000825 ++Index;
826 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000827 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000828 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000829}
830
Douglas Gregor930d8b52009-01-30 22:09:00 +0000831void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
832 unsigned &Index,
833 InitListExpr *StructuredList,
834 unsigned &StructuredIndex) {
835 if (Index < IList->getNumInits()) {
836 Expr *expr = IList->getInit(Index);
837 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000838 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000839 << DeclType << IList->getSourceRange();
840 hadError = true;
841 ++Index;
842 ++StructuredIndex;
843 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000844 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000845
846 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000847 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000848 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000849 /*SuppressUserConversions=*/false,
850 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000851 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000852 hadError = true;
853 else if (savExpr != expr) {
854 // The type was promoted, update initializer list.
855 IList->setInit(Index, expr);
856 }
857 if (hadError)
858 ++StructuredIndex;
859 else
860 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
861 ++Index;
862 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000863 // FIXME: It would be wonderful if we could point at the actual member. In
864 // general, it would be useful to pass location information down the stack,
865 // so that we know the location (or decl) of the "current object" being
866 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000867 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000868 diag::err_init_reference_member_uninitialized)
869 << DeclType
870 << IList->getSourceRange();
871 hadError = true;
872 ++Index;
873 ++StructuredIndex;
874 return;
875 }
876}
877
Mike Stump1eb44332009-09-09 15:08:12 +0000878void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000879 unsigned &Index,
880 InitListExpr *StructuredList,
881 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000882 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000883 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000884 unsigned maxElements = VT->getNumElements();
885 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000886 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Nate Begeman2ef13e52009-08-10 23:49:36 +0000888 if (!SemaRef.getLangOptions().OpenCL) {
889 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
890 // Don't attempt to go past the end of the init list
891 if (Index >= IList->getNumInits())
892 break;
893 CheckSubElementType(IList, elementType, Index,
894 StructuredList, StructuredIndex);
895 }
896 } else {
897 // OpenCL initializers allows vectors to be constructed from vectors.
898 for (unsigned i = 0; i < maxElements; ++i) {
899 // Don't attempt to go past the end of the init list
900 if (Index >= IList->getNumInits())
901 break;
902 QualType IType = IList->getInit(Index)->getType();
903 if (!IType->isVectorType()) {
904 CheckSubElementType(IList, elementType, Index,
905 StructuredList, StructuredIndex);
906 ++numEltsInit;
907 } else {
John McCall183700f2009-09-21 23:43:11 +0000908 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000909 unsigned numIElts = IVT->getNumElements();
910 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
911 numIElts);
912 CheckSubElementType(IList, VecType, Index,
913 StructuredList, StructuredIndex);
914 numEltsInit += numIElts;
915 }
916 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Nate Begeman2ef13e52009-08-10 23:49:36 +0000919 // OpenCL & AltiVec require all elements to be initialized.
920 if (numEltsInit != maxElements)
921 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
922 SemaRef.Diag(IList->getSourceRange().getBegin(),
923 diag::err_vector_incorrect_num_initializers)
924 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000925 }
926}
927
Mike Stump1eb44332009-09-09 15:08:12 +0000928void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000929 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000930 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000931 unsigned &Index,
932 InitListExpr *StructuredList,
933 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000934 // Check for the special-case of initializing an array with a string.
935 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000936 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
937 SemaRef.Context)) {
938 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000939 // We place the string literal directly into the resulting
940 // initializer list. This is the only place where the structure
941 // of the structured initializer list doesn't match exactly,
942 // because doing so would involve allocating one character
943 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000944 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000945 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000946 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000947 return;
948 }
949 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000950 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000951 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000952 // Check for VLAs; in standard C it would be possible to check this
953 // earlier, but I don't know where clang accepts VLAs (gcc accepts
954 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000955 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000956 diag::err_variable_object_no_init)
957 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000958 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000959 ++Index;
960 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000961 return;
962 }
963
Douglas Gregor05c13a32009-01-22 00:58:24 +0000964 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000965 llvm::APSInt maxElements(elementIndex.getBitWidth(),
966 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000967 bool maxElementsKnown = false;
968 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000969 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000970 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000971 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000972 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000973 maxElementsKnown = true;
974 }
975
Chris Lattner08202542009-02-24 22:50:46 +0000976 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000977 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000978 while (Index < IList->getNumInits()) {
979 Expr *Init = IList->getInit(Index);
980 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000981 // If we're not the subobject that matches up with the '{' for
982 // the designator, we shouldn't be handling the
983 // designator. Return immediately.
984 if (!SubobjectIsDesignatorContext)
985 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000986
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000987 // Handle this designated initializer. elementIndex will be
988 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +0000989 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000990 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000991 StructuredList, StructuredIndex, true,
992 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000993 hadError = true;
994 continue;
995 }
996
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000997 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
998 maxElements.extend(elementIndex.getBitWidth());
999 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1000 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001001 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001002
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001003 // If the array is of incomplete type, keep track of the number of
1004 // elements in the initializer.
1005 if (!maxElementsKnown && elementIndex > maxElements)
1006 maxElements = elementIndex;
1007
Douglas Gregor05c13a32009-01-22 00:58:24 +00001008 continue;
1009 }
1010
1011 // If we know the maximum number of elements, and we've already
1012 // hit it, stop consuming elements in the initializer list.
1013 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001014 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001015
1016 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001017 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001018 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001019 ++elementIndex;
1020
1021 // If the array is of incomplete type, keep track of the number of
1022 // elements in the initializer.
1023 if (!maxElementsKnown && elementIndex > maxElements)
1024 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001025 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001026 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001027 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001028 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001029 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001030 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001031 // Sizing an array implicitly to zero is not allowed by ISO C,
1032 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001033 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001034 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001035 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001036
Mike Stump1eb44332009-09-09 15:08:12 +00001037 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001038 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001039 }
1040}
1041
Mike Stump1eb44332009-09-09 15:08:12 +00001042void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1043 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001044 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001045 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001046 unsigned &Index,
1047 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001048 unsigned &StructuredIndex,
1049 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001050 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Eli Friedmanb85f7072008-05-19 19:16:24 +00001052 // If the record is invalid, some of it's members are invalid. To avoid
1053 // confusion, we forgo checking the intializer for the entire record.
1054 if (structDecl->isInvalidDecl()) {
1055 hadError = true;
1056 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001057 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001058
1059 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1060 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001061 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001062 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001063 Field != FieldEnd; ++Field) {
1064 if (Field->getDeclName()) {
1065 StructuredList->setInitializedFieldInUnion(*Field);
1066 break;
1067 }
1068 }
1069 return;
1070 }
1071
Douglas Gregor05c13a32009-01-22 00:58:24 +00001072 // If structDecl is a forward declaration, this loop won't do
1073 // anything except look at designated initializers; That's okay,
1074 // because an error should get printed out elsewhere. It might be
1075 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001076 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001077 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001078 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001079 while (Index < IList->getNumInits()) {
1080 Expr *Init = IList->getInit(Index);
1081
1082 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001083 // If we're not the subobject that matches up with the '{' for
1084 // the designator, we shouldn't be handling the
1085 // designator. Return immediately.
1086 if (!SubobjectIsDesignatorContext)
1087 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001088
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001089 // Handle this designated initializer. Field will be updated to
1090 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001091 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001092 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001093 StructuredList, StructuredIndex,
1094 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001095 hadError = true;
1096
Douglas Gregordfb5e592009-02-12 19:00:39 +00001097 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001098 continue;
1099 }
1100
1101 if (Field == FieldEnd) {
1102 // We've run out of fields. We're done.
1103 break;
1104 }
1105
Douglas Gregordfb5e592009-02-12 19:00:39 +00001106 // We've already initialized a member of a union. We're done.
1107 if (InitializedSomething && DeclType->isUnionType())
1108 break;
1109
Douglas Gregor44b43212008-12-11 16:49:14 +00001110 // If we've hit the flexible array member at the end, we're done.
1111 if (Field->getType()->isIncompleteArrayType())
1112 break;
1113
Douglas Gregor0bb76892009-01-29 16:53:55 +00001114 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001115 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001116 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001117 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001118 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001119
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001120 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001121 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001122 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001123
1124 if (DeclType->isUnionType()) {
1125 // Initialize the first field within the union.
1126 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001127 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001128
1129 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001130 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001131
Mike Stump1eb44332009-09-09 15:08:12 +00001132 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001133 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001134 return;
1135
1136 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001137 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001138 (!isa<InitListExpr>(IList->getInit(Index)) ||
1139 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001140 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001141 diag::err_flexible_array_init_nonempty)
1142 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001143 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001144 << *Field;
1145 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001146 ++Index;
1147 return;
1148 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001149 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001150 diag::ext_flexible_array_init)
1151 << IList->getInit(Index)->getSourceRange().getBegin();
1152 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1153 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001154 }
1155
Douglas Gregora6457962009-03-20 00:32:56 +00001156 if (isa<InitListExpr>(IList->getInit(Index)))
1157 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1158 StructuredIndex);
1159 else
1160 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1161 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001162}
Steve Naroff0cca7492008-05-01 22:18:59 +00001163
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001164/// \brief Expand a field designator that refers to a member of an
1165/// anonymous struct or union into a series of field designators that
1166/// refers to the field within the appropriate subobject.
1167///
1168/// Field/FieldIndex will be updated to point to the (new)
1169/// currently-designated field.
1170static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001171 DesignatedInitExpr *DIE,
1172 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001173 FieldDecl *Field,
1174 RecordDecl::field_iterator &FieldIter,
1175 unsigned &FieldIndex) {
1176 typedef DesignatedInitExpr::Designator Designator;
1177
1178 // Build the path from the current object to the member of the
1179 // anonymous struct/union (backwards).
1180 llvm::SmallVector<FieldDecl *, 4> Path;
1181 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001183 // Build the replacement designators.
1184 llvm::SmallVector<Designator, 4> Replacements;
1185 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1186 FI = Path.rbegin(), FIEnd = Path.rend();
1187 FI != FIEnd; ++FI) {
1188 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001189 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001190 DIE->getDesignator(DesigIdx)->getDotLoc(),
1191 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1192 else
1193 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1194 SourceLocation()));
1195 Replacements.back().setField(*FI);
1196 }
1197
1198 // Expand the current designator into the set of replacement
1199 // designators, so we have a full subobject path down to where the
1200 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001201 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001202 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001204 // Update FieldIter/FieldIndex;
1205 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001206 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001207 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001208 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001209 FieldIter != FEnd; ++FieldIter) {
1210 if (FieldIter->isUnnamedBitfield())
1211 continue;
1212
1213 if (*FieldIter == Path.back())
1214 return;
1215
1216 ++FieldIndex;
1217 }
1218
1219 assert(false && "Unable to find anonymous struct/union field");
1220}
1221
Douglas Gregor05c13a32009-01-22 00:58:24 +00001222/// @brief Check the well-formedness of a C99 designated initializer.
1223///
1224/// Determines whether the designated initializer @p DIE, which
1225/// resides at the given @p Index within the initializer list @p
1226/// IList, is well-formed for a current object of type @p DeclType
1227/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001228/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001229/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001230///
1231/// @param IList The initializer list in which this designated
1232/// initializer occurs.
1233///
Douglas Gregor71199712009-04-15 04:56:10 +00001234/// @param DIE The designated initializer expression.
1235///
1236/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001237///
1238/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1239/// into which the designation in @p DIE should refer.
1240///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001241/// @param NextField If non-NULL and the first designator in @p DIE is
1242/// a field, this will be set to the field declaration corresponding
1243/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001244///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001245/// @param NextElementIndex If non-NULL and the first designator in @p
1246/// DIE is an array designator or GNU array-range designator, this
1247/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001248///
1249/// @param Index Index into @p IList where the designated initializer
1250/// @p DIE occurs.
1251///
Douglas Gregor4c678342009-01-28 21:54:33 +00001252/// @param StructuredList The initializer list expression that
1253/// describes all of the subobject initializers in the order they'll
1254/// actually be initialized.
1255///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001256/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001257bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001258InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001259 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001260 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001261 QualType &CurrentObjectType,
1262 RecordDecl::field_iterator *NextField,
1263 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001264 unsigned &Index,
1265 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001266 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001267 bool FinishSubobjectInit,
1268 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001269 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001270 // Check the actual initialization for the designated object type.
1271 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001272
1273 // Temporarily remove the designator expression from the
1274 // initializer list that the child calls see, so that we don't try
1275 // to re-process the designator.
1276 unsigned OldIndex = Index;
1277 IList->setInit(OldIndex, DIE->getInit());
1278
1279 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001280 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001281
1282 // Restore the designated initializer expression in the syntactic
1283 // form of the initializer list.
1284 if (IList->getInit(OldIndex) != DIE->getInit())
1285 DIE->setInit(IList->getInit(OldIndex));
1286 IList->setInit(OldIndex, DIE);
1287
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001288 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001289 }
1290
Douglas Gregor71199712009-04-15 04:56:10 +00001291 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001292 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001293 "Need a non-designated initializer list to start from");
1294
Douglas Gregor71199712009-04-15 04:56:10 +00001295 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001296 // Determine the structural initializer list that corresponds to the
1297 // current subobject.
1298 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001299 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001300 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001301 SourceRange(D->getStartLocation(),
1302 DIE->getSourceRange().getEnd()));
1303 assert(StructuredList && "Expected a structured initializer list");
1304
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001305 if (D->isFieldDesignator()) {
1306 // C99 6.7.8p7:
1307 //
1308 // If a designator has the form
1309 //
1310 // . identifier
1311 //
1312 // then the current object (defined below) shall have
1313 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001314 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001315 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001316 if (!RT) {
1317 SourceLocation Loc = D->getDotLoc();
1318 if (Loc.isInvalid())
1319 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001320 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1321 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001322 ++Index;
1323 return true;
1324 }
1325
Douglas Gregor4c678342009-01-28 21:54:33 +00001326 // Note: we perform a linear search of the fields here, despite
1327 // the fact that we have a faster lookup method, because we always
1328 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001329 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001330 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001331 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001332 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001333 Field = RT->getDecl()->field_begin(),
1334 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001335 for (; Field != FieldEnd; ++Field) {
1336 if (Field->isUnnamedBitfield())
1337 continue;
1338
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001339 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001340 break;
1341
1342 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001343 }
1344
Douglas Gregor4c678342009-01-28 21:54:33 +00001345 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001346 // There was no normal field in the struct with the designated
1347 // name. Perform another lookup for this name, which may find
1348 // something that we can't designate (e.g., a member function),
1349 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001350 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001351 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001352 if (Lookup.first == Lookup.second) {
1353 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001354 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001355 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001356 ++Index;
1357 return true;
1358 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1359 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1360 ->isAnonymousStructOrUnion()) {
1361 // Handle an field designator that refers to a member of an
1362 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001363 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001364 cast<FieldDecl>(*Lookup.first),
1365 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001366 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001367 } else {
1368 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001369 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001370 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001371 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001372 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001373 ++Index;
1374 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001375 }
1376 } else if (!KnownField &&
1377 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001378 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001379 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1380 Field, FieldIndex);
1381 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001382 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001383
1384 // All of the fields of a union are located at the same place in
1385 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001386 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001387 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001388 StructuredList->setInitializedFieldInUnion(*Field);
1389 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001390
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001391 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregor4c678342009-01-28 21:54:33 +00001394 // Make sure that our non-designated initializer list has space
1395 // for a subobject corresponding to this field.
1396 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001397 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001398
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001399 // This designator names a flexible array member.
1400 if (Field->getType()->isIncompleteArrayType()) {
1401 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001402 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001403 // We can't designate an object within the flexible array
1404 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001405 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001406 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001407 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001408 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001409 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001410 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001411 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001412 << *Field;
1413 Invalid = true;
1414 }
1415
1416 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1417 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001418 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001419 diag::err_flexible_array_init_needs_braces)
1420 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001421 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001422 << *Field;
1423 Invalid = true;
1424 }
1425
1426 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001427 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001428 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001429 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001430 diag::err_flexible_array_init_nonempty)
1431 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001432 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001433 << *Field;
1434 Invalid = true;
1435 }
1436
1437 if (Invalid) {
1438 ++Index;
1439 return true;
1440 }
1441
1442 // Initialize the array.
1443 bool prevHadError = hadError;
1444 unsigned newStructuredIndex = FieldIndex;
1445 unsigned OldIndex = Index;
1446 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001447 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001448 StructuredList, newStructuredIndex);
1449 IList->setInit(OldIndex, DIE);
1450 if (hadError && !prevHadError) {
1451 ++Field;
1452 ++FieldIndex;
1453 if (NextField)
1454 *NextField = Field;
1455 StructuredIndex = FieldIndex;
1456 return true;
1457 }
1458 } else {
1459 // Recurse to check later designated subobjects.
1460 QualType FieldType = (*Field)->getType();
1461 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001462 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1463 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001464 true, false))
1465 return true;
1466 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001467
1468 // Find the position of the next field to be initialized in this
1469 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001470 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001471 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001472
1473 // If this the first designator, our caller will continue checking
1474 // the rest of this struct/class/union subobject.
1475 if (IsFirstDesignator) {
1476 if (NextField)
1477 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001478 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001479 return false;
1480 }
1481
Douglas Gregor34e79462009-01-28 23:36:17 +00001482 if (!FinishSubobjectInit)
1483 return false;
1484
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001485 // We've already initialized something in the union; we're done.
1486 if (RT->getDecl()->isUnion())
1487 return hadError;
1488
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001489 // Check the remaining fields within this class/struct/union subobject.
1490 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001491 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1492 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001493 return hadError && !prevHadError;
1494 }
1495
1496 // C99 6.7.8p6:
1497 //
1498 // If a designator has the form
1499 //
1500 // [ constant-expression ]
1501 //
1502 // then the current object (defined below) shall have array
1503 // type and the expression shall be an integer constant
1504 // expression. If the array is of unknown size, any
1505 // nonnegative value is valid.
1506 //
1507 // Additionally, cope with the GNU extension that permits
1508 // designators of the form
1509 //
1510 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001511 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001512 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001513 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001514 << CurrentObjectType;
1515 ++Index;
1516 return true;
1517 }
1518
1519 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001520 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1521 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001522 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001523 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001524 DesignatedEndIndex = DesignatedStartIndex;
1525 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001526 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001527
Mike Stump1eb44332009-09-09 15:08:12 +00001528
1529 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001530 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001531 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001532 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001533 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001534
Chris Lattner3bf68932009-04-25 21:59:05 +00001535 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001536 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 }
1538
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001539 if (isa<ConstantArrayType>(AT)) {
1540 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001541 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1542 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1543 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1544 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1545 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001546 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001547 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001548 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001549 << IndexExpr->getSourceRange();
1550 ++Index;
1551 return true;
1552 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001553 } else {
1554 // Make sure the bit-widths and signedness match.
1555 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1556 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001557 else if (DesignatedStartIndex.getBitWidth() <
1558 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001559 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1560 DesignatedStartIndex.setIsUnsigned(true);
1561 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Douglas Gregor4c678342009-01-28 21:54:33 +00001564 // Make sure that our non-designated initializer list has space
1565 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001566 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001567 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001569
Douglas Gregor34e79462009-01-28 23:36:17 +00001570 // Repeatedly perform subobject initializations in the range
1571 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572
Douglas Gregor34e79462009-01-28 23:36:17 +00001573 // Move to the next designator
1574 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1575 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001576 while (DesignatedStartIndex <= DesignatedEndIndex) {
1577 // Recurse to check later designated subobjects.
1578 QualType ElementType = AT->getElementType();
1579 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001580 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1581 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001582 (DesignatedStartIndex == DesignatedEndIndex),
1583 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001584 return true;
1585
1586 // Move to the next index in the array that we'll be initializing.
1587 ++DesignatedStartIndex;
1588 ElementIndex = DesignatedStartIndex.getZExtValue();
1589 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001590
1591 // If this the first designator, our caller will continue checking
1592 // the rest of this array subobject.
1593 if (IsFirstDesignator) {
1594 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001595 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001596 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 return false;
1598 }
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Douglas Gregor34e79462009-01-28 23:36:17 +00001600 if (!FinishSubobjectInit)
1601 return false;
1602
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001603 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001604 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001605 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001606 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001607 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001608}
1609
Douglas Gregor4c678342009-01-28 21:54:33 +00001610// Get the structured initializer list for a subobject of type
1611// @p CurrentObjectType.
1612InitListExpr *
1613InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1614 QualType CurrentObjectType,
1615 InitListExpr *StructuredList,
1616 unsigned StructuredIndex,
1617 SourceRange InitRange) {
1618 Expr *ExistingInit = 0;
1619 if (!StructuredList)
1620 ExistingInit = SyntacticToSemantic[IList];
1621 else if (StructuredIndex < StructuredList->getNumInits())
1622 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Douglas Gregor4c678342009-01-28 21:54:33 +00001624 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1625 return Result;
1626
1627 if (ExistingInit) {
1628 // We are creating an initializer list that initializes the
1629 // subobjects of the current object, but there was already an
1630 // initialization that completely initialized the current
1631 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001632 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001633 // struct X { int a, b; };
1634 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001635 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001636 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1637 // designated initializer re-initializes the whole
1638 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001639 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001640 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001641 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001642 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001643 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001644 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001645 << ExistingInit->getSourceRange();
1646 }
1647
Mike Stump1eb44332009-09-09 15:08:12 +00001648 InitListExpr *Result
1649 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001650 InitRange.getEnd());
1651
Douglas Gregor4c678342009-01-28 21:54:33 +00001652 Result->setType(CurrentObjectType);
1653
Douglas Gregorfa219202009-03-20 23:58:33 +00001654 // Pre-allocate storage for the structured initializer list.
1655 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001656 unsigned NumInits = 0;
1657 if (!StructuredList)
1658 NumInits = IList->getNumInits();
1659 else if (Index < IList->getNumInits()) {
1660 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1661 NumInits = SubList->getNumInits();
1662 }
1663
Mike Stump1eb44332009-09-09 15:08:12 +00001664 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001665 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1666 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1667 NumElements = CAType->getSize().getZExtValue();
1668 // Simple heuristic so that we don't allocate a very large
1669 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001670 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001671 NumElements = 0;
1672 }
John McCall183700f2009-09-21 23:43:11 +00001673 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001674 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001675 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001676 RecordDecl *RDecl = RType->getDecl();
1677 if (RDecl->isUnion())
1678 NumElements = 1;
1679 else
Mike Stump1eb44332009-09-09 15:08:12 +00001680 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001681 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001682 }
1683
Douglas Gregor08457732009-03-21 18:13:52 +00001684 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001685 NumElements = IList->getNumInits();
1686
1687 Result->reserveInits(NumElements);
1688
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 // Link this new initializer list into the structured initializer
1690 // lists.
1691 if (StructuredList)
1692 StructuredList->updateInit(StructuredIndex, Result);
1693 else {
1694 Result->setSyntacticForm(IList);
1695 SyntacticToSemantic[IList] = Result;
1696 }
1697
1698 return Result;
1699}
1700
1701/// Update the initializer at index @p StructuredIndex within the
1702/// structured initializer list to the value @p expr.
1703void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1704 unsigned &StructuredIndex,
1705 Expr *expr) {
1706 // No structured initializer list to update
1707 if (!StructuredList)
1708 return;
1709
1710 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1711 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001712 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001713 diag::warn_initializer_overrides)
1714 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001715 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001716 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001717 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001718 << PrevInit->getSourceRange();
1719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Douglas Gregor4c678342009-01-28 21:54:33 +00001721 ++StructuredIndex;
1722}
1723
Douglas Gregor05c13a32009-01-22 00:58:24 +00001724/// Check that the given Index expression is a valid array designator
1725/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001726/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001727/// and produces a reasonable diagnostic if there is a
1728/// failure. Returns true if there was an error, false otherwise. If
1729/// everything went okay, Value will receive the value of the constant
1730/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001731static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001732CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001733 SourceLocation Loc = Index->getSourceRange().getBegin();
1734
1735 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001736 if (S.VerifyIntegerConstantExpression(Index, &Value))
1737 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001738
Chris Lattner3bf68932009-04-25 21:59:05 +00001739 if (Value.isSigned() && Value.isNegative())
1740 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001741 << Value.toString(10) << Index->getSourceRange();
1742
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001743 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001744 return false;
1745}
1746
1747Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1748 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001749 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001750 OwningExprResult Init) {
1751 typedef DesignatedInitExpr::Designator ASTDesignator;
1752
1753 bool Invalid = false;
1754 llvm::SmallVector<ASTDesignator, 32> Designators;
1755 llvm::SmallVector<Expr *, 32> InitExpressions;
1756
1757 // Build designators and check array designator expressions.
1758 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1759 const Designator &D = Desig.getDesignator(Idx);
1760 switch (D.getKind()) {
1761 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001762 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001763 D.getFieldLoc()));
1764 break;
1765
1766 case Designator::ArrayDesignator: {
1767 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1768 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001769 if (!Index->isTypeDependent() &&
1770 !Index->isValueDependent() &&
1771 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001772 Invalid = true;
1773 else {
1774 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001775 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001776 D.getRBracketLoc()));
1777 InitExpressions.push_back(Index);
1778 }
1779 break;
1780 }
1781
1782 case Designator::ArrayRangeDesignator: {
1783 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1784 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1785 llvm::APSInt StartValue;
1786 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001787 bool StartDependent = StartIndex->isTypeDependent() ||
1788 StartIndex->isValueDependent();
1789 bool EndDependent = EndIndex->isTypeDependent() ||
1790 EndIndex->isValueDependent();
1791 if ((!StartDependent &&
1792 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1793 (!EndDependent &&
1794 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001795 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001796 else {
1797 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001798 if (StartDependent || EndDependent) {
1799 // Nothing to compute.
1800 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001801 EndValue.extend(StartValue.getBitWidth());
1802 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1803 StartValue.extend(EndValue.getBitWidth());
1804
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001805 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001806 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001807 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001808 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1809 Invalid = true;
1810 } else {
1811 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001812 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001813 D.getEllipsisLoc(),
1814 D.getRBracketLoc()));
1815 InitExpressions.push_back(StartIndex);
1816 InitExpressions.push_back(EndIndex);
1817 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001818 }
1819 break;
1820 }
1821 }
1822 }
1823
1824 if (Invalid || Init.isInvalid())
1825 return ExprError();
1826
1827 // Clear out the expressions within the designation.
1828 Desig.ClearExprs(*this);
1829
1830 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001831 = DesignatedInitExpr::Create(Context,
1832 Designators.data(), Designators.size(),
1833 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001834 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001835 return Owned(DIE);
1836}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001837
1838bool Sema::CheckInitList(InitListExpr *&InitList, QualType &DeclType) {
Chris Lattner08202542009-02-24 22:50:46 +00001839 InitListChecker CheckInitList(*this, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001840 if (!CheckInitList.HadError())
1841 InitList = CheckInitList.getFullyStructuredList();
1842
1843 return CheckInitList.HadError();
1844}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001845
1846/// \brief Diagnose any semantic errors with value-initialization of
1847/// the given type.
1848///
1849/// Value-initialization effectively zero-initializes any types
1850/// without user-declared constructors, and calls the default
1851/// constructor for a for any type that has a user-declared
1852/// constructor (C++ [dcl.init]p5). Value-initialization can fail when
1853/// a type with a user-declared constructor does not have an
1854/// accessible, non-deleted default constructor. In C, everything can
1855/// be value-initialized, which corresponds to C's notion of
1856/// initializing objects with static storage duration when no
Mike Stump1eb44332009-09-09 15:08:12 +00001857/// initializer is provided for that object.
Douglas Gregor87fd7032009-02-02 17:43:21 +00001858///
1859/// \returns true if there was an error, false otherwise.
1860bool Sema::CheckValueInitialization(QualType Type, SourceLocation Loc) {
1861 // C++ [dcl.init]p5:
1862 //
1863 // To value-initialize an object of type T means:
1864
1865 // -- if T is an array type, then each element is value-initialized;
1866 if (const ArrayType *AT = Context.getAsArrayType(Type))
1867 return CheckValueInitialization(AT->getElementType(), Loc);
1868
Ted Kremenek6217b802009-07-29 21:53:49 +00001869 if (const RecordType *RT = Type->getAs<RecordType>()) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001870 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor87fd7032009-02-02 17:43:21 +00001871 // -- if T is a class type (clause 9) with a user-declared
1872 // constructor (12.1), then the default constructor for T is
1873 // called (and the initialization is ill-formed if T has no
1874 // accessible default constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00001875 if (ClassDecl->hasUserDeclaredConstructor()) {
1876 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1877
1878 CXXConstructorDecl *Constructor
1879 = PerformInitializationByConstructor(Type,
1880 MultiExprArg(*this, 0, 0),
1881 Loc, SourceRange(Loc),
1882 DeclarationName(),
1883 IK_Direct,
1884 ConstructorArgs);
1885 if (!Constructor)
1886 return true;
1887
1888 OwningExprResult Init
1889 = BuildCXXConstructExpr(Loc, Type, Constructor,
1890 move_arg(ConstructorArgs));
1891 if (Init.isInvalid())
1892 return true;
1893
1894 // FIXME: Actually perform the value-initialization!
1895 return false;
1896 }
Douglas Gregor87fd7032009-02-02 17:43:21 +00001897 }
1898 }
1899
1900 if (Type->isReferenceType()) {
1901 // C++ [dcl.init]p5:
1902 // [...] A program that calls for default-initialization or
1903 // value-initialization of an entity of reference type is
1904 // ill-formed. [...]
Mike Stump390b4cc2009-05-16 07:39:55 +00001905 // FIXME: Once we have code that goes through this path, add an actual
1906 // diagnostic :)
Douglas Gregor87fd7032009-02-02 17:43:21 +00001907 }
1908
1909 return false;
1910}