blob: 04506908f07b91ebde7a2a8da35f885817182964 [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.
195 if (DeclType->isReferenceType())
Douglas Gregor739d8282009-09-23 23:04:10 +0000196 return CheckReferenceInit(Init, DeclType, InitLoc,
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000197 /*SuppressUserConversions=*/false,
198 /*AllowExplicit=*/DirectInit,
199 /*ForceRValue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000201 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
202 // of unknown size ("[]") or an object type that is not a variable array type.
203 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
204 return Diag(InitLoc, diag::err_variable_object_no_init)
205 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000207 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
208 if (!InitList) {
209 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000210 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
211 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000212 return false;
213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000215 // C++ [dcl.init]p14:
216 // -- If the destination type is a (possibly cv-qualified) class
217 // type:
218 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
219 QualType DeclTypeC = Context.getCanonicalType(DeclType);
220 QualType InitTypeC = Context.getCanonicalType(Init->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000222 // -- If the initialization is direct-initialization, or if it is
223 // copy-initialization where the cv-unqualified version of the
224 // source type is the same class as, or a derived class of, the
225 // class of the destination, constructors are considered.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000226 if ((DeclTypeC.getLocalUnqualifiedType()
227 == InitTypeC.getLocalUnqualifiedType()) ||
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000228 IsDerivedFrom(InitTypeC, DeclTypeC)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000229 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000230 cast<CXXRecordDecl>(DeclType->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Anders Carlssonbffed8a2009-05-27 16:38:58 +0000232 // No need to make a CXXConstructExpr if both the ctor and dtor are
233 // trivial.
234 if (RD->hasTrivialConstructor() && RD->hasTrivialDestructor())
235 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Douglas Gregor39da0b82009-09-09 23:08:42 +0000237 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
238
Douglas Gregor20093b42009-12-09 23:02:17 +0000239 // FIXME: Poor location information
240 InitializationKind InitKind
241 = InitializationKind::CreateCopy(Init->getLocStart(),
242 SourceLocation());
243 if (DirectInit)
244 InitKind = InitializationKind::CreateDirect(Init->getLocStart(),
245 SourceLocation(),
246 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000247 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000248 = PerformInitializationByConstructor(DeclType,
249 MultiExprArg(*this,
250 (void **)&Init, 1),
251 InitLoc, Init->getSourceRange(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000252 InitEntity, InitKind,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000253 ConstructorArgs);
Anders Carlsson2078bb92009-05-27 16:10:08 +0000254 if (!Constructor)
255 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000256
257 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000258 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000259 DeclType, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000260 move_arg(ConstructorArgs));
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000261 if (InitResult.isInvalid())
262 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000264 Init = InitResult.takeAs<Expr>();
Anders Carlsson2078bb92009-05-27 16:10:08 +0000265 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000266 }
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000268 // -- Otherwise (i.e., for the remaining copy-initialization
269 // cases), user-defined conversion sequences that can
270 // convert from the source type to the destination type or
271 // (when a conversion function is used) to a derived class
272 // thereof are enumerated as described in 13.3.1.4, and the
273 // best one is chosen through overload resolution
274 // (13.3). If the conversion cannot be done or is
275 // ambiguous, the initialization is ill-formed. The
276 // function selected is called with the initializer
277 // expression as its argument; if the function is a
278 // constructor, the call initializes a temporary of the
279 // destination type.
Mike Stump390b4cc2009-05-16 07:39:55 +0000280 // FIXME: We're pretending to do copy elision here; return to this when we
281 // have ASTs for such things.
Douglas Gregor68647482009-12-16 03:45:30 +0000282 if (!PerformImplicitConversion(Init, DeclType, Sema::AA_Initializing))
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000283 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000285 if (InitEntity)
286 return Diag(InitLoc, diag::err_cannot_initialize_decl)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000287 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
288 << Init->getType() << Init->getSourceRange();
289 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000290 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
291 << Init->getType() << Init->getSourceRange();
292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000294 // C99 6.7.8p16.
295 if (DeclType->isArrayType())
296 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000297 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattner95e8d652009-02-24 22:46:58 +0000299 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 }
301
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000302 bool hadError = CheckInitList(Entity, InitList, DeclType);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000303 Init = InitList;
304 return hadError;
305}
306
307//===----------------------------------------------------------------------===//
308// Semantic checking for initializer lists.
309//===----------------------------------------------------------------------===//
310
Douglas Gregor9e80f722009-01-29 01:05:33 +0000311/// @brief Semantic checking for initializer lists.
312///
313/// The InitListChecker class contains a set of routines that each
314/// handle the initialization of a certain kind of entity, e.g.,
315/// arrays, vectors, struct/union types, scalars, etc. The
316/// InitListChecker itself performs a recursive walk of the subobject
317/// structure of the type to be initialized, while stepping through
318/// the initializer list one element at a time. The IList and Index
319/// parameters to each of the Check* routines contain the active
320/// (syntactic) initializer list and the index into that initializer
321/// list that represents the current initializer. Each routine is
322/// responsible for moving that Index forward as it consumes elements.
323///
324/// Each Check* routine also has a StructuredList/StructuredIndex
325/// arguments, which contains the current the "structured" (semantic)
326/// initializer list and the index into that initializer list where we
327/// are copying initializers as we map them over to the semantic
328/// list. Once we have completed our recursive walk of the subobject
329/// structure, we will have constructed a full semantic initializer
330/// list.
331///
332/// C99 designators cause changes in the initializer list traversal,
333/// because they make the initialization "jump" into a specific
334/// subobject and then continue the initialization from that
335/// point. CheckDesignatedInitializer() recursively steps into the
336/// designated subobject and manages backing out the recursion to
337/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000338namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000339class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000340 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000341 bool hadError;
342 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
343 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
345 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000346 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000347 unsigned &StructuredIndex,
348 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000349 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000350 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000351 unsigned &StructuredIndex,
352 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000353 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
354 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000355 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000356 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 CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000360 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000361 InitListExpr *StructuredList,
362 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000363 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000364 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000365 InitListExpr *StructuredList,
366 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000368 unsigned &Index,
369 InitListExpr *StructuredList,
370 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000371 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000372 InitListExpr *StructuredList,
373 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000374 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
375 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000376 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000377 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000378 unsigned &StructuredIndex,
379 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
381 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000382 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000383 InitListExpr *StructuredList,
384 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000386 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000387 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000388 RecordDecl::field_iterator *NextField,
389 llvm::APSInt *NextElementIndex,
390 unsigned &Index,
391 InitListExpr *StructuredList,
392 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000393 bool FinishSubobjectInit,
394 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000395 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
396 QualType CurrentObjectType,
397 InitListExpr *StructuredList,
398 unsigned StructuredIndex,
399 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000400 void UpdateStructuredListElement(InitListExpr *StructuredList,
401 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000402 Expr *expr);
403 int numArrayElements(QualType DeclType);
404 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000405
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000406 void FillInValueInitializations(const InitializedEntity &Entity,
407 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000408public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000409 InitListChecker(Sema &S, const InitializedEntity &Entity,
410 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000411 bool HadError() { return hadError; }
412
413 // @brief Retrieves the fully-structured initializer list used for
414 // semantic analysis and code generation.
415 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
416};
Chris Lattner8b419b92009-02-24 22:48:58 +0000417} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000418
Douglas Gregor4c678342009-01-28 21:54:33 +0000419/// Recursively replaces NULL values within the given initializer list
420/// with expressions that perform value-initialization of the
421/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000422void
423InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
424 InitListExpr *ILE,
425 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000426 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000427 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000428 SourceLocation Loc = ILE->getSourceRange().getBegin();
429 if (ILE->getSyntacticForm())
430 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Ted Kremenek6217b802009-07-29 21:53:49 +0000432 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000433 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump1eb44332009-09-09 15:08:12 +0000434 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000435 Field = RType->getDecl()->field_begin(),
436 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000437 Field != FieldEnd; ++Field) {
438 if (Field->isUnnamedBitfield())
439 continue;
440
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441 InitializedEntity MemberEntity
442 = InitializedEntity::InitializeMember(*Field, &Entity);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000443 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000444 // FIXME: We probably don't need to handle references
445 // specially here, since value-initialization of references is
446 // handled in InitializationSequence.
Douglas Gregor930d8b52009-01-30 22:09:00 +0000447 if (Field->getType()->isReferenceType()) {
448 // C++ [dcl.init.aggr]p9:
449 // If an incomplete or empty initializer-list leaves a
450 // member of reference type uninitialized, the program is
Mike Stump1eb44332009-09-09 15:08:12 +0000451 // ill-formed.
Chris Lattner08202542009-02-24 22:50:46 +0000452 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000453 << Field->getType()
454 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000455 SemaRef.Diag(Field->getLocation(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000456 diag::note_uninit_reference_member);
457 hadError = true;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000458 return;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000459 }
460
461 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
462 true);
463 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
464 if (!InitSeq) {
465 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000466 hadError = true;
467 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000468 }
Douglas Gregor87fd7032009-02-02 17:43:21 +0000469
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000470 Sema::OwningExprResult MemberInit
471 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
472 Sema::MultiExprArg(SemaRef, 0, 0));
473 if (MemberInit.isInvalid()) {
474 hadError = 0;
475 return;
476 }
477
478 if (hadError) {
479 // Do nothing
480 } else if (Init < NumInits) {
481 ILE->setInit(Init, MemberInit.takeAs<Expr>());
482 } else if (InitSeq.getKind()
483 == InitializationSequence::ConstructorInitialization) {
484 // Value-initialization requires a constructor call, so
485 // extend the initializer list to include the constructor
486 // call and make a note that we'll need to take another pass
487 // through the initializer list.
488 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
489 RequiresSecondPass = true;
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491 } else if (InitListExpr *InnerILE
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000492 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000493 FillInValueInitializations(MemberEntity, InnerILE,
494 RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 ++Init;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000496
497 // Only look at the first initialization of a union.
498 if (RType->getDecl()->isUnion())
499 break;
Douglas Gregor4c678342009-01-28 21:54:33 +0000500 }
501
502 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000503 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000504
505 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000507 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000508 unsigned NumInits = ILE->getNumInits();
509 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000510 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000511 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000512 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
513 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000514 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
515 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000516 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000517 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000518 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000519 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
520 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000521 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000524
Douglas Gregor87fd7032009-02-02 17:43:21 +0000525 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000526 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
527 ElementEntity.setElementIndex(Init);
528
Douglas Gregor87fd7032009-02-02 17:43:21 +0000529 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000530 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
531 true);
532 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
533 if (!InitSeq) {
534 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000535 hadError = true;
536 return;
537 }
538
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000539 Sema::OwningExprResult ElementInit
540 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
541 Sema::MultiExprArg(SemaRef, 0, 0));
542 if (ElementInit.isInvalid()) {
543 hadError = 0;
544 return;
545 }
546
547 if (hadError) {
548 // Do nothing
549 } else if (Init < NumInits) {
550 ILE->setInit(Init, ElementInit.takeAs<Expr>());
551 } else if (InitSeq.getKind()
552 == InitializationSequence::ConstructorInitialization) {
553 // Value-initialization requires a constructor call, so
554 // extend the initializer list to include the constructor
555 // call and make a note that we'll need to take another pass
556 // through the initializer list.
557 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
558 RequiresSecondPass = true;
559 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000560 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000561 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
562 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000563 }
564}
565
Chris Lattner68355a52009-01-29 05:10:57 +0000566
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000567InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
568 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000569 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000570 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000571
Eli Friedmanb85f7072008-05-19 19:16:24 +0000572 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000573 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000575 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000576 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
577 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000578
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000579 if (!hadError) {
580 bool RequiresSecondPass = false;
581 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
582 if (RequiresSecondPass)
583 FillInValueInitializations(Entity, FullyStructuredList,
584 RequiresSecondPass);
585 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000586}
587
588int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000589 // FIXME: use a proper constant
590 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000591 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000592 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000593 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
594 }
595 return maxElements;
596}
597
598int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000599 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000600 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000601 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000602 Field = structDecl->field_begin(),
603 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000604 Field != FieldEnd; ++Field) {
605 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
606 ++InitializableMembers;
607 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000608 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000609 return std::min(InitializableMembers, 1);
610 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000611}
612
Mike Stump1eb44332009-09-09 15:08:12 +0000613void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000614 QualType T, unsigned &Index,
615 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000616 unsigned &StructuredIndex,
617 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000618 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Steve Naroff0cca7492008-05-01 22:18:59 +0000620 if (T->isArrayType())
621 maxElements = numArrayElements(T);
622 else if (T->isStructureType() || T->isUnionType())
623 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000624 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000625 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000626 else
627 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000628
Eli Friedman402256f2008-05-25 13:49:22 +0000629 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000630 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000631 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000632 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000633 hadError = true;
634 return;
635 }
636
Douglas Gregor4c678342009-01-28 21:54:33 +0000637 // Build a structured initializer list corresponding to this subobject.
638 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000639 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
640 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000641 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
642 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000643 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000644
Douglas Gregor4c678342009-01-28 21:54:33 +0000645 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000646 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000648 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000649 StructuredSubobjectInitIndex,
650 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000651 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000652 StructuredSubobjectInitList->setType(T);
653
Douglas Gregored8a93d2009-03-01 17:12:46 +0000654 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000655 // range corresponds with the end of the last initializer it used.
656 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000657 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000658 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
659 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
660 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000661}
662
Steve Naroffa647caa2008-05-06 00:23:44 +0000663void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000664 unsigned &Index,
665 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000666 unsigned &StructuredIndex,
667 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000668 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000669 SyntacticToSemantic[IList] = StructuredList;
670 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000671 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000672 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000673 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000675 if (hadError)
676 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000677
Eli Friedman638e1442008-05-25 13:22:35 +0000678 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000679 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000680 if (StructuredIndex == 1 &&
681 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000682 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000683 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000684 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000685 hadError = true;
686 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000687 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000688 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000689 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000690 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000691 // Don't complain for incomplete types, since we'll get an error
692 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000693 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000694 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000695 CurrentObjectType->isArrayType()? 0 :
696 CurrentObjectType->isVectorType()? 1 :
697 CurrentObjectType->isScalarType()? 2 :
698 CurrentObjectType->isUnionType()? 3 :
699 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000700
701 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000702 if (SemaRef.getLangOptions().CPlusPlus) {
703 DK = diag::err_excess_initializers;
704 hadError = true;
705 }
Nate Begeman08634522009-07-07 21:53:06 +0000706 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
707 DK = diag::err_excess_initializers;
708 hadError = true;
709 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000710
Chris Lattner08202542009-02-24 22:50:46 +0000711 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000712 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000713 }
714 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000715
Eli Friedman759f2522009-05-16 11:45:48 +0000716 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000717 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000718 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000719 << CodeModificationHint::CreateRemoval(IList->getLocStart())
720 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000721}
722
Eli Friedmanb85f7072008-05-19 19:16:24 +0000723void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000724 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000725 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000726 unsigned &Index,
727 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000728 unsigned &StructuredIndex,
729 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000730 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000731 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000732 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000733 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000734 } else if (DeclType->isAggregateType()) {
735 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000736 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000737 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000738 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000739 StructuredList, StructuredIndex,
740 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000741 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000742 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000743 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000744 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000745 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
746 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000747 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000748 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000749 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
750 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000751 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000752 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000753 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000754 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000755 } else if (DeclType->isRecordType()) {
756 // C++ [dcl.init]p14:
757 // [...] If the class is an aggregate (8.5.1), and the initializer
758 // is a brace-enclosed list, see 8.5.1.
759 //
760 // Note: 8.5.1 is handled below; here, we diagnose the case where
761 // we have an initializer list and a destination type that is not
762 // an aggregate.
763 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000764 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000765 << DeclType << IList->getSourceRange();
766 hadError = true;
767 } else if (DeclType->isReferenceType()) {
768 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000769 } else {
770 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000771 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000772 assert(0 && "Unsupported initializer type");
773 }
774}
775
Eli Friedmanb85f7072008-05-19 19:16:24 +0000776void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000777 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000778 unsigned &Index,
779 InitListExpr *StructuredList,
780 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000781 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000782 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
783 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000784 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000785 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000786 = getStructuredSubobjectInit(IList, Index, ElemType,
787 StructuredList, StructuredIndex,
788 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000789 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000790 newStructuredList, newStructuredIndex);
791 ++StructuredIndex;
792 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000793 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
794 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000795 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000796 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000797 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000798 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000799 } else if (ElemType->isReferenceType()) {
800 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000801 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000802 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000803 // C++ [dcl.init.aggr]p12:
804 // All implicit type conversions (clause 4) are considered when
805 // initializing the aggregate member with an ini- tializer from
806 // an initializer-list. If the initializer can initialize a
807 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000808 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000809 = SemaRef.TryCopyInitialization(expr, ElemType,
810 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000811 /*ForceRValue=*/false,
812 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000813
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000815 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000816 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000817 hadError = true;
818 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
819 ++Index;
820 return;
821 }
822
823 // Fall through for subaggregate initialization
824 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000825 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000826 //
827 // The initializer for a structure or union object that has
828 // automatic storage duration shall be either an initializer
829 // list as described below, or a single expression that has
830 // compatible structure or union type. In the latter case, the
831 // initial value of the object, including unnamed members, is
832 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000833 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000834 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000835 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
836 ++Index;
837 return;
838 }
839
840 // Fall through for subaggregate initialization
841 }
842
843 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000844 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000845 // [...] Otherwise, if the member is itself a non-empty
846 // subaggregate, brace elision is assumed and the initializer is
847 // considered for the initialization of the first member of
848 // the subaggregate.
849 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000850 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000851 StructuredIndex);
852 ++StructuredIndex;
853 } else {
854 // We cannot initialize this element, so let
855 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000856 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000857 hadError = true;
858 ++Index;
859 ++StructuredIndex;
860 }
861 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000862}
863
Douglas Gregor930d8b52009-01-30 22:09:00 +0000864void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000865 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000866 InitListExpr *StructuredList,
867 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000868 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000869 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000870 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000871 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000872 diag::err_many_braces_around_scalar_init)
873 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000874 hadError = true;
875 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000876 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000877 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000878 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000879 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000880 diag::err_designator_for_scalar_init)
881 << DeclType << expr->getSourceRange();
882 hadError = true;
883 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000884 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000885 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000886 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000887
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000888 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000889 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000890 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000891 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000892 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000893 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000894 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000895 if (hadError)
896 ++StructuredIndex;
897 else
898 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000899 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000900 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000901 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000902 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000903 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000904 ++Index;
905 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000906 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000907 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000908}
909
Douglas Gregor930d8b52009-01-30 22:09:00 +0000910void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
911 unsigned &Index,
912 InitListExpr *StructuredList,
913 unsigned &StructuredIndex) {
914 if (Index < IList->getNumInits()) {
915 Expr *expr = IList->getInit(Index);
916 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000917 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000918 << DeclType << IList->getSourceRange();
919 hadError = true;
920 ++Index;
921 ++StructuredIndex;
922 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000923 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000924
925 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000926 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000927 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000928 /*SuppressUserConversions=*/false,
929 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000930 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000931 hadError = true;
932 else if (savExpr != expr) {
933 // The type was promoted, update initializer list.
934 IList->setInit(Index, expr);
935 }
936 if (hadError)
937 ++StructuredIndex;
938 else
939 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
940 ++Index;
941 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000942 // FIXME: It would be wonderful if we could point at the actual member. In
943 // general, it would be useful to pass location information down the stack,
944 // so that we know the location (or decl) of the "current object" being
945 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000946 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000947 diag::err_init_reference_member_uninitialized)
948 << DeclType
949 << IList->getSourceRange();
950 hadError = true;
951 ++Index;
952 ++StructuredIndex;
953 return;
954 }
955}
956
Mike Stump1eb44332009-09-09 15:08:12 +0000957void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000958 unsigned &Index,
959 InitListExpr *StructuredList,
960 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000961 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000962 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000963 unsigned maxElements = VT->getNumElements();
964 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000965 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Nate Begeman2ef13e52009-08-10 23:49:36 +0000967 if (!SemaRef.getLangOptions().OpenCL) {
968 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
969 // Don't attempt to go past the end of the init list
970 if (Index >= IList->getNumInits())
971 break;
972 CheckSubElementType(IList, elementType, Index,
973 StructuredList, StructuredIndex);
974 }
975 } else {
976 // OpenCL initializers allows vectors to be constructed from vectors.
977 for (unsigned i = 0; i < maxElements; ++i) {
978 // Don't attempt to go past the end of the init list
979 if (Index >= IList->getNumInits())
980 break;
981 QualType IType = IList->getInit(Index)->getType();
982 if (!IType->isVectorType()) {
983 CheckSubElementType(IList, elementType, Index,
984 StructuredList, StructuredIndex);
985 ++numEltsInit;
986 } else {
John McCall183700f2009-09-21 23:43:11 +0000987 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000988 unsigned numIElts = IVT->getNumElements();
989 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
990 numIElts);
991 CheckSubElementType(IList, VecType, Index,
992 StructuredList, StructuredIndex);
993 numEltsInit += numIElts;
994 }
995 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000996 }
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Nate Begeman2ef13e52009-08-10 23:49:36 +0000998 // OpenCL & AltiVec require all elements to be initialized.
999 if (numEltsInit != maxElements)
1000 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
1001 SemaRef.Diag(IList->getSourceRange().getBegin(),
1002 diag::err_vector_incorrect_num_initializers)
1003 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001004 }
1005}
1006
Mike Stump1eb44332009-09-09 15:08:12 +00001007void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001008 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001009 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001010 unsigned &Index,
1011 InitListExpr *StructuredList,
1012 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001013 // Check for the special-case of initializing an array with a string.
1014 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +00001015 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
1016 SemaRef.Context)) {
1017 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001018 // We place the string literal directly into the resulting
1019 // initializer list. This is the only place where the structure
1020 // of the structured initializer list doesn't match exactly,
1021 // because doing so would involve allocating one character
1022 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001023 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001024 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001025 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001026 return;
1027 }
1028 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001029 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +00001030 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001031 // Check for VLAs; in standard C it would be possible to check this
1032 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1033 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001034 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001035 diag::err_variable_object_no_init)
1036 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001037 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001038 ++Index;
1039 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001040 return;
1041 }
1042
Douglas Gregor05c13a32009-01-22 00:58:24 +00001043 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001044 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1045 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001046 bool maxElementsKnown = false;
1047 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +00001048 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001049 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001050 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001051 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 maxElementsKnown = true;
1053 }
1054
Chris Lattner08202542009-02-24 22:50:46 +00001055 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001056 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001057 while (Index < IList->getNumInits()) {
1058 Expr *Init = IList->getInit(Index);
1059 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001060 // If we're not the subobject that matches up with the '{' for
1061 // the designator, we shouldn't be handling the
1062 // designator. Return immediately.
1063 if (!SubobjectIsDesignatorContext)
1064 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001065
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001066 // Handle this designated initializer. elementIndex will be
1067 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +00001068 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001069 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001070 StructuredList, StructuredIndex, true,
1071 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001072 hadError = true;
1073 continue;
1074 }
1075
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001076 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1077 maxElements.extend(elementIndex.getBitWidth());
1078 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1079 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001080 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001081
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001082 // If the array is of incomplete type, keep track of the number of
1083 // elements in the initializer.
1084 if (!maxElementsKnown && elementIndex > maxElements)
1085 maxElements = elementIndex;
1086
Douglas Gregor05c13a32009-01-22 00:58:24 +00001087 continue;
1088 }
1089
1090 // If we know the maximum number of elements, and we've already
1091 // hit it, stop consuming elements in the initializer list.
1092 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001093 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001094
1095 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001096 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001097 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001098 ++elementIndex;
1099
1100 // If the array is of incomplete type, keep track of the number of
1101 // elements in the initializer.
1102 if (!maxElementsKnown && elementIndex > maxElements)
1103 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001104 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001105 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001106 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001107 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001108 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001109 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001110 // Sizing an array implicitly to zero is not allowed by ISO C,
1111 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001112 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001113 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001114 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001115
Mike Stump1eb44332009-09-09 15:08:12 +00001116 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001117 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001118 }
1119}
1120
Mike Stump1eb44332009-09-09 15:08:12 +00001121void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1122 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001123 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001124 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001125 unsigned &Index,
1126 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001127 unsigned &StructuredIndex,
1128 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001129 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Eli Friedmanb85f7072008-05-19 19:16:24 +00001131 // If the record is invalid, some of it's members are invalid. To avoid
1132 // confusion, we forgo checking the intializer for the entire record.
1133 if (structDecl->isInvalidDecl()) {
1134 hadError = true;
1135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001136 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001137
1138 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1139 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001140 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001141 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001142 Field != FieldEnd; ++Field) {
1143 if (Field->getDeclName()) {
1144 StructuredList->setInitializedFieldInUnion(*Field);
1145 break;
1146 }
1147 }
1148 return;
1149 }
1150
Douglas Gregor05c13a32009-01-22 00:58:24 +00001151 // If structDecl is a forward declaration, this loop won't do
1152 // anything except look at designated initializers; That's okay,
1153 // because an error should get printed out elsewhere. It might be
1154 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001155 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001156 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001157 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001158 while (Index < IList->getNumInits()) {
1159 Expr *Init = IList->getInit(Index);
1160
1161 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001162 // If we're not the subobject that matches up with the '{' for
1163 // the designator, we shouldn't be handling the
1164 // designator. Return immediately.
1165 if (!SubobjectIsDesignatorContext)
1166 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001167
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001168 // Handle this designated initializer. Field will be updated to
1169 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001170 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001171 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001172 StructuredList, StructuredIndex,
1173 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 hadError = true;
1175
Douglas Gregordfb5e592009-02-12 19:00:39 +00001176 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001177 continue;
1178 }
1179
1180 if (Field == FieldEnd) {
1181 // We've run out of fields. We're done.
1182 break;
1183 }
1184
Douglas Gregordfb5e592009-02-12 19:00:39 +00001185 // We've already initialized a member of a union. We're done.
1186 if (InitializedSomething && DeclType->isUnionType())
1187 break;
1188
Douglas Gregor44b43212008-12-11 16:49:14 +00001189 // If we've hit the flexible array member at the end, we're done.
1190 if (Field->getType()->isIncompleteArrayType())
1191 break;
1192
Douglas Gregor0bb76892009-01-29 16:53:55 +00001193 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001194 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001195 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001196 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001197 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001198
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001199 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001200 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001201 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001202
1203 if (DeclType->isUnionType()) {
1204 // Initialize the first field within the union.
1205 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001206 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001207
1208 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001209 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001210
Mike Stump1eb44332009-09-09 15:08:12 +00001211 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001212 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001213 return;
1214
1215 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001216 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001217 (!isa<InitListExpr>(IList->getInit(Index)) ||
1218 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001220 diag::err_flexible_array_init_nonempty)
1221 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001222 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001223 << *Field;
1224 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001225 ++Index;
1226 return;
1227 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001228 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001229 diag::ext_flexible_array_init)
1230 << IList->getInit(Index)->getSourceRange().getBegin();
1231 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1232 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001233 }
1234
Douglas Gregora6457962009-03-20 00:32:56 +00001235 if (isa<InitListExpr>(IList->getInit(Index)))
1236 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1237 StructuredIndex);
1238 else
1239 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1240 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001241}
Steve Naroff0cca7492008-05-01 22:18:59 +00001242
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001243/// \brief Expand a field designator that refers to a member of an
1244/// anonymous struct or union into a series of field designators that
1245/// refers to the field within the appropriate subobject.
1246///
1247/// Field/FieldIndex will be updated to point to the (new)
1248/// currently-designated field.
1249static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001250 DesignatedInitExpr *DIE,
1251 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001252 FieldDecl *Field,
1253 RecordDecl::field_iterator &FieldIter,
1254 unsigned &FieldIndex) {
1255 typedef DesignatedInitExpr::Designator Designator;
1256
1257 // Build the path from the current object to the member of the
1258 // anonymous struct/union (backwards).
1259 llvm::SmallVector<FieldDecl *, 4> Path;
1260 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001262 // Build the replacement designators.
1263 llvm::SmallVector<Designator, 4> Replacements;
1264 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1265 FI = Path.rbegin(), FIEnd = Path.rend();
1266 FI != FIEnd; ++FI) {
1267 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001268 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001269 DIE->getDesignator(DesigIdx)->getDotLoc(),
1270 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1271 else
1272 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1273 SourceLocation()));
1274 Replacements.back().setField(*FI);
1275 }
1276
1277 // Expand the current designator into the set of replacement
1278 // designators, so we have a full subobject path down to where the
1279 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001280 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001281 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001283 // Update FieldIter/FieldIndex;
1284 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001285 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001286 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001287 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001288 FieldIter != FEnd; ++FieldIter) {
1289 if (FieldIter->isUnnamedBitfield())
1290 continue;
1291
1292 if (*FieldIter == Path.back())
1293 return;
1294
1295 ++FieldIndex;
1296 }
1297
1298 assert(false && "Unable to find anonymous struct/union field");
1299}
1300
Douglas Gregor05c13a32009-01-22 00:58:24 +00001301/// @brief Check the well-formedness of a C99 designated initializer.
1302///
1303/// Determines whether the designated initializer @p DIE, which
1304/// resides at the given @p Index within the initializer list @p
1305/// IList, is well-formed for a current object of type @p DeclType
1306/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001307/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001308/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001309///
1310/// @param IList The initializer list in which this designated
1311/// initializer occurs.
1312///
Douglas Gregor71199712009-04-15 04:56:10 +00001313/// @param DIE The designated initializer expression.
1314///
1315/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001316///
1317/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1318/// into which the designation in @p DIE should refer.
1319///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001320/// @param NextField If non-NULL and the first designator in @p DIE is
1321/// a field, this will be set to the field declaration corresponding
1322/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001323///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001324/// @param NextElementIndex If non-NULL and the first designator in @p
1325/// DIE is an array designator or GNU array-range designator, this
1326/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001327///
1328/// @param Index Index into @p IList where the designated initializer
1329/// @p DIE occurs.
1330///
Douglas Gregor4c678342009-01-28 21:54:33 +00001331/// @param StructuredList The initializer list expression that
1332/// describes all of the subobject initializers in the order they'll
1333/// actually be initialized.
1334///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001335/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001336bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001337InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001338 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001339 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001340 QualType &CurrentObjectType,
1341 RecordDecl::field_iterator *NextField,
1342 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001343 unsigned &Index,
1344 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001345 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001346 bool FinishSubobjectInit,
1347 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001348 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001349 // Check the actual initialization for the designated object type.
1350 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001351
1352 // Temporarily remove the designator expression from the
1353 // initializer list that the child calls see, so that we don't try
1354 // to re-process the designator.
1355 unsigned OldIndex = Index;
1356 IList->setInit(OldIndex, DIE->getInit());
1357
1358 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001359 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001360
1361 // Restore the designated initializer expression in the syntactic
1362 // form of the initializer list.
1363 if (IList->getInit(OldIndex) != DIE->getInit())
1364 DIE->setInit(IList->getInit(OldIndex));
1365 IList->setInit(OldIndex, DIE);
1366
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001367 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001368 }
1369
Douglas Gregor71199712009-04-15 04:56:10 +00001370 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001371 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001372 "Need a non-designated initializer list to start from");
1373
Douglas Gregor71199712009-04-15 04:56:10 +00001374 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001375 // Determine the structural initializer list that corresponds to the
1376 // current subobject.
1377 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001378 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001379 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001380 SourceRange(D->getStartLocation(),
1381 DIE->getSourceRange().getEnd()));
1382 assert(StructuredList && "Expected a structured initializer list");
1383
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001384 if (D->isFieldDesignator()) {
1385 // C99 6.7.8p7:
1386 //
1387 // If a designator has the form
1388 //
1389 // . identifier
1390 //
1391 // then the current object (defined below) shall have
1392 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001393 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001394 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001395 if (!RT) {
1396 SourceLocation Loc = D->getDotLoc();
1397 if (Loc.isInvalid())
1398 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001399 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1400 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001401 ++Index;
1402 return true;
1403 }
1404
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 // Note: we perform a linear search of the fields here, despite
1406 // the fact that we have a faster lookup method, because we always
1407 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001408 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001409 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001410 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001411 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001412 Field = RT->getDecl()->field_begin(),
1413 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001414 for (; Field != FieldEnd; ++Field) {
1415 if (Field->isUnnamedBitfield())
1416 continue;
1417
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001418 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001419 break;
1420
1421 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001422 }
1423
Douglas Gregor4c678342009-01-28 21:54:33 +00001424 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001425 // There was no normal field in the struct with the designated
1426 // name. Perform another lookup for this name, which may find
1427 // something that we can't designate (e.g., a member function),
1428 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001429 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001430 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001431 if (Lookup.first == Lookup.second) {
1432 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001433 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001434 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001435 ++Index;
1436 return true;
1437 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1438 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1439 ->isAnonymousStructOrUnion()) {
1440 // Handle an field designator that refers to a member of an
1441 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001442 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001443 cast<FieldDecl>(*Lookup.first),
1444 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001445 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001446 } else {
1447 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001448 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001449 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001450 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001451 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001452 ++Index;
1453 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001454 }
1455 } else if (!KnownField &&
1456 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001457 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001458 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1459 Field, FieldIndex);
1460 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001461 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001462
1463 // All of the fields of a union are located at the same place in
1464 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001465 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001466 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001467 StructuredList->setInitializedFieldInUnion(*Field);
1468 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001469
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001470 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001471 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Douglas Gregor4c678342009-01-28 21:54:33 +00001473 // Make sure that our non-designated initializer list has space
1474 // for a subobject corresponding to this field.
1475 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001476 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001477
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001478 // This designator names a flexible array member.
1479 if (Field->getType()->isIncompleteArrayType()) {
1480 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001481 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001482 // We can't designate an object within the flexible array
1483 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001484 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001485 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001486 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001487 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001488 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001489 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001490 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001491 << *Field;
1492 Invalid = true;
1493 }
1494
1495 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1496 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001497 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001498 diag::err_flexible_array_init_needs_braces)
1499 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001500 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001501 << *Field;
1502 Invalid = true;
1503 }
1504
1505 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001506 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001507 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001508 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001509 diag::err_flexible_array_init_nonempty)
1510 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001511 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001512 << *Field;
1513 Invalid = true;
1514 }
1515
1516 if (Invalid) {
1517 ++Index;
1518 return true;
1519 }
1520
1521 // Initialize the array.
1522 bool prevHadError = hadError;
1523 unsigned newStructuredIndex = FieldIndex;
1524 unsigned OldIndex = Index;
1525 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001526 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001527 StructuredList, newStructuredIndex);
1528 IList->setInit(OldIndex, DIE);
1529 if (hadError && !prevHadError) {
1530 ++Field;
1531 ++FieldIndex;
1532 if (NextField)
1533 *NextField = Field;
1534 StructuredIndex = FieldIndex;
1535 return true;
1536 }
1537 } else {
1538 // Recurse to check later designated subobjects.
1539 QualType FieldType = (*Field)->getType();
1540 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001541 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1542 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001543 true, false))
1544 return true;
1545 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546
1547 // Find the position of the next field to be initialized in this
1548 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001549 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001550 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001551
1552 // If this the first designator, our caller will continue checking
1553 // the rest of this struct/class/union subobject.
1554 if (IsFirstDesignator) {
1555 if (NextField)
1556 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001557 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001558 return false;
1559 }
1560
Douglas Gregor34e79462009-01-28 23:36:17 +00001561 if (!FinishSubobjectInit)
1562 return false;
1563
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001564 // We've already initialized something in the union; we're done.
1565 if (RT->getDecl()->isUnion())
1566 return hadError;
1567
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001568 // Check the remaining fields within this class/struct/union subobject.
1569 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001570 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1571 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572 return hadError && !prevHadError;
1573 }
1574
1575 // C99 6.7.8p6:
1576 //
1577 // If a designator has the form
1578 //
1579 // [ constant-expression ]
1580 //
1581 // then the current object (defined below) shall have array
1582 // type and the expression shall be an integer constant
1583 // expression. If the array is of unknown size, any
1584 // nonnegative value is valid.
1585 //
1586 // Additionally, cope with the GNU extension that permits
1587 // designators of the form
1588 //
1589 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001590 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001591 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001592 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001593 << CurrentObjectType;
1594 ++Index;
1595 return true;
1596 }
1597
1598 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001599 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1600 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001601 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001602 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001603 DesignatedEndIndex = DesignatedStartIndex;
1604 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001605 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001606
Mike Stump1eb44332009-09-09 15:08:12 +00001607
1608 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001609 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001610 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001611 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001612 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001613
Chris Lattner3bf68932009-04-25 21:59:05 +00001614 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001615 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001616 }
1617
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001618 if (isa<ConstantArrayType>(AT)) {
1619 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001620 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1621 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1622 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1623 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1624 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001625 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001626 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001627 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001628 << IndexExpr->getSourceRange();
1629 ++Index;
1630 return true;
1631 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001632 } else {
1633 // Make sure the bit-widths and signedness match.
1634 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1635 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001636 else if (DesignatedStartIndex.getBitWidth() <
1637 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001638 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1639 DesignatedStartIndex.setIsUnsigned(true);
1640 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001641 }
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor4c678342009-01-28 21:54:33 +00001643 // Make sure that our non-designated initializer list has space
1644 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001645 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001646 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001647 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001648
Douglas Gregor34e79462009-01-28 23:36:17 +00001649 // Repeatedly perform subobject initializations in the range
1650 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001651
Douglas Gregor34e79462009-01-28 23:36:17 +00001652 // Move to the next designator
1653 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1654 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 while (DesignatedStartIndex <= DesignatedEndIndex) {
1656 // Recurse to check later designated subobjects.
1657 QualType ElementType = AT->getElementType();
1658 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001659 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1660 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001661 (DesignatedStartIndex == DesignatedEndIndex),
1662 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001663 return true;
1664
1665 // Move to the next index in the array that we'll be initializing.
1666 ++DesignatedStartIndex;
1667 ElementIndex = DesignatedStartIndex.getZExtValue();
1668 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001669
1670 // If this the first designator, our caller will continue checking
1671 // the rest of this array subobject.
1672 if (IsFirstDesignator) {
1673 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001674 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001675 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001676 return false;
1677 }
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Douglas Gregor34e79462009-01-28 23:36:17 +00001679 if (!FinishSubobjectInit)
1680 return false;
1681
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001682 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001683 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001684 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001685 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001686 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001687}
1688
Douglas Gregor4c678342009-01-28 21:54:33 +00001689// Get the structured initializer list for a subobject of type
1690// @p CurrentObjectType.
1691InitListExpr *
1692InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1693 QualType CurrentObjectType,
1694 InitListExpr *StructuredList,
1695 unsigned StructuredIndex,
1696 SourceRange InitRange) {
1697 Expr *ExistingInit = 0;
1698 if (!StructuredList)
1699 ExistingInit = SyntacticToSemantic[IList];
1700 else if (StructuredIndex < StructuredList->getNumInits())
1701 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor4c678342009-01-28 21:54:33 +00001703 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1704 return Result;
1705
1706 if (ExistingInit) {
1707 // We are creating an initializer list that initializes the
1708 // subobjects of the current object, but there was already an
1709 // initialization that completely initialized the current
1710 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001711 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001712 // struct X { int a, b; };
1713 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001714 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001715 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1716 // designated initializer re-initializes the whole
1717 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001718 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001719 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001720 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001721 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001722 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001723 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001724 << ExistingInit->getSourceRange();
1725 }
1726
Mike Stump1eb44332009-09-09 15:08:12 +00001727 InitListExpr *Result
1728 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001729 InitRange.getEnd());
1730
Douglas Gregor4c678342009-01-28 21:54:33 +00001731 Result->setType(CurrentObjectType);
1732
Douglas Gregorfa219202009-03-20 23:58:33 +00001733 // Pre-allocate storage for the structured initializer list.
1734 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001735 unsigned NumInits = 0;
1736 if (!StructuredList)
1737 NumInits = IList->getNumInits();
1738 else if (Index < IList->getNumInits()) {
1739 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1740 NumInits = SubList->getNumInits();
1741 }
1742
Mike Stump1eb44332009-09-09 15:08:12 +00001743 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001744 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1745 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1746 NumElements = CAType->getSize().getZExtValue();
1747 // Simple heuristic so that we don't allocate a very large
1748 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001749 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001750 NumElements = 0;
1751 }
John McCall183700f2009-09-21 23:43:11 +00001752 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001753 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001754 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001755 RecordDecl *RDecl = RType->getDecl();
1756 if (RDecl->isUnion())
1757 NumElements = 1;
1758 else
Mike Stump1eb44332009-09-09 15:08:12 +00001759 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001760 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001761 }
1762
Douglas Gregor08457732009-03-21 18:13:52 +00001763 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001764 NumElements = IList->getNumInits();
1765
1766 Result->reserveInits(NumElements);
1767
Douglas Gregor4c678342009-01-28 21:54:33 +00001768 // Link this new initializer list into the structured initializer
1769 // lists.
1770 if (StructuredList)
1771 StructuredList->updateInit(StructuredIndex, Result);
1772 else {
1773 Result->setSyntacticForm(IList);
1774 SyntacticToSemantic[IList] = Result;
1775 }
1776
1777 return Result;
1778}
1779
1780/// Update the initializer at index @p StructuredIndex within the
1781/// structured initializer list to the value @p expr.
1782void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1783 unsigned &StructuredIndex,
1784 Expr *expr) {
1785 // No structured initializer list to update
1786 if (!StructuredList)
1787 return;
1788
1789 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1790 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001791 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001792 diag::warn_initializer_overrides)
1793 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001794 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001795 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001796 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 << PrevInit->getSourceRange();
1798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Douglas Gregor4c678342009-01-28 21:54:33 +00001800 ++StructuredIndex;
1801}
1802
Douglas Gregor05c13a32009-01-22 00:58:24 +00001803/// Check that the given Index expression is a valid array designator
1804/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001805/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001806/// and produces a reasonable diagnostic if there is a
1807/// failure. Returns true if there was an error, false otherwise. If
1808/// everything went okay, Value will receive the value of the constant
1809/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001810static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001811CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001812 SourceLocation Loc = Index->getSourceRange().getBegin();
1813
1814 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001815 if (S.VerifyIntegerConstantExpression(Index, &Value))
1816 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001817
Chris Lattner3bf68932009-04-25 21:59:05 +00001818 if (Value.isSigned() && Value.isNegative())
1819 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001820 << Value.toString(10) << Index->getSourceRange();
1821
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001822 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001823 return false;
1824}
1825
1826Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1827 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001828 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001829 OwningExprResult Init) {
1830 typedef DesignatedInitExpr::Designator ASTDesignator;
1831
1832 bool Invalid = false;
1833 llvm::SmallVector<ASTDesignator, 32> Designators;
1834 llvm::SmallVector<Expr *, 32> InitExpressions;
1835
1836 // Build designators and check array designator expressions.
1837 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1838 const Designator &D = Desig.getDesignator(Idx);
1839 switch (D.getKind()) {
1840 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001841 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001842 D.getFieldLoc()));
1843 break;
1844
1845 case Designator::ArrayDesignator: {
1846 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1847 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001848 if (!Index->isTypeDependent() &&
1849 !Index->isValueDependent() &&
1850 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001851 Invalid = true;
1852 else {
1853 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001854 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001855 D.getRBracketLoc()));
1856 InitExpressions.push_back(Index);
1857 }
1858 break;
1859 }
1860
1861 case Designator::ArrayRangeDesignator: {
1862 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1863 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1864 llvm::APSInt StartValue;
1865 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001866 bool StartDependent = StartIndex->isTypeDependent() ||
1867 StartIndex->isValueDependent();
1868 bool EndDependent = EndIndex->isTypeDependent() ||
1869 EndIndex->isValueDependent();
1870 if ((!StartDependent &&
1871 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1872 (!EndDependent &&
1873 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001874 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001875 else {
1876 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001877 if (StartDependent || EndDependent) {
1878 // Nothing to compute.
1879 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001880 EndValue.extend(StartValue.getBitWidth());
1881 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1882 StartValue.extend(EndValue.getBitWidth());
1883
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001884 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001885 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001886 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001887 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1888 Invalid = true;
1889 } else {
1890 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001891 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001892 D.getEllipsisLoc(),
1893 D.getRBracketLoc()));
1894 InitExpressions.push_back(StartIndex);
1895 InitExpressions.push_back(EndIndex);
1896 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001897 }
1898 break;
1899 }
1900 }
1901 }
1902
1903 if (Invalid || Init.isInvalid())
1904 return ExprError();
1905
1906 // Clear out the expressions within the designation.
1907 Desig.ClearExprs(*this);
1908
1909 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001910 = DesignatedInitExpr::Create(Context,
1911 Designators.data(), Designators.size(),
1912 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001913 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001914 return Owned(DIE);
1915}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001916
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001917bool Sema::CheckInitList(const InitializedEntity &Entity,
1918 InitListExpr *&InitList, QualType &DeclType) {
1919 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001920 if (!CheckInitList.HadError())
1921 InitList = CheckInitList.getFullyStructuredList();
1922
1923 return CheckInitList.HadError();
1924}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001925
Douglas Gregor20093b42009-12-09 23:02:17 +00001926//===----------------------------------------------------------------------===//
1927// Initialization entity
1928//===----------------------------------------------------------------------===//
1929
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001930InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1931 const InitializedEntity &Parent)
1932 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1933{
1934 if (isa<ArrayType>(Parent.TL.getType())) {
1935 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1936 return;
1937 }
1938
1939 // FIXME: should be able to get type location information for vectors, too.
1940
1941 QualType T;
1942 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1943 T = AT->getElementType();
1944 else
1945 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1946
1947 // FIXME: Once we've gone through the effort to create the fake
1948 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1949 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1950 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1951 TL = DI->getTypeLoc();
1952}
1953
Douglas Gregor20093b42009-12-09 23:02:17 +00001954void InitializedEntity::InitDeclLoc() {
1955 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1956 "InitDeclLoc cannot be used with non-declaration entities.");
1957
1958 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1959 TL = DI->getTypeLoc();
1960 return;
1961 }
1962
1963 // FIXME: Once we've gone through the effort to create the fake
1964 // TypeSourceInfo, should we cache it in the declaration?
1965 // (If not, we "leak" it).
1966 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1967 .CreateTypeSourceInfo(VariableOrMember->getType());
1968 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1969 TL = DI->getTypeLoc();
1970}
1971
1972InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1973 CXXBaseSpecifier *Base)
1974{
1975 InitializedEntity Result;
1976 Result.Kind = EK_Base;
1977 Result.Base = Base;
1978 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1979 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1980 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1981 Result.TL = DI->getTypeLoc();
1982 return Result;
1983}
1984
Douglas Gregor99a2e602009-12-16 01:38:02 +00001985DeclarationName InitializedEntity::getName() const {
1986 switch (getKind()) {
1987 case EK_Variable:
1988 case EK_Parameter:
1989 case EK_Member:
1990 return VariableOrMember->getDeclName();
1991
1992 case EK_Result:
1993 case EK_Exception:
1994 case EK_Temporary:
1995 case EK_Base:
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001996 case EK_ArrayOrVectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001997 return DeclarationName();
1998 }
1999
2000 // Silence GCC warning
2001 return DeclarationName();
2002}
2003
Douglas Gregor20093b42009-12-09 23:02:17 +00002004//===----------------------------------------------------------------------===//
2005// Initialization sequence
2006//===----------------------------------------------------------------------===//
2007
2008void InitializationSequence::Step::Destroy() {
2009 switch (Kind) {
2010 case SK_ResolveAddressOfOverloadedFunction:
2011 case SK_CastDerivedToBaseRValue:
2012 case SK_CastDerivedToBaseLValue:
2013 case SK_BindReference:
2014 case SK_BindReferenceToTemporary:
2015 case SK_UserConversion:
2016 case SK_QualificationConversionRValue:
2017 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002018 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002019 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002020 case SK_ZeroInitialization:
Douglas Gregor20093b42009-12-09 23:02:17 +00002021 break;
2022
2023 case SK_ConversionSequence:
2024 delete ICS;
2025 }
2026}
2027
2028void InitializationSequence::AddAddressOverloadResolutionStep(
2029 FunctionDecl *Function) {
2030 Step S;
2031 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2032 S.Type = Function->getType();
2033 S.Function = Function;
2034 Steps.push_back(S);
2035}
2036
2037void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2038 bool IsLValue) {
2039 Step S;
2040 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2041 S.Type = BaseType;
2042 Steps.push_back(S);
2043}
2044
2045void InitializationSequence::AddReferenceBindingStep(QualType T,
2046 bool BindingTemporary) {
2047 Step S;
2048 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2049 S.Type = T;
2050 Steps.push_back(S);
2051}
2052
Eli Friedman03981012009-12-11 02:42:07 +00002053void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2054 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002055 Step S;
2056 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002057 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002058 S.Function = Function;
2059 Steps.push_back(S);
2060}
2061
2062void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2063 bool IsLValue) {
2064 Step S;
2065 S.Kind = IsLValue? SK_QualificationConversionLValue
2066 : SK_QualificationConversionRValue;
2067 S.Type = Ty;
2068 Steps.push_back(S);
2069}
2070
2071void InitializationSequence::AddConversionSequenceStep(
2072 const ImplicitConversionSequence &ICS,
2073 QualType T) {
2074 Step S;
2075 S.Kind = SK_ConversionSequence;
2076 S.Type = T;
2077 S.ICS = new ImplicitConversionSequence(ICS);
2078 Steps.push_back(S);
2079}
2080
Douglas Gregord87b61f2009-12-10 17:56:55 +00002081void InitializationSequence::AddListInitializationStep(QualType T) {
2082 Step S;
2083 S.Kind = SK_ListInitialization;
2084 S.Type = T;
2085 Steps.push_back(S);
2086}
2087
Douglas Gregor51c56d62009-12-14 20:49:26 +00002088void
2089InitializationSequence::AddConstructorInitializationStep(
2090 CXXConstructorDecl *Constructor,
2091 QualType T) {
2092 Step S;
2093 S.Kind = SK_ConstructorInitialization;
2094 S.Type = T;
2095 S.Function = Constructor;
2096 Steps.push_back(S);
2097}
2098
Douglas Gregor71d17402009-12-15 00:01:57 +00002099void InitializationSequence::AddZeroInitializationStep(QualType T) {
2100 Step S;
2101 S.Kind = SK_ZeroInitialization;
2102 S.Type = T;
2103 Steps.push_back(S);
2104}
2105
Douglas Gregor20093b42009-12-09 23:02:17 +00002106void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2107 OverloadingResult Result) {
2108 SequenceKind = FailedSequence;
2109 this->Failure = Failure;
2110 this->FailedOverloadResult = Result;
2111}
2112
2113//===----------------------------------------------------------------------===//
2114// Attempt initialization
2115//===----------------------------------------------------------------------===//
2116
2117/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002118static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002119 const InitializedEntity &Entity,
2120 const InitializationKind &Kind,
2121 InitListExpr *InitList,
2122 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002123 // FIXME: We only perform rudimentary checking of list
2124 // initializations at this point, then assume that any list
2125 // initialization of an array, aggregate, or scalar will be
2126 // well-formed. We we actually "perform" list initialization, we'll
2127 // do all of the necessary checking. C++0x initializer lists will
2128 // force us to perform more checking here.
2129 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2130
2131 QualType DestType = Entity.getType().getType();
2132
2133 // C++ [dcl.init]p13:
2134 // If T is a scalar type, then a declaration of the form
2135 //
2136 // T x = { a };
2137 //
2138 // is equivalent to
2139 //
2140 // T x = a;
2141 if (DestType->isScalarType()) {
2142 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2143 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2144 return;
2145 }
2146
2147 // Assume scalar initialization from a single value works.
2148 } else if (DestType->isAggregateType()) {
2149 // Assume aggregate initialization works.
2150 } else if (DestType->isVectorType()) {
2151 // Assume vector initialization works.
2152 } else if (DestType->isReferenceType()) {
2153 // FIXME: C++0x defines behavior for this.
2154 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2155 return;
2156 } else if (DestType->isRecordType()) {
2157 // FIXME: C++0x defines behavior for this
2158 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2159 }
2160
2161 // Add a general "list initialization" step.
2162 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002163}
2164
2165/// \brief Try a reference initialization that involves calling a conversion
2166/// function.
2167///
2168/// FIXME: look intos DRs 656, 896
2169static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2170 const InitializedEntity &Entity,
2171 const InitializationKind &Kind,
2172 Expr *Initializer,
2173 bool AllowRValues,
2174 InitializationSequence &Sequence) {
2175 QualType DestType = Entity.getType().getType();
2176 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2177 QualType T1 = cv1T1.getUnqualifiedType();
2178 QualType cv2T2 = Initializer->getType();
2179 QualType T2 = cv2T2.getUnqualifiedType();
2180
2181 bool DerivedToBase;
2182 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2183 T1, T2, DerivedToBase) &&
2184 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002185 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002186
2187 // Build the candidate set directly in the initialization sequence
2188 // structure, so that it will persist if we fail.
2189 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2190 CandidateSet.clear();
2191
2192 // Determine whether we are allowed to call explicit constructors or
2193 // explicit conversion operators.
2194 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2195
2196 const RecordType *T1RecordType = 0;
2197 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2198 // The type we're converting to is a class type. Enumerate its constructors
2199 // to see if there is a suitable conversion.
2200 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2201
2202 DeclarationName ConstructorName
2203 = S.Context.DeclarationNames.getCXXConstructorName(
2204 S.Context.getCanonicalType(T1).getUnqualifiedType());
2205 DeclContext::lookup_iterator Con, ConEnd;
2206 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2207 Con != ConEnd; ++Con) {
2208 // Find the constructor (which may be a template).
2209 CXXConstructorDecl *Constructor = 0;
2210 FunctionTemplateDecl *ConstructorTmpl
2211 = dyn_cast<FunctionTemplateDecl>(*Con);
2212 if (ConstructorTmpl)
2213 Constructor = cast<CXXConstructorDecl>(
2214 ConstructorTmpl->getTemplatedDecl());
2215 else
2216 Constructor = cast<CXXConstructorDecl>(*Con);
2217
2218 if (!Constructor->isInvalidDecl() &&
2219 Constructor->isConvertingConstructor(AllowExplicit)) {
2220 if (ConstructorTmpl)
2221 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2222 &Initializer, 1, CandidateSet);
2223 else
2224 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2225 }
2226 }
2227 }
2228
2229 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2230 // The type we're converting from is a class type, enumerate its conversion
2231 // functions.
2232 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2233
2234 // Determine the type we are converting to. If we are allowed to
2235 // convert to an rvalue, take the type that the destination type
2236 // refers to.
2237 QualType ToType = AllowRValues? cv1T1 : DestType;
2238
2239 const UnresolvedSet *Conversions
2240 = T2RecordDecl->getVisibleConversionFunctions();
2241 for (UnresolvedSet::iterator I = Conversions->begin(),
2242 E = Conversions->end();
2243 I != E; ++I) {
2244 NamedDecl *D = *I;
2245 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2246 if (isa<UsingShadowDecl>(D))
2247 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2248
2249 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2250 CXXConversionDecl *Conv;
2251 if (ConvTemplate)
2252 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2253 else
2254 Conv = cast<CXXConversionDecl>(*I);
2255
2256 // If the conversion function doesn't return a reference type,
2257 // it can't be considered for this conversion unless we're allowed to
2258 // consider rvalues.
2259 // FIXME: Do we need to make sure that we only consider conversion
2260 // candidates with reference-compatible results? That might be needed to
2261 // break recursion.
2262 if ((AllowExplicit || !Conv->isExplicit()) &&
2263 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2264 if (ConvTemplate)
2265 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2266 ToType, CandidateSet);
2267 else
2268 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2269 CandidateSet);
2270 }
2271 }
2272 }
2273
2274 SourceLocation DeclLoc = Initializer->getLocStart();
2275
2276 // Perform overload resolution. If it fails, return the failed result.
2277 OverloadCandidateSet::iterator Best;
2278 if (OverloadingResult Result
2279 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2280 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002281
Douglas Gregor20093b42009-12-09 23:02:17 +00002282 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002283
2284 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002285 if (isa<CXXConversionDecl>(Function))
2286 T2 = Function->getResultType();
2287 else
2288 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002289
2290 // Add the user-defined conversion step.
2291 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2292
2293 // Determine whether we need to perform derived-to-base or
2294 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002295 bool NewDerivedToBase = false;
2296 Sema::ReferenceCompareResult NewRefRelationship
2297 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2298 NewDerivedToBase);
2299 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2300 "Overload resolution picked a bad conversion function");
2301 (void)NewRefRelationship;
2302 if (NewDerivedToBase)
2303 Sequence.AddDerivedToBaseCastStep(
2304 S.Context.getQualifiedType(T1,
2305 T2.getNonReferenceType().getQualifiers()),
2306 /*isLValue=*/true);
2307
2308 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2309 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2310
2311 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2312 return OR_Success;
2313}
2314
2315/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2316static void TryReferenceInitialization(Sema &S,
2317 const InitializedEntity &Entity,
2318 const InitializationKind &Kind,
2319 Expr *Initializer,
2320 InitializationSequence &Sequence) {
2321 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2322
2323 QualType DestType = Entity.getType().getType();
2324 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2325 QualType T1 = cv1T1.getUnqualifiedType();
2326 QualType cv2T2 = Initializer->getType();
2327 QualType T2 = cv2T2.getUnqualifiedType();
2328 SourceLocation DeclLoc = Initializer->getLocStart();
2329
2330 // If the initializer is the address of an overloaded function, try
2331 // to resolve the overloaded function. If all goes well, T2 is the
2332 // type of the resulting function.
2333 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2334 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2335 T1,
2336 false);
2337 if (!Fn) {
2338 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2339 return;
2340 }
2341
2342 Sequence.AddAddressOverloadResolutionStep(Fn);
2343 cv2T2 = Fn->getType();
2344 T2 = cv2T2.getUnqualifiedType();
2345 }
2346
2347 // FIXME: Rvalue references
2348 bool ForceRValue = false;
2349
2350 // Compute some basic properties of the types and the initializer.
2351 bool isLValueRef = DestType->isLValueReferenceType();
2352 bool isRValueRef = !isLValueRef;
2353 bool DerivedToBase = false;
2354 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2355 Initializer->isLvalue(S.Context);
2356 Sema::ReferenceCompareResult RefRelationship
2357 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2358
2359 // C++0x [dcl.init.ref]p5:
2360 // A reference to type "cv1 T1" is initialized by an expression of type
2361 // "cv2 T2" as follows:
2362 //
2363 // - If the reference is an lvalue reference and the initializer
2364 // expression
2365 OverloadingResult ConvOvlResult = OR_Success;
2366 if (isLValueRef) {
2367 if (InitLvalue == Expr::LV_Valid &&
2368 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2369 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2370 // reference-compatible with "cv2 T2," or
2371 //
2372 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2373 // bit-field when we're determining whether the reference initialization
2374 // can occur. This property will be checked by PerformInitialization.
2375 if (DerivedToBase)
2376 Sequence.AddDerivedToBaseCastStep(
2377 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2378 /*isLValue=*/true);
2379 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2380 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2381 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2382 return;
2383 }
2384
2385 // - has a class type (i.e., T2 is a class type), where T1 is not
2386 // reference-related to T2, and can be implicitly converted to an
2387 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2388 // with "cv3 T3" (this conversion is selected by enumerating the
2389 // applicable conversion functions (13.3.1.6) and choosing the best
2390 // one through overload resolution (13.3)),
2391 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2392 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2393 Initializer,
2394 /*AllowRValues=*/false,
2395 Sequence);
2396 if (ConvOvlResult == OR_Success)
2397 return;
2398 }
2399 }
2400
2401 // - Otherwise, the reference shall be an lvalue reference to a
2402 // non-volatile const type (i.e., cv1 shall be const), or the reference
2403 // shall be an rvalue reference and the initializer expression shall
2404 // be an rvalue.
2405 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2406 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2407 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2408 Sequence.SetOverloadFailure(
2409 InitializationSequence::FK_ReferenceInitOverloadFailed,
2410 ConvOvlResult);
2411 else if (isLValueRef)
2412 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2413 ? (RefRelationship == Sema::Ref_Related
2414 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2415 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2416 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2417 else
2418 Sequence.SetFailed(
2419 InitializationSequence::FK_RValueReferenceBindingToLValue);
2420
2421 return;
2422 }
2423
2424 // - If T1 and T2 are class types and
2425 if (T1->isRecordType() && T2->isRecordType()) {
2426 // - the initializer expression is an rvalue and "cv1 T1" is
2427 // reference-compatible with "cv2 T2", or
2428 if (InitLvalue != Expr::LV_Valid &&
2429 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2430 if (DerivedToBase)
2431 Sequence.AddDerivedToBaseCastStep(
2432 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2433 /*isLValue=*/false);
2434 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2435 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2436 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2437 return;
2438 }
2439
2440 // - T1 is not reference-related to T2 and the initializer expression
2441 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2442 // conversion is selected by enumerating the applicable conversion
2443 // functions (13.3.1.6) and choosing the best one through overload
2444 // resolution (13.3)),
2445 if (RefRelationship == Sema::Ref_Incompatible) {
2446 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2447 Kind, Initializer,
2448 /*AllowRValues=*/true,
2449 Sequence);
2450 if (ConvOvlResult)
2451 Sequence.SetOverloadFailure(
2452 InitializationSequence::FK_ReferenceInitOverloadFailed,
2453 ConvOvlResult);
2454
2455 return;
2456 }
2457
2458 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2459 return;
2460 }
2461
2462 // - If the initializer expression is an rvalue, with T2 an array type,
2463 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2464 // is bound to the object represented by the rvalue (see 3.10).
2465 // FIXME: How can an array type be reference-compatible with anything?
2466 // Don't we mean the element types of T1 and T2?
2467
2468 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2469 // from the initializer expression using the rules for a non-reference
2470 // copy initialization (8.5). The reference is then bound to the
2471 // temporary. [...]
2472 // Determine whether we are allowed to call explicit constructors or
2473 // explicit conversion operators.
2474 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2475 ImplicitConversionSequence ICS
2476 = S.TryImplicitConversion(Initializer, cv1T1,
2477 /*SuppressUserConversions=*/false, AllowExplicit,
2478 /*ForceRValue=*/false,
2479 /*FIXME:InOverloadResolution=*/false,
2480 /*UserCast=*/Kind.isExplicitCast());
2481
2482 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2483 // FIXME: Use the conversion function set stored in ICS to turn
2484 // this into an overloading ambiguity diagnostic. However, we need
2485 // to keep that set as an OverloadCandidateSet rather than as some
2486 // other kind of set.
2487 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
2488 return;
2489 }
2490
2491 // [...] If T1 is reference-related to T2, cv1 must be the
2492 // same cv-qualification as, or greater cv-qualification
2493 // than, cv2; otherwise, the program is ill-formed.
2494 if (RefRelationship == Sema::Ref_Related &&
2495 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2496 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2497 return;
2498 }
2499
2500 // Perform the actual conversion.
2501 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2502 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2503 return;
2504}
2505
2506/// \brief Attempt character array initialization from a string literal
2507/// (C++ [dcl.init.string], C99 6.7.8).
2508static void TryStringLiteralInitialization(Sema &S,
2509 const InitializedEntity &Entity,
2510 const InitializationKind &Kind,
2511 Expr *Initializer,
2512 InitializationSequence &Sequence) {
2513 // FIXME: Implement!
2514}
2515
Douglas Gregor20093b42009-12-09 23:02:17 +00002516/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2517/// enumerates the constructors of the initialized entity and performs overload
2518/// resolution to select the best.
2519static void TryConstructorInitialization(Sema &S,
2520 const InitializedEntity &Entity,
2521 const InitializationKind &Kind,
2522 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002523 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002524 InitializationSequence &Sequence) {
Douglas Gregora6ca6502009-12-14 20:57:13 +00002525 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002526
2527 // Build the candidate set directly in the initialization sequence
2528 // structure, so that it will persist if we fail.
2529 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2530 CandidateSet.clear();
2531
2532 // Determine whether we are allowed to call explicit constructors or
2533 // explicit conversion operators.
2534 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2535 Kind.getKind() == InitializationKind::IK_Value ||
2536 Kind.getKind() == InitializationKind::IK_Default);
2537
2538 // The type we're converting to is a class type. Enumerate its constructors
2539 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002540 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2541 assert(DestRecordType && "Constructor initialization requires record type");
2542 CXXRecordDecl *DestRecordDecl
2543 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2544
2545 DeclarationName ConstructorName
2546 = S.Context.DeclarationNames.getCXXConstructorName(
2547 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2548 DeclContext::lookup_iterator Con, ConEnd;
2549 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2550 Con != ConEnd; ++Con) {
2551 // Find the constructor (which may be a template).
2552 CXXConstructorDecl *Constructor = 0;
2553 FunctionTemplateDecl *ConstructorTmpl
2554 = dyn_cast<FunctionTemplateDecl>(*Con);
2555 if (ConstructorTmpl)
2556 Constructor = cast<CXXConstructorDecl>(
2557 ConstructorTmpl->getTemplatedDecl());
2558 else
2559 Constructor = cast<CXXConstructorDecl>(*Con);
2560
2561 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002562 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002563 if (ConstructorTmpl)
2564 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2565 Args, NumArgs, CandidateSet);
2566 else
2567 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2568 }
2569 }
2570
2571 SourceLocation DeclLoc = Kind.getLocation();
2572
2573 // Perform overload resolution. If it fails, return the failed result.
2574 OverloadCandidateSet::iterator Best;
2575 if (OverloadingResult Result
2576 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2577 Sequence.SetOverloadFailure(
2578 InitializationSequence::FK_ConstructorOverloadFailed,
2579 Result);
2580 return;
2581 }
2582
2583 // Add the constructor initialization step. Any cv-qualification conversion is
2584 // subsumed by the initialization.
2585 Sequence.AddConstructorInitializationStep(
2586 cast<CXXConstructorDecl>(Best->Function),
2587 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002588}
2589
Douglas Gregor71d17402009-12-15 00:01:57 +00002590/// \brief Attempt value initialization (C++ [dcl.init]p7).
2591static void TryValueInitialization(Sema &S,
2592 const InitializedEntity &Entity,
2593 const InitializationKind &Kind,
2594 InitializationSequence &Sequence) {
2595 // C++ [dcl.init]p5:
2596 //
2597 // To value-initialize an object of type T means:
2598 QualType T = Entity.getType().getType();
2599
2600 // -- if T is an array type, then each element is value-initialized;
2601 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2602 T = AT->getElementType();
2603
2604 if (const RecordType *RT = T->getAs<RecordType>()) {
2605 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2606 // -- if T is a class type (clause 9) with a user-declared
2607 // constructor (12.1), then the default constructor for T is
2608 // called (and the initialization is ill-formed if T has no
2609 // accessible default constructor);
2610 //
2611 // FIXME: we really want to refer to a single subobject of the array,
2612 // but Entity doesn't have a way to capture that (yet).
2613 if (ClassDecl->hasUserDeclaredConstructor())
2614 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2615
2616 // FIXME: non-union class type w/ non-trivial default constructor gets
2617 // zero-initialized, then constructor gets called.
2618 }
2619 }
2620
2621 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2622 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2623}
2624
Douglas Gregor99a2e602009-12-16 01:38:02 +00002625/// \brief Attempt default initialization (C++ [dcl.init]p6).
2626static void TryDefaultInitialization(Sema &S,
2627 const InitializedEntity &Entity,
2628 const InitializationKind &Kind,
2629 InitializationSequence &Sequence) {
2630 assert(Kind.getKind() == InitializationKind::IK_Default);
2631
2632 // C++ [dcl.init]p6:
2633 // To default-initialize an object of type T means:
2634 // - if T is an array type, each element is default-initialized;
2635 QualType DestType = Entity.getType().getType();
2636 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2637 DestType = Array->getElementType();
2638
2639 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2640 // constructor for T is called (and the initialization is ill-formed if
2641 // T has no accessible default constructor);
2642 if (DestType->isRecordType()) {
2643 // FIXME: If a program calls for the default initialization of an object of
2644 // a const-qualified type T, T shall be a class type with a user-provided
2645 // default constructor.
2646 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2647 Sequence);
2648 }
2649
2650 // - otherwise, no initialization is performed.
2651 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2652
2653 // If a program calls for the default initialization of an object of
2654 // a const-qualified type T, T shall be a class type with a user-provided
2655 // default constructor.
2656 if (DestType.isConstQualified())
2657 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2658}
2659
Douglas Gregor20093b42009-12-09 23:02:17 +00002660/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2661/// which enumerates all conversion functions and performs overload resolution
2662/// to select the best.
2663static void TryUserDefinedConversion(Sema &S,
2664 const InitializedEntity &Entity,
2665 const InitializationKind &Kind,
2666 Expr *Initializer,
2667 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002668 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2669
2670 QualType DestType = Entity.getType().getType();
2671 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2672 QualType SourceType = Initializer->getType();
2673 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2674 "Must have a class type to perform a user-defined conversion");
2675
2676 // Build the candidate set directly in the initialization sequence
2677 // structure, so that it will persist if we fail.
2678 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2679 CandidateSet.clear();
2680
2681 // Determine whether we are allowed to call explicit constructors or
2682 // explicit conversion operators.
2683 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2684
2685 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2686 // The type we're converting to is a class type. Enumerate its constructors
2687 // to see if there is a suitable conversion.
2688 CXXRecordDecl *DestRecordDecl
2689 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2690
2691 DeclarationName ConstructorName
2692 = S.Context.DeclarationNames.getCXXConstructorName(
2693 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2694 DeclContext::lookup_iterator Con, ConEnd;
2695 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2696 Con != ConEnd; ++Con) {
2697 // Find the constructor (which may be a template).
2698 CXXConstructorDecl *Constructor = 0;
2699 FunctionTemplateDecl *ConstructorTmpl
2700 = dyn_cast<FunctionTemplateDecl>(*Con);
2701 if (ConstructorTmpl)
2702 Constructor = cast<CXXConstructorDecl>(
2703 ConstructorTmpl->getTemplatedDecl());
2704 else
2705 Constructor = cast<CXXConstructorDecl>(*Con);
2706
2707 if (!Constructor->isInvalidDecl() &&
2708 Constructor->isConvertingConstructor(AllowExplicit)) {
2709 if (ConstructorTmpl)
2710 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2711 &Initializer, 1, CandidateSet);
2712 else
2713 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2714 }
2715 }
2716 }
2717
2718 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2719 // The type we're converting from is a class type, enumerate its conversion
2720 // functions.
2721 CXXRecordDecl *SourceRecordDecl
2722 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2723
2724 const UnresolvedSet *Conversions
2725 = SourceRecordDecl->getVisibleConversionFunctions();
2726 for (UnresolvedSet::iterator I = Conversions->begin(),
2727 E = Conversions->end();
2728 I != E; ++I) {
2729 NamedDecl *D = *I;
2730 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2731 if (isa<UsingShadowDecl>(D))
2732 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2733
2734 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2735 CXXConversionDecl *Conv;
2736 if (ConvTemplate)
2737 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2738 else
2739 Conv = cast<CXXConversionDecl>(*I);
2740
2741 if (AllowExplicit || !Conv->isExplicit()) {
2742 if (ConvTemplate)
2743 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2744 DestType, CandidateSet);
2745 else
2746 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2747 CandidateSet);
2748 }
2749 }
2750 }
2751
2752 SourceLocation DeclLoc = Initializer->getLocStart();
2753
2754 // Perform overload resolution. If it fails, return the failed result.
2755 OverloadCandidateSet::iterator Best;
2756 if (OverloadingResult Result
2757 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2758 Sequence.SetOverloadFailure(
2759 InitializationSequence::FK_UserConversionOverloadFailed,
2760 Result);
2761 return;
2762 }
2763
2764 FunctionDecl *Function = Best->Function;
2765
2766 if (isa<CXXConstructorDecl>(Function)) {
2767 // Add the user-defined conversion step. Any cv-qualification conversion is
2768 // subsumed by the initialization.
2769 Sequence.AddUserConversionStep(Function, DestType);
2770 return;
2771 }
2772
2773 // Add the user-defined conversion step that calls the conversion function.
2774 QualType ConvType = Function->getResultType().getNonReferenceType();
2775 Sequence.AddUserConversionStep(Function, ConvType);
2776
2777 // If the conversion following the call to the conversion function is
2778 // interesting, add it as a separate step.
2779 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2780 Best->FinalConversion.Third) {
2781 ImplicitConversionSequence ICS;
2782 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2783 ICS.Standard = Best->FinalConversion;
2784 Sequence.AddConversionSequenceStep(ICS, DestType);
2785 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002786}
2787
2788/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2789/// non-class type to another.
2790static void TryImplicitConversion(Sema &S,
2791 const InitializedEntity &Entity,
2792 const InitializationKind &Kind,
2793 Expr *Initializer,
2794 InitializationSequence &Sequence) {
2795 ImplicitConversionSequence ICS
2796 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2797 /*SuppressUserConversions=*/true,
2798 /*AllowExplicit=*/false,
2799 /*ForceRValue=*/false,
2800 /*FIXME:InOverloadResolution=*/false,
2801 /*UserCast=*/Kind.isExplicitCast());
2802
2803 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2804 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2805 return;
2806 }
2807
2808 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2809}
2810
2811InitializationSequence::InitializationSequence(Sema &S,
2812 const InitializedEntity &Entity,
2813 const InitializationKind &Kind,
2814 Expr **Args,
2815 unsigned NumArgs) {
2816 ASTContext &Context = S.Context;
2817
2818 // C++0x [dcl.init]p16:
2819 // The semantics of initializers are as follows. The destination type is
2820 // the type of the object or reference being initialized and the source
2821 // type is the type of the initializer expression. The source type is not
2822 // defined when the initializer is a braced-init-list or when it is a
2823 // parenthesized list of expressions.
2824 QualType DestType = Entity.getType().getType();
2825
2826 if (DestType->isDependentType() ||
2827 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2828 SequenceKind = DependentSequence;
2829 return;
2830 }
2831
2832 QualType SourceType;
2833 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002834 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002835 Initializer = Args[0];
2836 if (!isa<InitListExpr>(Initializer))
2837 SourceType = Initializer->getType();
2838 }
2839
2840 // - If the initializer is a braced-init-list, the object is
2841 // list-initialized (8.5.4).
2842 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2843 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002844 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002845 }
2846
2847 // - If the destination type is a reference type, see 8.5.3.
2848 if (DestType->isReferenceType()) {
2849 // C++0x [dcl.init.ref]p1:
2850 // A variable declared to be a T& or T&&, that is, "reference to type T"
2851 // (8.3.2), shall be initialized by an object, or function, of type T or
2852 // by an object that can be converted into a T.
2853 // (Therefore, multiple arguments are not permitted.)
2854 if (NumArgs != 1)
2855 SetFailed(FK_TooManyInitsForReference);
2856 else
2857 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2858 return;
2859 }
2860
2861 // - If the destination type is an array of characters, an array of
2862 // char16_t, an array of char32_t, or an array of wchar_t, and the
2863 // initializer is a string literal, see 8.5.2.
2864 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2865 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2866 return;
2867 }
2868
2869 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002870 if (Kind.getKind() == InitializationKind::IK_Value ||
2871 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002872 TryValueInitialization(S, Entity, Kind, *this);
2873 return;
2874 }
2875
Douglas Gregor99a2e602009-12-16 01:38:02 +00002876 // Handle default initialization.
2877 if (Kind.getKind() == InitializationKind::IK_Default){
2878 TryDefaultInitialization(S, Entity, Kind, *this);
2879 return;
2880 }
2881
Douglas Gregor20093b42009-12-09 23:02:17 +00002882 // - Otherwise, if the destination type is an array, the program is
2883 // ill-formed.
2884 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2885 if (AT->getElementType()->isAnyCharacterType())
2886 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2887 else
2888 SetFailed(FK_ArrayNeedsInitList);
2889
2890 return;
2891 }
2892
2893 // - If the destination type is a (possibly cv-qualified) class type:
2894 if (DestType->isRecordType()) {
2895 // - If the initialization is direct-initialization, or if it is
2896 // copy-initialization where the cv-unqualified version of the
2897 // source type is the same class as, or a derived class of, the
2898 // class of the destination, constructors are considered. [...]
2899 if (Kind.getKind() == InitializationKind::IK_Direct ||
2900 (Kind.getKind() == InitializationKind::IK_Copy &&
2901 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2902 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002903 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2904 Entity.getType().getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002905 // - Otherwise (i.e., for the remaining copy-initialization cases),
2906 // user-defined conversion sequences that can convert from the source
2907 // type to the destination type or (when a conversion function is
2908 // used) to a derived class thereof are enumerated as described in
2909 // 13.3.1.4, and the best one is chosen through overload resolution
2910 // (13.3).
2911 else
2912 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2913 return;
2914 }
2915
Douglas Gregor99a2e602009-12-16 01:38:02 +00002916 if (NumArgs > 1) {
2917 SetFailed(FK_TooManyInitsForScalar);
2918 return;
2919 }
2920 assert(NumArgs == 1 && "Zero-argument case handled above");
2921
Douglas Gregor20093b42009-12-09 23:02:17 +00002922 // - Otherwise, if the source type is a (possibly cv-qualified) class
2923 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002924 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002925 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2926 return;
2927 }
2928
2929 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002930 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002931 // conversions (Clause 4) will be used, if necessary, to convert the
2932 // initializer expression to the cv-unqualified version of the
2933 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002934 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002935 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2936}
2937
2938InitializationSequence::~InitializationSequence() {
2939 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2940 StepEnd = Steps.end();
2941 Step != StepEnd; ++Step)
2942 Step->Destroy();
2943}
2944
2945//===----------------------------------------------------------------------===//
2946// Perform initialization
2947//===----------------------------------------------------------------------===//
2948
2949Action::OwningExprResult
2950InitializationSequence::Perform(Sema &S,
2951 const InitializedEntity &Entity,
2952 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00002953 Action::MultiExprArg Args,
2954 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002955 if (SequenceKind == FailedSequence) {
2956 unsigned NumArgs = Args.size();
2957 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
2958 return S.ExprError();
2959 }
2960
2961 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002962 // If the declaration is a non-dependent, incomplete array type
2963 // that has an initializer, then its type will be completed once
2964 // the initializer is instantiated.
2965 if (ResultType && !Entity.getType().getType()->isDependentType() &&
2966 Args.size() == 1) {
2967 QualType DeclType = Entity.getType().getType();
2968 if (const IncompleteArrayType *ArrayT
2969 = S.Context.getAsIncompleteArrayType(DeclType)) {
2970 // FIXME: We don't currently have the ability to accurately
2971 // compute the length of an initializer list without
2972 // performing full type-checking of the initializer list
2973 // (since we have to determine where braces are implicitly
2974 // introduced and such). So, we fall back to making the array
2975 // type a dependently-sized array type with no specified
2976 // bound.
2977 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
2978 SourceRange Brackets;
2979 // Scavange the location of the brackets from the entity, if we can.
2980 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
2981 IncompleteArrayTypeLoc ArrayLoc
2982 = cast<IncompleteArrayTypeLoc>(Entity.getType());
2983 Brackets = ArrayLoc.getBracketsRange();
2984 }
2985
2986 *ResultType
2987 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
2988 /*NumElts=*/0,
2989 ArrayT->getSizeModifier(),
2990 ArrayT->getIndexTypeCVRQualifiers(),
2991 Brackets);
2992 }
2993
2994 }
2995 }
2996
Douglas Gregor20093b42009-12-09 23:02:17 +00002997 if (Kind.getKind() == InitializationKind::IK_Copy)
2998 return Sema::OwningExprResult(S, Args.release()[0]);
2999
3000 unsigned NumArgs = Args.size();
3001 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3002 SourceLocation(),
3003 (Expr **)Args.release(),
3004 NumArgs,
3005 SourceLocation()));
3006 }
3007
Douglas Gregor99a2e602009-12-16 01:38:02 +00003008 if (SequenceKind == NoInitialization)
3009 return S.Owned((Expr *)0);
3010
Douglas Gregor20093b42009-12-09 23:02:17 +00003011 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003012 if (ResultType)
3013 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003014
Douglas Gregor99a2e602009-12-16 01:38:02 +00003015 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3016
3017 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3018
3019 // For initialization steps that start with a single initializer,
3020 // grab the only argument out the Args and place it into the "current"
3021 // initializer.
3022 switch (Steps.front().Kind) {
3023 case SK_ResolveAddressOfOverloadedFunction:
3024 case SK_CastDerivedToBaseRValue:
3025 case SK_CastDerivedToBaseLValue:
3026 case SK_BindReference:
3027 case SK_BindReferenceToTemporary:
3028 case SK_UserConversion:
3029 case SK_QualificationConversionLValue:
3030 case SK_QualificationConversionRValue:
3031 case SK_ConversionSequence:
3032 case SK_ListInitialization:
3033 assert(Args.size() == 1);
3034 CurInit = Sema::OwningExprResult(S,
3035 ((Expr **)(Args.get()))[0]->Retain());
3036 if (CurInit.isInvalid())
3037 return S.ExprError();
3038 break;
3039
3040 case SK_ConstructorInitialization:
3041 case SK_ZeroInitialization:
3042 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003043 }
3044
3045 // Walk through the computed steps for the initialization sequence,
3046 // performing the specified conversions along the way.
3047 for (step_iterator Step = step_begin(), StepEnd = step_end();
3048 Step != StepEnd; ++Step) {
3049 if (CurInit.isInvalid())
3050 return S.ExprError();
3051
3052 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003053 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003054
3055 switch (Step->Kind) {
3056 case SK_ResolveAddressOfOverloadedFunction:
3057 // Overload resolution determined which function invoke; update the
3058 // initializer to reflect that choice.
3059 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3060 break;
3061
3062 case SK_CastDerivedToBaseRValue:
3063 case SK_CastDerivedToBaseLValue: {
3064 // We have a derived-to-base cast that produces either an rvalue or an
3065 // lvalue. Perform that cast.
3066
3067 // Casts to inaccessible base classes are allowed with C-style casts.
3068 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3069 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3070 CurInitExpr->getLocStart(),
3071 CurInitExpr->getSourceRange(),
3072 IgnoreBaseAccess))
3073 return S.ExprError();
3074
3075 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3076 CastExpr::CK_DerivedToBase,
3077 (Expr*)CurInit.release(),
3078 Step->Kind == SK_CastDerivedToBaseLValue));
3079 break;
3080 }
3081
3082 case SK_BindReference:
3083 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3084 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3085 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3086 << Entity.getType().getType().isVolatileQualified()
3087 << BitField->getDeclName()
3088 << CurInitExpr->getSourceRange();
3089 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3090 return S.ExprError();
3091 }
3092
3093 // Reference binding does not have any corresponding ASTs.
3094
3095 // Check exception specifications
3096 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3097 return S.ExprError();
3098 break;
3099
3100 case SK_BindReferenceToTemporary:
3101 // Check exception specifications
3102 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3103 return S.ExprError();
3104
3105 // FIXME: At present, we have no AST to describe when we need to make a
3106 // temporary to bind a reference to. We should.
3107 break;
3108
3109 case SK_UserConversion: {
3110 // We have a user-defined conversion that invokes either a constructor
3111 // or a conversion function.
3112 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
3113 if (CXXConstructorDecl *Constructor
3114 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3115 // Build a call to the selected constructor.
3116 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3117 SourceLocation Loc = CurInitExpr->getLocStart();
3118 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3119
3120 // Determine the arguments required to actually perform the constructor
3121 // call.
3122 if (S.CompleteConstructorCall(Constructor,
3123 Sema::MultiExprArg(S,
3124 (void **)&CurInitExpr,
3125 1),
3126 Loc, ConstructorArgs))
3127 return S.ExprError();
3128
3129 // Build the an expression that constructs a temporary.
3130 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3131 move_arg(ConstructorArgs));
3132 if (CurInit.isInvalid())
3133 return S.ExprError();
3134
3135 CastKind = CastExpr::CK_ConstructorConversion;
3136 } else {
3137 // Build a call to the conversion function.
3138 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
3139
3140 // FIXME: Should we move this initialization into a separate
3141 // derived-to-base conversion? I believe the answer is "no", because
3142 // we don't want to turn off access control here for c-style casts.
3143 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3144 return S.ExprError();
3145
3146 // Do a little dance to make sure that CurInit has the proper
3147 // pointer.
3148 CurInit.release();
3149
3150 // Build the actual call to the conversion function.
3151 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3152 if (CurInit.isInvalid() || !CurInit.get())
3153 return S.ExprError();
3154
3155 CastKind = CastExpr::CK_UserDefinedConversion;
3156 }
3157
3158 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3159 CurInitExpr = CurInit.takeAs<Expr>();
3160 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3161 CastKind,
3162 CurInitExpr,
3163 false));
3164 break;
3165 }
3166
3167 case SK_QualificationConversionLValue:
3168 case SK_QualificationConversionRValue:
3169 // Perform a qualification conversion; these can never go wrong.
3170 S.ImpCastExprToType(CurInitExpr, Step->Type,
3171 CastExpr::CK_NoOp,
3172 Step->Kind == SK_QualificationConversionLValue);
3173 CurInit.release();
3174 CurInit = S.Owned(CurInitExpr);
3175 break;
3176
3177 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003178 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003179 false, false, *Step->ICS))
3180 return S.ExprError();
3181
3182 CurInit.release();
3183 CurInit = S.Owned(CurInitExpr);
3184 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003185
3186 case SK_ListInitialization: {
3187 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3188 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003189 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003190 return S.ExprError();
3191
3192 CurInit.release();
3193 CurInit = S.Owned(InitList);
3194 break;
3195 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003196
3197 case SK_ConstructorInitialization: {
3198 CXXConstructorDecl *Constructor
3199 = cast<CXXConstructorDecl>(Step->Function);
3200
3201 // Build a call to the selected constructor.
3202 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3203 SourceLocation Loc = Kind.getLocation();
3204
3205 // Determine the arguments required to actually perform the constructor
3206 // call.
3207 if (S.CompleteConstructorCall(Constructor, move(Args),
3208 Loc, ConstructorArgs))
3209 return S.ExprError();
3210
3211 // Build the an expression that constructs a temporary.
3212 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3213 move_arg(ConstructorArgs));
3214 if (CurInit.isInvalid())
3215 return S.ExprError();
3216
Douglas Gregor51c56d62009-12-14 20:49:26 +00003217 break;
3218 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003219
3220 case SK_ZeroInitialization: {
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003221 if (Kind.getKind() == InitializationKind::IK_Value &&
3222 S.getLangOptions().CPlusPlus &&
3223 !Kind.isImplicitValueInit())
Douglas Gregor71d17402009-12-15 00:01:57 +00003224 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3225 Kind.getRange().getBegin(),
3226 Kind.getRange().getEnd()));
3227 else
3228 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
3229 break;
3230 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003231 }
3232 }
3233
3234 return move(CurInit);
3235}
3236
3237//===----------------------------------------------------------------------===//
3238// Diagnose initialization failures
3239//===----------------------------------------------------------------------===//
3240bool InitializationSequence::Diagnose(Sema &S,
3241 const InitializedEntity &Entity,
3242 const InitializationKind &Kind,
3243 Expr **Args, unsigned NumArgs) {
3244 if (SequenceKind != FailedSequence)
3245 return false;
3246
3247 QualType DestType = Entity.getType().getType();
3248 switch (Failure) {
3249 case FK_TooManyInitsForReference:
3250 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3251 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3252 break;
3253
3254 case FK_ArrayNeedsInitList:
3255 case FK_ArrayNeedsInitListOrStringLiteral:
3256 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3257 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3258 break;
3259
3260 case FK_AddressOfOverloadFailed:
3261 S.ResolveAddressOfOverloadedFunction(Args[0],
3262 DestType.getNonReferenceType(),
3263 true);
3264 break;
3265
3266 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003267 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003268 switch (FailedOverloadResult) {
3269 case OR_Ambiguous:
3270 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3271 << Args[0]->getType() << DestType.getNonReferenceType()
3272 << Args[0]->getSourceRange();
3273 S.PrintOverloadCandidates(FailedCandidateSet, true);
3274 break;
3275
3276 case OR_No_Viable_Function:
3277 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3278 << Args[0]->getType() << DestType.getNonReferenceType()
3279 << Args[0]->getSourceRange();
3280 S.PrintOverloadCandidates(FailedCandidateSet, false);
3281 break;
3282
3283 case OR_Deleted: {
3284 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3285 << Args[0]->getType() << DestType.getNonReferenceType()
3286 << Args[0]->getSourceRange();
3287 OverloadCandidateSet::iterator Best;
3288 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3289 Kind.getLocation(),
3290 Best);
3291 if (Ovl == OR_Deleted) {
3292 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3293 << Best->Function->isDeleted();
3294 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003295 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003296 }
3297 break;
3298 }
3299
3300 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003301 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003302 break;
3303 }
3304 break;
3305
3306 case FK_NonConstLValueReferenceBindingToTemporary:
3307 case FK_NonConstLValueReferenceBindingToUnrelated:
3308 S.Diag(Kind.getLocation(),
3309 Failure == FK_NonConstLValueReferenceBindingToTemporary
3310 ? diag::err_lvalue_reference_bind_to_temporary
3311 : diag::err_lvalue_reference_bind_to_unrelated)
3312 << DestType.getNonReferenceType()
3313 << Args[0]->getType()
3314 << Args[0]->getSourceRange();
3315 break;
3316
3317 case FK_RValueReferenceBindingToLValue:
3318 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3319 << Args[0]->getSourceRange();
3320 break;
3321
3322 case FK_ReferenceInitDropsQualifiers:
3323 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3324 << DestType.getNonReferenceType()
3325 << Args[0]->getType()
3326 << Args[0]->getSourceRange();
3327 break;
3328
3329 case FK_ReferenceInitFailed:
3330 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3331 << DestType.getNonReferenceType()
3332 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3333 << Args[0]->getType()
3334 << Args[0]->getSourceRange();
3335 break;
3336
3337 case FK_ConversionFailed:
3338 S.Diag(Kind.getLocation(), diag::err_cannot_initialize_decl_noname)
3339 << DestType
3340 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3341 << Args[0]->getType()
3342 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003343 break;
3344
3345 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003346 SourceRange R;
3347
3348 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3349 R = SourceRange(InitList->getInit(1)->getLocStart(),
3350 InitList->getLocEnd());
3351 else
3352 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003353
3354 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003355 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003356 break;
3357 }
3358
3359 case FK_ReferenceBindingToInitList:
3360 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3361 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3362 break;
3363
3364 case FK_InitListBadDestinationType:
3365 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3366 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3367 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003368
3369 case FK_ConstructorOverloadFailed: {
3370 SourceRange ArgsRange;
3371 if (NumArgs)
3372 ArgsRange = SourceRange(Args[0]->getLocStart(),
3373 Args[NumArgs - 1]->getLocEnd());
3374
3375 // FIXME: Using "DestType" for the entity we're printing is probably
3376 // bad.
3377 switch (FailedOverloadResult) {
3378 case OR_Ambiguous:
3379 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3380 << DestType << ArgsRange;
3381 S.PrintOverloadCandidates(FailedCandidateSet, true);
3382 break;
3383
3384 case OR_No_Viable_Function:
3385 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3386 << DestType << ArgsRange;
3387 S.PrintOverloadCandidates(FailedCandidateSet, false);
3388 break;
3389
3390 case OR_Deleted: {
3391 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3392 << true << DestType << ArgsRange;
3393 OverloadCandidateSet::iterator Best;
3394 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3395 Kind.getLocation(),
3396 Best);
3397 if (Ovl == OR_Deleted) {
3398 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3399 << Best->Function->isDeleted();
3400 } else {
3401 llvm_unreachable("Inconsistent overload resolution?");
3402 }
3403 break;
3404 }
3405
3406 case OR_Success:
3407 llvm_unreachable("Conversion did not fail!");
3408 break;
3409 }
3410 break;
3411 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003412
3413 case FK_DefaultInitOfConst:
3414 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3415 << DestType;
3416 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003417 }
3418
3419 return true;
3420}