blob: 6f11a87d114ab3a2a32623aeddf443575699d949 [file] [log] [blame]
Steve Narofff8ecff22008-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 Lattner0cb78032009-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 Lattner9ececce2009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Narofff8ecff22008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor3e1e5272009-12-09 23:02:17 +000018#include "SemaInit.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000025#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000026using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000027
Chris Lattner0cb78032009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
Chris Lattnerd8b741c82009-02-24 23:10:27 +000032static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000033 const ArrayType *AT = Context.getAsArrayType(DeclType);
34 if (!AT) return 0;
35
Eli Friedman893abe42009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattnera9196812009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnera9196812009-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 Lattner012b3392009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-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 Friedman42a84652009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000055
Eli Friedman42a84652009-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 Lattnera9196812009-02-26 23:26:43 +000062 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0cb78032009-02-24 22:27:37 +000064 return 0;
65}
66
Mike Stump11289f42009-09-09 15:08:12 +000067static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner94d2f682009-02-24 22:46:58 +000068 bool DirectInit, Sema &S) {
Chris Lattner0cb78032009-02-24 22:27:37 +000069 // Get the type before calling CheckSingleAssignmentConstraints(), since
70 // it can promote the expression.
Mike Stump11289f42009-09-09 15:08:12 +000071 QualType InitType = Init->getType();
72
Chris Lattner94d2f682009-02-24 22:46:58 +000073 if (S.getLangOptions().CPlusPlus) {
Chris Lattner0cb78032009-02-24 22:27:37 +000074 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000075 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000076 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000077 ImplicitConversionSequence ICS;
78 OverloadCandidateSet CandidateSet;
79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80 CandidateSet,
Douglas Gregor3e1e5272009-12-09 23:02:17 +000081 true, false, false) != OR_Ambiguous)
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000082 return S.Diag(Init->getSourceRange().getBegin(),
83 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000084 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian3e6b57e2009-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 Lattner0cb78032009-02-24 22:27:37 +000092 return false;
93 }
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner94d2f682009-02-24 22:46:58 +000095 Sema::AssignConvertType ConvTy =
96 S.CheckSingleAssignmentConstraints(DeclType, Init);
97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000098 InitType, Init, Sema::AA_Initializing);
Chris Lattner0cb78032009-02-24 22:27:37 +000099}
100
Chris Lattnerd8b741c82009-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 Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000117 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Eli Friedman893abe42009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000121
Eli Friedman893abe42009-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 Stump11289f42009-09-09 15:08:12 +0000129
Eli Friedman893abe42009-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 Lattner0cb78032009-02-24 22:27:37 +0000135}
136
137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
Douglas Gregor85dabae2009-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 Stump11289f42009-09-09 15:08:12 +0000144 if (DeclType->isDependentType() ||
Douglas Gregorad2956c2009-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 Gregordeebf6e2009-11-19 23:25:22 +0000152 // the initializer is instantiated.
Douglas Gregorad2956c2009-11-19 18:03:26 +0000153 if (!DeclType->isDependentType()) {
154 if (const IncompleteArrayType *ArrayT
155 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregordeebf6e2009-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 Gregorad2956c2009-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 Lattner0cb78032009-02-24 22:27:37 +0000188 return false;
Douglas Gregorad2956c2009-11-19 18:03:26 +0000189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattner0cb78032009-02-24 22:27:37 +0000191 // C++ [dcl.init.ref]p1:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000192 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattner0cb78032009-02-24 22:27:37 +0000193 // (8.3.2), shall be initialized by an object, or function, of
194 // type T or by an object that can be converted into a T.
Douglas Gregor59ae3c82009-12-16 16:54:16 +0000195 if (DeclType->isReferenceType()) {
196 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
197 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
198 MultiExprArg(*this, (void**)&Init, 1),
199 &DeclType);
200 if (CurInit.isInvalid())
201 return true;
202
203 Init = CurInit.takeAs<Expr>();
204 return false;
205 }
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattner0cb78032009-02-24 22:27:37 +0000207 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
208 // of unknown size ("[]") or an object type that is not a variable array type.
209 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
210 return Diag(InitLoc, diag::err_variable_object_no_init)
211 << VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner0cb78032009-02-24 22:27:37 +0000213 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
214 if (!InitList) {
215 // FIXME: Handle wide strings
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000216 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
217 CheckStringInit(Str, DeclType, *this);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000218 return false;
219 }
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattner0cb78032009-02-24 22:27:37 +0000221 // C++ [dcl.init]p14:
222 // -- If the destination type is a (possibly cv-qualified) class
223 // type:
224 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
Douglas Gregora4b592a2009-12-19 03:01:41 +0000225 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
226 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
227 MultiExprArg(*this, (void**)&Init, 1),
228 &DeclType);
229 if (CurInit.isInvalid())
230 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000231
Douglas Gregora4b592a2009-12-19 03:01:41 +0000232 Init = CurInit.takeAs<Expr>();
233 return false;
Chris Lattner0cb78032009-02-24 22:27:37 +0000234 }
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattner0cb78032009-02-24 22:27:37 +0000236 // C99 6.7.8p16.
237 if (DeclType->isArrayType())
238 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerd86a13e2009-06-26 04:45:06 +0000239 << Init->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000240
Chris Lattner94d2f682009-02-24 22:46:58 +0000241 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump11289f42009-09-09 15:08:12 +0000242 }
243
Douglas Gregor723796a2009-12-16 06:35:08 +0000244 bool hadError = CheckInitList(Entity, InitList, DeclType);
Chris Lattner0cb78032009-02-24 22:27:37 +0000245 Init = InitList;
246 return hadError;
247}
248
249//===----------------------------------------------------------------------===//
250// Semantic checking for initializer lists.
251//===----------------------------------------------------------------------===//
252
Douglas Gregorcde232f2009-01-29 01:05:33 +0000253/// @brief Semantic checking for initializer lists.
254///
255/// The InitListChecker class contains a set of routines that each
256/// handle the initialization of a certain kind of entity, e.g.,
257/// arrays, vectors, struct/union types, scalars, etc. The
258/// InitListChecker itself performs a recursive walk of the subobject
259/// structure of the type to be initialized, while stepping through
260/// the initializer list one element at a time. The IList and Index
261/// parameters to each of the Check* routines contain the active
262/// (syntactic) initializer list and the index into that initializer
263/// list that represents the current initializer. Each routine is
264/// responsible for moving that Index forward as it consumes elements.
265///
266/// Each Check* routine also has a StructuredList/StructuredIndex
267/// arguments, which contains the current the "structured" (semantic)
268/// initializer list and the index into that initializer list where we
269/// are copying initializers as we map them over to the semantic
270/// list. Once we have completed our recursive walk of the subobject
271/// structure, we will have constructed a full semantic initializer
272/// list.
273///
274/// C99 designators cause changes in the initializer list traversal,
275/// because they make the initialization "jump" into a specific
276/// subobject and then continue the initialization from that
277/// point. CheckDesignatedInitializer() recursively steps into the
278/// designated subobject and manages backing out the recursion to
279/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000280namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000281class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000282 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000283 bool hadError;
284 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
285 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000286
287 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000288 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000291 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000292 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000293 unsigned &StructuredIndex,
294 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000295 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
296 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000297 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000299 unsigned &StructuredIndex,
300 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000301 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000302 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000303 InitListExpr *StructuredList,
304 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000305 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000306 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000309 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000310 unsigned &Index,
311 InitListExpr *StructuredList,
312 unsigned &StructuredIndex);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000313 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000314 InitListExpr *StructuredList,
315 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000316 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
317 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000318 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000319 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000320 unsigned &StructuredIndex,
321 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000322 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
323 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000324 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000325 InitListExpr *StructuredList,
326 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000327 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000328 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000329 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000330 RecordDecl::field_iterator *NextField,
331 llvm::APSInt *NextElementIndex,
332 unsigned &Index,
333 InitListExpr *StructuredList,
334 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000335 bool FinishSubobjectInit,
336 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000337 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
338 QualType CurrentObjectType,
339 InitListExpr *StructuredList,
340 unsigned StructuredIndex,
341 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000342 void UpdateStructuredListElement(InitListExpr *StructuredList,
343 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000344 Expr *expr);
345 int numArrayElements(QualType DeclType);
346 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000347
Douglas Gregor723796a2009-12-16 06:35:08 +0000348 void FillInValueInitializations(const InitializedEntity &Entity,
349 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000350public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000351 InitListChecker(Sema &S, const InitializedEntity &Entity,
352 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000353 bool HadError() { return hadError; }
354
355 // @brief Retrieves the fully-structured initializer list used for
356 // semantic analysis and code generation.
357 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
358};
Chris Lattner9ececce2009-02-24 22:48:58 +0000359} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000360
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000361/// Recursively replaces NULL values within the given initializer list
362/// with expressions that perform value-initialization of the
363/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000364void
365InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
366 InitListExpr *ILE,
367 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000368 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000369 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000370 SourceLocation Loc = ILE->getSourceRange().getBegin();
371 if (ILE->getSyntacticForm())
372 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000373
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000374 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000375 unsigned Init = 0, NumInits = ILE->getNumInits();
Mike Stump11289f42009-09-09 15:08:12 +0000376 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000377 Field = RType->getDecl()->field_begin(),
378 FieldEnd = RType->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000379 Field != FieldEnd; ++Field) {
380 if (Field->isUnnamedBitfield())
381 continue;
382
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000383 if (hadError)
384 return;
385
Douglas Gregor723796a2009-12-16 06:35:08 +0000386 InitializedEntity MemberEntity
387 = InitializedEntity::InitializeMember(*Field, &Entity);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000388 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000389 // FIXME: We probably don't need to handle references
390 // specially here, since value-initialization of references is
391 // handled in InitializationSequence.
Douglas Gregord14247a2009-01-30 22:09:00 +0000392 if (Field->getType()->isReferenceType()) {
393 // C++ [dcl.init.aggr]p9:
394 // If an incomplete or empty initializer-list leaves a
395 // member of reference type uninitialized, the program is
Mike Stump11289f42009-09-09 15:08:12 +0000396 // ill-formed.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000397 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
Douglas Gregord14247a2009-01-30 22:09:00 +0000398 << Field->getType()
399 << ILE->getSyntacticForm()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000400 SemaRef.Diag(Field->getLocation(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000401 diag::note_uninit_reference_member);
402 hadError = true;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000403 return;
Douglas Gregor723796a2009-12-16 06:35:08 +0000404 }
405
406 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
407 true);
408 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
409 if (!InitSeq) {
410 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000411 hadError = true;
412 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000413 }
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000414
Douglas Gregor723796a2009-12-16 06:35:08 +0000415 Sema::OwningExprResult MemberInit
416 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
417 Sema::MultiExprArg(SemaRef, 0, 0));
418 if (MemberInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000419 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 return;
421 }
422
423 if (hadError) {
424 // Do nothing
425 } else if (Init < NumInits) {
426 ILE->setInit(Init, MemberInit.takeAs<Expr>());
427 } else if (InitSeq.getKind()
428 == InitializationSequence::ConstructorInitialization) {
429 // Value-initialization requires a constructor call, so
430 // extend the initializer list to include the constructor
431 // call and make a note that we'll need to take another pass
432 // through the initializer list.
433 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
434 RequiresSecondPass = true;
435 }
Mike Stump11289f42009-09-09 15:08:12 +0000436 } else if (InitListExpr *InnerILE
Douglas Gregor0202cb42009-01-29 17:44:32 +0000437 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
Douglas Gregor723796a2009-12-16 06:35:08 +0000438 FillInValueInitializations(MemberEntity, InnerILE,
439 RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000440 ++Init;
Douglas Gregord14247a2009-01-30 22:09:00 +0000441
442 // Only look at the first initialization of a union.
443 if (RType->getDecl()->isUnion())
444 break;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000445 }
446
447 return;
Mike Stump11289f42009-09-09 15:08:12 +0000448 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000449
450 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000451
Douglas Gregor723796a2009-12-16 06:35:08 +0000452 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000453 unsigned NumInits = ILE->getNumInits();
454 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000455 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000456 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000457 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
458 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000459 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
460 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000461 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000462 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000463 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000464 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
465 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000466 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000467 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000468
Douglas Gregor723796a2009-12-16 06:35:08 +0000469
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000470 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000471 if (hadError)
472 return;
473
Douglas Gregor723796a2009-12-16 06:35:08 +0000474 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
475 ElementEntity.setElementIndex(Init);
476
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000477 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000478 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
479 true);
480 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
481 if (!InitSeq) {
482 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000483 hadError = true;
484 return;
485 }
486
Douglas Gregor723796a2009-12-16 06:35:08 +0000487 Sema::OwningExprResult ElementInit
488 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
489 Sema::MultiExprArg(SemaRef, 0, 0));
490 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000491 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000492 return;
493 }
494
495 if (hadError) {
496 // Do nothing
497 } else if (Init < NumInits) {
498 ILE->setInit(Init, ElementInit.takeAs<Expr>());
499 } else if (InitSeq.getKind()
500 == InitializationSequence::ConstructorInitialization) {
501 // Value-initialization requires a constructor call, so
502 // extend the initializer list to include the constructor
503 // call and make a note that we'll need to take another pass
504 // through the initializer list.
505 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
506 RequiresSecondPass = true;
507 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000508 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000509 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
510 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000511 }
512}
513
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000514
Douglas Gregor723796a2009-12-16 06:35:08 +0000515InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
516 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000517 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000518 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000519
Eli Friedman23a9e312008-05-19 19:16:24 +0000520 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000521 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000522 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000523 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000524 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
525 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000526
Douglas Gregor723796a2009-12-16 06:35:08 +0000527 if (!hadError) {
528 bool RequiresSecondPass = false;
529 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000530 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000531 FillInValueInitializations(Entity, FullyStructuredList,
532 RequiresSecondPass);
533 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000534}
535
536int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000537 // FIXME: use a proper constant
538 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000539 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000540 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000541 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
542 }
543 return maxElements;
544}
545
546int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000547 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000548 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000549 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000550 Field = structDecl->field_begin(),
551 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000552 Field != FieldEnd; ++Field) {
553 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
554 ++InitializableMembers;
555 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000556 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000557 return std::min(InitializableMembers, 1);
558 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000559}
560
Mike Stump11289f42009-09-09 15:08:12 +0000561void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000562 QualType T, unsigned &Index,
563 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000564 unsigned &StructuredIndex,
565 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000566 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Steve Narofff8ecff22008-05-01 22:18:59 +0000568 if (T->isArrayType())
569 maxElements = numArrayElements(T);
570 else if (T->isStructureType() || T->isUnionType())
571 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000572 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000573 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000574 else
575 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000576
Eli Friedmane0f832b2008-05-25 13:49:22 +0000577 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000578 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000579 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000580 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000581 hadError = true;
582 return;
583 }
584
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000585 // Build a structured initializer list corresponding to this subobject.
586 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000587 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
588 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000589 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
590 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000591 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000592
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000593 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000594 unsigned StartIndex = Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000595 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000596 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 StructuredSubobjectInitIndex,
598 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000599 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000600 StructuredSubobjectInitList->setType(T);
601
Douglas Gregor5741efb2009-03-01 17:12:46 +0000602 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000603 // range corresponds with the end of the last initializer it used.
604 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000605 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000606 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
607 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
608 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000609}
610
Steve Naroff125d73d2008-05-06 00:23:44 +0000611void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000612 unsigned &Index,
613 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000614 unsigned &StructuredIndex,
615 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000616 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000617 SyntacticToSemantic[IList] = StructuredList;
618 StructuredList->setSyntacticForm(IList);
Mike Stump11289f42009-09-09 15:08:12 +0000619 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000620 StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000621 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000622 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000623 if (hadError)
624 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000625
Eli Friedman85f54972008-05-25 13:22:35 +0000626 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000627 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000628 if (StructuredIndex == 1 &&
629 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000630 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000631 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000632 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000633 hadError = true;
634 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000635 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000636 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000637 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000638 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000639 // Don't complain for incomplete types, since we'll get an error
640 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000641 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000642 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000643 CurrentObjectType->isArrayType()? 0 :
644 CurrentObjectType->isVectorType()? 1 :
645 CurrentObjectType->isScalarType()? 2 :
646 CurrentObjectType->isUnionType()? 3 :
647 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000648
649 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000650 if (SemaRef.getLangOptions().CPlusPlus) {
651 DK = diag::err_excess_initializers;
652 hadError = true;
653 }
Nate Begeman425038c2009-07-07 21:53:06 +0000654 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
655 DK = diag::err_excess_initializers;
656 hadError = true;
657 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000658
Chris Lattnerb0912a52009-02-24 22:50:46 +0000659 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000660 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000661 }
662 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000663
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000664 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000666 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000667 << CodeModificationHint::CreateRemoval(IList->getLocStart())
668 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000669}
670
Eli Friedman23a9e312008-05-19 19:16:24 +0000671void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000672 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000673 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000674 unsigned &Index,
675 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000676 unsigned &StructuredIndex,
677 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000678 if (DeclType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000679 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000680 } else if (DeclType->isVectorType()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000681 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000682 } else if (DeclType->isAggregateType()) {
683 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000684 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000685 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000686 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000687 StructuredList, StructuredIndex,
688 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000689 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000690 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000691 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000692 false);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000693 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
694 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000695 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000696 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000697 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
698 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000699 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000700 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000701 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000702 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000703 } else if (DeclType->isRecordType()) {
704 // C++ [dcl.init]p14:
705 // [...] If the class is an aggregate (8.5.1), and the initializer
706 // is a brace-enclosed list, see 8.5.1.
707 //
708 // Note: 8.5.1 is handled below; here, we diagnose the case where
709 // we have an initializer list and a destination type that is not
710 // an aggregate.
711 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000712 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000713 << DeclType << IList->getSourceRange();
714 hadError = true;
715 } else if (DeclType->isReferenceType()) {
716 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000717 } else {
718 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000719 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000720 assert(0 && "Unsupported initializer type");
721 }
722}
723
Eli Friedman23a9e312008-05-19 19:16:24 +0000724void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000725 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000726 unsigned &Index,
727 InitListExpr *StructuredList,
728 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000729 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000730 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
731 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000732 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000733 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000734 = getStructuredSubobjectInit(IList, Index, ElemType,
735 StructuredList, StructuredIndex,
736 SubInitList->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +0000737 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000738 newStructuredList, newStructuredIndex);
739 ++StructuredIndex;
740 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000741 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
742 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000743 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000744 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000745 } else if (ElemType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000746 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000747 } else if (ElemType->isReferenceType()) {
748 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000749 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000750 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000751 // C++ [dcl.init.aggr]p12:
752 // All implicit type conversions (clause 4) are considered when
753 // initializing the aggregate member with an ini- tializer from
754 // an initializer-list. If the initializer can initialize a
755 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000756 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000757 = SemaRef.TryCopyInitialization(expr, ElemType,
758 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000759 /*ForceRValue=*/false,
760 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000761
Douglas Gregord14247a2009-01-30 22:09:00 +0000762 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +0000763 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000764 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000765 hadError = true;
766 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
767 ++Index;
768 return;
769 }
770
771 // Fall through for subaggregate initialization
772 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000773 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000774 //
775 // The initializer for a structure or union object that has
776 // automatic storage duration shall be either an initializer
777 // list as described below, or a single expression that has
778 // compatible structure or union type. In the latter case, the
779 // initial value of the object, including unnamed members, is
780 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000781 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000782 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000783 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
784 ++Index;
785 return;
786 }
787
788 // Fall through for subaggregate initialization
789 }
790
791 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000792 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000793 // [...] Otherwise, if the member is itself a non-empty
794 // subaggregate, brace elision is assumed and the initializer is
795 // considered for the initialization of the first member of
796 // the subaggregate.
797 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000798 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000799 StructuredIndex);
800 ++StructuredIndex;
801 } else {
802 // We cannot initialize this element, so let
803 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000804 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000805 hadError = true;
806 ++Index;
807 ++StructuredIndex;
808 }
809 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000810}
811
Douglas Gregord14247a2009-01-30 22:09:00 +0000812void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000813 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000814 InitListExpr *StructuredList,
815 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000816 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000817 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000818 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000819 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000820 diag::err_many_braces_around_scalar_init)
821 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000822 hadError = true;
823 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000824 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000825 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000826 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000827 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000828 diag::err_designator_for_scalar_init)
829 << DeclType << expr->getSourceRange();
830 hadError = true;
831 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000832 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000833 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000834 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000835
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000836 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000837 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000838 hadError = true; // types weren't compatible.
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000839 else if (savExpr != expr) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000840 // The type was promoted, update initializer list.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000841 IList->setInit(Index, expr);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000842 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000843 if (hadError)
844 ++StructuredIndex;
845 else
846 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000847 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000848 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000849 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000850 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000851 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000852 ++Index;
853 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000854 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000855 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000856}
857
Douglas Gregord14247a2009-01-30 22:09:00 +0000858void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
859 unsigned &Index,
860 InitListExpr *StructuredList,
861 unsigned &StructuredIndex) {
862 if (Index < IList->getNumInits()) {
863 Expr *expr = IList->getInit(Index);
864 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000866 << DeclType << IList->getSourceRange();
867 hadError = true;
868 ++Index;
869 ++StructuredIndex;
870 return;
Mike Stump11289f42009-09-09 15:08:12 +0000871 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000872
873 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000874 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000875 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000876 /*SuppressUserConversions=*/false,
877 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000878 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000879 hadError = true;
880 else if (savExpr != expr) {
881 // The type was promoted, update initializer list.
882 IList->setInit(Index, expr);
883 }
884 if (hadError)
885 ++StructuredIndex;
886 else
887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
888 ++Index;
889 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000890 // FIXME: It would be wonderful if we could point at the actual member. In
891 // general, it would be useful to pass location information down the stack,
892 // so that we know the location (or decl) of the "current object" being
893 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000894 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000895 diag::err_init_reference_member_uninitialized)
896 << DeclType
897 << IList->getSourceRange();
898 hadError = true;
899 ++Index;
900 ++StructuredIndex;
901 return;
902 }
903}
904
Mike Stump11289f42009-09-09 15:08:12 +0000905void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000906 unsigned &Index,
907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000909 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000910 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000911 unsigned maxElements = VT->getNumElements();
912 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000913 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000914
Nate Begeman5ec4b312009-08-10 23:49:36 +0000915 if (!SemaRef.getLangOptions().OpenCL) {
916 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
917 // Don't attempt to go past the end of the init list
918 if (Index >= IList->getNumInits())
919 break;
920 CheckSubElementType(IList, elementType, Index,
921 StructuredList, StructuredIndex);
922 }
923 } else {
924 // OpenCL initializers allows vectors to be constructed from vectors.
925 for (unsigned i = 0; i < maxElements; ++i) {
926 // Don't attempt to go past the end of the init list
927 if (Index >= IList->getNumInits())
928 break;
929 QualType IType = IList->getInit(Index)->getType();
930 if (!IType->isVectorType()) {
931 CheckSubElementType(IList, elementType, Index,
932 StructuredList, StructuredIndex);
933 ++numEltsInit;
934 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000935 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000936 unsigned numIElts = IVT->getNumElements();
937 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
938 numIElts);
939 CheckSubElementType(IList, VecType, Index,
940 StructuredList, StructuredIndex);
941 numEltsInit += numIElts;
942 }
943 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000944 }
Mike Stump11289f42009-09-09 15:08:12 +0000945
Nate Begeman5ec4b312009-08-10 23:49:36 +0000946 // OpenCL & AltiVec require all elements to be initialized.
947 if (numEltsInit != maxElements)
948 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
949 SemaRef.Diag(IList->getSourceRange().getBegin(),
950 diag::err_vector_incorrect_num_initializers)
951 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000952 }
953}
954
Mike Stump11289f42009-09-09 15:08:12 +0000955void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000956 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000957 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000958 unsigned &Index,
959 InitListExpr *StructuredList,
960 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000961 // Check for the special-case of initializing an array with a string.
962 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000963 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
964 SemaRef.Context)) {
965 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000966 // We place the string literal directly into the resulting
967 // initializer list. This is the only place where the structure
968 // of the structured initializer list doesn't match exactly,
969 // because doing so would involve allocating one character
970 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000971 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000972 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000973 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000974 return;
975 }
976 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000977 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000978 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000979 // Check for VLAs; in standard C it would be possible to check this
980 // earlier, but I don't know where clang accepts VLAs (gcc accepts
981 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000982 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000983 diag::err_variable_object_no_init)
984 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000985 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000986 ++Index;
987 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000988 return;
989 }
990
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000991 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000992 llvm::APSInt maxElements(elementIndex.getBitWidth(),
993 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000994 bool maxElementsKnown = false;
995 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000996 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000997 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000998 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000999 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001000 maxElementsKnown = true;
1001 }
1002
Chris Lattnerb0912a52009-02-24 22:50:46 +00001003 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +00001004 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001005 while (Index < IList->getNumInits()) {
1006 Expr *Init = IList->getInit(Index);
1007 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001008 // If we're not the subobject that matches up with the '{' for
1009 // the designator, we shouldn't be handling the
1010 // designator. Return immediately.
1011 if (!SubobjectIsDesignatorContext)
1012 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001013
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001014 // Handle this designated initializer. elementIndex will be
1015 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +00001016 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001017 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001018 StructuredList, StructuredIndex, true,
1019 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001020 hadError = true;
1021 continue;
1022 }
1023
Douglas Gregor033d1252009-01-23 16:54:12 +00001024 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1025 maxElements.extend(elementIndex.getBitWidth());
1026 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1027 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001028 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001029
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001030 // If the array is of incomplete type, keep track of the number of
1031 // elements in the initializer.
1032 if (!maxElementsKnown && elementIndex > maxElements)
1033 maxElements = elementIndex;
1034
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001035 continue;
1036 }
1037
1038 // If we know the maximum number of elements, and we've already
1039 // hit it, stop consuming elements in the initializer list.
1040 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001041 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001042
1043 // Check this element.
Douglas Gregorf6d27522009-01-29 00:39:20 +00001044 CheckSubElementType(IList, elementType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001045 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001046 ++elementIndex;
1047
1048 // If the array is of incomplete type, keep track of the number of
1049 // elements in the initializer.
1050 if (!maxElementsKnown && elementIndex > maxElements)
1051 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001052 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001053 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001054 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001055 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001056 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001057 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001058 // Sizing an array implicitly to zero is not allowed by ISO C,
1059 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001060 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001061 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001062 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001063
Mike Stump11289f42009-09-09 15:08:12 +00001064 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001065 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001066 }
1067}
1068
Mike Stump11289f42009-09-09 15:08:12 +00001069void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1070 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001071 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001072 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001073 unsigned &Index,
1074 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001075 unsigned &StructuredIndex,
1076 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001077 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001078
Eli Friedman23a9e312008-05-19 19:16:24 +00001079 // If the record is invalid, some of it's members are invalid. To avoid
1080 // confusion, we forgo checking the intializer for the entire record.
1081 if (structDecl->isInvalidDecl()) {
1082 hadError = true;
1083 return;
Mike Stump11289f42009-09-09 15:08:12 +00001084 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001085
1086 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1087 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001088 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001089 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001090 Field != FieldEnd; ++Field) {
1091 if (Field->getDeclName()) {
1092 StructuredList->setInitializedFieldInUnion(*Field);
1093 break;
1094 }
1095 }
1096 return;
1097 }
1098
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001099 // If structDecl is a forward declaration, this loop won't do
1100 // anything except look at designated initializers; That's okay,
1101 // because an error should get printed out elsewhere. It might be
1102 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001103 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001104 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001105 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001106 while (Index < IList->getNumInits()) {
1107 Expr *Init = IList->getInit(Index);
1108
1109 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001110 // If we're not the subobject that matches up with the '{' for
1111 // the designator, we shouldn't be handling the
1112 // designator. Return immediately.
1113 if (!SubobjectIsDesignatorContext)
1114 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001115
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001116 // Handle this designated initializer. Field will be updated to
1117 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001118 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001119 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001120 StructuredList, StructuredIndex,
1121 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001122 hadError = true;
1123
Douglas Gregora9add4e2009-02-12 19:00:39 +00001124 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001125 continue;
1126 }
1127
1128 if (Field == FieldEnd) {
1129 // We've run out of fields. We're done.
1130 break;
1131 }
1132
Douglas Gregora9add4e2009-02-12 19:00:39 +00001133 // We've already initialized a member of a union. We're done.
1134 if (InitializedSomething && DeclType->isUnionType())
1135 break;
1136
Douglas Gregor91f84212008-12-11 16:49:14 +00001137 // If we've hit the flexible array member at the end, we're done.
1138 if (Field->getType()->isIncompleteArrayType())
1139 break;
1140
Douglas Gregor51695702009-01-29 16:53:55 +00001141 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001142 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001143 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001144 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001145 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001146
Douglas Gregorf6d27522009-01-29 00:39:20 +00001147 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001148 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001149 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001150
1151 if (DeclType->isUnionType()) {
1152 // Initialize the first field within the union.
1153 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001154 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001155
1156 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001157 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001158
Mike Stump11289f42009-09-09 15:08:12 +00001159 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001160 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001161 return;
1162
1163 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001165 (!isa<InitListExpr>(IList->getInit(Index)) ||
1166 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001167 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001168 diag::err_flexible_array_init_nonempty)
1169 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001170 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001171 << *Field;
1172 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001173 ++Index;
1174 return;
1175 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001176 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001177 diag::ext_flexible_array_init)
1178 << IList->getInit(Index)->getSourceRange().getBegin();
1179 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1180 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001181 }
1182
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001183 if (isa<InitListExpr>(IList->getInit(Index)))
1184 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1185 StructuredIndex);
1186 else
1187 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1188 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001189}
Steve Narofff8ecff22008-05-01 22:18:59 +00001190
Douglas Gregord5846a12009-04-15 06:41:24 +00001191/// \brief Expand a field designator that refers to a member of an
1192/// anonymous struct or union into a series of field designators that
1193/// refers to the field within the appropriate subobject.
1194///
1195/// Field/FieldIndex will be updated to point to the (new)
1196/// currently-designated field.
1197static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001198 DesignatedInitExpr *DIE,
1199 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001200 FieldDecl *Field,
1201 RecordDecl::field_iterator &FieldIter,
1202 unsigned &FieldIndex) {
1203 typedef DesignatedInitExpr::Designator Designator;
1204
1205 // Build the path from the current object to the member of the
1206 // anonymous struct/union (backwards).
1207 llvm::SmallVector<FieldDecl *, 4> Path;
1208 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregord5846a12009-04-15 06:41:24 +00001210 // Build the replacement designators.
1211 llvm::SmallVector<Designator, 4> Replacements;
1212 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1213 FI = Path.rbegin(), FIEnd = Path.rend();
1214 FI != FIEnd; ++FI) {
1215 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001216 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001217 DIE->getDesignator(DesigIdx)->getDotLoc(),
1218 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1219 else
1220 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1221 SourceLocation()));
1222 Replacements.back().setField(*FI);
1223 }
1224
1225 // Expand the current designator into the set of replacement
1226 // designators, so we have a full subobject path down to where the
1227 // member of the anonymous struct/union is actually stored.
Mike Stump11289f42009-09-09 15:08:12 +00001228 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001229 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001230
Douglas Gregord5846a12009-04-15 06:41:24 +00001231 // Update FieldIter/FieldIndex;
1232 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001233 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001234 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001235 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001236 FieldIter != FEnd; ++FieldIter) {
1237 if (FieldIter->isUnnamedBitfield())
1238 continue;
1239
1240 if (*FieldIter == Path.back())
1241 return;
1242
1243 ++FieldIndex;
1244 }
1245
1246 assert(false && "Unable to find anonymous struct/union field");
1247}
1248
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001249/// @brief Check the well-formedness of a C99 designated initializer.
1250///
1251/// Determines whether the designated initializer @p DIE, which
1252/// resides at the given @p Index within the initializer list @p
1253/// IList, is well-formed for a current object of type @p DeclType
1254/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001255/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001256/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001257///
1258/// @param IList The initializer list in which this designated
1259/// initializer occurs.
1260///
Douglas Gregora5324162009-04-15 04:56:10 +00001261/// @param DIE The designated initializer expression.
1262///
1263/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001264///
1265/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1266/// into which the designation in @p DIE should refer.
1267///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001268/// @param NextField If non-NULL and the first designator in @p DIE is
1269/// a field, this will be set to the field declaration corresponding
1270/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001271///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001272/// @param NextElementIndex If non-NULL and the first designator in @p
1273/// DIE is an array designator or GNU array-range designator, this
1274/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001275///
1276/// @param Index Index into @p IList where the designated initializer
1277/// @p DIE occurs.
1278///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001279/// @param StructuredList The initializer list expression that
1280/// describes all of the subobject initializers in the order they'll
1281/// actually be initialized.
1282///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001283/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001284bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001285InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001286 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001287 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001288 QualType &CurrentObjectType,
1289 RecordDecl::field_iterator *NextField,
1290 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001291 unsigned &Index,
1292 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001293 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001294 bool FinishSubobjectInit,
1295 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001296 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001297 // Check the actual initialization for the designated object type.
1298 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001299
1300 // Temporarily remove the designator expression from the
1301 // initializer list that the child calls see, so that we don't try
1302 // to re-process the designator.
1303 unsigned OldIndex = Index;
1304 IList->setInit(OldIndex, DIE->getInit());
1305
1306 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001307 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001308
1309 // Restore the designated initializer expression in the syntactic
1310 // form of the initializer list.
1311 if (IList->getInit(OldIndex) != DIE->getInit())
1312 DIE->setInit(IList->getInit(OldIndex));
1313 IList->setInit(OldIndex, DIE);
1314
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001315 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001316 }
1317
Douglas Gregora5324162009-04-15 04:56:10 +00001318 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001319 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001320 "Need a non-designated initializer list to start from");
1321
Douglas Gregora5324162009-04-15 04:56:10 +00001322 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001323 // Determine the structural initializer list that corresponds to the
1324 // current subobject.
1325 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001326 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001327 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001328 SourceRange(D->getStartLocation(),
1329 DIE->getSourceRange().getEnd()));
1330 assert(StructuredList && "Expected a structured initializer list");
1331
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001332 if (D->isFieldDesignator()) {
1333 // C99 6.7.8p7:
1334 //
1335 // If a designator has the form
1336 //
1337 // . identifier
1338 //
1339 // then the current object (defined below) shall have
1340 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001341 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001342 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001343 if (!RT) {
1344 SourceLocation Loc = D->getDotLoc();
1345 if (Loc.isInvalid())
1346 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001347 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1348 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001349 ++Index;
1350 return true;
1351 }
1352
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001353 // Note: we perform a linear search of the fields here, despite
1354 // the fact that we have a faster lookup method, because we always
1355 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001356 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001357 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001358 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001359 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001360 Field = RT->getDecl()->field_begin(),
1361 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001362 for (; Field != FieldEnd; ++Field) {
1363 if (Field->isUnnamedBitfield())
1364 continue;
1365
Douglas Gregord5846a12009-04-15 06:41:24 +00001366 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 break;
1368
1369 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001370 }
1371
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001372 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001373 // There was no normal field in the struct with the designated
1374 // name. Perform another lookup for this name, which may find
1375 // something that we can't designate (e.g., a member function),
1376 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001377 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001378 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001379 if (Lookup.first == Lookup.second) {
1380 // Name lookup didn't find anything.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001381 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001382 << FieldName << CurrentObjectType;
Douglas Gregord5846a12009-04-15 06:41:24 +00001383 ++Index;
1384 return true;
1385 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1386 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1387 ->isAnonymousStructOrUnion()) {
1388 // Handle an field designator that refers to a member of an
1389 // anonymous struct or union.
Mike Stump11289f42009-09-09 15:08:12 +00001390 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001391 cast<FieldDecl>(*Lookup.first),
1392 Field, FieldIndex);
Eli Friedman8d25b092009-04-16 17:49:48 +00001393 D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001394 } else {
1395 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001396 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001397 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001398 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001399 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001400 ++Index;
1401 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001402 }
1403 } else if (!KnownField &&
1404 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001405 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001406 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1407 Field, FieldIndex);
1408 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001409 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001410
1411 // All of the fields of a union are located at the same place in
1412 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001413 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001414 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001415 StructuredList->setInitializedFieldInUnion(*Field);
1416 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001417
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001418 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001419 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001420
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001421 // Make sure that our non-designated initializer list has space
1422 // for a subobject corresponding to this field.
1423 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001424 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001425
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001426 // This designator names a flexible array member.
1427 if (Field->getType()->isIncompleteArrayType()) {
1428 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001429 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001430 // We can't designate an object within the flexible array
1431 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001432 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001433 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001434 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001435 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001436 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001437 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001438 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001439 << *Field;
1440 Invalid = true;
1441 }
1442
1443 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1444 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001445 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001446 diag::err_flexible_array_init_needs_braces)
1447 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001448 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001449 << *Field;
1450 Invalid = true;
1451 }
1452
1453 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001455 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001456 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001457 diag::err_flexible_array_init_nonempty)
1458 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001460 << *Field;
1461 Invalid = true;
1462 }
1463
1464 if (Invalid) {
1465 ++Index;
1466 return true;
1467 }
1468
1469 // Initialize the array.
1470 bool prevHadError = hadError;
1471 unsigned newStructuredIndex = FieldIndex;
1472 unsigned OldIndex = Index;
1473 IList->setInit(Index, DIE->getInit());
Mike Stump11289f42009-09-09 15:08:12 +00001474 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001475 StructuredList, newStructuredIndex);
1476 IList->setInit(OldIndex, DIE);
1477 if (hadError && !prevHadError) {
1478 ++Field;
1479 ++FieldIndex;
1480 if (NextField)
1481 *NextField = Field;
1482 StructuredIndex = FieldIndex;
1483 return true;
1484 }
1485 } else {
1486 // Recurse to check later designated subobjects.
1487 QualType FieldType = (*Field)->getType();
1488 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001489 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1490 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001491 true, false))
1492 return true;
1493 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001494
1495 // Find the position of the next field to be initialized in this
1496 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001497 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001498 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001499
1500 // If this the first designator, our caller will continue checking
1501 // the rest of this struct/class/union subobject.
1502 if (IsFirstDesignator) {
1503 if (NextField)
1504 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001505 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001506 return false;
1507 }
1508
Douglas Gregor17bd0942009-01-28 23:36:17 +00001509 if (!FinishSubobjectInit)
1510 return false;
1511
Douglas Gregord5846a12009-04-15 06:41:24 +00001512 // We've already initialized something in the union; we're done.
1513 if (RT->getDecl()->isUnion())
1514 return hadError;
1515
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001516 // Check the remaining fields within this class/struct/union subobject.
1517 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001518 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1519 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001520 return hadError && !prevHadError;
1521 }
1522
1523 // C99 6.7.8p6:
1524 //
1525 // If a designator has the form
1526 //
1527 // [ constant-expression ]
1528 //
1529 // then the current object (defined below) shall have array
1530 // type and the expression shall be an integer constant
1531 // expression. If the array is of unknown size, any
1532 // nonnegative value is valid.
1533 //
1534 // Additionally, cope with the GNU extension that permits
1535 // designators of the form
1536 //
1537 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001538 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001539 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001540 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001541 << CurrentObjectType;
1542 ++Index;
1543 return true;
1544 }
1545
1546 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001547 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1548 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001549 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001550 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001551 DesignatedEndIndex = DesignatedStartIndex;
1552 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001553 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001554
Mike Stump11289f42009-09-09 15:08:12 +00001555
1556 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001557 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001558 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001559 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001560 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001561
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001562 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001563 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001564 }
1565
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001566 if (isa<ConstantArrayType>(AT)) {
1567 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001568 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1569 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1570 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1571 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1572 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001573 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001574 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001575 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001576 << IndexExpr->getSourceRange();
1577 ++Index;
1578 return true;
1579 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001580 } else {
1581 // Make sure the bit-widths and signedness match.
1582 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1583 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001584 else if (DesignatedStartIndex.getBitWidth() <
1585 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001586 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1587 DesignatedStartIndex.setIsUnsigned(true);
1588 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001589 }
Mike Stump11289f42009-09-09 15:08:12 +00001590
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001591 // Make sure that our non-designated initializer list has space
1592 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001593 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001594 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001595 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001596
Douglas Gregor17bd0942009-01-28 23:36:17 +00001597 // Repeatedly perform subobject initializations in the range
1598 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001599
Douglas Gregor17bd0942009-01-28 23:36:17 +00001600 // Move to the next designator
1601 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1602 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001603 while (DesignatedStartIndex <= DesignatedEndIndex) {
1604 // Recurse to check later designated subobjects.
1605 QualType ElementType = AT->getElementType();
1606 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001607 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1608 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001609 (DesignatedStartIndex == DesignatedEndIndex),
1610 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001611 return true;
1612
1613 // Move to the next index in the array that we'll be initializing.
1614 ++DesignatedStartIndex;
1615 ElementIndex = DesignatedStartIndex.getZExtValue();
1616 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001617
1618 // If this the first designator, our caller will continue checking
1619 // the rest of this array subobject.
1620 if (IsFirstDesignator) {
1621 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001622 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001623 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001624 return false;
1625 }
Mike Stump11289f42009-09-09 15:08:12 +00001626
Douglas Gregor17bd0942009-01-28 23:36:17 +00001627 if (!FinishSubobjectInit)
1628 return false;
1629
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001630 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001631 bool prevHadError = hadError;
Douglas Gregoraef040a2009-02-09 19:45:19 +00001632 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001633 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001634 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001635}
1636
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001637// Get the structured initializer list for a subobject of type
1638// @p CurrentObjectType.
1639InitListExpr *
1640InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1641 QualType CurrentObjectType,
1642 InitListExpr *StructuredList,
1643 unsigned StructuredIndex,
1644 SourceRange InitRange) {
1645 Expr *ExistingInit = 0;
1646 if (!StructuredList)
1647 ExistingInit = SyntacticToSemantic[IList];
1648 else if (StructuredIndex < StructuredList->getNumInits())
1649 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001651 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1652 return Result;
1653
1654 if (ExistingInit) {
1655 // We are creating an initializer list that initializes the
1656 // subobjects of the current object, but there was already an
1657 // initialization that completely initialized the current
1658 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001659 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001660 // struct X { int a, b; };
1661 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001662 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001663 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1664 // designated initializer re-initializes the whole
1665 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001666 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001667 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001668 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001669 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001670 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001671 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001672 << ExistingInit->getSourceRange();
1673 }
1674
Mike Stump11289f42009-09-09 15:08:12 +00001675 InitListExpr *Result
1676 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001677 InitRange.getEnd());
1678
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001679 Result->setType(CurrentObjectType);
1680
Douglas Gregor6d00c992009-03-20 23:58:33 +00001681 // Pre-allocate storage for the structured initializer list.
1682 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001683 unsigned NumInits = 0;
1684 if (!StructuredList)
1685 NumInits = IList->getNumInits();
1686 else if (Index < IList->getNumInits()) {
1687 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1688 NumInits = SubList->getNumInits();
1689 }
1690
Mike Stump11289f42009-09-09 15:08:12 +00001691 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001692 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1693 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1694 NumElements = CAType->getSize().getZExtValue();
1695 // Simple heuristic so that we don't allocate a very large
1696 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001697 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001698 NumElements = 0;
1699 }
John McCall9dd450b2009-09-21 23:43:11 +00001700 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001701 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001702 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001703 RecordDecl *RDecl = RType->getDecl();
1704 if (RDecl->isUnion())
1705 NumElements = 1;
1706 else
Mike Stump11289f42009-09-09 15:08:12 +00001707 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001708 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001709 }
1710
Douglas Gregor221c9a52009-03-21 18:13:52 +00001711 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001712 NumElements = IList->getNumInits();
1713
1714 Result->reserveInits(NumElements);
1715
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001716 // Link this new initializer list into the structured initializer
1717 // lists.
1718 if (StructuredList)
1719 StructuredList->updateInit(StructuredIndex, Result);
1720 else {
1721 Result->setSyntacticForm(IList);
1722 SyntacticToSemantic[IList] = Result;
1723 }
1724
1725 return Result;
1726}
1727
1728/// Update the initializer at index @p StructuredIndex within the
1729/// structured initializer list to the value @p expr.
1730void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1731 unsigned &StructuredIndex,
1732 Expr *expr) {
1733 // No structured initializer list to update
1734 if (!StructuredList)
1735 return;
1736
1737 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1738 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001739 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001740 diag::warn_initializer_overrides)
1741 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001742 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001743 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001744 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001745 << PrevInit->getSourceRange();
1746 }
Mike Stump11289f42009-09-09 15:08:12 +00001747
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001748 ++StructuredIndex;
1749}
1750
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001751/// Check that the given Index expression is a valid array designator
1752/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001753/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001754/// and produces a reasonable diagnostic if there is a
1755/// failure. Returns true if there was an error, false otherwise. If
1756/// everything went okay, Value will receive the value of the constant
1757/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001758static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001759CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001760 SourceLocation Loc = Index->getSourceRange().getBegin();
1761
1762 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001763 if (S.VerifyIntegerConstantExpression(Index, &Value))
1764 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001765
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001766 if (Value.isSigned() && Value.isNegative())
1767 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001768 << Value.toString(10) << Index->getSourceRange();
1769
Douglas Gregor51650d32009-01-23 21:04:18 +00001770 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001771 return false;
1772}
1773
1774Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1775 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001776 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001777 OwningExprResult Init) {
1778 typedef DesignatedInitExpr::Designator ASTDesignator;
1779
1780 bool Invalid = false;
1781 llvm::SmallVector<ASTDesignator, 32> Designators;
1782 llvm::SmallVector<Expr *, 32> InitExpressions;
1783
1784 // Build designators and check array designator expressions.
1785 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1786 const Designator &D = Desig.getDesignator(Idx);
1787 switch (D.getKind()) {
1788 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001789 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001790 D.getFieldLoc()));
1791 break;
1792
1793 case Designator::ArrayDesignator: {
1794 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1795 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001796 if (!Index->isTypeDependent() &&
1797 !Index->isValueDependent() &&
1798 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001799 Invalid = true;
1800 else {
1801 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001802 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001803 D.getRBracketLoc()));
1804 InitExpressions.push_back(Index);
1805 }
1806 break;
1807 }
1808
1809 case Designator::ArrayRangeDesignator: {
1810 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1811 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1812 llvm::APSInt StartValue;
1813 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001814 bool StartDependent = StartIndex->isTypeDependent() ||
1815 StartIndex->isValueDependent();
1816 bool EndDependent = EndIndex->isTypeDependent() ||
1817 EndIndex->isValueDependent();
1818 if ((!StartDependent &&
1819 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1820 (!EndDependent &&
1821 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001822 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001823 else {
1824 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001825 if (StartDependent || EndDependent) {
1826 // Nothing to compute.
1827 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001828 EndValue.extend(StartValue.getBitWidth());
1829 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1830 StartValue.extend(EndValue.getBitWidth());
1831
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001832 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001833 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001834 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001835 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1836 Invalid = true;
1837 } else {
1838 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001839 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001840 D.getEllipsisLoc(),
1841 D.getRBracketLoc()));
1842 InitExpressions.push_back(StartIndex);
1843 InitExpressions.push_back(EndIndex);
1844 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001845 }
1846 break;
1847 }
1848 }
1849 }
1850
1851 if (Invalid || Init.isInvalid())
1852 return ExprError();
1853
1854 // Clear out the expressions within the designation.
1855 Desig.ClearExprs(*this);
1856
1857 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001858 = DesignatedInitExpr::Create(Context,
1859 Designators.data(), Designators.size(),
1860 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001861 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001862 return Owned(DIE);
1863}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001864
Douglas Gregor723796a2009-12-16 06:35:08 +00001865bool Sema::CheckInitList(const InitializedEntity &Entity,
1866 InitListExpr *&InitList, QualType &DeclType) {
1867 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001868 if (!CheckInitList.HadError())
1869 InitList = CheckInitList.getFullyStructuredList();
1870
1871 return CheckInitList.HadError();
1872}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001873
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001874//===----------------------------------------------------------------------===//
1875// Initialization entity
1876//===----------------------------------------------------------------------===//
1877
Douglas Gregor723796a2009-12-16 06:35:08 +00001878InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1879 const InitializedEntity &Parent)
1880 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1881{
1882 if (isa<ArrayType>(Parent.TL.getType())) {
1883 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1884 return;
1885 }
1886
1887 // FIXME: should be able to get type location information for vectors, too.
1888
1889 QualType T;
1890 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1891 T = AT->getElementType();
1892 else
1893 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1894
1895 // FIXME: Once we've gone through the effort to create the fake
1896 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1897 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1898 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1899 TL = DI->getTypeLoc();
1900}
1901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001902void InitializedEntity::InitDeclLoc() {
1903 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1904 "InitDeclLoc cannot be used with non-declaration entities.");
1905
1906 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1907 TL = DI->getTypeLoc();
1908 return;
1909 }
1910
1911 // FIXME: Once we've gone through the effort to create the fake
1912 // TypeSourceInfo, should we cache it in the declaration?
1913 // (If not, we "leak" it).
1914 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1915 .CreateTypeSourceInfo(VariableOrMember->getType());
1916 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1917 TL = DI->getTypeLoc();
1918}
1919
1920InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1921 CXXBaseSpecifier *Base)
1922{
1923 InitializedEntity Result;
1924 Result.Kind = EK_Base;
1925 Result.Base = Base;
1926 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1927 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1928 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1929 Result.TL = DI->getTypeLoc();
1930 return Result;
1931}
1932
Douglas Gregor85dabae2009-12-16 01:38:02 +00001933DeclarationName InitializedEntity::getName() const {
1934 switch (getKind()) {
1935 case EK_Variable:
1936 case EK_Parameter:
1937 case EK_Member:
1938 return VariableOrMember->getDeclName();
1939
1940 case EK_Result:
1941 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001942 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001943 case EK_Temporary:
1944 case EK_Base:
Douglas Gregor723796a2009-12-16 06:35:08 +00001945 case EK_ArrayOrVectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001946 return DeclarationName();
1947 }
1948
1949 // Silence GCC warning
1950 return DeclarationName();
1951}
1952
Douglas Gregora4b592a2009-12-19 03:01:41 +00001953DeclaratorDecl *InitializedEntity::getDecl() const {
1954 switch (getKind()) {
1955 case EK_Variable:
1956 case EK_Parameter:
1957 case EK_Member:
1958 return VariableOrMember;
1959
1960 case EK_Result:
1961 case EK_Exception:
1962 case EK_New:
1963 case EK_Temporary:
1964 case EK_Base:
1965 case EK_ArrayOrVectorElement:
1966 return 0;
1967 }
1968
1969 // Silence GCC warning
1970 return 0;
1971}
1972
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001973//===----------------------------------------------------------------------===//
1974// Initialization sequence
1975//===----------------------------------------------------------------------===//
1976
1977void InitializationSequence::Step::Destroy() {
1978 switch (Kind) {
1979 case SK_ResolveAddressOfOverloadedFunction:
1980 case SK_CastDerivedToBaseRValue:
1981 case SK_CastDerivedToBaseLValue:
1982 case SK_BindReference:
1983 case SK_BindReferenceToTemporary:
1984 case SK_UserConversion:
1985 case SK_QualificationConversionRValue:
1986 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001987 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001988 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001989 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001990 case SK_CAssignment:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001991 break;
1992
1993 case SK_ConversionSequence:
1994 delete ICS;
1995 }
1996}
1997
1998void InitializationSequence::AddAddressOverloadResolutionStep(
1999 FunctionDecl *Function) {
2000 Step S;
2001 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2002 S.Type = Function->getType();
2003 S.Function = Function;
2004 Steps.push_back(S);
2005}
2006
2007void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2008 bool IsLValue) {
2009 Step S;
2010 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2011 S.Type = BaseType;
2012 Steps.push_back(S);
2013}
2014
2015void InitializationSequence::AddReferenceBindingStep(QualType T,
2016 bool BindingTemporary) {
2017 Step S;
2018 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2019 S.Type = T;
2020 Steps.push_back(S);
2021}
2022
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002023void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2024 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002025 Step S;
2026 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002027 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002028 S.Function = Function;
2029 Steps.push_back(S);
2030}
2031
2032void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2033 bool IsLValue) {
2034 Step S;
2035 S.Kind = IsLValue? SK_QualificationConversionLValue
2036 : SK_QualificationConversionRValue;
2037 S.Type = Ty;
2038 Steps.push_back(S);
2039}
2040
2041void InitializationSequence::AddConversionSequenceStep(
2042 const ImplicitConversionSequence &ICS,
2043 QualType T) {
2044 Step S;
2045 S.Kind = SK_ConversionSequence;
2046 S.Type = T;
2047 S.ICS = new ImplicitConversionSequence(ICS);
2048 Steps.push_back(S);
2049}
2050
Douglas Gregor51e77d52009-12-10 17:56:55 +00002051void InitializationSequence::AddListInitializationStep(QualType T) {
2052 Step S;
2053 S.Kind = SK_ListInitialization;
2054 S.Type = T;
2055 Steps.push_back(S);
2056}
2057
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002058void
2059InitializationSequence::AddConstructorInitializationStep(
2060 CXXConstructorDecl *Constructor,
2061 QualType T) {
2062 Step S;
2063 S.Kind = SK_ConstructorInitialization;
2064 S.Type = T;
2065 S.Function = Constructor;
2066 Steps.push_back(S);
2067}
2068
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002069void InitializationSequence::AddZeroInitializationStep(QualType T) {
2070 Step S;
2071 S.Kind = SK_ZeroInitialization;
2072 S.Type = T;
2073 Steps.push_back(S);
2074}
2075
Douglas Gregore1314a62009-12-18 05:02:21 +00002076void InitializationSequence::AddCAssignmentStep(QualType T) {
2077 Step S;
2078 S.Kind = SK_CAssignment;
2079 S.Type = T;
2080 Steps.push_back(S);
2081}
2082
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002083void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2084 OverloadingResult Result) {
2085 SequenceKind = FailedSequence;
2086 this->Failure = Failure;
2087 this->FailedOverloadResult = Result;
2088}
2089
2090//===----------------------------------------------------------------------===//
2091// Attempt initialization
2092//===----------------------------------------------------------------------===//
2093
2094/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002095static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002096 const InitializedEntity &Entity,
2097 const InitializationKind &Kind,
2098 InitListExpr *InitList,
2099 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002100 // FIXME: We only perform rudimentary checking of list
2101 // initializations at this point, then assume that any list
2102 // initialization of an array, aggregate, or scalar will be
2103 // well-formed. We we actually "perform" list initialization, we'll
2104 // do all of the necessary checking. C++0x initializer lists will
2105 // force us to perform more checking here.
2106 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2107
2108 QualType DestType = Entity.getType().getType();
2109
2110 // C++ [dcl.init]p13:
2111 // If T is a scalar type, then a declaration of the form
2112 //
2113 // T x = { a };
2114 //
2115 // is equivalent to
2116 //
2117 // T x = a;
2118 if (DestType->isScalarType()) {
2119 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2120 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2121 return;
2122 }
2123
2124 // Assume scalar initialization from a single value works.
2125 } else if (DestType->isAggregateType()) {
2126 // Assume aggregate initialization works.
2127 } else if (DestType->isVectorType()) {
2128 // Assume vector initialization works.
2129 } else if (DestType->isReferenceType()) {
2130 // FIXME: C++0x defines behavior for this.
2131 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2132 return;
2133 } else if (DestType->isRecordType()) {
2134 // FIXME: C++0x defines behavior for this
2135 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2136 }
2137
2138 // Add a general "list initialization" step.
2139 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002140}
2141
2142/// \brief Try a reference initialization that involves calling a conversion
2143/// function.
2144///
2145/// FIXME: look intos DRs 656, 896
2146static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2147 const InitializedEntity &Entity,
2148 const InitializationKind &Kind,
2149 Expr *Initializer,
2150 bool AllowRValues,
2151 InitializationSequence &Sequence) {
2152 QualType DestType = Entity.getType().getType();
2153 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2154 QualType T1 = cv1T1.getUnqualifiedType();
2155 QualType cv2T2 = Initializer->getType();
2156 QualType T2 = cv2T2.getUnqualifiedType();
2157
2158 bool DerivedToBase;
2159 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2160 T1, T2, DerivedToBase) &&
2161 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002162 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002163
2164 // Build the candidate set directly in the initialization sequence
2165 // structure, so that it will persist if we fail.
2166 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2167 CandidateSet.clear();
2168
2169 // Determine whether we are allowed to call explicit constructors or
2170 // explicit conversion operators.
2171 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2172
2173 const RecordType *T1RecordType = 0;
2174 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2175 // The type we're converting to is a class type. Enumerate its constructors
2176 // to see if there is a suitable conversion.
2177 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2178
2179 DeclarationName ConstructorName
2180 = S.Context.DeclarationNames.getCXXConstructorName(
2181 S.Context.getCanonicalType(T1).getUnqualifiedType());
2182 DeclContext::lookup_iterator Con, ConEnd;
2183 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2184 Con != ConEnd; ++Con) {
2185 // Find the constructor (which may be a template).
2186 CXXConstructorDecl *Constructor = 0;
2187 FunctionTemplateDecl *ConstructorTmpl
2188 = dyn_cast<FunctionTemplateDecl>(*Con);
2189 if (ConstructorTmpl)
2190 Constructor = cast<CXXConstructorDecl>(
2191 ConstructorTmpl->getTemplatedDecl());
2192 else
2193 Constructor = cast<CXXConstructorDecl>(*Con);
2194
2195 if (!Constructor->isInvalidDecl() &&
2196 Constructor->isConvertingConstructor(AllowExplicit)) {
2197 if (ConstructorTmpl)
2198 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2199 &Initializer, 1, CandidateSet);
2200 else
2201 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2202 }
2203 }
2204 }
2205
2206 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2207 // The type we're converting from is a class type, enumerate its conversion
2208 // functions.
2209 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2210
2211 // Determine the type we are converting to. If we are allowed to
2212 // convert to an rvalue, take the type that the destination type
2213 // refers to.
2214 QualType ToType = AllowRValues? cv1T1 : DestType;
2215
2216 const UnresolvedSet *Conversions
2217 = T2RecordDecl->getVisibleConversionFunctions();
2218 for (UnresolvedSet::iterator I = Conversions->begin(),
2219 E = Conversions->end();
2220 I != E; ++I) {
2221 NamedDecl *D = *I;
2222 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2223 if (isa<UsingShadowDecl>(D))
2224 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2225
2226 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2227 CXXConversionDecl *Conv;
2228 if (ConvTemplate)
2229 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2230 else
2231 Conv = cast<CXXConversionDecl>(*I);
2232
2233 // If the conversion function doesn't return a reference type,
2234 // it can't be considered for this conversion unless we're allowed to
2235 // consider rvalues.
2236 // FIXME: Do we need to make sure that we only consider conversion
2237 // candidates with reference-compatible results? That might be needed to
2238 // break recursion.
2239 if ((AllowExplicit || !Conv->isExplicit()) &&
2240 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2241 if (ConvTemplate)
2242 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2243 ToType, CandidateSet);
2244 else
2245 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2246 CandidateSet);
2247 }
2248 }
2249 }
2250
2251 SourceLocation DeclLoc = Initializer->getLocStart();
2252
2253 // Perform overload resolution. If it fails, return the failed result.
2254 OverloadCandidateSet::iterator Best;
2255 if (OverloadingResult Result
2256 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2257 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002258
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002259 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002260
2261 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002262 if (isa<CXXConversionDecl>(Function))
2263 T2 = Function->getResultType();
2264 else
2265 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002266
2267 // Add the user-defined conversion step.
2268 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2269
2270 // Determine whether we need to perform derived-to-base or
2271 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002272 bool NewDerivedToBase = false;
2273 Sema::ReferenceCompareResult NewRefRelationship
2274 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2275 NewDerivedToBase);
2276 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2277 "Overload resolution picked a bad conversion function");
2278 (void)NewRefRelationship;
2279 if (NewDerivedToBase)
2280 Sequence.AddDerivedToBaseCastStep(
2281 S.Context.getQualifiedType(T1,
2282 T2.getNonReferenceType().getQualifiers()),
2283 /*isLValue=*/true);
2284
2285 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2286 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2287
2288 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2289 return OR_Success;
2290}
2291
2292/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2293static void TryReferenceInitialization(Sema &S,
2294 const InitializedEntity &Entity,
2295 const InitializationKind &Kind,
2296 Expr *Initializer,
2297 InitializationSequence &Sequence) {
2298 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2299
2300 QualType DestType = Entity.getType().getType();
2301 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2302 QualType T1 = cv1T1.getUnqualifiedType();
2303 QualType cv2T2 = Initializer->getType();
2304 QualType T2 = cv2T2.getUnqualifiedType();
2305 SourceLocation DeclLoc = Initializer->getLocStart();
2306
2307 // If the initializer is the address of an overloaded function, try
2308 // to resolve the overloaded function. If all goes well, T2 is the
2309 // type of the resulting function.
2310 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2311 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2312 T1,
2313 false);
2314 if (!Fn) {
2315 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2316 return;
2317 }
2318
2319 Sequence.AddAddressOverloadResolutionStep(Fn);
2320 cv2T2 = Fn->getType();
2321 T2 = cv2T2.getUnqualifiedType();
2322 }
2323
2324 // FIXME: Rvalue references
2325 bool ForceRValue = false;
2326
2327 // Compute some basic properties of the types and the initializer.
2328 bool isLValueRef = DestType->isLValueReferenceType();
2329 bool isRValueRef = !isLValueRef;
2330 bool DerivedToBase = false;
2331 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2332 Initializer->isLvalue(S.Context);
2333 Sema::ReferenceCompareResult RefRelationship
2334 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2335
2336 // C++0x [dcl.init.ref]p5:
2337 // A reference to type "cv1 T1" is initialized by an expression of type
2338 // "cv2 T2" as follows:
2339 //
2340 // - If the reference is an lvalue reference and the initializer
2341 // expression
2342 OverloadingResult ConvOvlResult = OR_Success;
2343 if (isLValueRef) {
2344 if (InitLvalue == Expr::LV_Valid &&
2345 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2346 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2347 // reference-compatible with "cv2 T2," or
2348 //
2349 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2350 // bit-field when we're determining whether the reference initialization
2351 // can occur. This property will be checked by PerformInitialization.
2352 if (DerivedToBase)
2353 Sequence.AddDerivedToBaseCastStep(
2354 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2355 /*isLValue=*/true);
2356 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2357 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2358 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2359 return;
2360 }
2361
2362 // - has a class type (i.e., T2 is a class type), where T1 is not
2363 // reference-related to T2, and can be implicitly converted to an
2364 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2365 // with "cv3 T3" (this conversion is selected by enumerating the
2366 // applicable conversion functions (13.3.1.6) and choosing the best
2367 // one through overload resolution (13.3)),
2368 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2369 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2370 Initializer,
2371 /*AllowRValues=*/false,
2372 Sequence);
2373 if (ConvOvlResult == OR_Success)
2374 return;
2375 }
2376 }
2377
2378 // - Otherwise, the reference shall be an lvalue reference to a
2379 // non-volatile const type (i.e., cv1 shall be const), or the reference
2380 // shall be an rvalue reference and the initializer expression shall
2381 // be an rvalue.
2382 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2383 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2384 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2385 Sequence.SetOverloadFailure(
2386 InitializationSequence::FK_ReferenceInitOverloadFailed,
2387 ConvOvlResult);
2388 else if (isLValueRef)
2389 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2390 ? (RefRelationship == Sema::Ref_Related
2391 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2392 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2393 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2394 else
2395 Sequence.SetFailed(
2396 InitializationSequence::FK_RValueReferenceBindingToLValue);
2397
2398 return;
2399 }
2400
2401 // - If T1 and T2 are class types and
2402 if (T1->isRecordType() && T2->isRecordType()) {
2403 // - the initializer expression is an rvalue and "cv1 T1" is
2404 // reference-compatible with "cv2 T2", or
2405 if (InitLvalue != Expr::LV_Valid &&
2406 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2407 if (DerivedToBase)
2408 Sequence.AddDerivedToBaseCastStep(
2409 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2410 /*isLValue=*/false);
2411 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2412 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2413 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2414 return;
2415 }
2416
2417 // - T1 is not reference-related to T2 and the initializer expression
2418 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2419 // conversion is selected by enumerating the applicable conversion
2420 // functions (13.3.1.6) and choosing the best one through overload
2421 // resolution (13.3)),
2422 if (RefRelationship == Sema::Ref_Incompatible) {
2423 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2424 Kind, Initializer,
2425 /*AllowRValues=*/true,
2426 Sequence);
2427 if (ConvOvlResult)
2428 Sequence.SetOverloadFailure(
2429 InitializationSequence::FK_ReferenceInitOverloadFailed,
2430 ConvOvlResult);
2431
2432 return;
2433 }
2434
2435 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2436 return;
2437 }
2438
2439 // - If the initializer expression is an rvalue, with T2 an array type,
2440 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2441 // is bound to the object represented by the rvalue (see 3.10).
2442 // FIXME: How can an array type be reference-compatible with anything?
2443 // Don't we mean the element types of T1 and T2?
2444
2445 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2446 // from the initializer expression using the rules for a non-reference
2447 // copy initialization (8.5). The reference is then bound to the
2448 // temporary. [...]
2449 // Determine whether we are allowed to call explicit constructors or
2450 // explicit conversion operators.
2451 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2452 ImplicitConversionSequence ICS
2453 = S.TryImplicitConversion(Initializer, cv1T1,
2454 /*SuppressUserConversions=*/false, AllowExplicit,
2455 /*ForceRValue=*/false,
2456 /*FIXME:InOverloadResolution=*/false,
2457 /*UserCast=*/Kind.isExplicitCast());
2458
2459 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2460 // FIXME: Use the conversion function set stored in ICS to turn
2461 // this into an overloading ambiguity diagnostic. However, we need
2462 // to keep that set as an OverloadCandidateSet rather than as some
2463 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002464 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2465 Sequence.SetOverloadFailure(
2466 InitializationSequence::FK_ReferenceInitOverloadFailed,
2467 ConvOvlResult);
2468 else
2469 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002470 return;
2471 }
2472
2473 // [...] If T1 is reference-related to T2, cv1 must be the
2474 // same cv-qualification as, or greater cv-qualification
2475 // than, cv2; otherwise, the program is ill-formed.
2476 if (RefRelationship == Sema::Ref_Related &&
2477 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2478 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2479 return;
2480 }
2481
2482 // Perform the actual conversion.
2483 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2484 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2485 return;
2486}
2487
2488/// \brief Attempt character array initialization from a string literal
2489/// (C++ [dcl.init.string], C99 6.7.8).
2490static void TryStringLiteralInitialization(Sema &S,
2491 const InitializedEntity &Entity,
2492 const InitializationKind &Kind,
2493 Expr *Initializer,
2494 InitializationSequence &Sequence) {
2495 // FIXME: Implement!
2496}
2497
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2499/// enumerates the constructors of the initialized entity and performs overload
2500/// resolution to select the best.
2501static void TryConstructorInitialization(Sema &S,
2502 const InitializedEntity &Entity,
2503 const InitializationKind &Kind,
2504 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002505 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002506 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002507 if (Kind.getKind() == InitializationKind::IK_Copy)
2508 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2509 else
2510 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002511
2512 // Build the candidate set directly in the initialization sequence
2513 // structure, so that it will persist if we fail.
2514 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2515 CandidateSet.clear();
2516
2517 // Determine whether we are allowed to call explicit constructors or
2518 // explicit conversion operators.
2519 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2520 Kind.getKind() == InitializationKind::IK_Value ||
2521 Kind.getKind() == InitializationKind::IK_Default);
2522
2523 // The type we're converting to is a class type. Enumerate its constructors
2524 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002525 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2526 assert(DestRecordType && "Constructor initialization requires record type");
2527 CXXRecordDecl *DestRecordDecl
2528 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2529
2530 DeclarationName ConstructorName
2531 = S.Context.DeclarationNames.getCXXConstructorName(
2532 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2533 DeclContext::lookup_iterator Con, ConEnd;
2534 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2535 Con != ConEnd; ++Con) {
2536 // Find the constructor (which may be a template).
2537 CXXConstructorDecl *Constructor = 0;
2538 FunctionTemplateDecl *ConstructorTmpl
2539 = dyn_cast<FunctionTemplateDecl>(*Con);
2540 if (ConstructorTmpl)
2541 Constructor = cast<CXXConstructorDecl>(
2542 ConstructorTmpl->getTemplatedDecl());
2543 else
2544 Constructor = cast<CXXConstructorDecl>(*Con);
2545
2546 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002547 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002548 if (ConstructorTmpl)
2549 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2550 Args, NumArgs, CandidateSet);
2551 else
2552 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2553 }
2554 }
2555
2556 SourceLocation DeclLoc = Kind.getLocation();
2557
2558 // Perform overload resolution. If it fails, return the failed result.
2559 OverloadCandidateSet::iterator Best;
2560 if (OverloadingResult Result
2561 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2562 Sequence.SetOverloadFailure(
2563 InitializationSequence::FK_ConstructorOverloadFailed,
2564 Result);
2565 return;
2566 }
2567
2568 // Add the constructor initialization step. Any cv-qualification conversion is
2569 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002570 if (Kind.getKind() == InitializationKind::IK_Copy) {
2571 Sequence.AddUserConversionStep(Best->Function, DestType);
2572 } else {
2573 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002574 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002575 DestType);
2576 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002577}
2578
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002579/// \brief Attempt value initialization (C++ [dcl.init]p7).
2580static void TryValueInitialization(Sema &S,
2581 const InitializedEntity &Entity,
2582 const InitializationKind &Kind,
2583 InitializationSequence &Sequence) {
2584 // C++ [dcl.init]p5:
2585 //
2586 // To value-initialize an object of type T means:
2587 QualType T = Entity.getType().getType();
2588
2589 // -- if T is an array type, then each element is value-initialized;
2590 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2591 T = AT->getElementType();
2592
2593 if (const RecordType *RT = T->getAs<RecordType>()) {
2594 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2595 // -- if T is a class type (clause 9) with a user-declared
2596 // constructor (12.1), then the default constructor for T is
2597 // called (and the initialization is ill-formed if T has no
2598 // accessible default constructor);
2599 //
2600 // FIXME: we really want to refer to a single subobject of the array,
2601 // but Entity doesn't have a way to capture that (yet).
2602 if (ClassDecl->hasUserDeclaredConstructor())
2603 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2604
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002605 // -- if T is a (possibly cv-qualified) non-union class type
2606 // without a user-provided constructor, then the object is
2607 // zero-initialized and, if T’s implicitly-declared default
2608 // constructor is non-trivial, that constructor is called.
2609 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2610 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2611 !ClassDecl->hasTrivialConstructor()) {
2612 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2613 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2614 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002615 }
2616 }
2617
2618 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2619 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2620}
2621
Douglas Gregor85dabae2009-12-16 01:38:02 +00002622/// \brief Attempt default initialization (C++ [dcl.init]p6).
2623static void TryDefaultInitialization(Sema &S,
2624 const InitializedEntity &Entity,
2625 const InitializationKind &Kind,
2626 InitializationSequence &Sequence) {
2627 assert(Kind.getKind() == InitializationKind::IK_Default);
2628
2629 // C++ [dcl.init]p6:
2630 // To default-initialize an object of type T means:
2631 // - if T is an array type, each element is default-initialized;
2632 QualType DestType = Entity.getType().getType();
2633 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2634 DestType = Array->getElementType();
2635
2636 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2637 // constructor for T is called (and the initialization is ill-formed if
2638 // T has no accessible default constructor);
2639 if (DestType->isRecordType()) {
2640 // FIXME: If a program calls for the default initialization of an object of
2641 // a const-qualified type T, T shall be a class type with a user-provided
2642 // default constructor.
2643 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2644 Sequence);
2645 }
2646
2647 // - otherwise, no initialization is performed.
2648 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2649
2650 // If a program calls for the default initialization of an object of
2651 // a const-qualified type T, T shall be a class type with a user-provided
2652 // default constructor.
2653 if (DestType.isConstQualified())
2654 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2655}
2656
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002657/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2658/// which enumerates all conversion functions and performs overload resolution
2659/// to select the best.
2660static void TryUserDefinedConversion(Sema &S,
2661 const InitializedEntity &Entity,
2662 const InitializationKind &Kind,
2663 Expr *Initializer,
2664 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002665 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2666
2667 QualType DestType = Entity.getType().getType();
2668 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2669 QualType SourceType = Initializer->getType();
2670 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2671 "Must have a class type to perform a user-defined conversion");
2672
2673 // Build the candidate set directly in the initialization sequence
2674 // structure, so that it will persist if we fail.
2675 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2676 CandidateSet.clear();
2677
2678 // Determine whether we are allowed to call explicit constructors or
2679 // explicit conversion operators.
2680 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2681
2682 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2683 // The type we're converting to is a class type. Enumerate its constructors
2684 // to see if there is a suitable conversion.
2685 CXXRecordDecl *DestRecordDecl
2686 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2687
2688 DeclarationName ConstructorName
2689 = S.Context.DeclarationNames.getCXXConstructorName(
2690 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2691 DeclContext::lookup_iterator Con, ConEnd;
2692 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2693 Con != ConEnd; ++Con) {
2694 // Find the constructor (which may be a template).
2695 CXXConstructorDecl *Constructor = 0;
2696 FunctionTemplateDecl *ConstructorTmpl
2697 = dyn_cast<FunctionTemplateDecl>(*Con);
2698 if (ConstructorTmpl)
2699 Constructor = cast<CXXConstructorDecl>(
2700 ConstructorTmpl->getTemplatedDecl());
2701 else
2702 Constructor = cast<CXXConstructorDecl>(*Con);
2703
2704 if (!Constructor->isInvalidDecl() &&
2705 Constructor->isConvertingConstructor(AllowExplicit)) {
2706 if (ConstructorTmpl)
2707 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2708 &Initializer, 1, CandidateSet);
2709 else
2710 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2711 }
2712 }
2713 }
2714
2715 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2716 // The type we're converting from is a class type, enumerate its conversion
2717 // functions.
2718 CXXRecordDecl *SourceRecordDecl
2719 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2720
2721 const UnresolvedSet *Conversions
2722 = SourceRecordDecl->getVisibleConversionFunctions();
2723 for (UnresolvedSet::iterator I = Conversions->begin(),
2724 E = Conversions->end();
2725 I != E; ++I) {
2726 NamedDecl *D = *I;
2727 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2728 if (isa<UsingShadowDecl>(D))
2729 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2730
2731 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2732 CXXConversionDecl *Conv;
2733 if (ConvTemplate)
2734 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2735 else
2736 Conv = cast<CXXConversionDecl>(*I);
2737
2738 if (AllowExplicit || !Conv->isExplicit()) {
2739 if (ConvTemplate)
2740 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2741 DestType, CandidateSet);
2742 else
2743 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2744 CandidateSet);
2745 }
2746 }
2747 }
2748
2749 SourceLocation DeclLoc = Initializer->getLocStart();
2750
2751 // Perform overload resolution. If it fails, return the failed result.
2752 OverloadCandidateSet::iterator Best;
2753 if (OverloadingResult Result
2754 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2755 Sequence.SetOverloadFailure(
2756 InitializationSequence::FK_UserConversionOverloadFailed,
2757 Result);
2758 return;
2759 }
2760
2761 FunctionDecl *Function = Best->Function;
2762
2763 if (isa<CXXConstructorDecl>(Function)) {
2764 // Add the user-defined conversion step. Any cv-qualification conversion is
2765 // subsumed by the initialization.
2766 Sequence.AddUserConversionStep(Function, DestType);
2767 return;
2768 }
2769
2770 // Add the user-defined conversion step that calls the conversion function.
2771 QualType ConvType = Function->getResultType().getNonReferenceType();
2772 Sequence.AddUserConversionStep(Function, ConvType);
2773
2774 // If the conversion following the call to the conversion function is
2775 // interesting, add it as a separate step.
2776 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2777 Best->FinalConversion.Third) {
2778 ImplicitConversionSequence ICS;
2779 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2780 ICS.Standard = Best->FinalConversion;
2781 Sequence.AddConversionSequenceStep(ICS, DestType);
2782 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002783}
2784
2785/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2786/// non-class type to another.
2787static void TryImplicitConversion(Sema &S,
2788 const InitializedEntity &Entity,
2789 const InitializationKind &Kind,
2790 Expr *Initializer,
2791 InitializationSequence &Sequence) {
2792 ImplicitConversionSequence ICS
2793 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2794 /*SuppressUserConversions=*/true,
2795 /*AllowExplicit=*/false,
2796 /*ForceRValue=*/false,
2797 /*FIXME:InOverloadResolution=*/false,
2798 /*UserCast=*/Kind.isExplicitCast());
2799
2800 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2801 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2802 return;
2803 }
2804
2805 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2806}
2807
2808InitializationSequence::InitializationSequence(Sema &S,
2809 const InitializedEntity &Entity,
2810 const InitializationKind &Kind,
2811 Expr **Args,
2812 unsigned NumArgs) {
2813 ASTContext &Context = S.Context;
2814
2815 // C++0x [dcl.init]p16:
2816 // The semantics of initializers are as follows. The destination type is
2817 // the type of the object or reference being initialized and the source
2818 // type is the type of the initializer expression. The source type is not
2819 // defined when the initializer is a braced-init-list or when it is a
2820 // parenthesized list of expressions.
2821 QualType DestType = Entity.getType().getType();
2822
2823 if (DestType->isDependentType() ||
2824 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2825 SequenceKind = DependentSequence;
2826 return;
2827 }
2828
2829 QualType SourceType;
2830 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002831 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002832 Initializer = Args[0];
2833 if (!isa<InitListExpr>(Initializer))
2834 SourceType = Initializer->getType();
2835 }
2836
2837 // - If the initializer is a braced-init-list, the object is
2838 // list-initialized (8.5.4).
2839 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2840 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002841 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002842 }
2843
2844 // - If the destination type is a reference type, see 8.5.3.
2845 if (DestType->isReferenceType()) {
2846 // C++0x [dcl.init.ref]p1:
2847 // A variable declared to be a T& or T&&, that is, "reference to type T"
2848 // (8.3.2), shall be initialized by an object, or function, of type T or
2849 // by an object that can be converted into a T.
2850 // (Therefore, multiple arguments are not permitted.)
2851 if (NumArgs != 1)
2852 SetFailed(FK_TooManyInitsForReference);
2853 else
2854 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2855 return;
2856 }
2857
2858 // - If the destination type is an array of characters, an array of
2859 // char16_t, an array of char32_t, or an array of wchar_t, and the
2860 // initializer is a string literal, see 8.5.2.
2861 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2862 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2863 return;
2864 }
2865
2866 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002867 if (Kind.getKind() == InitializationKind::IK_Value ||
2868 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002869 TryValueInitialization(S, Entity, Kind, *this);
2870 return;
2871 }
2872
Douglas Gregor85dabae2009-12-16 01:38:02 +00002873 // Handle default initialization.
2874 if (Kind.getKind() == InitializationKind::IK_Default){
2875 TryDefaultInitialization(S, Entity, Kind, *this);
2876 return;
2877 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002878
2879 // Handle initialization in C
2880 if (!S.getLangOptions().CPlusPlus) {
2881 setSequenceKind(CAssignment);
2882 AddCAssignmentStep(DestType);
2883 return;
2884 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00002885
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002886 // - Otherwise, if the destination type is an array, the program is
2887 // ill-formed.
2888 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2889 if (AT->getElementType()->isAnyCharacterType())
2890 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2891 else
2892 SetFailed(FK_ArrayNeedsInitList);
2893
2894 return;
2895 }
2896
2897 // - If the destination type is a (possibly cv-qualified) class type:
2898 if (DestType->isRecordType()) {
2899 // - If the initialization is direct-initialization, or if it is
2900 // copy-initialization where the cv-unqualified version of the
2901 // source type is the same class as, or a derived class of, the
2902 // class of the destination, constructors are considered. [...]
2903 if (Kind.getKind() == InitializationKind::IK_Direct ||
2904 (Kind.getKind() == InitializationKind::IK_Copy &&
2905 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2906 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002907 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2908 Entity.getType().getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002909 // - Otherwise (i.e., for the remaining copy-initialization cases),
2910 // user-defined conversion sequences that can convert from the source
2911 // type to the destination type or (when a conversion function is
2912 // used) to a derived class thereof are enumerated as described in
2913 // 13.3.1.4, and the best one is chosen through overload resolution
2914 // (13.3).
2915 else
2916 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2917 return;
2918 }
2919
Douglas Gregor85dabae2009-12-16 01:38:02 +00002920 if (NumArgs > 1) {
2921 SetFailed(FK_TooManyInitsForScalar);
2922 return;
2923 }
2924 assert(NumArgs == 1 && "Zero-argument case handled above");
2925
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002926 // - Otherwise, if the source type is a (possibly cv-qualified) class
2927 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002928 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002929 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2930 return;
2931 }
2932
2933 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002934 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002935 // conversions (Clause 4) will be used, if necessary, to convert the
2936 // initializer expression to the cv-unqualified version of the
2937 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002938 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002939 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2940}
2941
2942InitializationSequence::~InitializationSequence() {
2943 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2944 StepEnd = Steps.end();
2945 Step != StepEnd; ++Step)
2946 Step->Destroy();
2947}
2948
2949//===----------------------------------------------------------------------===//
2950// Perform initialization
2951//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002952static Sema::AssignmentAction
2953getAssignmentAction(const InitializedEntity &Entity) {
2954 switch(Entity.getKind()) {
2955 case InitializedEntity::EK_Variable:
2956 case InitializedEntity::EK_New:
2957 return Sema::AA_Initializing;
2958
2959 case InitializedEntity::EK_Parameter:
2960 // FIXME: Can we tell when we're sending vs. passing?
2961 return Sema::AA_Passing;
2962
2963 case InitializedEntity::EK_Result:
2964 return Sema::AA_Returning;
2965
2966 case InitializedEntity::EK_Exception:
2967 case InitializedEntity::EK_Base:
2968 llvm_unreachable("No assignment action for C++-specific initialization");
2969 break;
2970
2971 case InitializedEntity::EK_Temporary:
2972 // FIXME: Can we tell apart casting vs. converting?
2973 return Sema::AA_Casting;
2974
2975 case InitializedEntity::EK_Member:
2976 case InitializedEntity::EK_ArrayOrVectorElement:
2977 return Sema::AA_Initializing;
2978 }
2979
2980 return Sema::AA_Converting;
2981}
2982
2983static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2984 bool IsCopy) {
2985 switch (Entity.getKind()) {
2986 case InitializedEntity::EK_Result:
2987 case InitializedEntity::EK_Exception:
2988 return !IsCopy;
2989
2990 case InitializedEntity::EK_New:
2991 case InitializedEntity::EK_Variable:
2992 case InitializedEntity::EK_Base:
2993 case InitializedEntity::EK_Member:
2994 case InitializedEntity::EK_ArrayOrVectorElement:
2995 return false;
2996
2997 case InitializedEntity::EK_Parameter:
2998 case InitializedEntity::EK_Temporary:
2999 return true;
3000 }
3001
3002 llvm_unreachable("missed an InitializedEntity kind?");
3003}
3004
3005/// \brief If we need to perform an additional copy of the initialized object
3006/// for this kind of entity (e.g., the result of a function or an object being
3007/// thrown), make the copy.
3008static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3009 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00003010 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00003011 Sema::OwningExprResult CurInit) {
3012 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003013
3014 switch (Entity.getKind()) {
3015 case InitializedEntity::EK_Result:
3016 if (Entity.getType().getType()->isReferenceType())
3017 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00003018 Loc = Entity.getReturnLoc();
3019 break;
3020
3021 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003022 Loc = Entity.getThrowLoc();
3023 break;
3024
3025 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003026 if (Entity.getType().getType()->isReferenceType() ||
3027 Kind.getKind() != InitializationKind::IK_Copy)
3028 return move(CurInit);
3029 Loc = Entity.getDecl()->getLocation();
3030 break;
3031
Douglas Gregore1314a62009-12-18 05:02:21 +00003032 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003033 // FIXME: Do we need this initialization for a parameter?
3034 return move(CurInit);
3035
Douglas Gregore1314a62009-12-18 05:02:21 +00003036 case InitializedEntity::EK_New:
3037 case InitializedEntity::EK_Temporary:
3038 case InitializedEntity::EK_Base:
3039 case InitializedEntity::EK_Member:
3040 case InitializedEntity::EK_ArrayOrVectorElement:
3041 // We don't need to copy for any of these initialized entities.
3042 return move(CurInit);
3043 }
3044
3045 Expr *CurInitExpr = (Expr *)CurInit.get();
3046 CXXRecordDecl *Class = 0;
3047 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3048 Class = cast<CXXRecordDecl>(Record->getDecl());
3049 if (!Class)
3050 return move(CurInit);
3051
3052 // Perform overload resolution using the class's copy constructors.
3053 DeclarationName ConstructorName
3054 = S.Context.DeclarationNames.getCXXConstructorName(
3055 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3056 DeclContext::lookup_iterator Con, ConEnd;
3057 OverloadCandidateSet CandidateSet;
3058 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3059 Con != ConEnd; ++Con) {
3060 // Find the constructor (which may be a template).
3061 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3062 if (!Constructor || Constructor->isInvalidDecl() ||
3063 !Constructor->isCopyConstructor(S.Context))
3064 continue;
3065
3066 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3067 }
3068
3069 OverloadCandidateSet::iterator Best;
3070 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3071 case OR_Success:
3072 break;
3073
3074 case OR_No_Viable_Function:
3075 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003076 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003077 << CurInitExpr->getSourceRange();
3078 S.PrintOverloadCandidates(CandidateSet, false);
3079 return S.ExprError();
3080
3081 case OR_Ambiguous:
3082 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003083 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003084 << CurInitExpr->getSourceRange();
3085 S.PrintOverloadCandidates(CandidateSet, true);
3086 return S.ExprError();
3087
3088 case OR_Deleted:
3089 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003090 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003091 << CurInitExpr->getSourceRange();
3092 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3093 << Best->Function->isDeleted();
3094 return S.ExprError();
3095 }
3096
3097 CurInit.release();
3098 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3099 cast<CXXConstructorDecl>(Best->Function),
3100 /*Elidable=*/true,
3101 Sema::MultiExprArg(S,
3102 (void**)&CurInitExpr, 1));
3103}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003104
3105Action::OwningExprResult
3106InitializationSequence::Perform(Sema &S,
3107 const InitializedEntity &Entity,
3108 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003109 Action::MultiExprArg Args,
3110 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003111 if (SequenceKind == FailedSequence) {
3112 unsigned NumArgs = Args.size();
3113 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3114 return S.ExprError();
3115 }
3116
3117 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003118 // If the declaration is a non-dependent, incomplete array type
3119 // that has an initializer, then its type will be completed once
3120 // the initializer is instantiated.
3121 if (ResultType && !Entity.getType().getType()->isDependentType() &&
3122 Args.size() == 1) {
3123 QualType DeclType = Entity.getType().getType();
3124 if (const IncompleteArrayType *ArrayT
3125 = S.Context.getAsIncompleteArrayType(DeclType)) {
3126 // FIXME: We don't currently have the ability to accurately
3127 // compute the length of an initializer list without
3128 // performing full type-checking of the initializer list
3129 // (since we have to determine where braces are implicitly
3130 // introduced and such). So, we fall back to making the array
3131 // type a dependently-sized array type with no specified
3132 // bound.
3133 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3134 SourceRange Brackets;
3135 // Scavange the location of the brackets from the entity, if we can.
3136 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
3137 IncompleteArrayTypeLoc ArrayLoc
3138 = cast<IncompleteArrayTypeLoc>(Entity.getType());
3139 Brackets = ArrayLoc.getBracketsRange();
3140 }
3141
3142 *ResultType
3143 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3144 /*NumElts=*/0,
3145 ArrayT->getSizeModifier(),
3146 ArrayT->getIndexTypeCVRQualifiers(),
3147 Brackets);
3148 }
3149
3150 }
3151 }
3152
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003153 if (Kind.getKind() == InitializationKind::IK_Copy)
3154 return Sema::OwningExprResult(S, Args.release()[0]);
3155
3156 unsigned NumArgs = Args.size();
3157 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3158 SourceLocation(),
3159 (Expr **)Args.release(),
3160 NumArgs,
3161 SourceLocation()));
3162 }
3163
Douglas Gregor85dabae2009-12-16 01:38:02 +00003164 if (SequenceKind == NoInitialization)
3165 return S.Owned((Expr *)0);
3166
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003167 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003168 if (ResultType)
3169 *ResultType = Entity.getType().getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003170
Douglas Gregor85dabae2009-12-16 01:38:02 +00003171 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3172
3173 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3174
3175 // For initialization steps that start with a single initializer,
3176 // grab the only argument out the Args and place it into the "current"
3177 // initializer.
3178 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003179 case SK_ResolveAddressOfOverloadedFunction:
3180 case SK_CastDerivedToBaseRValue:
3181 case SK_CastDerivedToBaseLValue:
3182 case SK_BindReference:
3183 case SK_BindReferenceToTemporary:
3184 case SK_UserConversion:
3185 case SK_QualificationConversionLValue:
3186 case SK_QualificationConversionRValue:
3187 case SK_ConversionSequence:
3188 case SK_ListInitialization:
3189 case SK_CAssignment:
3190 assert(Args.size() == 1);
3191 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3192 if (CurInit.isInvalid())
3193 return S.ExprError();
3194 break;
3195
3196 case SK_ConstructorInitialization:
3197 case SK_ZeroInitialization:
3198 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003199 }
3200
3201 // Walk through the computed steps for the initialization sequence,
3202 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003203 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003204 for (step_iterator Step = step_begin(), StepEnd = step_end();
3205 Step != StepEnd; ++Step) {
3206 if (CurInit.isInvalid())
3207 return S.ExprError();
3208
3209 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003210 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003211
3212 switch (Step->Kind) {
3213 case SK_ResolveAddressOfOverloadedFunction:
3214 // Overload resolution determined which function invoke; update the
3215 // initializer to reflect that choice.
3216 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3217 break;
3218
3219 case SK_CastDerivedToBaseRValue:
3220 case SK_CastDerivedToBaseLValue: {
3221 // We have a derived-to-base cast that produces either an rvalue or an
3222 // lvalue. Perform that cast.
3223
3224 // Casts to inaccessible base classes are allowed with C-style casts.
3225 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3226 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3227 CurInitExpr->getLocStart(),
3228 CurInitExpr->getSourceRange(),
3229 IgnoreBaseAccess))
3230 return S.ExprError();
3231
3232 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3233 CastExpr::CK_DerivedToBase,
3234 (Expr*)CurInit.release(),
3235 Step->Kind == SK_CastDerivedToBaseLValue));
3236 break;
3237 }
3238
3239 case SK_BindReference:
3240 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3241 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3242 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3243 << Entity.getType().getType().isVolatileQualified()
3244 << BitField->getDeclName()
3245 << CurInitExpr->getSourceRange();
3246 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3247 return S.ExprError();
3248 }
3249
3250 // Reference binding does not have any corresponding ASTs.
3251
3252 // Check exception specifications
3253 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3254 return S.ExprError();
3255 break;
3256
3257 case SK_BindReferenceToTemporary:
3258 // Check exception specifications
3259 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3260 return S.ExprError();
3261
3262 // FIXME: At present, we have no AST to describe when we need to make a
3263 // temporary to bind a reference to. We should.
3264 break;
3265
3266 case SK_UserConversion: {
3267 // We have a user-defined conversion that invokes either a constructor
3268 // or a conversion function.
3269 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003270 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003271 if (CXXConstructorDecl *Constructor
3272 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3273 // Build a call to the selected constructor.
3274 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3275 SourceLocation Loc = CurInitExpr->getLocStart();
3276 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3277
3278 // Determine the arguments required to actually perform the constructor
3279 // call.
3280 if (S.CompleteConstructorCall(Constructor,
3281 Sema::MultiExprArg(S,
3282 (void **)&CurInitExpr,
3283 1),
3284 Loc, ConstructorArgs))
3285 return S.ExprError();
3286
3287 // Build the an expression that constructs a temporary.
3288 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3289 move_arg(ConstructorArgs));
3290 if (CurInit.isInvalid())
3291 return S.ExprError();
3292
3293 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003294 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3295 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3296 S.IsDerivedFrom(SourceType, Class))
3297 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003298 } else {
3299 // Build a call to the conversion function.
3300 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003301
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003302 // FIXME: Should we move this initialization into a separate
3303 // derived-to-base conversion? I believe the answer is "no", because
3304 // we don't want to turn off access control here for c-style casts.
3305 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3306 return S.ExprError();
3307
3308 // Do a little dance to make sure that CurInit has the proper
3309 // pointer.
3310 CurInit.release();
3311
3312 // Build the actual call to the conversion function.
3313 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3314 if (CurInit.isInvalid() || !CurInit.get())
3315 return S.ExprError();
3316
3317 CastKind = CastExpr::CK_UserDefinedConversion;
3318 }
3319
Douglas Gregore1314a62009-12-18 05:02:21 +00003320 if (shouldBindAsTemporary(Entity, IsCopy))
3321 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3322
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003323 CurInitExpr = CurInit.takeAs<Expr>();
3324 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3325 CastKind,
3326 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003327 false));
3328
3329 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003330 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003331 break;
3332 }
3333
3334 case SK_QualificationConversionLValue:
3335 case SK_QualificationConversionRValue:
3336 // Perform a qualification conversion; these can never go wrong.
3337 S.ImpCastExprToType(CurInitExpr, Step->Type,
3338 CastExpr::CK_NoOp,
3339 Step->Kind == SK_QualificationConversionLValue);
3340 CurInit.release();
3341 CurInit = S.Owned(CurInitExpr);
3342 break;
3343
3344 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003345 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003346 false, false, *Step->ICS))
3347 return S.ExprError();
3348
3349 CurInit.release();
3350 CurInit = S.Owned(CurInitExpr);
3351 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003352
3353 case SK_ListInitialization: {
3354 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3355 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003356 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003357 return S.ExprError();
3358
3359 CurInit.release();
3360 CurInit = S.Owned(InitList);
3361 break;
3362 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003363
3364 case SK_ConstructorInitialization: {
3365 CXXConstructorDecl *Constructor
3366 = cast<CXXConstructorDecl>(Step->Function);
3367
3368 // Build a call to the selected constructor.
3369 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3370 SourceLocation Loc = Kind.getLocation();
3371
3372 // Determine the arguments required to actually perform the constructor
3373 // call.
3374 if (S.CompleteConstructorCall(Constructor, move(Args),
3375 Loc, ConstructorArgs))
3376 return S.ExprError();
3377
3378 // Build the an expression that constructs a temporary.
3379 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003380 move_arg(ConstructorArgs),
3381 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003382 if (CurInit.isInvalid())
3383 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003384
3385 bool Elidable
3386 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3387 if (shouldBindAsTemporary(Entity, Elidable))
3388 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3389
3390 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003391 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003392 break;
3393 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003394
3395 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003396 step_iterator NextStep = Step;
3397 ++NextStep;
3398 if (NextStep != StepEnd &&
3399 NextStep->Kind == SK_ConstructorInitialization) {
3400 // The need for zero-initialization is recorded directly into
3401 // the call to the object's constructor within the next step.
3402 ConstructorInitRequiresZeroInit = true;
3403 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3404 S.getLangOptions().CPlusPlus &&
3405 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003406 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3407 Kind.getRange().getBegin(),
3408 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003409 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003410 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003411 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003412 break;
3413 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003414
3415 case SK_CAssignment: {
3416 QualType SourceType = CurInitExpr->getType();
3417 Sema::AssignConvertType ConvTy =
3418 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
3419 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3420 Step->Type, SourceType,
3421 CurInitExpr, getAssignmentAction(Entity)))
3422 return S.ExprError();
3423
3424 CurInit.release();
3425 CurInit = S.Owned(CurInitExpr);
3426 break;
3427 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003428 }
3429 }
3430
3431 return move(CurInit);
3432}
3433
3434//===----------------------------------------------------------------------===//
3435// Diagnose initialization failures
3436//===----------------------------------------------------------------------===//
3437bool InitializationSequence::Diagnose(Sema &S,
3438 const InitializedEntity &Entity,
3439 const InitializationKind &Kind,
3440 Expr **Args, unsigned NumArgs) {
3441 if (SequenceKind != FailedSequence)
3442 return false;
3443
3444 QualType DestType = Entity.getType().getType();
3445 switch (Failure) {
3446 case FK_TooManyInitsForReference:
3447 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3448 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3449 break;
3450
3451 case FK_ArrayNeedsInitList:
3452 case FK_ArrayNeedsInitListOrStringLiteral:
3453 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3454 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3455 break;
3456
3457 case FK_AddressOfOverloadFailed:
3458 S.ResolveAddressOfOverloadedFunction(Args[0],
3459 DestType.getNonReferenceType(),
3460 true);
3461 break;
3462
3463 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003464 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003465 switch (FailedOverloadResult) {
3466 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003467 if (Failure == FK_UserConversionOverloadFailed)
3468 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3469 << Args[0]->getType() << DestType
3470 << Args[0]->getSourceRange();
3471 else
3472 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3473 << DestType << Args[0]->getType()
3474 << Args[0]->getSourceRange();
3475
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003476 S.PrintOverloadCandidates(FailedCandidateSet, true);
3477 break;
3478
3479 case OR_No_Viable_Function:
3480 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3481 << Args[0]->getType() << DestType.getNonReferenceType()
3482 << Args[0]->getSourceRange();
3483 S.PrintOverloadCandidates(FailedCandidateSet, false);
3484 break;
3485
3486 case OR_Deleted: {
3487 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3488 << Args[0]->getType() << DestType.getNonReferenceType()
3489 << Args[0]->getSourceRange();
3490 OverloadCandidateSet::iterator Best;
3491 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3492 Kind.getLocation(),
3493 Best);
3494 if (Ovl == OR_Deleted) {
3495 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3496 << Best->Function->isDeleted();
3497 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003498 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003499 }
3500 break;
3501 }
3502
3503 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003504 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003505 break;
3506 }
3507 break;
3508
3509 case FK_NonConstLValueReferenceBindingToTemporary:
3510 case FK_NonConstLValueReferenceBindingToUnrelated:
3511 S.Diag(Kind.getLocation(),
3512 Failure == FK_NonConstLValueReferenceBindingToTemporary
3513 ? diag::err_lvalue_reference_bind_to_temporary
3514 : diag::err_lvalue_reference_bind_to_unrelated)
3515 << DestType.getNonReferenceType()
3516 << Args[0]->getType()
3517 << Args[0]->getSourceRange();
3518 break;
3519
3520 case FK_RValueReferenceBindingToLValue:
3521 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3522 << Args[0]->getSourceRange();
3523 break;
3524
3525 case FK_ReferenceInitDropsQualifiers:
3526 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3527 << DestType.getNonReferenceType()
3528 << Args[0]->getType()
3529 << Args[0]->getSourceRange();
3530 break;
3531
3532 case FK_ReferenceInitFailed:
3533 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3534 << DestType.getNonReferenceType()
3535 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3536 << Args[0]->getType()
3537 << Args[0]->getSourceRange();
3538 break;
3539
3540 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003541 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3542 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003543 << DestType
3544 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3545 << Args[0]->getType()
3546 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003547 break;
3548
3549 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003550 SourceRange R;
3551
3552 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3553 R = SourceRange(InitList->getInit(1)->getLocStart(),
3554 InitList->getLocEnd());
3555 else
3556 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003557
3558 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003559 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003560 break;
3561 }
3562
3563 case FK_ReferenceBindingToInitList:
3564 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3565 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3566 break;
3567
3568 case FK_InitListBadDestinationType:
3569 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3570 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3571 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003572
3573 case FK_ConstructorOverloadFailed: {
3574 SourceRange ArgsRange;
3575 if (NumArgs)
3576 ArgsRange = SourceRange(Args[0]->getLocStart(),
3577 Args[NumArgs - 1]->getLocEnd());
3578
3579 // FIXME: Using "DestType" for the entity we're printing is probably
3580 // bad.
3581 switch (FailedOverloadResult) {
3582 case OR_Ambiguous:
3583 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3584 << DestType << ArgsRange;
3585 S.PrintOverloadCandidates(FailedCandidateSet, true);
3586 break;
3587
3588 case OR_No_Viable_Function:
3589 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3590 << DestType << ArgsRange;
3591 S.PrintOverloadCandidates(FailedCandidateSet, false);
3592 break;
3593
3594 case OR_Deleted: {
3595 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3596 << true << DestType << ArgsRange;
3597 OverloadCandidateSet::iterator Best;
3598 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3599 Kind.getLocation(),
3600 Best);
3601 if (Ovl == OR_Deleted) {
3602 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3603 << Best->Function->isDeleted();
3604 } else {
3605 llvm_unreachable("Inconsistent overload resolution?");
3606 }
3607 break;
3608 }
3609
3610 case OR_Success:
3611 llvm_unreachable("Conversion did not fail!");
3612 break;
3613 }
3614 break;
3615 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003616
3617 case FK_DefaultInitOfConst:
3618 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3619 << DestType;
3620 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003621 }
3622
3623 return true;
3624}
Douglas Gregore1314a62009-12-18 05:02:21 +00003625
3626//===----------------------------------------------------------------------===//
3627// Initialization helper functions
3628//===----------------------------------------------------------------------===//
3629Sema::OwningExprResult
3630Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3631 SourceLocation EqualLoc,
3632 OwningExprResult Init) {
3633 if (Init.isInvalid())
3634 return ExprError();
3635
3636 Expr *InitE = (Expr *)Init.get();
3637 assert(InitE && "No initialization expression?");
3638
3639 if (EqualLoc.isInvalid())
3640 EqualLoc = InitE->getLocStart();
3641
3642 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3643 EqualLoc);
3644 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3645 Init.release();
3646 return Seq.Perform(*this, Entity, Kind,
3647 MultiExprArg(*this, (void**)&InitE, 1));
3648}