blob: 60de672c0aa7e70bf0bd4ae3f877a484fc01d793 [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
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000025#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000026using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000027
Chris Lattnerdd8e0062009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
Chris Lattner79e079d2009-02-24 23:10:27 +000032static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000033 const ArrayType *AT = Context.getAsArrayType(DeclType);
34 if (!AT) return 0;
35
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
Mike Stump1eb44332009-09-09 15:08:12 +000067static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner95e8d652009-02-24 22:46:58 +000068 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000069 // Get the type before calling CheckSingleAssignmentConstraints(), since
70 // it can promote the expression.
Mike Stump1eb44332009-09-09 15:08:12 +000071 QualType InitType = Init->getType();
72
Chris Lattner95e8d652009-02-24 22:46:58 +000073 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000075 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000076 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000077 ImplicitConversionSequence ICS;
78 OverloadCandidateSet CandidateSet;
79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80 CandidateSet,
Douglas Gregor20093b42009-12-09 23:02:17 +000081 true, false, false) != OR_Ambiguous)
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000082 return S.Diag(Init->getSourceRange().getBegin(),
83 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +000084 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000085 << Init->getSourceRange();
86 S.Diag(Init->getSourceRange().getBegin(),
87 diag::err_typecheck_convert_ambiguous)
88 << DeclType << Init->getType() << Init->getSourceRange();
89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
90 return true;
91 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 return false;
93 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattner95e8d652009-02-24 22:46:58 +000095 Sema::AssignConvertType ConvTy =
96 S.CheckSingleAssignmentConstraints(DeclType, Init);
97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000098 InitType, Init, Sema::AA_Initializing);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000099}
100
Chris Lattner79e079d2009-02-24 23:10:27 +0000101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102 // Get the length of the string as parsed.
103 uint64_t StrLength =
104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner79e079d2009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000117 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Eli Friedman8718a6a2009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Eli Friedman8718a6a2009-05-29 18:22:49 +0000122 // C99 6.7.8p14. We have an array of character type with known size. However,
123 // the size may be smaller or larger than the string we are initializing.
124 // FIXME: Avoid truncation for 64-bit length strings.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000138 const InitializedEntity &Entity,
139 const InitializationKind &Kind) {
140 SourceLocation InitLoc = Kind.getLocation();
141 DeclarationName InitEntity = Entity.getName();
142 bool DirectInit = (Kind.getKind() == InitializationKind::IK_Direct);
143
Mike Stump1eb44332009-09-09 15:08:12 +0000144 if (DeclType->isDependentType() ||
Douglas Gregorcb78d882009-11-19 18:03:26 +0000145 Init->isTypeDependent() || Init->isValueDependent()) {
146 // We have either a dependent type or a type- or value-dependent
147 // initializer, so we don't perform any additional checking at
148 // this point.
149
150 // If the declaration is a non-dependent, incomplete array type
151 // that has an initializer, then its type will be completed once
Douglas Gregor73460a32009-11-19 23:25:22 +0000152 // the initializer is instantiated.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000153 if (!DeclType->isDependentType()) {
154 if (const IncompleteArrayType *ArrayT
155 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregor73460a32009-11-19 23:25:22 +0000156 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
157 if (!ILE->isTypeDependent()) {
158 // Compute the constant array type from the length of the
159 // initializer list.
160 // FIXME: This will be wrong if there are designated
161 // initializations. Good thing they don't exist in C++!
162 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
163 ILE->getNumInits());
164 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
165 if (NumElements == Zero) {
166 // Sizing an array implicitly to zero is not allowed by ISO C,
167 // but is supported by GNU.
168 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
169 }
170
171 DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
172 NumElements,
173 ArrayT->getSizeModifier(),
174 ArrayT->getIndexTypeCVRQualifiers());
175 return false;
176 }
177 }
178
179 // Make the array type-dependent by making it dependently-sized.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000180 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
181 /*NumElts=*/0,
182 ArrayT->getSizeModifier(),
183 ArrayT->getIndexTypeCVRQualifiers(),
184 SourceRange());
185 }
186 }
187
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000188 return false;
Douglas Gregorcb78d882009-11-19 18:03:26 +0000189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000191 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000192 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000193 // (8.3.2), shall be initialized by an object, or function, of
194 // type T or by an object that can be converted into a T.
Douglas Gregor52bb5d22009-12-16 16:54:16 +0000195 if (DeclType->isReferenceType()) {
196 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
197 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
198 MultiExprArg(*this, (void**)&Init, 1),
199 &DeclType);
200 if (CurInit.isInvalid())
201 return true;
202
203 Init = CurInit.takeAs<Expr>();
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000207 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
208 // of unknown size ("[]") or an object type that is not a variable array type.
209 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
210 return Diag(InitLoc, diag::err_variable_object_no_init)
211 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000213 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
214 if (!InitList) {
215 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000216 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
217 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000218 return false;
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000221 // C++ [dcl.init]p14:
222 // -- If the destination type is a (possibly cv-qualified) class
223 // type:
224 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
225 QualType DeclTypeC = Context.getCanonicalType(DeclType);
226 QualType InitTypeC = Context.getCanonicalType(Init->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000228 // -- If the initialization is direct-initialization, or if it is
229 // copy-initialization where the cv-unqualified version of the
230 // source type is the same class as, or a derived class of, the
231 // class of the destination, constructors are considered.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000232 if ((DeclTypeC.getLocalUnqualifiedType()
233 == InitTypeC.getLocalUnqualifiedType()) ||
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000234 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000235 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000236 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000238 // No need to make a CXXConstructExpr if both the ctor and dtor are
239 // trivial.
240 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
241 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Douglas Gregor39da0b82009-09-09 23:08:42 +0000243 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
244
Douglas Gregor20093b42009-12-09 23:02:17 +0000245 // FIXME: Poor location information
246 InitializationKind InitKind
247 = InitializationKind::CreateCopy(Init->getLocStart(),
248 SourceLocation());
249 if (DirectInit)
250 InitKind = InitializationKind::CreateDirect(Init->getLocStart(),
251 SourceLocation(),
252 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000253 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000254 = PerformInitializationByConstructor(DeclType,
255 MultiExprArg(*this,
256 (void **)&Init, 1),
257 InitLoc, Init->getSourceRange(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000258 InitEntity, InitKind,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000259 ConstructorArgs);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000260 if (!Constructor)
261 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000262
263 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000264 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000265 DeclType, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000266 move_arg(ConstructorArgs));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000267 if (InitResult.isInvalid())
268 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000270 Init = InitResult.takeAs<Expr>();
Anders Carlsson2078bb92009-05-27 16:10:08 +0000271 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000272 }
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000274 // -- Otherwise (i.e., for the remaining copy-initialization
275 // cases), user-defined conversion sequences that can
276 // convert from the source type to the destination type or
277 // (when a conversion function is used) to a derived class
278 // thereof are enumerated as described in 13.3.1.4, and the
279 // best one is chosen through overload resolution
280 // (13.3). If the conversion cannot be done or is
281 // ambiguous, the initialization is ill-formed. The
282 // function selected is called with the initializer
283 // expression as its argument; if the function is a
284 // constructor, the call initializes a temporary of the
285 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000286 // FIXME: We're pretending to do copy elision here; return to this when we
287 // have ASTs for such things.
Douglas Gregor68647482009-12-16 03:45:30 +0000288 if (!PerformImplicitConversion(Init, DeclType, Sema::AA_Initializing))
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000289 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000291 if (InitEntity)
292 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000293 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
294 << Init->getType() << Init->getSourceRange();
295 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000296 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
297 << Init->getType() << Init->getSourceRange();
298 }
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000300 // C99 6.7.8p16.
301 if (DeclType->isArrayType())
302 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000303 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner95e8d652009-02-24 22:46:58 +0000305 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000306 }
307
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000308 bool hadError = CheckInitList(Entity, InitList, DeclType);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000309 Init = InitList;
310 return hadError;
311}
312
313//===----------------------------------------------------------------------===//
314// Semantic checking for initializer lists.
315//===----------------------------------------------------------------------===//
316
Douglas Gregor9e80f722009-01-29 01:05:33 +0000317/// @brief Semantic checking for initializer lists.
318///
319/// The InitListChecker class contains a set of routines that each
320/// handle the initialization of a certain kind of entity, e.g.,
321/// arrays, vectors, struct/union types, scalars, etc. The
322/// InitListChecker itself performs a recursive walk of the subobject
323/// structure of the type to be initialized, while stepping through
324/// the initializer list one element at a time. The IList and Index
325/// parameters to each of the Check* routines contain the active
326/// (syntactic) initializer list and the index into that initializer
327/// list that represents the current initializer. Each routine is
328/// responsible for moving that Index forward as it consumes elements.
329///
330/// Each Check* routine also has a StructuredList/StructuredIndex
331/// arguments, which contains the current the "structured" (semantic)
332/// initializer list and the index into that initializer list where we
333/// are copying initializers as we map them over to the semantic
334/// list. Once we have completed our recursive walk of the subobject
335/// structure, we will have constructed a full semantic initializer
336/// list.
337///
338/// C99 designators cause changes in the initializer list traversal,
339/// because they make the initialization "jump" into a specific
340/// subobject and then continue the initialization from that
341/// point. CheckDesignatedInitializer() recursively steps into the
342/// designated subobject and manages backing out the recursion to
343/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000344namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000345class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000346 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000347 bool hadError;
348 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
349 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
351 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000352 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000353 unsigned &StructuredIndex,
354 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000355 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000356 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000357 unsigned &StructuredIndex,
358 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000359 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
360 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000361 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000362 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000363 unsigned &StructuredIndex,
364 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000366 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000367 InitListExpr *StructuredList,
368 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000369 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000370 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000371 InitListExpr *StructuredList,
372 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000373 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000374 unsigned &Index,
375 InitListExpr *StructuredList,
376 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000377 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000378 InitListExpr *StructuredList,
379 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
381 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000382 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000383 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000384 unsigned &StructuredIndex,
385 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000386 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
387 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000388 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000389 InitListExpr *StructuredList,
390 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000392 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000393 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000394 RecordDecl::field_iterator *NextField,
395 llvm::APSInt *NextElementIndex,
396 unsigned &Index,
397 InitListExpr *StructuredList,
398 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000399 bool FinishSubobjectInit,
400 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000401 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
402 QualType CurrentObjectType,
403 InitListExpr *StructuredList,
404 unsigned StructuredIndex,
405 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000406 void UpdateStructuredListElement(InitListExpr *StructuredList,
407 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000408 Expr *expr);
409 int numArrayElements(QualType DeclType);
410 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000411
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000412 void FillInValueInitializations(const InitializedEntity &Entity,
413 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000414public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 InitListChecker(Sema &S, const InitializedEntity &Entity,
416 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000417 bool HadError() { return hadError; }
418
419 // @brief Retrieves the fully-structured initializer list used for
420 // semantic analysis and code generation.
421 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
422};
Chris Lattner8b419b92009-02-24 22:48:58 +0000423} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000424
Douglas Gregor4c678342009-01-28 21:54:33 +0000425/// Recursively replaces NULL values within the given initializer list
426/// with expressions that perform value-initialization of the
427/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000428void
429InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
430 InitListExpr *ILE,
431 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000432 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000433 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000434 SourceLocation Loc = ILE->getSourceRange().getBegin();
435 if (ILE->getSyntacticForm())
436 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000439 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000440 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000441 Field = RType->getDecl()->field_begin(),
442 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000443 Field != FieldEnd; ++Field) {
444 if (Field->isUnnamedBitfield())
445 continue;
446
Douglas Gregor16006c92009-12-16 18:50:27 +0000447 if (hadError)
448 return;
449
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000450 InitializedEntity MemberEntity
451 = InitializedEntity::InitializeMember(*Field, &Entity);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000452 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000453 // FIXME: We probably don't need to handle references
454 // specially here, since value-initialization of references is
455 // handled in InitializationSequence.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000456 if (Field->getType()->isReferenceType()) {
457 // C++ [dcl.init.aggr]p9:
458 // If an incomplete or empty initializer-list leaves a
459 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000460 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000461 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000462 << Field->getType()
463 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000464 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000465 diag::note_uninit_reference_member);
466 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000467 return;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468 }
469
470 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
471 true);
472 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
473 if (!InitSeq) {
474 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000475 hadError = true;
476 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000477 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000478
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000479 Sema::OwningExprResult MemberInit
480 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
481 Sema::MultiExprArg(SemaRef, 0, 0));
482 if (MemberInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000483 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000484 return;
485 }
486
487 if (hadError) {
488 // Do nothing
489 } else if (Init < NumInits) {
490 ILE->setInit(Init, MemberInit.takeAs<Expr>());
491 } else if (InitSeq.getKind()
492 == InitializationSequence::ConstructorInitialization) {
493 // Value-initialization requires a constructor call, so
494 // extend the initializer list to include the constructor
495 // call and make a note that we'll need to take another pass
496 // through the initializer list.
497 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
498 RequiresSecondPass = true;
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000501 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000502 FillInValueInitializations(MemberEntity, InnerILE,
503 RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000504 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000505
506 // Only look at the first initialization of a union.
507 if (RType->getDecl()->isUnion())
508 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000509 }
510
511 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000512 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000513
514 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000516 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000517 unsigned NumInits = ILE->getNumInits();
518 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000519 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000520 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000521 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
522 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000523 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
524 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000525 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000527 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000528 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
529 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000530 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000531 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000533
Douglas Gregor87fd7032009-02-02 17:43:21 +0000534 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000535 if (hadError)
536 return;
537
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000538 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
539 ElementEntity.setElementIndex(Init);
540
Douglas Gregor87fd7032009-02-02 17:43:21 +0000541 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000542 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
543 true);
544 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
545 if (!InitSeq) {
546 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000547 hadError = true;
548 return;
549 }
550
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000551 Sema::OwningExprResult ElementInit
552 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
553 Sema::MultiExprArg(SemaRef, 0, 0));
554 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000555 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000556 return;
557 }
558
559 if (hadError) {
560 // Do nothing
561 } else if (Init < NumInits) {
562 ILE->setInit(Init, ElementInit.takeAs<Expr>());
563 } else if (InitSeq.getKind()
564 == InitializationSequence::ConstructorInitialization) {
565 // Value-initialization requires a constructor call, so
566 // extend the initializer list to include the constructor
567 // call and make a note that we'll need to take another pass
568 // through the initializer list.
569 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
570 RequiresSecondPass = true;
571 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000572 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000573 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
574 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000575 }
576}
577
Chris Lattner68355a52009-01-29 05:10:57 +0000578
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000579InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
580 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000581 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000582 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000583
Eli Friedmanb85f7072008-05-19 19:16:24 +0000584 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000585 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000586 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000587 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000588 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
589 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000590
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000591 if (!hadError) {
592 bool RequiresSecondPass = false;
593 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000594 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000595 FillInValueInitializations(Entity, FullyStructuredList,
596 RequiresSecondPass);
597 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000598}
599
600int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000601 // FIXME: use a proper constant
602 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000603 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000604 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000605 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
606 }
607 return maxElements;
608}
609
610int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000611 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000613 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000614 Field = structDecl->field_begin(),
615 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000616 Field != FieldEnd; ++Field) {
617 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
618 ++InitializableMembers;
619 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000620 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000621 return std::min(InitializableMembers, 1);
622 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000623}
624
Mike Stump1eb44332009-09-09 15:08:12 +0000625void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000626 QualType T, unsigned &Index,
627 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000628 unsigned &StructuredIndex,
629 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000630 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Steve Naroff0cca7492008-05-01 22:18:59 +0000632 if (T->isArrayType())
633 maxElements = numArrayElements(T);
634 else if (T->isStructureType() || T->isUnionType())
635 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000636 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000637 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000638 else
639 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000640
Eli Friedman402256f2008-05-25 13:49:22 +0000641 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000642 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000643 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000644 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000645 hadError = true;
646 return;
647 }
648
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 // Build a structured initializer list corresponding to this subobject.
650 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000651 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
652 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000653 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
654 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000655 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000656
Douglas Gregor4c678342009-01-28 21:54:33 +0000657 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000658 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000659 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000660 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000661 StructuredSubobjectInitIndex,
662 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000663 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000664 StructuredSubobjectInitList->setType(T);
665
Douglas Gregored8a93d2009-03-01 17:12:46 +0000666 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000667 // range corresponds with the end of the last initializer it used.
668 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000669 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000670 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
671 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
672 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000673}
674
Steve Naroffa647caa2008-05-06 00:23:44 +0000675void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000676 unsigned &Index,
677 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000678 unsigned &StructuredIndex,
679 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000680 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000681 SyntacticToSemantic[IList] = StructuredList;
682 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000683 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000684 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000685 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000686 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000687 if (hadError)
688 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000689
Eli Friedman638e1442008-05-25 13:22:35 +0000690 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000691 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000692 if (StructuredIndex == 1 &&
693 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000694 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000695 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000696 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000697 hadError = true;
698 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000699 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000700 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000701 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000702 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000703 // Don't complain for incomplete types, since we'll get an error
704 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000705 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000706 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000707 CurrentObjectType->isArrayType()? 0 :
708 CurrentObjectType->isVectorType()? 1 :
709 CurrentObjectType->isScalarType()? 2 :
710 CurrentObjectType->isUnionType()? 3 :
711 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000712
713 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000714 if (SemaRef.getLangOptions().CPlusPlus) {
715 DK = diag::err_excess_initializers;
716 hadError = true;
717 }
Nate Begeman08634522009-07-07 21:53:06 +0000718 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
719 DK = diag::err_excess_initializers;
720 hadError = true;
721 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000722
Chris Lattner08202542009-02-24 22:50:46 +0000723 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000724 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000725 }
726 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000727
Eli Friedman759f2522009-05-16 11:45:48 +0000728 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000729 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000730 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000731 << CodeModificationHint::CreateRemoval(IList->getLocStart())
732 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000733}
734
Eli Friedmanb85f7072008-05-19 19:16:24 +0000735void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000736 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000737 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000738 unsigned &Index,
739 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000740 unsigned &StructuredIndex,
741 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000742 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000743 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000744 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000745 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000746 } else if (DeclType->isAggregateType()) {
747 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000748 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000749 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000750 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000751 StructuredList, StructuredIndex,
752 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000753 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000754 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000755 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000756 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000757 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
758 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000759 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000760 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000761 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
762 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000763 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000764 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000765 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000766 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000767 } else if (DeclType->isRecordType()) {
768 // C++ [dcl.init]p14:
769 // [...] If the class is an aggregate (8.5.1), and the initializer
770 // is a brace-enclosed list, see 8.5.1.
771 //
772 // Note: 8.5.1 is handled below; here, we diagnose the case where
773 // we have an initializer list and a destination type that is not
774 // an aggregate.
775 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000776 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000777 << DeclType << IList->getSourceRange();
778 hadError = true;
779 } else if (DeclType->isReferenceType()) {
780 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000781 } else {
782 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000783 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000784 assert(0 && "Unsupported initializer type");
785 }
786}
787
Eli Friedmanb85f7072008-05-19 19:16:24 +0000788void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000789 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000790 unsigned &Index,
791 InitListExpr *StructuredList,
792 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000793 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000794 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
795 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000797 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000798 = getStructuredSubobjectInit(IList, Index, ElemType,
799 StructuredList, StructuredIndex,
800 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000801 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000802 newStructuredList, newStructuredIndex);
803 ++StructuredIndex;
804 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000805 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
806 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000807 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000808 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000809 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000810 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000811 } else if (ElemType->isReferenceType()) {
812 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000813 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000814 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000815 // C++ [dcl.init.aggr]p12:
816 // All implicit type conversions (clause 4) are considered when
817 // initializing the aggregate member with an ini- tializer from
818 // an initializer-list. If the initializer can initialize a
819 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000820 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000821 = SemaRef.TryCopyInitialization(expr, ElemType,
822 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000823 /*ForceRValue=*/false,
824 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000825
Douglas Gregor930d8b52009-01-30 22:09:00 +0000826 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000827 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000828 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000829 hadError = true;
830 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
831 ++Index;
832 return;
833 }
834
835 // Fall through for subaggregate initialization
836 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000837 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000838 //
839 // The initializer for a structure or union object that has
840 // automatic storage duration shall be either an initializer
841 // list as described below, or a single expression that has
842 // compatible structure or union type. In the latter case, the
843 // initial value of the object, including unnamed members, is
844 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000845 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000846 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000847 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
848 ++Index;
849 return;
850 }
851
852 // Fall through for subaggregate initialization
853 }
854
855 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000856 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000857 // [...] Otherwise, if the member is itself a non-empty
858 // subaggregate, brace elision is assumed and the initializer is
859 // considered for the initialization of the first member of
860 // the subaggregate.
861 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000862 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000863 StructuredIndex);
864 ++StructuredIndex;
865 } else {
866 // We cannot initialize this element, so let
867 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000868 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000869 hadError = true;
870 ++Index;
871 ++StructuredIndex;
872 }
873 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000874}
875
Douglas Gregor930d8b52009-01-30 22:09:00 +0000876void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000877 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000878 InitListExpr *StructuredList,
879 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000880 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000881 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000882 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000883 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000884 diag::err_many_braces_around_scalar_init)
885 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000886 hadError = true;
887 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000888 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000889 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000890 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000891 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000892 diag::err_designator_for_scalar_init)
893 << DeclType << expr->getSourceRange();
894 hadError = true;
895 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000896 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000897 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000898 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000899
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000900 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000901 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000902 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000903 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000904 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000905 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000906 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000907 if (hadError)
908 ++StructuredIndex;
909 else
910 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000911 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000912 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000913 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000914 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000915 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000916 ++Index;
917 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000918 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000919 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000920}
921
Douglas Gregor930d8b52009-01-30 22:09:00 +0000922void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
923 unsigned &Index,
924 InitListExpr *StructuredList,
925 unsigned &StructuredIndex) {
926 if (Index < IList->getNumInits()) {
927 Expr *expr = IList->getInit(Index);
928 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000929 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000930 << DeclType << IList->getSourceRange();
931 hadError = true;
932 ++Index;
933 ++StructuredIndex;
934 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000935 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000936
937 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000938 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000939 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000940 /*SuppressUserConversions=*/false,
941 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000942 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000943 hadError = true;
944 else if (savExpr != expr) {
945 // The type was promoted, update initializer list.
946 IList->setInit(Index, expr);
947 }
948 if (hadError)
949 ++StructuredIndex;
950 else
951 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
952 ++Index;
953 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000954 // FIXME: It would be wonderful if we could point at the actual member. In
955 // general, it would be useful to pass location information down the stack,
956 // so that we know the location (or decl) of the "current object" being
957 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000958 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000959 diag::err_init_reference_member_uninitialized)
960 << DeclType
961 << IList->getSourceRange();
962 hadError = true;
963 ++Index;
964 ++StructuredIndex;
965 return;
966 }
967}
968
Mike Stump1eb44332009-09-09 15:08:12 +0000969void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000970 unsigned &Index,
971 InitListExpr *StructuredList,
972 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000973 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000974 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000975 unsigned maxElements = VT->getNumElements();
976 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000977 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Nate Begeman2ef13e52009-08-10 23:49:36 +0000979 if (!SemaRef.getLangOptions().OpenCL) {
980 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
981 // Don't attempt to go past the end of the init list
982 if (Index >= IList->getNumInits())
983 break;
984 CheckSubElementType(IList, elementType, Index,
985 StructuredList, StructuredIndex);
986 }
987 } else {
988 // OpenCL initializers allows vectors to be constructed from vectors.
989 for (unsigned i = 0; i < maxElements; ++i) {
990 // Don't attempt to go past the end of the init list
991 if (Index >= IList->getNumInits())
992 break;
993 QualType IType = IList->getInit(Index)->getType();
994 if (!IType->isVectorType()) {
995 CheckSubElementType(IList, elementType, Index,
996 StructuredList, StructuredIndex);
997 ++numEltsInit;
998 } else {
John McCall183700f2009-09-21 23:43:11 +0000999 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +00001000 unsigned numIElts = IVT->getNumElements();
1001 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
1002 numIElts);
1003 CheckSubElementType(IList, VecType, Index,
1004 StructuredList, StructuredIndex);
1005 numEltsInit += numIElts;
1006 }
1007 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Nate Begeman2ef13e52009-08-10 23:49:36 +00001010 // OpenCL & AltiVec require all elements to be initialized.
1011 if (numEltsInit != maxElements)
1012 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
1013 SemaRef.Diag(IList->getSourceRange().getBegin(),
1014 diag::err_vector_incorrect_num_initializers)
1015 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001016 }
1017}
1018
Mike Stump1eb44332009-09-09 15:08:12 +00001019void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001020 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001021 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001022 unsigned &Index,
1023 InitListExpr *StructuredList,
1024 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001025 // Check for the special-case of initializing an array with a string.
1026 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +00001027 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
1028 SemaRef.Context)) {
1029 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001030 // We place the string literal directly into the resulting
1031 // initializer list. This is the only place where the structure
1032 // of the structured initializer list doesn't match exactly,
1033 // because doing so would involve allocating one character
1034 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001035 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001036 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001037 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001038 return;
1039 }
1040 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001041 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +00001042 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001043 // Check for VLAs; in standard C it would be possible to check this
1044 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1045 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001046 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001047 diag::err_variable_object_no_init)
1048 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001049 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001050 ++Index;
1051 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001052 return;
1053 }
1054
Douglas Gregor05c13a32009-01-22 00:58:24 +00001055 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001056 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1057 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001058 bool maxElementsKnown = false;
1059 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +00001060 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001061 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001062 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001063 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001064 maxElementsKnown = true;
1065 }
1066
Chris Lattner08202542009-02-24 22:50:46 +00001067 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001068 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001069 while (Index < IList->getNumInits()) {
1070 Expr *Init = IList->getInit(Index);
1071 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001072 // If we're not the subobject that matches up with the '{' for
1073 // the designator, we shouldn't be handling the
1074 // designator. Return immediately.
1075 if (!SubobjectIsDesignatorContext)
1076 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001077
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001078 // Handle this designated initializer. elementIndex will be
1079 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +00001080 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001081 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001082 StructuredList, StructuredIndex, true,
1083 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001084 hadError = true;
1085 continue;
1086 }
1087
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001088 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1089 maxElements.extend(elementIndex.getBitWidth());
1090 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1091 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001092 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001093
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001094 // If the array is of incomplete type, keep track of the number of
1095 // elements in the initializer.
1096 if (!maxElementsKnown && elementIndex > maxElements)
1097 maxElements = elementIndex;
1098
Douglas Gregor05c13a32009-01-22 00:58:24 +00001099 continue;
1100 }
1101
1102 // If we know the maximum number of elements, and we've already
1103 // hit it, stop consuming elements in the initializer list.
1104 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001105 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001106
1107 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001108 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001109 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001110 ++elementIndex;
1111
1112 // If the array is of incomplete type, keep track of the number of
1113 // elements in the initializer.
1114 if (!maxElementsKnown && elementIndex > maxElements)
1115 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001116 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001117 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001118 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001119 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001120 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001121 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001122 // Sizing an array implicitly to zero is not allowed by ISO C,
1123 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001124 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001125 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001126 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001127
Mike Stump1eb44332009-09-09 15:08:12 +00001128 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001129 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001130 }
1131}
1132
Mike Stump1eb44332009-09-09 15:08:12 +00001133void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1134 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001135 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001136 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001137 unsigned &Index,
1138 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001139 unsigned &StructuredIndex,
1140 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Eli Friedmanb85f7072008-05-19 19:16:24 +00001143 // If the record is invalid, some of it's members are invalid. To avoid
1144 // confusion, we forgo checking the intializer for the entire record.
1145 if (structDecl->isInvalidDecl()) {
1146 hadError = true;
1147 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001148 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001149
1150 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1151 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001152 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001153 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001154 Field != FieldEnd; ++Field) {
1155 if (Field->getDeclName()) {
1156 StructuredList->setInitializedFieldInUnion(*Field);
1157 break;
1158 }
1159 }
1160 return;
1161 }
1162
Douglas Gregor05c13a32009-01-22 00:58:24 +00001163 // If structDecl is a forward declaration, this loop won't do
1164 // anything except look at designated initializers; That's okay,
1165 // because an error should get printed out elsewhere. It might be
1166 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001167 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001168 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001169 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001170 while (Index < IList->getNumInits()) {
1171 Expr *Init = IList->getInit(Index);
1172
1173 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 // If we're not the subobject that matches up with the '{' for
1175 // the designator, we shouldn't be handling the
1176 // designator. Return immediately.
1177 if (!SubobjectIsDesignatorContext)
1178 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001179
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001180 // Handle this designated initializer. Field will be updated to
1181 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001182 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001183 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001184 StructuredList, StructuredIndex,
1185 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001186 hadError = true;
1187
Douglas Gregordfb5e592009-02-12 19:00:39 +00001188 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001189 continue;
1190 }
1191
1192 if (Field == FieldEnd) {
1193 // We've run out of fields. We're done.
1194 break;
1195 }
1196
Douglas Gregordfb5e592009-02-12 19:00:39 +00001197 // We've already initialized a member of a union. We're done.
1198 if (InitializedSomething && DeclType->isUnionType())
1199 break;
1200
Douglas Gregor44b43212008-12-11 16:49:14 +00001201 // If we've hit the flexible array member at the end, we're done.
1202 if (Field->getType()->isIncompleteArrayType())
1203 break;
1204
Douglas Gregor0bb76892009-01-29 16:53:55 +00001205 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001206 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001207 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001208 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001209 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001210
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001211 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001212 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001213 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001214
1215 if (DeclType->isUnionType()) {
1216 // Initialize the first field within the union.
1217 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001218 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001219
1220 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001221 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001222
Mike Stump1eb44332009-09-09 15:08:12 +00001223 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001224 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001225 return;
1226
1227 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001229 (!isa<InitListExpr>(IList->getInit(Index)) ||
1230 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001231 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001232 diag::err_flexible_array_init_nonempty)
1233 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001234 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001235 << *Field;
1236 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001237 ++Index;
1238 return;
1239 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001240 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001241 diag::ext_flexible_array_init)
1242 << IList->getInit(Index)->getSourceRange().getBegin();
1243 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1244 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001245 }
1246
Douglas Gregora6457962009-03-20 00:32:56 +00001247 if (isa<InitListExpr>(IList->getInit(Index)))
1248 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1249 StructuredIndex);
1250 else
1251 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1252 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001253}
Steve Naroff0cca7492008-05-01 22:18:59 +00001254
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001255/// \brief Expand a field designator that refers to a member of an
1256/// anonymous struct or union into a series of field designators that
1257/// refers to the field within the appropriate subobject.
1258///
1259/// Field/FieldIndex will be updated to point to the (new)
1260/// currently-designated field.
1261static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001262 DesignatedInitExpr *DIE,
1263 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001264 FieldDecl *Field,
1265 RecordDecl::field_iterator &FieldIter,
1266 unsigned &FieldIndex) {
1267 typedef DesignatedInitExpr::Designator Designator;
1268
1269 // Build the path from the current object to the member of the
1270 // anonymous struct/union (backwards).
1271 llvm::SmallVector<FieldDecl *, 4> Path;
1272 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001274 // Build the replacement designators.
1275 llvm::SmallVector<Designator, 4> Replacements;
1276 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1277 FI = Path.rbegin(), FIEnd = Path.rend();
1278 FI != FIEnd; ++FI) {
1279 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001280 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001281 DIE->getDesignator(DesigIdx)->getDotLoc(),
1282 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1283 else
1284 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1285 SourceLocation()));
1286 Replacements.back().setField(*FI);
1287 }
1288
1289 // Expand the current designator into the set of replacement
1290 // designators, so we have a full subobject path down to where the
1291 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001292 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001293 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001295 // Update FieldIter/FieldIndex;
1296 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001297 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001298 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001299 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001300 FieldIter != FEnd; ++FieldIter) {
1301 if (FieldIter->isUnnamedBitfield())
1302 continue;
1303
1304 if (*FieldIter == Path.back())
1305 return;
1306
1307 ++FieldIndex;
1308 }
1309
1310 assert(false && "Unable to find anonymous struct/union field");
1311}
1312
Douglas Gregor05c13a32009-01-22 00:58:24 +00001313/// @brief Check the well-formedness of a C99 designated initializer.
1314///
1315/// Determines whether the designated initializer @p DIE, which
1316/// resides at the given @p Index within the initializer list @p
1317/// IList, is well-formed for a current object of type @p DeclType
1318/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001319/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001320/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001321///
1322/// @param IList The initializer list in which this designated
1323/// initializer occurs.
1324///
Douglas Gregor71199712009-04-15 04:56:10 +00001325/// @param DIE The designated initializer expression.
1326///
1327/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001328///
1329/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1330/// into which the designation in @p DIE should refer.
1331///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001332/// @param NextField If non-NULL and the first designator in @p DIE is
1333/// a field, this will be set to the field declaration corresponding
1334/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001335///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001336/// @param NextElementIndex If non-NULL and the first designator in @p
1337/// DIE is an array designator or GNU array-range designator, this
1338/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001339///
1340/// @param Index Index into @p IList where the designated initializer
1341/// @p DIE occurs.
1342///
Douglas Gregor4c678342009-01-28 21:54:33 +00001343/// @param StructuredList The initializer list expression that
1344/// describes all of the subobject initializers in the order they'll
1345/// actually be initialized.
1346///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001347/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001348bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001349InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001350 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001351 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001352 QualType &CurrentObjectType,
1353 RecordDecl::field_iterator *NextField,
1354 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001355 unsigned &Index,
1356 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001357 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001358 bool FinishSubobjectInit,
1359 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001360 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001361 // Check the actual initialization for the designated object type.
1362 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001363
1364 // Temporarily remove the designator expression from the
1365 // initializer list that the child calls see, so that we don't try
1366 // to re-process the designator.
1367 unsigned OldIndex = Index;
1368 IList->setInit(OldIndex, DIE->getInit());
1369
1370 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001371 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001372
1373 // Restore the designated initializer expression in the syntactic
1374 // form of the initializer list.
1375 if (IList->getInit(OldIndex) != DIE->getInit())
1376 DIE->setInit(IList->getInit(OldIndex));
1377 IList->setInit(OldIndex, DIE);
1378
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001379 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001380 }
1381
Douglas Gregor71199712009-04-15 04:56:10 +00001382 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001383 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001384 "Need a non-designated initializer list to start from");
1385
Douglas Gregor71199712009-04-15 04:56:10 +00001386 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001387 // Determine the structural initializer list that corresponds to the
1388 // current subobject.
1389 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001390 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001391 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001392 SourceRange(D->getStartLocation(),
1393 DIE->getSourceRange().getEnd()));
1394 assert(StructuredList && "Expected a structured initializer list");
1395
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001396 if (D->isFieldDesignator()) {
1397 // C99 6.7.8p7:
1398 //
1399 // If a designator has the form
1400 //
1401 // . identifier
1402 //
1403 // then the current object (defined below) shall have
1404 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001405 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001406 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001407 if (!RT) {
1408 SourceLocation Loc = D->getDotLoc();
1409 if (Loc.isInvalid())
1410 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001411 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1412 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001413 ++Index;
1414 return true;
1415 }
1416
Douglas Gregor4c678342009-01-28 21:54:33 +00001417 // Note: we perform a linear search of the fields here, despite
1418 // the fact that we have a faster lookup method, because we always
1419 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001420 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001421 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001422 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001423 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001424 Field = RT->getDecl()->field_begin(),
1425 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001426 for (; Field != FieldEnd; ++Field) {
1427 if (Field->isUnnamedBitfield())
1428 continue;
1429
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001430 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001431 break;
1432
1433 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001434 }
1435
Douglas Gregor4c678342009-01-28 21:54:33 +00001436 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001437 // There was no normal field in the struct with the designated
1438 // name. Perform another lookup for this name, which may find
1439 // something that we can't designate (e.g., a member function),
1440 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001442 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001443 if (Lookup.first == Lookup.second) {
1444 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001445 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001446 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001447 ++Index;
1448 return true;
1449 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1450 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1451 ->isAnonymousStructOrUnion()) {
1452 // Handle an field designator that refers to a member of an
1453 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001454 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001455 cast<FieldDecl>(*Lookup.first),
1456 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001457 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001458 } else {
1459 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001460 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001461 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001462 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001463 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001464 ++Index;
1465 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001466 }
1467 } else if (!KnownField &&
1468 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001469 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001470 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1471 Field, FieldIndex);
1472 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001473 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001474
1475 // All of the fields of a union are located at the same place in
1476 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001477 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001478 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001479 StructuredList->setInitializedFieldInUnion(*Field);
1480 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001481
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001482 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001483 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Douglas Gregor4c678342009-01-28 21:54:33 +00001485 // Make sure that our non-designated initializer list has space
1486 // for a subobject corresponding to this field.
1487 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001488 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001489
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001490 // This designator names a flexible array member.
1491 if (Field->getType()->isIncompleteArrayType()) {
1492 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001493 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001494 // We can't designate an object within the flexible array
1495 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001496 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001497 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001498 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001499 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001500 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001501 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001502 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001503 << *Field;
1504 Invalid = true;
1505 }
1506
1507 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1508 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001509 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001510 diag::err_flexible_array_init_needs_braces)
1511 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001512 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001513 << *Field;
1514 Invalid = true;
1515 }
1516
1517 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001518 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001519 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001520 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 diag::err_flexible_array_init_nonempty)
1522 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001523 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001524 << *Field;
1525 Invalid = true;
1526 }
1527
1528 if (Invalid) {
1529 ++Index;
1530 return true;
1531 }
1532
1533 // Initialize the array.
1534 bool prevHadError = hadError;
1535 unsigned newStructuredIndex = FieldIndex;
1536 unsigned OldIndex = Index;
1537 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001538 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001539 StructuredList, newStructuredIndex);
1540 IList->setInit(OldIndex, DIE);
1541 if (hadError && !prevHadError) {
1542 ++Field;
1543 ++FieldIndex;
1544 if (NextField)
1545 *NextField = Field;
1546 StructuredIndex = FieldIndex;
1547 return true;
1548 }
1549 } else {
1550 // Recurse to check later designated subobjects.
1551 QualType FieldType = (*Field)->getType();
1552 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001553 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1554 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001555 true, false))
1556 return true;
1557 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001558
1559 // Find the position of the next field to be initialized in this
1560 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001562 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563
1564 // If this the first designator, our caller will continue checking
1565 // the rest of this struct/class/union subobject.
1566 if (IsFirstDesignator) {
1567 if (NextField)
1568 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001569 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001570 return false;
1571 }
1572
Douglas Gregor34e79462009-01-28 23:36:17 +00001573 if (!FinishSubobjectInit)
1574 return false;
1575
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001576 // We've already initialized something in the union; we're done.
1577 if (RT->getDecl()->isUnion())
1578 return hadError;
1579
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001580 // Check the remaining fields within this class/struct/union subobject.
1581 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001582 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1583 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001584 return hadError && !prevHadError;
1585 }
1586
1587 // C99 6.7.8p6:
1588 //
1589 // If a designator has the form
1590 //
1591 // [ constant-expression ]
1592 //
1593 // then the current object (defined below) shall have array
1594 // type and the expression shall be an integer constant
1595 // expression. If the array is of unknown size, any
1596 // nonnegative value is valid.
1597 //
1598 // Additionally, cope with the GNU extension that permits
1599 // designators of the form
1600 //
1601 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001602 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001603 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001604 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001605 << CurrentObjectType;
1606 ++Index;
1607 return true;
1608 }
1609
1610 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001611 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1612 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001613 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001614 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001615 DesignatedEndIndex = DesignatedStartIndex;
1616 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001618
Mike Stump1eb44332009-09-09 15:08:12 +00001619
1620 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001621 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001622 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001623 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001624 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001625
Chris Lattner3bf68932009-04-25 21:59:05 +00001626 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001627 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001628 }
1629
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001630 if (isa<ConstantArrayType>(AT)) {
1631 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001632 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1633 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1634 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1635 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1636 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001637 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001638 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001639 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001640 << IndexExpr->getSourceRange();
1641 ++Index;
1642 return true;
1643 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001644 } else {
1645 // Make sure the bit-widths and signedness match.
1646 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1647 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001648 else if (DesignatedStartIndex.getBitWidth() <
1649 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001650 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1651 DesignatedStartIndex.setIsUnsigned(true);
1652 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Douglas Gregor4c678342009-01-28 21:54:33 +00001655 // Make sure that our non-designated initializer list has space
1656 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001657 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001658 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001659 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001660
Douglas Gregor34e79462009-01-28 23:36:17 +00001661 // Repeatedly perform subobject initializations in the range
1662 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001663
Douglas Gregor34e79462009-01-28 23:36:17 +00001664 // Move to the next designator
1665 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1666 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001667 while (DesignatedStartIndex <= DesignatedEndIndex) {
1668 // Recurse to check later designated subobjects.
1669 QualType ElementType = AT->getElementType();
1670 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001671 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1672 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001673 (DesignatedStartIndex == DesignatedEndIndex),
1674 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001675 return true;
1676
1677 // Move to the next index in the array that we'll be initializing.
1678 ++DesignatedStartIndex;
1679 ElementIndex = DesignatedStartIndex.getZExtValue();
1680 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001681
1682 // If this the first designator, our caller will continue checking
1683 // the rest of this array subobject.
1684 if (IsFirstDesignator) {
1685 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001686 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001687 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001688 return false;
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Douglas Gregor34e79462009-01-28 23:36:17 +00001691 if (!FinishSubobjectInit)
1692 return false;
1693
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001694 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001695 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001696 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001697 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001698 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001699}
1700
Douglas Gregor4c678342009-01-28 21:54:33 +00001701// Get the structured initializer list for a subobject of type
1702// @p CurrentObjectType.
1703InitListExpr *
1704InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1705 QualType CurrentObjectType,
1706 InitListExpr *StructuredList,
1707 unsigned StructuredIndex,
1708 SourceRange InitRange) {
1709 Expr *ExistingInit = 0;
1710 if (!StructuredList)
1711 ExistingInit = SyntacticToSemantic[IList];
1712 else if (StructuredIndex < StructuredList->getNumInits())
1713 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor4c678342009-01-28 21:54:33 +00001715 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1716 return Result;
1717
1718 if (ExistingInit) {
1719 // We are creating an initializer list that initializes the
1720 // subobjects of the current object, but there was already an
1721 // initialization that completely initialized the current
1722 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001723 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001724 // struct X { int a, b; };
1725 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001726 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001727 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1728 // designated initializer re-initializes the whole
1729 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001730 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001731 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001732 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001733 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001734 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001735 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001736 << ExistingInit->getSourceRange();
1737 }
1738
Mike Stump1eb44332009-09-09 15:08:12 +00001739 InitListExpr *Result
1740 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001741 InitRange.getEnd());
1742
Douglas Gregor4c678342009-01-28 21:54:33 +00001743 Result->setType(CurrentObjectType);
1744
Douglas Gregorfa219202009-03-20 23:58:33 +00001745 // Pre-allocate storage for the structured initializer list.
1746 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001747 unsigned NumInits = 0;
1748 if (!StructuredList)
1749 NumInits = IList->getNumInits();
1750 else if (Index < IList->getNumInits()) {
1751 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1752 NumInits = SubList->getNumInits();
1753 }
1754
Mike Stump1eb44332009-09-09 15:08:12 +00001755 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001756 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1757 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1758 NumElements = CAType->getSize().getZExtValue();
1759 // Simple heuristic so that we don't allocate a very large
1760 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001761 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001762 NumElements = 0;
1763 }
John McCall183700f2009-09-21 23:43:11 +00001764 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001765 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001766 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001767 RecordDecl *RDecl = RType->getDecl();
1768 if (RDecl->isUnion())
1769 NumElements = 1;
1770 else
Mike Stump1eb44332009-09-09 15:08:12 +00001771 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001772 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001773 }
1774
Douglas Gregor08457732009-03-21 18:13:52 +00001775 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001776 NumElements = IList->getNumInits();
1777
1778 Result->reserveInits(NumElements);
1779
Douglas Gregor4c678342009-01-28 21:54:33 +00001780 // Link this new initializer list into the structured initializer
1781 // lists.
1782 if (StructuredList)
1783 StructuredList->updateInit(StructuredIndex, Result);
1784 else {
1785 Result->setSyntacticForm(IList);
1786 SyntacticToSemantic[IList] = Result;
1787 }
1788
1789 return Result;
1790}
1791
1792/// Update the initializer at index @p StructuredIndex within the
1793/// structured initializer list to the value @p expr.
1794void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1795 unsigned &StructuredIndex,
1796 Expr *expr) {
1797 // No structured initializer list to update
1798 if (!StructuredList)
1799 return;
1800
1801 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1802 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001803 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001804 diag::warn_initializer_overrides)
1805 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001806 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001807 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001808 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001809 << PrevInit->getSourceRange();
1810 }
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregor4c678342009-01-28 21:54:33 +00001812 ++StructuredIndex;
1813}
1814
Douglas Gregor05c13a32009-01-22 00:58:24 +00001815/// Check that the given Index expression is a valid array designator
1816/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001817/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001818/// and produces a reasonable diagnostic if there is a
1819/// failure. Returns true if there was an error, false otherwise. If
1820/// everything went okay, Value will receive the value of the constant
1821/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001822static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001823CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001824 SourceLocation Loc = Index->getSourceRange().getBegin();
1825
1826 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001827 if (S.VerifyIntegerConstantExpression(Index, &Value))
1828 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001829
Chris Lattner3bf68932009-04-25 21:59:05 +00001830 if (Value.isSigned() && Value.isNegative())
1831 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001832 << Value.toString(10) << Index->getSourceRange();
1833
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001834 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001835 return false;
1836}
1837
1838Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1839 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001840 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001841 OwningExprResult Init) {
1842 typedef DesignatedInitExpr::Designator ASTDesignator;
1843
1844 bool Invalid = false;
1845 llvm::SmallVector<ASTDesignator, 32> Designators;
1846 llvm::SmallVector<Expr *, 32> InitExpressions;
1847
1848 // Build designators and check array designator expressions.
1849 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1850 const Designator &D = Desig.getDesignator(Idx);
1851 switch (D.getKind()) {
1852 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001853 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001854 D.getFieldLoc()));
1855 break;
1856
1857 case Designator::ArrayDesignator: {
1858 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1859 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001860 if (!Index->isTypeDependent() &&
1861 !Index->isValueDependent() &&
1862 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001863 Invalid = true;
1864 else {
1865 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001866 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001867 D.getRBracketLoc()));
1868 InitExpressions.push_back(Index);
1869 }
1870 break;
1871 }
1872
1873 case Designator::ArrayRangeDesignator: {
1874 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1875 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1876 llvm::APSInt StartValue;
1877 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001878 bool StartDependent = StartIndex->isTypeDependent() ||
1879 StartIndex->isValueDependent();
1880 bool EndDependent = EndIndex->isTypeDependent() ||
1881 EndIndex->isValueDependent();
1882 if ((!StartDependent &&
1883 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1884 (!EndDependent &&
1885 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001886 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001887 else {
1888 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001889 if (StartDependent || EndDependent) {
1890 // Nothing to compute.
1891 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001892 EndValue.extend(StartValue.getBitWidth());
1893 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1894 StartValue.extend(EndValue.getBitWidth());
1895
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001896 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001897 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001898 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001899 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1900 Invalid = true;
1901 } else {
1902 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001903 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001904 D.getEllipsisLoc(),
1905 D.getRBracketLoc()));
1906 InitExpressions.push_back(StartIndex);
1907 InitExpressions.push_back(EndIndex);
1908 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001909 }
1910 break;
1911 }
1912 }
1913 }
1914
1915 if (Invalid || Init.isInvalid())
1916 return ExprError();
1917
1918 // Clear out the expressions within the designation.
1919 Desig.ClearExprs(*this);
1920
1921 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001922 = DesignatedInitExpr::Create(Context,
1923 Designators.data(), Designators.size(),
1924 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001925 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001926 return Owned(DIE);
1927}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001928
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001929bool Sema::CheckInitList(const InitializedEntity &Entity,
1930 InitListExpr *&InitList, QualType &DeclType) {
1931 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001932 if (!CheckInitList.HadError())
1933 InitList = CheckInitList.getFullyStructuredList();
1934
1935 return CheckInitList.HadError();
1936}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001937
Douglas Gregor20093b42009-12-09 23:02:17 +00001938//===----------------------------------------------------------------------===//
1939// Initialization entity
1940//===----------------------------------------------------------------------===//
1941
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001942InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1943 const InitializedEntity &Parent)
1944 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1945{
1946 if (isa<ArrayType>(Parent.TL.getType())) {
1947 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1948 return;
1949 }
1950
1951 // FIXME: should be able to get type location information for vectors, too.
1952
1953 QualType T;
1954 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1955 T = AT->getElementType();
1956 else
1957 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1958
1959 // FIXME: Once we've gone through the effort to create the fake
1960 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1961 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1962 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1963 TL = DI->getTypeLoc();
1964}
1965
Douglas Gregor20093b42009-12-09 23:02:17 +00001966void InitializedEntity::InitDeclLoc() {
1967 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1968 "InitDeclLoc cannot be used with non-declaration entities.");
1969
1970 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1971 TL = DI->getTypeLoc();
1972 return;
1973 }
1974
1975 // FIXME: Once we've gone through the effort to create the fake
1976 // TypeSourceInfo, should we cache it in the declaration?
1977 // (If not, we "leak" it).
1978 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1979 .CreateTypeSourceInfo(VariableOrMember->getType());
1980 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1981 TL = DI->getTypeLoc();
1982}
1983
1984InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1985 CXXBaseSpecifier *Base)
1986{
1987 InitializedEntity Result;
1988 Result.Kind = EK_Base;
1989 Result.Base = Base;
1990 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1991 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1992 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1993 Result.TL = DI->getTypeLoc();
1994 return Result;
1995}
1996
Douglas Gregor99a2e602009-12-16 01:38:02 +00001997DeclarationName InitializedEntity::getName() const {
1998 switch (getKind()) {
1999 case EK_Variable:
2000 case EK_Parameter:
2001 case EK_Member:
2002 return VariableOrMember->getDeclName();
2003
2004 case EK_Result:
2005 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002006 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002007 case EK_Temporary:
2008 case EK_Base:
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002009 case EK_ArrayOrVectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002010 return DeclarationName();
2011 }
2012
2013 // Silence GCC warning
2014 return DeclarationName();
2015}
2016
Douglas Gregor20093b42009-12-09 23:02:17 +00002017//===----------------------------------------------------------------------===//
2018// Initialization sequence
2019//===----------------------------------------------------------------------===//
2020
2021void InitializationSequence::Step::Destroy() {
2022 switch (Kind) {
2023 case SK_ResolveAddressOfOverloadedFunction:
2024 case SK_CastDerivedToBaseRValue:
2025 case SK_CastDerivedToBaseLValue:
2026 case SK_BindReference:
2027 case SK_BindReferenceToTemporary:
2028 case SK_UserConversion:
2029 case SK_QualificationConversionRValue:
2030 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002031 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002032 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002033 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002034 case SK_CAssignment:
Douglas Gregor20093b42009-12-09 23:02:17 +00002035 break;
2036
2037 case SK_ConversionSequence:
2038 delete ICS;
2039 }
2040}
2041
2042void InitializationSequence::AddAddressOverloadResolutionStep(
2043 FunctionDecl *Function) {
2044 Step S;
2045 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2046 S.Type = Function->getType();
2047 S.Function = Function;
2048 Steps.push_back(S);
2049}
2050
2051void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2052 bool IsLValue) {
2053 Step S;
2054 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2055 S.Type = BaseType;
2056 Steps.push_back(S);
2057}
2058
2059void InitializationSequence::AddReferenceBindingStep(QualType T,
2060 bool BindingTemporary) {
2061 Step S;
2062 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2063 S.Type = T;
2064 Steps.push_back(S);
2065}
2066
Eli Friedman03981012009-12-11 02:42:07 +00002067void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2068 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002069 Step S;
2070 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002071 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002072 S.Function = Function;
2073 Steps.push_back(S);
2074}
2075
2076void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2077 bool IsLValue) {
2078 Step S;
2079 S.Kind = IsLValue? SK_QualificationConversionLValue
2080 : SK_QualificationConversionRValue;
2081 S.Type = Ty;
2082 Steps.push_back(S);
2083}
2084
2085void InitializationSequence::AddConversionSequenceStep(
2086 const ImplicitConversionSequence &ICS,
2087 QualType T) {
2088 Step S;
2089 S.Kind = SK_ConversionSequence;
2090 S.Type = T;
2091 S.ICS = new ImplicitConversionSequence(ICS);
2092 Steps.push_back(S);
2093}
2094
Douglas Gregord87b61f2009-12-10 17:56:55 +00002095void InitializationSequence::AddListInitializationStep(QualType T) {
2096 Step S;
2097 S.Kind = SK_ListInitialization;
2098 S.Type = T;
2099 Steps.push_back(S);
2100}
2101
Douglas Gregor51c56d62009-12-14 20:49:26 +00002102void
2103InitializationSequence::AddConstructorInitializationStep(
2104 CXXConstructorDecl *Constructor,
2105 QualType T) {
2106 Step S;
2107 S.Kind = SK_ConstructorInitialization;
2108 S.Type = T;
2109 S.Function = Constructor;
2110 Steps.push_back(S);
2111}
2112
Douglas Gregor71d17402009-12-15 00:01:57 +00002113void InitializationSequence::AddZeroInitializationStep(QualType T) {
2114 Step S;
2115 S.Kind = SK_ZeroInitialization;
2116 S.Type = T;
2117 Steps.push_back(S);
2118}
2119
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002120void InitializationSequence::AddCAssignmentStep(QualType T) {
2121 Step S;
2122 S.Kind = SK_CAssignment;
2123 S.Type = T;
2124 Steps.push_back(S);
2125}
2126
Douglas Gregor20093b42009-12-09 23:02:17 +00002127void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2128 OverloadingResult Result) {
2129 SequenceKind = FailedSequence;
2130 this->Failure = Failure;
2131 this->FailedOverloadResult = Result;
2132}
2133
2134//===----------------------------------------------------------------------===//
2135// Attempt initialization
2136//===----------------------------------------------------------------------===//
2137
2138/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002139static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002140 const InitializedEntity &Entity,
2141 const InitializationKind &Kind,
2142 InitListExpr *InitList,
2143 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002144 // FIXME: We only perform rudimentary checking of list
2145 // initializations at this point, then assume that any list
2146 // initialization of an array, aggregate, or scalar will be
2147 // well-formed. We we actually "perform" list initialization, we'll
2148 // do all of the necessary checking. C++0x initializer lists will
2149 // force us to perform more checking here.
2150 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2151
2152 QualType DestType = Entity.getType().getType();
2153
2154 // C++ [dcl.init]p13:
2155 // If T is a scalar type, then a declaration of the form
2156 //
2157 // T x = { a };
2158 //
2159 // is equivalent to
2160 //
2161 // T x = a;
2162 if (DestType->isScalarType()) {
2163 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2164 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2165 return;
2166 }
2167
2168 // Assume scalar initialization from a single value works.
2169 } else if (DestType->isAggregateType()) {
2170 // Assume aggregate initialization works.
2171 } else if (DestType->isVectorType()) {
2172 // Assume vector initialization works.
2173 } else if (DestType->isReferenceType()) {
2174 // FIXME: C++0x defines behavior for this.
2175 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2176 return;
2177 } else if (DestType->isRecordType()) {
2178 // FIXME: C++0x defines behavior for this
2179 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2180 }
2181
2182 // Add a general "list initialization" step.
2183 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002184}
2185
2186/// \brief Try a reference initialization that involves calling a conversion
2187/// function.
2188///
2189/// FIXME: look intos DRs 656, 896
2190static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2191 const InitializedEntity &Entity,
2192 const InitializationKind &Kind,
2193 Expr *Initializer,
2194 bool AllowRValues,
2195 InitializationSequence &Sequence) {
2196 QualType DestType = Entity.getType().getType();
2197 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2198 QualType T1 = cv1T1.getUnqualifiedType();
2199 QualType cv2T2 = Initializer->getType();
2200 QualType T2 = cv2T2.getUnqualifiedType();
2201
2202 bool DerivedToBase;
2203 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2204 T1, T2, DerivedToBase) &&
2205 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002206 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002207
2208 // Build the candidate set directly in the initialization sequence
2209 // structure, so that it will persist if we fail.
2210 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2211 CandidateSet.clear();
2212
2213 // Determine whether we are allowed to call explicit constructors or
2214 // explicit conversion operators.
2215 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2216
2217 const RecordType *T1RecordType = 0;
2218 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2219 // The type we're converting to is a class type. Enumerate its constructors
2220 // to see if there is a suitable conversion.
2221 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2222
2223 DeclarationName ConstructorName
2224 = S.Context.DeclarationNames.getCXXConstructorName(
2225 S.Context.getCanonicalType(T1).getUnqualifiedType());
2226 DeclContext::lookup_iterator Con, ConEnd;
2227 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2228 Con != ConEnd; ++Con) {
2229 // Find the constructor (which may be a template).
2230 CXXConstructorDecl *Constructor = 0;
2231 FunctionTemplateDecl *ConstructorTmpl
2232 = dyn_cast<FunctionTemplateDecl>(*Con);
2233 if (ConstructorTmpl)
2234 Constructor = cast<CXXConstructorDecl>(
2235 ConstructorTmpl->getTemplatedDecl());
2236 else
2237 Constructor = cast<CXXConstructorDecl>(*Con);
2238
2239 if (!Constructor->isInvalidDecl() &&
2240 Constructor->isConvertingConstructor(AllowExplicit)) {
2241 if (ConstructorTmpl)
2242 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2243 &Initializer, 1, CandidateSet);
2244 else
2245 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2246 }
2247 }
2248 }
2249
2250 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2251 // The type we're converting from is a class type, enumerate its conversion
2252 // functions.
2253 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2254
2255 // Determine the type we are converting to. If we are allowed to
2256 // convert to an rvalue, take the type that the destination type
2257 // refers to.
2258 QualType ToType = AllowRValues? cv1T1 : DestType;
2259
2260 const UnresolvedSet *Conversions
2261 = T2RecordDecl->getVisibleConversionFunctions();
2262 for (UnresolvedSet::iterator I = Conversions->begin(),
2263 E = Conversions->end();
2264 I != E; ++I) {
2265 NamedDecl *D = *I;
2266 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2267 if (isa<UsingShadowDecl>(D))
2268 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2269
2270 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2271 CXXConversionDecl *Conv;
2272 if (ConvTemplate)
2273 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2274 else
2275 Conv = cast<CXXConversionDecl>(*I);
2276
2277 // If the conversion function doesn't return a reference type,
2278 // it can't be considered for this conversion unless we're allowed to
2279 // consider rvalues.
2280 // FIXME: Do we need to make sure that we only consider conversion
2281 // candidates with reference-compatible results? That might be needed to
2282 // break recursion.
2283 if ((AllowExplicit || !Conv->isExplicit()) &&
2284 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2285 if (ConvTemplate)
2286 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2287 ToType, CandidateSet);
2288 else
2289 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2290 CandidateSet);
2291 }
2292 }
2293 }
2294
2295 SourceLocation DeclLoc = Initializer->getLocStart();
2296
2297 // Perform overload resolution. If it fails, return the failed result.
2298 OverloadCandidateSet::iterator Best;
2299 if (OverloadingResult Result
2300 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2301 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002302
Douglas Gregor20093b42009-12-09 23:02:17 +00002303 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002304
2305 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002306 if (isa<CXXConversionDecl>(Function))
2307 T2 = Function->getResultType();
2308 else
2309 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002310
2311 // Add the user-defined conversion step.
2312 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2313
2314 // Determine whether we need to perform derived-to-base or
2315 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002316 bool NewDerivedToBase = false;
2317 Sema::ReferenceCompareResult NewRefRelationship
2318 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2319 NewDerivedToBase);
2320 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2321 "Overload resolution picked a bad conversion function");
2322 (void)NewRefRelationship;
2323 if (NewDerivedToBase)
2324 Sequence.AddDerivedToBaseCastStep(
2325 S.Context.getQualifiedType(T1,
2326 T2.getNonReferenceType().getQualifiers()),
2327 /*isLValue=*/true);
2328
2329 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2330 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2331
2332 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2333 return OR_Success;
2334}
2335
2336/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2337static void TryReferenceInitialization(Sema &S,
2338 const InitializedEntity &Entity,
2339 const InitializationKind &Kind,
2340 Expr *Initializer,
2341 InitializationSequence &Sequence) {
2342 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2343
2344 QualType DestType = Entity.getType().getType();
2345 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2346 QualType T1 = cv1T1.getUnqualifiedType();
2347 QualType cv2T2 = Initializer->getType();
2348 QualType T2 = cv2T2.getUnqualifiedType();
2349 SourceLocation DeclLoc = Initializer->getLocStart();
2350
2351 // If the initializer is the address of an overloaded function, try
2352 // to resolve the overloaded function. If all goes well, T2 is the
2353 // type of the resulting function.
2354 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2355 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2356 T1,
2357 false);
2358 if (!Fn) {
2359 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2360 return;
2361 }
2362
2363 Sequence.AddAddressOverloadResolutionStep(Fn);
2364 cv2T2 = Fn->getType();
2365 T2 = cv2T2.getUnqualifiedType();
2366 }
2367
2368 // FIXME: Rvalue references
2369 bool ForceRValue = false;
2370
2371 // Compute some basic properties of the types and the initializer.
2372 bool isLValueRef = DestType->isLValueReferenceType();
2373 bool isRValueRef = !isLValueRef;
2374 bool DerivedToBase = false;
2375 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2376 Initializer->isLvalue(S.Context);
2377 Sema::ReferenceCompareResult RefRelationship
2378 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2379
2380 // C++0x [dcl.init.ref]p5:
2381 // A reference to type "cv1 T1" is initialized by an expression of type
2382 // "cv2 T2" as follows:
2383 //
2384 // - If the reference is an lvalue reference and the initializer
2385 // expression
2386 OverloadingResult ConvOvlResult = OR_Success;
2387 if (isLValueRef) {
2388 if (InitLvalue == Expr::LV_Valid &&
2389 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2390 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2391 // reference-compatible with "cv2 T2," or
2392 //
2393 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2394 // bit-field when we're determining whether the reference initialization
2395 // can occur. This property will be checked by PerformInitialization.
2396 if (DerivedToBase)
2397 Sequence.AddDerivedToBaseCastStep(
2398 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2399 /*isLValue=*/true);
2400 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2401 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2402 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2403 return;
2404 }
2405
2406 // - has a class type (i.e., T2 is a class type), where T1 is not
2407 // reference-related to T2, and can be implicitly converted to an
2408 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2409 // with "cv3 T3" (this conversion is selected by enumerating the
2410 // applicable conversion functions (13.3.1.6) and choosing the best
2411 // one through overload resolution (13.3)),
2412 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2413 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2414 Initializer,
2415 /*AllowRValues=*/false,
2416 Sequence);
2417 if (ConvOvlResult == OR_Success)
2418 return;
2419 }
2420 }
2421
2422 // - Otherwise, the reference shall be an lvalue reference to a
2423 // non-volatile const type (i.e., cv1 shall be const), or the reference
2424 // shall be an rvalue reference and the initializer expression shall
2425 // be an rvalue.
2426 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2427 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2428 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2429 Sequence.SetOverloadFailure(
2430 InitializationSequence::FK_ReferenceInitOverloadFailed,
2431 ConvOvlResult);
2432 else if (isLValueRef)
2433 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2434 ? (RefRelationship == Sema::Ref_Related
2435 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2436 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2437 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2438 else
2439 Sequence.SetFailed(
2440 InitializationSequence::FK_RValueReferenceBindingToLValue);
2441
2442 return;
2443 }
2444
2445 // - If T1 and T2 are class types and
2446 if (T1->isRecordType() && T2->isRecordType()) {
2447 // - the initializer expression is an rvalue and "cv1 T1" is
2448 // reference-compatible with "cv2 T2", or
2449 if (InitLvalue != Expr::LV_Valid &&
2450 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2451 if (DerivedToBase)
2452 Sequence.AddDerivedToBaseCastStep(
2453 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2454 /*isLValue=*/false);
2455 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2456 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2457 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2458 return;
2459 }
2460
2461 // - T1 is not reference-related to T2 and the initializer expression
2462 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2463 // conversion is selected by enumerating the applicable conversion
2464 // functions (13.3.1.6) and choosing the best one through overload
2465 // resolution (13.3)),
2466 if (RefRelationship == Sema::Ref_Incompatible) {
2467 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2468 Kind, Initializer,
2469 /*AllowRValues=*/true,
2470 Sequence);
2471 if (ConvOvlResult)
2472 Sequence.SetOverloadFailure(
2473 InitializationSequence::FK_ReferenceInitOverloadFailed,
2474 ConvOvlResult);
2475
2476 return;
2477 }
2478
2479 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2480 return;
2481 }
2482
2483 // - If the initializer expression is an rvalue, with T2 an array type,
2484 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2485 // is bound to the object represented by the rvalue (see 3.10).
2486 // FIXME: How can an array type be reference-compatible with anything?
2487 // Don't we mean the element types of T1 and T2?
2488
2489 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2490 // from the initializer expression using the rules for a non-reference
2491 // copy initialization (8.5). The reference is then bound to the
2492 // temporary. [...]
2493 // Determine whether we are allowed to call explicit constructors or
2494 // explicit conversion operators.
2495 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2496 ImplicitConversionSequence ICS
2497 = S.TryImplicitConversion(Initializer, cv1T1,
2498 /*SuppressUserConversions=*/false, AllowExplicit,
2499 /*ForceRValue=*/false,
2500 /*FIXME:InOverloadResolution=*/false,
2501 /*UserCast=*/Kind.isExplicitCast());
2502
2503 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2504 // FIXME: Use the conversion function set stored in ICS to turn
2505 // this into an overloading ambiguity diagnostic. However, we need
2506 // to keep that set as an OverloadCandidateSet rather than as some
2507 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002508 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2509 Sequence.SetOverloadFailure(
2510 InitializationSequence::FK_ReferenceInitOverloadFailed,
2511 ConvOvlResult);
2512 else
2513 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002514 return;
2515 }
2516
2517 // [...] If T1 is reference-related to T2, cv1 must be the
2518 // same cv-qualification as, or greater cv-qualification
2519 // than, cv2; otherwise, the program is ill-formed.
2520 if (RefRelationship == Sema::Ref_Related &&
2521 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2522 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2523 return;
2524 }
2525
2526 // Perform the actual conversion.
2527 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2528 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2529 return;
2530}
2531
2532/// \brief Attempt character array initialization from a string literal
2533/// (C++ [dcl.init.string], C99 6.7.8).
2534static void TryStringLiteralInitialization(Sema &S,
2535 const InitializedEntity &Entity,
2536 const InitializationKind &Kind,
2537 Expr *Initializer,
2538 InitializationSequence &Sequence) {
2539 // FIXME: Implement!
2540}
2541
Douglas Gregor20093b42009-12-09 23:02:17 +00002542/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2543/// enumerates the constructors of the initialized entity and performs overload
2544/// resolution to select the best.
2545static void TryConstructorInitialization(Sema &S,
2546 const InitializedEntity &Entity,
2547 const InitializationKind &Kind,
2548 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002549 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002550 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002551 if (Kind.getKind() == InitializationKind::IK_Copy)
2552 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2553 else
2554 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002555
2556 // Build the candidate set directly in the initialization sequence
2557 // structure, so that it will persist if we fail.
2558 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2559 CandidateSet.clear();
2560
2561 // Determine whether we are allowed to call explicit constructors or
2562 // explicit conversion operators.
2563 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2564 Kind.getKind() == InitializationKind::IK_Value ||
2565 Kind.getKind() == InitializationKind::IK_Default);
2566
2567 // The type we're converting to is a class type. Enumerate its constructors
2568 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002569 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2570 assert(DestRecordType && "Constructor initialization requires record type");
2571 CXXRecordDecl *DestRecordDecl
2572 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2573
2574 DeclarationName ConstructorName
2575 = S.Context.DeclarationNames.getCXXConstructorName(
2576 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2577 DeclContext::lookup_iterator Con, ConEnd;
2578 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2579 Con != ConEnd; ++Con) {
2580 // Find the constructor (which may be a template).
2581 CXXConstructorDecl *Constructor = 0;
2582 FunctionTemplateDecl *ConstructorTmpl
2583 = dyn_cast<FunctionTemplateDecl>(*Con);
2584 if (ConstructorTmpl)
2585 Constructor = cast<CXXConstructorDecl>(
2586 ConstructorTmpl->getTemplatedDecl());
2587 else
2588 Constructor = cast<CXXConstructorDecl>(*Con);
2589
2590 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002591 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002592 if (ConstructorTmpl)
2593 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2594 Args, NumArgs, CandidateSet);
2595 else
2596 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2597 }
2598 }
2599
2600 SourceLocation DeclLoc = Kind.getLocation();
2601
2602 // Perform overload resolution. If it fails, return the failed result.
2603 OverloadCandidateSet::iterator Best;
2604 if (OverloadingResult Result
2605 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2606 Sequence.SetOverloadFailure(
2607 InitializationSequence::FK_ConstructorOverloadFailed,
2608 Result);
2609 return;
2610 }
2611
2612 // Add the constructor initialization step. Any cv-qualification conversion is
2613 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002614 if (Kind.getKind() == InitializationKind::IK_Copy) {
2615 Sequence.AddUserConversionStep(Best->Function, DestType);
2616 } else {
2617 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002618 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002619 DestType);
2620 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002621}
2622
Douglas Gregor71d17402009-12-15 00:01:57 +00002623/// \brief Attempt value initialization (C++ [dcl.init]p7).
2624static void TryValueInitialization(Sema &S,
2625 const InitializedEntity &Entity,
2626 const InitializationKind &Kind,
2627 InitializationSequence &Sequence) {
2628 // C++ [dcl.init]p5:
2629 //
2630 // To value-initialize an object of type T means:
2631 QualType T = Entity.getType().getType();
2632
2633 // -- if T is an array type, then each element is value-initialized;
2634 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2635 T = AT->getElementType();
2636
2637 if (const RecordType *RT = T->getAs<RecordType>()) {
2638 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2639 // -- if T is a class type (clause 9) with a user-declared
2640 // constructor (12.1), then the default constructor for T is
2641 // called (and the initialization is ill-formed if T has no
2642 // accessible default constructor);
2643 //
2644 // FIXME: we really want to refer to a single subobject of the array,
2645 // but Entity doesn't have a way to capture that (yet).
2646 if (ClassDecl->hasUserDeclaredConstructor())
2647 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2648
Douglas Gregor16006c92009-12-16 18:50:27 +00002649 // -- if T is a (possibly cv-qualified) non-union class type
2650 // without a user-provided constructor, then the object is
2651 // zero-initialized and, if T’s implicitly-declared default
2652 // constructor is non-trivial, that constructor is called.
2653 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2654 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2655 !ClassDecl->hasTrivialConstructor()) {
2656 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2657 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2658 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002659 }
2660 }
2661
2662 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2663 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2664}
2665
Douglas Gregor99a2e602009-12-16 01:38:02 +00002666/// \brief Attempt default initialization (C++ [dcl.init]p6).
2667static void TryDefaultInitialization(Sema &S,
2668 const InitializedEntity &Entity,
2669 const InitializationKind &Kind,
2670 InitializationSequence &Sequence) {
2671 assert(Kind.getKind() == InitializationKind::IK_Default);
2672
2673 // C++ [dcl.init]p6:
2674 // To default-initialize an object of type T means:
2675 // - if T is an array type, each element is default-initialized;
2676 QualType DestType = Entity.getType().getType();
2677 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2678 DestType = Array->getElementType();
2679
2680 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2681 // constructor for T is called (and the initialization is ill-formed if
2682 // T has no accessible default constructor);
2683 if (DestType->isRecordType()) {
2684 // FIXME: If a program calls for the default initialization of an object of
2685 // a const-qualified type T, T shall be a class type with a user-provided
2686 // default constructor.
2687 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2688 Sequence);
2689 }
2690
2691 // - otherwise, no initialization is performed.
2692 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2693
2694 // If a program calls for the default initialization of an object of
2695 // a const-qualified type T, T shall be a class type with a user-provided
2696 // default constructor.
2697 if (DestType.isConstQualified())
2698 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2699}
2700
Douglas Gregor20093b42009-12-09 23:02:17 +00002701/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2702/// which enumerates all conversion functions and performs overload resolution
2703/// to select the best.
2704static void TryUserDefinedConversion(Sema &S,
2705 const InitializedEntity &Entity,
2706 const InitializationKind &Kind,
2707 Expr *Initializer,
2708 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002709 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2710
2711 QualType DestType = Entity.getType().getType();
2712 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2713 QualType SourceType = Initializer->getType();
2714 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2715 "Must have a class type to perform a user-defined conversion");
2716
2717 // Build the candidate set directly in the initialization sequence
2718 // structure, so that it will persist if we fail.
2719 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2720 CandidateSet.clear();
2721
2722 // Determine whether we are allowed to call explicit constructors or
2723 // explicit conversion operators.
2724 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2725
2726 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2727 // The type we're converting to is a class type. Enumerate its constructors
2728 // to see if there is a suitable conversion.
2729 CXXRecordDecl *DestRecordDecl
2730 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2731
2732 DeclarationName ConstructorName
2733 = S.Context.DeclarationNames.getCXXConstructorName(
2734 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2735 DeclContext::lookup_iterator Con, ConEnd;
2736 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2737 Con != ConEnd; ++Con) {
2738 // Find the constructor (which may be a template).
2739 CXXConstructorDecl *Constructor = 0;
2740 FunctionTemplateDecl *ConstructorTmpl
2741 = dyn_cast<FunctionTemplateDecl>(*Con);
2742 if (ConstructorTmpl)
2743 Constructor = cast<CXXConstructorDecl>(
2744 ConstructorTmpl->getTemplatedDecl());
2745 else
2746 Constructor = cast<CXXConstructorDecl>(*Con);
2747
2748 if (!Constructor->isInvalidDecl() &&
2749 Constructor->isConvertingConstructor(AllowExplicit)) {
2750 if (ConstructorTmpl)
2751 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2752 &Initializer, 1, CandidateSet);
2753 else
2754 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2755 }
2756 }
2757 }
2758
2759 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2760 // The type we're converting from is a class type, enumerate its conversion
2761 // functions.
2762 CXXRecordDecl *SourceRecordDecl
2763 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2764
2765 const UnresolvedSet *Conversions
2766 = SourceRecordDecl->getVisibleConversionFunctions();
2767 for (UnresolvedSet::iterator I = Conversions->begin(),
2768 E = Conversions->end();
2769 I != E; ++I) {
2770 NamedDecl *D = *I;
2771 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2772 if (isa<UsingShadowDecl>(D))
2773 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2774
2775 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2776 CXXConversionDecl *Conv;
2777 if (ConvTemplate)
2778 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2779 else
2780 Conv = cast<CXXConversionDecl>(*I);
2781
2782 if (AllowExplicit || !Conv->isExplicit()) {
2783 if (ConvTemplate)
2784 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2785 DestType, CandidateSet);
2786 else
2787 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2788 CandidateSet);
2789 }
2790 }
2791 }
2792
2793 SourceLocation DeclLoc = Initializer->getLocStart();
2794
2795 // Perform overload resolution. If it fails, return the failed result.
2796 OverloadCandidateSet::iterator Best;
2797 if (OverloadingResult Result
2798 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2799 Sequence.SetOverloadFailure(
2800 InitializationSequence::FK_UserConversionOverloadFailed,
2801 Result);
2802 return;
2803 }
2804
2805 FunctionDecl *Function = Best->Function;
2806
2807 if (isa<CXXConstructorDecl>(Function)) {
2808 // Add the user-defined conversion step. Any cv-qualification conversion is
2809 // subsumed by the initialization.
2810 Sequence.AddUserConversionStep(Function, DestType);
2811 return;
2812 }
2813
2814 // Add the user-defined conversion step that calls the conversion function.
2815 QualType ConvType = Function->getResultType().getNonReferenceType();
2816 Sequence.AddUserConversionStep(Function, ConvType);
2817
2818 // If the conversion following the call to the conversion function is
2819 // interesting, add it as a separate step.
2820 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2821 Best->FinalConversion.Third) {
2822 ImplicitConversionSequence ICS;
2823 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2824 ICS.Standard = Best->FinalConversion;
2825 Sequence.AddConversionSequenceStep(ICS, DestType);
2826 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002827}
2828
2829/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2830/// non-class type to another.
2831static void TryImplicitConversion(Sema &S,
2832 const InitializedEntity &Entity,
2833 const InitializationKind &Kind,
2834 Expr *Initializer,
2835 InitializationSequence &Sequence) {
2836 ImplicitConversionSequence ICS
2837 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2838 /*SuppressUserConversions=*/true,
2839 /*AllowExplicit=*/false,
2840 /*ForceRValue=*/false,
2841 /*FIXME:InOverloadResolution=*/false,
2842 /*UserCast=*/Kind.isExplicitCast());
2843
2844 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2845 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2846 return;
2847 }
2848
2849 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2850}
2851
2852InitializationSequence::InitializationSequence(Sema &S,
2853 const InitializedEntity &Entity,
2854 const InitializationKind &Kind,
2855 Expr **Args,
2856 unsigned NumArgs) {
2857 ASTContext &Context = S.Context;
2858
2859 // C++0x [dcl.init]p16:
2860 // The semantics of initializers are as follows. The destination type is
2861 // the type of the object or reference being initialized and the source
2862 // type is the type of the initializer expression. The source type is not
2863 // defined when the initializer is a braced-init-list or when it is a
2864 // parenthesized list of expressions.
2865 QualType DestType = Entity.getType().getType();
2866
2867 if (DestType->isDependentType() ||
2868 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2869 SequenceKind = DependentSequence;
2870 return;
2871 }
2872
2873 QualType SourceType;
2874 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002875 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002876 Initializer = Args[0];
2877 if (!isa<InitListExpr>(Initializer))
2878 SourceType = Initializer->getType();
2879 }
2880
2881 // - If the initializer is a braced-init-list, the object is
2882 // list-initialized (8.5.4).
2883 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2884 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002885 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002886 }
2887
2888 // - If the destination type is a reference type, see 8.5.3.
2889 if (DestType->isReferenceType()) {
2890 // C++0x [dcl.init.ref]p1:
2891 // A variable declared to be a T& or T&&, that is, "reference to type T"
2892 // (8.3.2), shall be initialized by an object, or function, of type T or
2893 // by an object that can be converted into a T.
2894 // (Therefore, multiple arguments are not permitted.)
2895 if (NumArgs != 1)
2896 SetFailed(FK_TooManyInitsForReference);
2897 else
2898 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2899 return;
2900 }
2901
2902 // - If the destination type is an array of characters, an array of
2903 // char16_t, an array of char32_t, or an array of wchar_t, and the
2904 // initializer is a string literal, see 8.5.2.
2905 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2906 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2907 return;
2908 }
2909
2910 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002911 if (Kind.getKind() == InitializationKind::IK_Value ||
2912 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002913 TryValueInitialization(S, Entity, Kind, *this);
2914 return;
2915 }
2916
Douglas Gregor99a2e602009-12-16 01:38:02 +00002917 // Handle default initialization.
2918 if (Kind.getKind() == InitializationKind::IK_Default){
2919 TryDefaultInitialization(S, Entity, Kind, *this);
2920 return;
2921 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002922
2923 // Handle initialization in C
2924 if (!S.getLangOptions().CPlusPlus) {
2925 setSequenceKind(CAssignment);
2926 AddCAssignmentStep(DestType);
2927 return;
2928 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00002929
Douglas Gregor20093b42009-12-09 23:02:17 +00002930 // - Otherwise, if the destination type is an array, the program is
2931 // ill-formed.
2932 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2933 if (AT->getElementType()->isAnyCharacterType())
2934 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2935 else
2936 SetFailed(FK_ArrayNeedsInitList);
2937
2938 return;
2939 }
2940
2941 // - If the destination type is a (possibly cv-qualified) class type:
2942 if (DestType->isRecordType()) {
2943 // - If the initialization is direct-initialization, or if it is
2944 // copy-initialization where the cv-unqualified version of the
2945 // source type is the same class as, or a derived class of, the
2946 // class of the destination, constructors are considered. [...]
2947 if (Kind.getKind() == InitializationKind::IK_Direct ||
2948 (Kind.getKind() == InitializationKind::IK_Copy &&
2949 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2950 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002951 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2952 Entity.getType().getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002953 // - Otherwise (i.e., for the remaining copy-initialization cases),
2954 // user-defined conversion sequences that can convert from the source
2955 // type to the destination type or (when a conversion function is
2956 // used) to a derived class thereof are enumerated as described in
2957 // 13.3.1.4, and the best one is chosen through overload resolution
2958 // (13.3).
2959 else
2960 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2961 return;
2962 }
2963
Douglas Gregor99a2e602009-12-16 01:38:02 +00002964 if (NumArgs > 1) {
2965 SetFailed(FK_TooManyInitsForScalar);
2966 return;
2967 }
2968 assert(NumArgs == 1 && "Zero-argument case handled above");
2969
Douglas Gregor20093b42009-12-09 23:02:17 +00002970 // - Otherwise, if the source type is a (possibly cv-qualified) class
2971 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002972 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002973 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2974 return;
2975 }
2976
2977 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002978 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002979 // conversions (Clause 4) will be used, if necessary, to convert the
2980 // initializer expression to the cv-unqualified version of the
2981 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002982 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002983 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2984}
2985
2986InitializationSequence::~InitializationSequence() {
2987 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2988 StepEnd = Steps.end();
2989 Step != StepEnd; ++Step)
2990 Step->Destroy();
2991}
2992
2993//===----------------------------------------------------------------------===//
2994// Perform initialization
2995//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002996static Sema::AssignmentAction
2997getAssignmentAction(const InitializedEntity &Entity) {
2998 switch(Entity.getKind()) {
2999 case InitializedEntity::EK_Variable:
3000 case InitializedEntity::EK_New:
3001 return Sema::AA_Initializing;
3002
3003 case InitializedEntity::EK_Parameter:
3004 // FIXME: Can we tell when we're sending vs. passing?
3005 return Sema::AA_Passing;
3006
3007 case InitializedEntity::EK_Result:
3008 return Sema::AA_Returning;
3009
3010 case InitializedEntity::EK_Exception:
3011 case InitializedEntity::EK_Base:
3012 llvm_unreachable("No assignment action for C++-specific initialization");
3013 break;
3014
3015 case InitializedEntity::EK_Temporary:
3016 // FIXME: Can we tell apart casting vs. converting?
3017 return Sema::AA_Casting;
3018
3019 case InitializedEntity::EK_Member:
3020 case InitializedEntity::EK_ArrayOrVectorElement:
3021 return Sema::AA_Initializing;
3022 }
3023
3024 return Sema::AA_Converting;
3025}
3026
3027static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3028 bool IsCopy) {
3029 switch (Entity.getKind()) {
3030 case InitializedEntity::EK_Result:
3031 case InitializedEntity::EK_Exception:
3032 return !IsCopy;
3033
3034 case InitializedEntity::EK_New:
3035 case InitializedEntity::EK_Variable:
3036 case InitializedEntity::EK_Base:
3037 case InitializedEntity::EK_Member:
3038 case InitializedEntity::EK_ArrayOrVectorElement:
3039 return false;
3040
3041 case InitializedEntity::EK_Parameter:
3042 case InitializedEntity::EK_Temporary:
3043 return true;
3044 }
3045
3046 llvm_unreachable("missed an InitializedEntity kind?");
3047}
3048
3049/// \brief If we need to perform an additional copy of the initialized object
3050/// for this kind of entity (e.g., the result of a function or an object being
3051/// thrown), make the copy.
3052static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3053 const InitializedEntity &Entity,
3054 Sema::OwningExprResult CurInit) {
3055 SourceLocation Loc;
3056 bool isReturn = false;
3057
3058 switch (Entity.getKind()) {
3059 case InitializedEntity::EK_Result:
3060 if (Entity.getType().getType()->isReferenceType())
3061 return move(CurInit);
3062 isReturn = true;
3063 Loc = Entity.getReturnLoc();
3064 break;
3065
3066 case InitializedEntity::EK_Exception:
3067 isReturn = false;
3068 Loc = Entity.getThrowLoc();
3069 break;
3070
3071 case InitializedEntity::EK_Variable:
3072 case InitializedEntity::EK_Parameter:
3073 case InitializedEntity::EK_New:
3074 case InitializedEntity::EK_Temporary:
3075 case InitializedEntity::EK_Base:
3076 case InitializedEntity::EK_Member:
3077 case InitializedEntity::EK_ArrayOrVectorElement:
3078 // We don't need to copy for any of these initialized entities.
3079 return move(CurInit);
3080 }
3081
3082 Expr *CurInitExpr = (Expr *)CurInit.get();
3083 CXXRecordDecl *Class = 0;
3084 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3085 Class = cast<CXXRecordDecl>(Record->getDecl());
3086 if (!Class)
3087 return move(CurInit);
3088
3089 // Perform overload resolution using the class's copy constructors.
3090 DeclarationName ConstructorName
3091 = S.Context.DeclarationNames.getCXXConstructorName(
3092 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3093 DeclContext::lookup_iterator Con, ConEnd;
3094 OverloadCandidateSet CandidateSet;
3095 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3096 Con != ConEnd; ++Con) {
3097 // Find the constructor (which may be a template).
3098 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3099 if (!Constructor || Constructor->isInvalidDecl() ||
3100 !Constructor->isCopyConstructor(S.Context))
3101 continue;
3102
3103 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3104 }
3105
3106 OverloadCandidateSet::iterator Best;
3107 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3108 case OR_Success:
3109 break;
3110
3111 case OR_No_Viable_Function:
3112 S.Diag(Loc, diag::err_temp_copy_no_viable)
3113 << isReturn << CurInitExpr->getType()
3114 << CurInitExpr->getSourceRange();
3115 S.PrintOverloadCandidates(CandidateSet, false);
3116 return S.ExprError();
3117
3118 case OR_Ambiguous:
3119 S.Diag(Loc, diag::err_temp_copy_ambiguous)
3120 << isReturn << CurInitExpr->getType()
3121 << CurInitExpr->getSourceRange();
3122 S.PrintOverloadCandidates(CandidateSet, true);
3123 return S.ExprError();
3124
3125 case OR_Deleted:
3126 S.Diag(Loc, diag::err_temp_copy_deleted)
3127 << isReturn << CurInitExpr->getType()
3128 << CurInitExpr->getSourceRange();
3129 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3130 << Best->Function->isDeleted();
3131 return S.ExprError();
3132 }
3133
3134 CurInit.release();
3135 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3136 cast<CXXConstructorDecl>(Best->Function),
3137 /*Elidable=*/true,
3138 Sema::MultiExprArg(S,
3139 (void**)&CurInitExpr, 1));
3140}
Douglas Gregor20093b42009-12-09 23:02:17 +00003141
3142Action::OwningExprResult
3143InitializationSequence::Perform(Sema &S,
3144 const InitializedEntity &Entity,
3145 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003146 Action::MultiExprArg Args,
3147 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 if (SequenceKind == FailedSequence) {
3149 unsigned NumArgs = Args.size();
3150 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3151 return S.ExprError();
3152 }
3153
3154 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003155 // If the declaration is a non-dependent, incomplete array type
3156 // that has an initializer, then its type will be completed once
3157 // the initializer is instantiated.
3158 if (ResultType && !Entity.getType().getType()->isDependentType() &&
3159 Args.size() == 1) {
3160 QualType DeclType = Entity.getType().getType();
3161 if (const IncompleteArrayType *ArrayT
3162 = S.Context.getAsIncompleteArrayType(DeclType)) {
3163 // FIXME: We don't currently have the ability to accurately
3164 // compute the length of an initializer list without
3165 // performing full type-checking of the initializer list
3166 // (since we have to determine where braces are implicitly
3167 // introduced and such). So, we fall back to making the array
3168 // type a dependently-sized array type with no specified
3169 // bound.
3170 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3171 SourceRange Brackets;
3172 // Scavange the location of the brackets from the entity, if we can.
3173 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
3174 IncompleteArrayTypeLoc ArrayLoc
3175 = cast<IncompleteArrayTypeLoc>(Entity.getType());
3176 Brackets = ArrayLoc.getBracketsRange();
3177 }
3178
3179 *ResultType
3180 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3181 /*NumElts=*/0,
3182 ArrayT->getSizeModifier(),
3183 ArrayT->getIndexTypeCVRQualifiers(),
3184 Brackets);
3185 }
3186
3187 }
3188 }
3189
Douglas Gregor20093b42009-12-09 23:02:17 +00003190 if (Kind.getKind() == InitializationKind::IK_Copy)
3191 return Sema::OwningExprResult(S, Args.release()[0]);
3192
3193 unsigned NumArgs = Args.size();
3194 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3195 SourceLocation(),
3196 (Expr **)Args.release(),
3197 NumArgs,
3198 SourceLocation()));
3199 }
3200
Douglas Gregor99a2e602009-12-16 01:38:02 +00003201 if (SequenceKind == NoInitialization)
3202 return S.Owned((Expr *)0);
3203
Douglas Gregor20093b42009-12-09 23:02:17 +00003204 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003205 if (ResultType)
3206 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003207
Douglas Gregor99a2e602009-12-16 01:38:02 +00003208 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3209
3210 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3211
3212 // For initialization steps that start with a single initializer,
3213 // grab the only argument out the Args and place it into the "current"
3214 // initializer.
3215 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003216 case SK_ResolveAddressOfOverloadedFunction:
3217 case SK_CastDerivedToBaseRValue:
3218 case SK_CastDerivedToBaseLValue:
3219 case SK_BindReference:
3220 case SK_BindReferenceToTemporary:
3221 case SK_UserConversion:
3222 case SK_QualificationConversionLValue:
3223 case SK_QualificationConversionRValue:
3224 case SK_ConversionSequence:
3225 case SK_ListInitialization:
3226 case SK_CAssignment:
3227 assert(Args.size() == 1);
3228 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3229 if (CurInit.isInvalid())
3230 return S.ExprError();
3231 break;
3232
3233 case SK_ConstructorInitialization:
3234 case SK_ZeroInitialization:
3235 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003236 }
3237
3238 // Walk through the computed steps for the initialization sequence,
3239 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003240 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003241 for (step_iterator Step = step_begin(), StepEnd = step_end();
3242 Step != StepEnd; ++Step) {
3243 if (CurInit.isInvalid())
3244 return S.ExprError();
3245
3246 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003247 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003248
3249 switch (Step->Kind) {
3250 case SK_ResolveAddressOfOverloadedFunction:
3251 // Overload resolution determined which function invoke; update the
3252 // initializer to reflect that choice.
3253 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3254 break;
3255
3256 case SK_CastDerivedToBaseRValue:
3257 case SK_CastDerivedToBaseLValue: {
3258 // We have a derived-to-base cast that produces either an rvalue or an
3259 // lvalue. Perform that cast.
3260
3261 // Casts to inaccessible base classes are allowed with C-style casts.
3262 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3263 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3264 CurInitExpr->getLocStart(),
3265 CurInitExpr->getSourceRange(),
3266 IgnoreBaseAccess))
3267 return S.ExprError();
3268
3269 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3270 CastExpr::CK_DerivedToBase,
3271 (Expr*)CurInit.release(),
3272 Step->Kind == SK_CastDerivedToBaseLValue));
3273 break;
3274 }
3275
3276 case SK_BindReference:
3277 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3278 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3279 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3280 << Entity.getType().getType().isVolatileQualified()
3281 << BitField->getDeclName()
3282 << CurInitExpr->getSourceRange();
3283 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3284 return S.ExprError();
3285 }
3286
3287 // Reference binding does not have any corresponding ASTs.
3288
3289 // Check exception specifications
3290 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3291 return S.ExprError();
3292 break;
3293
3294 case SK_BindReferenceToTemporary:
3295 // Check exception specifications
3296 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3297 return S.ExprError();
3298
3299 // FIXME: At present, we have no AST to describe when we need to make a
3300 // temporary to bind a reference to. We should.
3301 break;
3302
3303 case SK_UserConversion: {
3304 // We have a user-defined conversion that invokes either a constructor
3305 // or a conversion function.
3306 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003307 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 if (CXXConstructorDecl *Constructor
3309 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3310 // Build a call to the selected constructor.
3311 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3312 SourceLocation Loc = CurInitExpr->getLocStart();
3313 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3314
3315 // Determine the arguments required to actually perform the constructor
3316 // call.
3317 if (S.CompleteConstructorCall(Constructor,
3318 Sema::MultiExprArg(S,
3319 (void **)&CurInitExpr,
3320 1),
3321 Loc, ConstructorArgs))
3322 return S.ExprError();
3323
3324 // Build the an expression that constructs a temporary.
3325 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3326 move_arg(ConstructorArgs));
3327 if (CurInit.isInvalid())
3328 return S.ExprError();
3329
3330 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003331 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3332 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3333 S.IsDerivedFrom(SourceType, Class))
3334 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003335 } else {
3336 // Build a call to the conversion function.
3337 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338
Douglas Gregor20093b42009-12-09 23:02:17 +00003339 // FIXME: Should we move this initialization into a separate
3340 // derived-to-base conversion? I believe the answer is "no", because
3341 // we don't want to turn off access control here for c-style casts.
3342 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3343 return S.ExprError();
3344
3345 // Do a little dance to make sure that CurInit has the proper
3346 // pointer.
3347 CurInit.release();
3348
3349 // Build the actual call to the conversion function.
3350 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3351 if (CurInit.isInvalid() || !CurInit.get())
3352 return S.ExprError();
3353
3354 CastKind = CastExpr::CK_UserDefinedConversion;
3355 }
3356
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003357 if (shouldBindAsTemporary(Entity, IsCopy))
3358 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3359
Douglas Gregor20093b42009-12-09 23:02:17 +00003360 CurInitExpr = CurInit.takeAs<Expr>();
3361 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3362 CastKind,
3363 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003364 false));
3365
3366 if (!IsCopy)
3367 CurInit = CopyIfRequiredForEntity(S, Entity, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003368 break;
3369 }
3370
3371 case SK_QualificationConversionLValue:
3372 case SK_QualificationConversionRValue:
3373 // Perform a qualification conversion; these can never go wrong.
3374 S.ImpCastExprToType(CurInitExpr, Step->Type,
3375 CastExpr::CK_NoOp,
3376 Step->Kind == SK_QualificationConversionLValue);
3377 CurInit.release();
3378 CurInit = S.Owned(CurInitExpr);
3379 break;
3380
3381 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003382 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 false, false, *Step->ICS))
3384 return S.ExprError();
3385
3386 CurInit.release();
3387 CurInit = S.Owned(CurInitExpr);
3388 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003389
3390 case SK_ListInitialization: {
3391 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3392 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003393 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003394 return S.ExprError();
3395
3396 CurInit.release();
3397 CurInit = S.Owned(InitList);
3398 break;
3399 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003400
3401 case SK_ConstructorInitialization: {
3402 CXXConstructorDecl *Constructor
3403 = cast<CXXConstructorDecl>(Step->Function);
3404
3405 // Build a call to the selected constructor.
3406 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3407 SourceLocation Loc = Kind.getLocation();
3408
3409 // Determine the arguments required to actually perform the constructor
3410 // call.
3411 if (S.CompleteConstructorCall(Constructor, move(Args),
3412 Loc, ConstructorArgs))
3413 return S.ExprError();
3414
3415 // Build the an expression that constructs a temporary.
3416 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003417 move_arg(ConstructorArgs),
3418 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003419 if (CurInit.isInvalid())
3420 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003421
3422 bool Elidable
3423 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3424 if (shouldBindAsTemporary(Entity, Elidable))
3425 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3426
3427 if (!Elidable)
3428 CurInit = CopyIfRequiredForEntity(S, Entity, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003429 break;
3430 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003431
3432 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003433 step_iterator NextStep = Step;
3434 ++NextStep;
3435 if (NextStep != StepEnd &&
3436 NextStep->Kind == SK_ConstructorInitialization) {
3437 // The need for zero-initialization is recorded directly into
3438 // the call to the object's constructor within the next step.
3439 ConstructorInitRequiresZeroInit = true;
3440 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3441 S.getLangOptions().CPlusPlus &&
3442 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003443 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3444 Kind.getRange().getBegin(),
3445 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003446 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003447 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003448 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003449 break;
3450 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003451
3452 case SK_CAssignment: {
3453 QualType SourceType = CurInitExpr->getType();
3454 Sema::AssignConvertType ConvTy =
3455 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
3456 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3457 Step->Type, SourceType,
3458 CurInitExpr, getAssignmentAction(Entity)))
3459 return S.ExprError();
3460
3461 CurInit.release();
3462 CurInit = S.Owned(CurInitExpr);
3463 break;
3464 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003465 }
3466 }
3467
3468 return move(CurInit);
3469}
3470
3471//===----------------------------------------------------------------------===//
3472// Diagnose initialization failures
3473//===----------------------------------------------------------------------===//
3474bool InitializationSequence::Diagnose(Sema &S,
3475 const InitializedEntity &Entity,
3476 const InitializationKind &Kind,
3477 Expr **Args, unsigned NumArgs) {
3478 if (SequenceKind != FailedSequence)
3479 return false;
3480
3481 QualType DestType = Entity.getType().getType();
3482 switch (Failure) {
3483 case FK_TooManyInitsForReference:
3484 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3485 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3486 break;
3487
3488 case FK_ArrayNeedsInitList:
3489 case FK_ArrayNeedsInitListOrStringLiteral:
3490 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3491 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3492 break;
3493
3494 case FK_AddressOfOverloadFailed:
3495 S.ResolveAddressOfOverloadedFunction(Args[0],
3496 DestType.getNonReferenceType(),
3497 true);
3498 break;
3499
3500 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003501 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003502 switch (FailedOverloadResult) {
3503 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003504 if (Failure == FK_UserConversionOverloadFailed)
3505 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3506 << Args[0]->getType() << DestType
3507 << Args[0]->getSourceRange();
3508 else
3509 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3510 << DestType << Args[0]->getType()
3511 << Args[0]->getSourceRange();
3512
Douglas Gregor20093b42009-12-09 23:02:17 +00003513 S.PrintOverloadCandidates(FailedCandidateSet, true);
3514 break;
3515
3516 case OR_No_Viable_Function:
3517 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3518 << Args[0]->getType() << DestType.getNonReferenceType()
3519 << Args[0]->getSourceRange();
3520 S.PrintOverloadCandidates(FailedCandidateSet, false);
3521 break;
3522
3523 case OR_Deleted: {
3524 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3525 << Args[0]->getType() << DestType.getNonReferenceType()
3526 << Args[0]->getSourceRange();
3527 OverloadCandidateSet::iterator Best;
3528 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3529 Kind.getLocation(),
3530 Best);
3531 if (Ovl == OR_Deleted) {
3532 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3533 << Best->Function->isDeleted();
3534 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003535 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003536 }
3537 break;
3538 }
3539
3540 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003541 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003542 break;
3543 }
3544 break;
3545
3546 case FK_NonConstLValueReferenceBindingToTemporary:
3547 case FK_NonConstLValueReferenceBindingToUnrelated:
3548 S.Diag(Kind.getLocation(),
3549 Failure == FK_NonConstLValueReferenceBindingToTemporary
3550 ? diag::err_lvalue_reference_bind_to_temporary
3551 : diag::err_lvalue_reference_bind_to_unrelated)
3552 << DestType.getNonReferenceType()
3553 << Args[0]->getType()
3554 << Args[0]->getSourceRange();
3555 break;
3556
3557 case FK_RValueReferenceBindingToLValue:
3558 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3559 << Args[0]->getSourceRange();
3560 break;
3561
3562 case FK_ReferenceInitDropsQualifiers:
3563 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3564 << DestType.getNonReferenceType()
3565 << Args[0]->getType()
3566 << Args[0]->getSourceRange();
3567 break;
3568
3569 case FK_ReferenceInitFailed:
3570 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3571 << DestType.getNonReferenceType()
3572 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3573 << Args[0]->getType()
3574 << Args[0]->getSourceRange();
3575 break;
3576
3577 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003578 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3579 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003580 << DestType
3581 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3582 << Args[0]->getType()
3583 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003584 break;
3585
3586 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003587 SourceRange R;
3588
3589 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3590 R = SourceRange(InitList->getInit(1)->getLocStart(),
3591 InitList->getLocEnd());
3592 else
3593 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003594
3595 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003596 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003597 break;
3598 }
3599
3600 case FK_ReferenceBindingToInitList:
3601 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3602 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3603 break;
3604
3605 case FK_InitListBadDestinationType:
3606 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3607 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3608 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003609
3610 case FK_ConstructorOverloadFailed: {
3611 SourceRange ArgsRange;
3612 if (NumArgs)
3613 ArgsRange = SourceRange(Args[0]->getLocStart(),
3614 Args[NumArgs - 1]->getLocEnd());
3615
3616 // FIXME: Using "DestType" for the entity we're printing is probably
3617 // bad.
3618 switch (FailedOverloadResult) {
3619 case OR_Ambiguous:
3620 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3621 << DestType << ArgsRange;
3622 S.PrintOverloadCandidates(FailedCandidateSet, true);
3623 break;
3624
3625 case OR_No_Viable_Function:
3626 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3627 << DestType << ArgsRange;
3628 S.PrintOverloadCandidates(FailedCandidateSet, false);
3629 break;
3630
3631 case OR_Deleted: {
3632 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3633 << true << DestType << ArgsRange;
3634 OverloadCandidateSet::iterator Best;
3635 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3636 Kind.getLocation(),
3637 Best);
3638 if (Ovl == OR_Deleted) {
3639 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3640 << Best->Function->isDeleted();
3641 } else {
3642 llvm_unreachable("Inconsistent overload resolution?");
3643 }
3644 break;
3645 }
3646
3647 case OR_Success:
3648 llvm_unreachable("Conversion did not fail!");
3649 break;
3650 }
3651 break;
3652 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003653
3654 case FK_DefaultInitOfConst:
3655 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3656 << DestType;
3657 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003658 }
3659
3660 return true;
3661}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003662
3663//===----------------------------------------------------------------------===//
3664// Initialization helper functions
3665//===----------------------------------------------------------------------===//
3666Sema::OwningExprResult
3667Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3668 SourceLocation EqualLoc,
3669 OwningExprResult Init) {
3670 if (Init.isInvalid())
3671 return ExprError();
3672
3673 Expr *InitE = (Expr *)Init.get();
3674 assert(InitE && "No initialization expression?");
3675
3676 if (EqualLoc.isInvalid())
3677 EqualLoc = InitE->getLocStart();
3678
3679 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3680 EqualLoc);
3681 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3682 Init.release();
3683 return Seq.Perform(*this, Entity, Kind,
3684 MultiExprArg(*this, (void**)&InitE, 1));
3685}