blob: 3ef51561ffe2b8bdab61b04b4f6b765449de8929 [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"
Douglas Gregor4e0299b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregore4a0bb72009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000027#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000028using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000029
Chris Lattner0cb78032009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattnerd8b741c82009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattnera9196812009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman893abe42009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattnera9196812009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000043
Chris Lattnera9196812009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattnera9196812009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedman42a84652009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattnera9196812009-02-26 23:26:43 +000057
Eli Friedman42a84652009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattnera9196812009-02-26 23:26:43 +000064 return Init;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner0cb78032009-02-24 22:27:37 +000066 return 0;
67}
68
Mike Stump11289f42009-09-09 15:08:12 +000069static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner94d2f682009-02-24 22:46:58 +000070 bool DirectInit, Sema &S) {
Chris Lattner0cb78032009-02-24 22:27:37 +000071 // Get the type before calling CheckSingleAssignmentConstraints(), since
72 // it can promote the expression.
Mike Stump11289f42009-09-09 15:08:12 +000073 QualType InitType = Init->getType();
74
Chris Lattner94d2f682009-02-24 22:46:58 +000075 if (S.getLangOptions().CPlusPlus) {
Chris Lattner0cb78032009-02-24 22:27:37 +000076 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000077 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000078 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000079 ImplicitConversionSequence ICS;
80 OverloadCandidateSet CandidateSet;
81 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
82 CandidateSet,
Douglas Gregor3e1e5272009-12-09 23:02:17 +000083 true, false, false) != OR_Ambiguous)
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000084 return S.Diag(Init->getSourceRange().getBegin(),
85 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +000086 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +000087 << Init->getSourceRange();
88 S.Diag(Init->getSourceRange().getBegin(),
89 diag::err_typecheck_convert_ambiguous)
90 << DeclType << Init->getType() << Init->getSourceRange();
91 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
92 return true;
93 }
Chris Lattner0cb78032009-02-24 22:27:37 +000094 return false;
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Chris Lattner94d2f682009-02-24 22:46:58 +000097 Sema::AssignConvertType ConvTy =
98 S.CheckSingleAssignmentConstraints(DeclType, Init);
99 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000100 InitType, Init, Sema::AA_Initializing);
Chris Lattner0cb78032009-02-24 22:27:37 +0000101}
102
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000103static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
104 // Get the length of the string as parsed.
105 uint64_t StrLength =
106 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
107
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000109 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000110 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +0000111 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +0000112 // being initialized to a string literal.
113 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000114 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +0000115 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +0000116 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
117 ConstVal,
118 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000119 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000120 }
Mike Stump11289f42009-09-09 15:08:12 +0000121
Eli Friedman893abe42009-05-29 18:22:49 +0000122 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000123
Eli Friedman893abe42009-05-29 18:22:49 +0000124 // C99 6.7.8p14. We have an array of character type with known size. However,
125 // the size may be smaller or larger than the string we are initializing.
126 // FIXME: Avoid truncation for 64-bit length strings.
127 if (StrLength-1 > CAT->getSize().getZExtValue())
128 S.Diag(Str->getSourceRange().getBegin(),
129 diag::warn_initializer_string_for_char_array_too_long)
130 << Str->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
157/// arguments, which contains the current the "structured" (semantic)
158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
177 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000179 unsigned &StructuredIndex,
180 bool TopLevelObject = false);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000181 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000185 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
186 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000187 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000188 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000189 unsigned &StructuredIndex,
190 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000191 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000192 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000193 InitListExpr *StructuredList,
194 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000195 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000199 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000203 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000204 InitListExpr *StructuredList,
205 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000206 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
207 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000208 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000209 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000210 unsigned &StructuredIndex,
211 bool TopLevelObject = false);
Mike Stump11289f42009-09-09 15:08:12 +0000212 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
213 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000214 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +0000217 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000218 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000219 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 RecordDecl::field_iterator *NextField,
221 llvm::APSInt *NextElementIndex,
222 unsigned &Index,
223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000225 bool FinishSubobjectInit,
226 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
228 QualType CurrentObjectType,
229 InitListExpr *StructuredList,
230 unsigned StructuredIndex,
231 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000232 void UpdateStructuredListElement(InitListExpr *StructuredList,
233 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 Expr *expr);
235 int numArrayElements(QualType DeclType);
236 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000237
Douglas Gregor2bb07652009-12-22 00:05:34 +0000238 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
239 const InitializedEntity &ParentEntity,
240 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000241 void FillInValueInitializations(const InitializedEntity &Entity,
242 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000243public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000244 InitListChecker(Sema &S, const InitializedEntity &Entity,
245 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000246 bool HadError() { return hadError; }
247
248 // @brief Retrieves the fully-structured initializer list used for
249 // semantic analysis and code generation.
250 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
251};
Chris Lattner9ececce2009-02-24 22:48:58 +0000252} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000253
Douglas Gregor2bb07652009-12-22 00:05:34 +0000254void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
255 const InitializedEntity &ParentEntity,
256 InitListExpr *ILE,
257 bool &RequiresSecondPass) {
258 SourceLocation Loc = ILE->getSourceRange().getBegin();
259 unsigned NumInits = ILE->getNumInits();
260 InitializedEntity MemberEntity
261 = InitializedEntity::InitializeMember(Field, &ParentEntity);
262 if (Init >= NumInits || !ILE->getInit(Init)) {
263 // FIXME: We probably don't need to handle references
264 // specially here, since value-initialization of references is
265 // handled in InitializationSequence.
266 if (Field->getType()->isReferenceType()) {
267 // C++ [dcl.init.aggr]p9:
268 // If an incomplete or empty initializer-list leaves a
269 // member of reference type uninitialized, the program is
270 // ill-formed.
271 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
272 << Field->getType()
273 << ILE->getSyntacticForm()->getSourceRange();
274 SemaRef.Diag(Field->getLocation(),
275 diag::note_uninit_reference_member);
276 hadError = true;
277 return;
278 }
279
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
283 if (!InitSeq) {
284 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
285 hadError = true;
286 return;
287 }
288
289 Sema::OwningExprResult MemberInit
290 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
291 Sema::MultiExprArg(SemaRef, 0, 0));
292 if (MemberInit.isInvalid()) {
293 hadError = true;
294 return;
295 }
296
297 if (hadError) {
298 // Do nothing
299 } else if (Init < NumInits) {
300 ILE->setInit(Init, MemberInit.takeAs<Expr>());
301 } else if (InitSeq.getKind()
302 == InitializationSequence::ConstructorInitialization) {
303 // Value-initialization requires a constructor call, so
304 // extend the initializer list to include the constructor
305 // call and make a note that we'll need to take another pass
306 // through the initializer list.
307 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
308 RequiresSecondPass = true;
309 }
310 } else if (InitListExpr *InnerILE
311 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
312 FillInValueInitializations(MemberEntity, InnerILE,
313 RequiresSecondPass);
314}
315
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000316/// Recursively replaces NULL values within the given initializer list
317/// with expressions that perform value-initialization of the
318/// appropriate type.
Douglas Gregor723796a2009-12-16 06:35:08 +0000319void
320InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
321 InitListExpr *ILE,
322 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000323 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000324 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000325 SourceLocation Loc = ILE->getSourceRange().getBegin();
326 if (ILE->getSyntacticForm())
327 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000328
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000329 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000330 if (RType->getDecl()->isUnion() &&
331 ILE->getInitializedFieldInUnion())
332 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
333 Entity, ILE, RequiresSecondPass);
334 else {
335 unsigned Init = 0;
336 for (RecordDecl::field_iterator
337 Field = RType->getDecl()->field_begin(),
338 FieldEnd = RType->getDecl()->field_end();
339 Field != FieldEnd; ++Field) {
340 if (Field->isUnnamedBitfield())
341 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000342
Douglas Gregor2bb07652009-12-22 00:05:34 +0000343 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000344 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000345
346 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
347 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000348 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000349
Douglas Gregor2bb07652009-12-22 00:05:34 +0000350 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000351
Douglas Gregor2bb07652009-12-22 00:05:34 +0000352 // Only look at the first initialization of a union.
353 if (RType->getDecl()->isUnion())
354 break;
355 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000356 }
357
358 return;
Mike Stump11289f42009-09-09 15:08:12 +0000359 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000360
361 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000362
Douglas Gregor723796a2009-12-16 06:35:08 +0000363 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000364 unsigned NumInits = ILE->getNumInits();
365 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000366 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000367 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000368 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
369 NumElements = CAType->getSize().getZExtValue();
Douglas Gregor723796a2009-12-16 06:35:08 +0000370 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
371 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000372 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000373 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000374 NumElements = VType->getNumElements();
Douglas Gregor723796a2009-12-16 06:35:08 +0000375 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
376 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000377 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000378 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000379
Douglas Gregor723796a2009-12-16 06:35:08 +0000380
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000381 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000382 if (hadError)
383 return;
384
Douglas Gregor723796a2009-12-16 06:35:08 +0000385 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
386 ElementEntity.setElementIndex(Init);
387
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000388 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000389 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
390 true);
391 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
392 if (!InitSeq) {
393 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000394 hadError = true;
395 return;
396 }
397
Douglas Gregor723796a2009-12-16 06:35:08 +0000398 Sema::OwningExprResult ElementInit
399 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
400 Sema::MultiExprArg(SemaRef, 0, 0));
401 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000402 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000403 return;
404 }
405
406 if (hadError) {
407 // Do nothing
408 } else if (Init < NumInits) {
409 ILE->setInit(Init, ElementInit.takeAs<Expr>());
410 } else if (InitSeq.getKind()
411 == InitializationSequence::ConstructorInitialization) {
412 // Value-initialization requires a constructor call, so
413 // extend the initializer list to include the constructor
414 // call and make a note that we'll need to take another pass
415 // through the initializer list.
416 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
417 RequiresSecondPass = true;
418 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000419 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000420 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
421 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000422 }
423}
424
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000425
Douglas Gregor723796a2009-12-16 06:35:08 +0000426InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
427 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000428 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000429 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000430
Eli Friedman23a9e312008-05-19 19:16:24 +0000431 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000432 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000433 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000434 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000435 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
436 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000437
Douglas Gregor723796a2009-12-16 06:35:08 +0000438 if (!hadError) {
439 bool RequiresSecondPass = false;
440 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000441 if (RequiresSecondPass && !hadError)
Douglas Gregor723796a2009-12-16 06:35:08 +0000442 FillInValueInitializations(Entity, FullyStructuredList,
443 RequiresSecondPass);
444 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000445}
446
447int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000448 // FIXME: use a proper constant
449 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000450 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000451 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000452 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
453 }
454 return maxElements;
455}
456
457int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000458 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000459 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000460 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000461 Field = structDecl->field_begin(),
462 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000463 Field != FieldEnd; ++Field) {
464 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
465 ++InitializableMembers;
466 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000467 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000468 return std::min(InitializableMembers, 1);
469 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000470}
471
Mike Stump11289f42009-09-09 15:08:12 +0000472void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000473 QualType T, unsigned &Index,
474 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000475 unsigned &StructuredIndex,
476 bool TopLevelObject) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000477 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000478
Steve Narofff8ecff22008-05-01 22:18:59 +0000479 if (T->isArrayType())
480 maxElements = numArrayElements(T);
481 else if (T->isStructureType() || T->isUnionType())
482 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000483 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000484 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000485 else
486 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000487
Eli Friedmane0f832b2008-05-25 13:49:22 +0000488 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000489 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000490 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000491 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000492 hadError = true;
493 return;
494 }
495
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000496 // Build a structured initializer list corresponding to this subobject.
497 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000498 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
499 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000500 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
501 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000502 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000503
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000504 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000505 unsigned StartIndex = Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000506 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000507 StructuredSubobjectInitList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000508 StructuredSubobjectInitIndex,
509 TopLevelObject);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000510 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000511 StructuredSubobjectInitList->setType(T);
512
Douglas Gregor5741efb2009-03-01 17:12:46 +0000513 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000514 // range corresponds with the end of the last initializer it used.
515 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000516 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000517 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
518 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
519 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000520}
521
Steve Naroff125d73d2008-05-06 00:23:44 +0000522void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000523 unsigned &Index,
524 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000525 unsigned &StructuredIndex,
526 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000527 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000528 SyntacticToSemantic[IList] = StructuredList;
529 StructuredList->setSyntacticForm(IList);
Mike Stump11289f42009-09-09 15:08:12 +0000530 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000531 StructuredIndex, TopLevelObject);
Steve Naroff125d73d2008-05-06 00:23:44 +0000532 IList->setType(T);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000533 StructuredList->setType(T);
Eli Friedman85f54972008-05-25 13:22:35 +0000534 if (hadError)
535 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000536
Eli Friedman85f54972008-05-25 13:22:35 +0000537 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000538 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000539 if (StructuredIndex == 1 &&
540 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000541 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000542 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000543 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000544 hadError = true;
545 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000546 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000547 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000548 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000549 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000550 // Don't complain for incomplete types, since we'll get an error
551 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000552 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000553 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000554 CurrentObjectType->isArrayType()? 0 :
555 CurrentObjectType->isVectorType()? 1 :
556 CurrentObjectType->isScalarType()? 2 :
557 CurrentObjectType->isUnionType()? 3 :
558 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000559
560 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000561 if (SemaRef.getLangOptions().CPlusPlus) {
562 DK = diag::err_excess_initializers;
563 hadError = true;
564 }
Nate Begeman425038c2009-07-07 21:53:06 +0000565 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
566 DK = diag::err_excess_initializers;
567 hadError = true;
568 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000569
Chris Lattnerb0912a52009-02-24 22:50:46 +0000570 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000571 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000572 }
573 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000574
Eli Friedman0b4af8f2009-05-16 11:45:48 +0000575 if (T->isScalarType() && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000577 << IList->getSourceRange()
Chris Lattner3c7b86f2009-12-06 17:36:05 +0000578 << CodeModificationHint::CreateRemoval(IList->getLocStart())
579 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000580}
581
Eli Friedman23a9e312008-05-19 19:16:24 +0000582void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000583 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000584 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000585 unsigned &Index,
586 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000587 unsigned &StructuredIndex,
588 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000589 if (DeclType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000590 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000591 } else if (DeclType->isVectorType()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000592 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000593 } else if (DeclType->isAggregateType()) {
594 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000595 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000596 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000597 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000598 StructuredList, StructuredIndex,
599 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000600 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000601 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000602 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000603 false);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000604 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
605 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000607 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000608 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
609 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000610 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000611 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000613 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000614 } else if (DeclType->isRecordType()) {
615 // C++ [dcl.init]p14:
616 // [...] If the class is an aggregate (8.5.1), and the initializer
617 // is a brace-enclosed list, see 8.5.1.
618 //
619 // Note: 8.5.1 is handled below; here, we diagnose the case where
620 // we have an initializer list and a destination type that is not
621 // an aggregate.
622 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000623 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000624 << DeclType << IList->getSourceRange();
625 hadError = true;
626 } else if (DeclType->isReferenceType()) {
627 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000628 } else {
629 // In C, all types are either scalars or aggregates, but
Mike Stump11289f42009-09-09 15:08:12 +0000630 // additional handling is needed here for C++ (and possibly others?).
Steve Narofff8ecff22008-05-01 22:18:59 +0000631 assert(0 && "Unsupported initializer type");
632 }
633}
634
Eli Friedman23a9e312008-05-19 19:16:24 +0000635void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000636 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000637 unsigned &Index,
638 InitListExpr *StructuredList,
639 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000640 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000641 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
642 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000643 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000644 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000645 = getStructuredSubobjectInit(IList, Index, ElemType,
646 StructuredList, StructuredIndex,
647 SubInitList->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +0000648 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000649 newStructuredList, newStructuredIndex);
650 ++StructuredIndex;
651 ++Index;
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000652 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
653 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000654 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000655 ++Index;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000656 } else if (ElemType->isScalarType()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000657 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000658 } else if (ElemType->isReferenceType()) {
659 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedman23a9e312008-05-19 19:16:24 +0000660 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000661 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000662 // C++ [dcl.init.aggr]p12:
663 // All implicit type conversions (clause 4) are considered when
664 // initializing the aggregate member with an ini- tializer from
665 // an initializer-list. If the initializer can initialize a
666 // member, the member is initialized. [...]
Mike Stump11289f42009-09-09 15:08:12 +0000667 ImplicitConversionSequence ICS
Anders Carlsson03068aa2009-08-27 17:18:13 +0000668 = SemaRef.TryCopyInitialization(expr, ElemType,
669 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +0000670 /*ForceRValue=*/false,
671 /*InOverloadResolution=*/false);
Anders Carlsson03068aa2009-08-27 17:18:13 +0000672
Douglas Gregord14247a2009-01-30 22:09:00 +0000673 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +0000674 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000675 Sema::AA_Initializing))
Douglas Gregord14247a2009-01-30 22:09:00 +0000676 hadError = true;
677 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
678 ++Index;
679 return;
680 }
681
682 // Fall through for subaggregate initialization
683 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000684 // C99 6.7.8p13:
Douglas Gregord14247a2009-01-30 22:09:00 +0000685 //
686 // The initializer for a structure or union object that has
687 // automatic storage duration shall be either an initializer
688 // list as described below, or a single expression that has
689 // compatible structure or union type. In the latter case, the
690 // initial value of the object, including unnamed members, is
691 // that of the expression.
Eli Friedman9782caa2009-06-13 10:38:46 +0000692 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman893abe42009-05-29 18:22:49 +0000693 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregord14247a2009-01-30 22:09:00 +0000694 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
695 ++Index;
696 return;
697 }
698
699 // Fall through for subaggregate initialization
700 }
701
702 // C++ [dcl.init.aggr]p12:
Mike Stump11289f42009-09-09 15:08:12 +0000703 //
Douglas Gregord14247a2009-01-30 22:09:00 +0000704 // [...] Otherwise, if the member is itself a non-empty
705 // subaggregate, brace elision is assumed and the initializer is
706 // considered for the initialization of the first member of
707 // the subaggregate.
708 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000709 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregord14247a2009-01-30 22:09:00 +0000710 StructuredIndex);
711 ++StructuredIndex;
712 } else {
713 // We cannot initialize this element, so let
714 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000715 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregord14247a2009-01-30 22:09:00 +0000716 hadError = true;
717 ++Index;
718 ++StructuredIndex;
719 }
720 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000721}
722
Douglas Gregord14247a2009-01-30 22:09:00 +0000723void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000724 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000725 InitListExpr *StructuredList,
726 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000727 if (Index < IList->getNumInits()) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000728 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000729 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000730 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000731 diag::err_many_braces_around_scalar_init)
732 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000733 hadError = true;
734 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000735 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000736 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000737 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump11289f42009-09-09 15:08:12 +0000738 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000739 diag::err_designator_for_scalar_init)
740 << DeclType << expr->getSourceRange();
741 hadError = true;
742 ++Index;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000743 ++StructuredIndex;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000744 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000745 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000746
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000747 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000748 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000749 hadError = true; // types weren't compatible.
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000750 else if (savExpr != expr) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000751 // The type was promoted, update initializer list.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000752 IList->setInit(Index, expr);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000753 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000754 if (hadError)
755 ++StructuredIndex;
756 else
757 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Narofff8ecff22008-05-01 22:18:59 +0000758 ++Index;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000759 } else {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000760 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000761 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000762 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000763 ++Index;
764 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000765 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000766 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000767}
768
Douglas Gregord14247a2009-01-30 22:09:00 +0000769void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
770 unsigned &Index,
771 InitListExpr *StructuredList,
772 unsigned &StructuredIndex) {
773 if (Index < IList->getNumInits()) {
774 Expr *expr = IList->getInit(Index);
775 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000776 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000777 << DeclType << IList->getSourceRange();
778 hadError = true;
779 ++Index;
780 ++StructuredIndex;
781 return;
Mike Stump11289f42009-09-09 15:08:12 +0000782 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000783
784 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson271e3a42009-08-27 17:30:43 +0000785 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000786 /*FIXME:*/expr->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000787 /*SuppressUserConversions=*/false,
788 /*AllowExplicit=*/false,
Mike Stump11289f42009-09-09 15:08:12 +0000789 /*ForceRValue=*/false))
Douglas Gregord14247a2009-01-30 22:09:00 +0000790 hadError = true;
791 else if (savExpr != expr) {
792 // The type was promoted, update initializer list.
793 IList->setInit(Index, expr);
794 }
795 if (hadError)
796 ++StructuredIndex;
797 else
798 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
799 ++Index;
800 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000801 // FIXME: It would be wonderful if we could point at the actual member. In
802 // general, it would be useful to pass location information down the stack,
803 // so that we know the location (or decl) of the "current object" being
804 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000805 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000806 diag::err_init_reference_member_uninitialized)
807 << DeclType
808 << IList->getSourceRange();
809 hadError = true;
810 ++Index;
811 ++StructuredIndex;
812 return;
813 }
814}
815
Mike Stump11289f42009-09-09 15:08:12 +0000816void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000817 unsigned &Index,
818 InitListExpr *StructuredList,
819 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000820 if (Index < IList->getNumInits()) {
John McCall9dd450b2009-09-21 23:43:11 +0000821 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000822 unsigned maxElements = VT->getNumElements();
823 unsigned numEltsInit = 0;
Steve Narofff8ecff22008-05-01 22:18:59 +0000824 QualType elementType = VT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +0000825
Nate Begeman5ec4b312009-08-10 23:49:36 +0000826 if (!SemaRef.getLangOptions().OpenCL) {
827 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
828 // Don't attempt to go past the end of the init list
829 if (Index >= IList->getNumInits())
830 break;
831 CheckSubElementType(IList, elementType, Index,
832 StructuredList, StructuredIndex);
833 }
834 } else {
835 // OpenCL initializers allows vectors to be constructed from vectors.
836 for (unsigned i = 0; i < maxElements; ++i) {
837 // Don't attempt to go past the end of the init list
838 if (Index >= IList->getNumInits())
839 break;
840 QualType IType = IList->getInit(Index)->getType();
841 if (!IType->isVectorType()) {
842 CheckSubElementType(IList, elementType, Index,
843 StructuredList, StructuredIndex);
844 ++numEltsInit;
845 } else {
John McCall9dd450b2009-09-21 23:43:11 +0000846 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman5ec4b312009-08-10 23:49:36 +0000847 unsigned numIElts = IVT->getNumElements();
848 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
849 numIElts);
850 CheckSubElementType(IList, VecType, Index,
851 StructuredList, StructuredIndex);
852 numEltsInit += numIElts;
853 }
854 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000855 }
Mike Stump11289f42009-09-09 15:08:12 +0000856
Nate Begeman5ec4b312009-08-10 23:49:36 +0000857 // OpenCL & AltiVec require all elements to be initialized.
858 if (numEltsInit != maxElements)
859 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
860 SemaRef.Diag(IList->getSourceRange().getBegin(),
861 diag::err_vector_incorrect_num_initializers)
862 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +0000863 }
864}
865
Mike Stump11289f42009-09-09 15:08:12 +0000866void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000867 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +0000868 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000869 unsigned &Index,
870 InitListExpr *StructuredList,
871 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000872 // Check for the special-case of initializing an array with a string.
873 if (Index < IList->getNumInits()) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +0000874 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
875 SemaRef.Context)) {
876 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000877 // We place the string literal directly into the resulting
878 // initializer list. This is the only place where the structure
879 // of the structured initializer list doesn't match exactly,
880 // because doing so would involve allocating one character
881 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +0000882 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +0000883 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +0000884 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000885 return;
886 }
887 }
Chris Lattner7adf0762008-08-04 07:31:14 +0000888 if (const VariableArrayType *VAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000889 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman85f54972008-05-25 13:22:35 +0000890 // Check for VLAs; in standard C it would be possible to check this
891 // earlier, but I don't know where clang accepts VLAs (gcc accepts
892 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +0000893 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +0000894 diag::err_variable_object_no_init)
895 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +0000896 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000897 ++Index;
898 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +0000899 return;
900 }
901
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000902 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000903 llvm::APSInt maxElements(elementIndex.getBitWidth(),
904 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000905 bool maxElementsKnown = false;
906 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000907 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000908 maxElements = CAT->getSize();
Douglas Gregor033d1252009-01-23 16:54:12 +0000909 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000910 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000911 maxElementsKnown = true;
912 }
913
Chris Lattnerb0912a52009-02-24 22:50:46 +0000914 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattner7adf0762008-08-04 07:31:14 +0000915 ->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000916 while (Index < IList->getNumInits()) {
917 Expr *Init = IList->getInit(Index);
918 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000919 // If we're not the subobject that matches up with the '{' for
920 // the designator, we shouldn't be handling the
921 // designator. Return immediately.
922 if (!SubobjectIsDesignatorContext)
923 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000924
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000925 // Handle this designated initializer. elementIndex will be
926 // updated to be the next array element we'll initialize.
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000928 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000929 StructuredList, StructuredIndex, true,
930 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000931 hadError = true;
932 continue;
933 }
934
Douglas Gregor033d1252009-01-23 16:54:12 +0000935 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
936 maxElements.extend(elementIndex.getBitWidth());
937 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
938 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000939 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +0000940
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000941 // If the array is of incomplete type, keep track of the number of
942 // elements in the initializer.
943 if (!maxElementsKnown && elementIndex > maxElements)
944 maxElements = elementIndex;
945
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000946 continue;
947 }
948
949 // If we know the maximum number of elements, and we've already
950 // hit it, stop consuming elements in the initializer list.
951 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +0000952 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000953
954 // Check this element.
Douglas Gregorf6d27522009-01-29 00:39:20 +0000955 CheckSubElementType(IList, elementType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000956 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000957 ++elementIndex;
958
959 // If the array is of incomplete type, keep track of the number of
960 // elements in the initializer.
961 if (!maxElementsKnown && elementIndex > maxElements)
962 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +0000963 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +0000964 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000965 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000966 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +0000967 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +0000968 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000969 // Sizing an array implicitly to zero is not allowed by ISO C,
970 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000971 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000972 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +0000973 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000974
Mike Stump11289f42009-09-09 15:08:12 +0000975 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +0000976 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +0000977 }
978}
979
Mike Stump11289f42009-09-09 15:08:12 +0000980void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
981 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000982 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +0000983 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000984 unsigned &Index,
985 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000986 unsigned &StructuredIndex,
987 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000988 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000989
Eli Friedman23a9e312008-05-19 19:16:24 +0000990 // If the record is invalid, some of it's members are invalid. To avoid
991 // confusion, we forgo checking the intializer for the entire record.
992 if (structDecl->isInvalidDecl()) {
993 hadError = true;
994 return;
Mike Stump11289f42009-09-09 15:08:12 +0000995 }
Douglas Gregor0202cb42009-01-29 17:44:32 +0000996
997 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
998 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000999 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001000 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001001 Field != FieldEnd; ++Field) {
1002 if (Field->getDeclName()) {
1003 StructuredList->setInitializedFieldInUnion(*Field);
1004 break;
1005 }
1006 }
1007 return;
1008 }
1009
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001010 // If structDecl is a forward declaration, this loop won't do
1011 // anything except look at designated initializers; That's okay,
1012 // because an error should get printed out elsewhere. It might be
1013 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001014 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001015 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001016 bool InitializedSomething = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001017 while (Index < IList->getNumInits()) {
1018 Expr *Init = IList->getInit(Index);
1019
1020 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001021 // If we're not the subobject that matches up with the '{' for
1022 // the designator, we shouldn't be handling the
1023 // designator. Return immediately.
1024 if (!SubobjectIsDesignatorContext)
1025 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001026
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001027 // Handle this designated initializer. Field will be updated to
1028 // the next field that we'll be initializing.
Mike Stump11289f42009-09-09 15:08:12 +00001029 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001030 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001031 StructuredList, StructuredIndex,
1032 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001033 hadError = true;
1034
Douglas Gregora9add4e2009-02-12 19:00:39 +00001035 InitializedSomething = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001036 continue;
1037 }
1038
1039 if (Field == FieldEnd) {
1040 // We've run out of fields. We're done.
1041 break;
1042 }
1043
Douglas Gregora9add4e2009-02-12 19:00:39 +00001044 // We've already initialized a member of a union. We're done.
1045 if (InitializedSomething && DeclType->isUnionType())
1046 break;
1047
Douglas Gregor91f84212008-12-11 16:49:14 +00001048 // If we've hit the flexible array member at the end, we're done.
1049 if (Field->getType()->isIncompleteArrayType())
1050 break;
1051
Douglas Gregor51695702009-01-29 16:53:55 +00001052 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001053 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001054 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001055 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001056 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001057
Douglas Gregorf6d27522009-01-29 00:39:20 +00001058 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001059 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001060 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001061
1062 if (DeclType->isUnionType()) {
1063 // Initialize the first field within the union.
1064 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001065 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001066
1067 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001068 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001069
Mike Stump11289f42009-09-09 15:08:12 +00001070 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001071 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001072 return;
1073
1074 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001075 if (!TopLevelObject &&
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001076 (!isa<InitListExpr>(IList->getInit(Index)) ||
1077 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00001078 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001079 diag::err_flexible_array_init_nonempty)
1080 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001081 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001082 << *Field;
1083 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001084 ++Index;
1085 return;
1086 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001087 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001088 diag::ext_flexible_array_init)
1089 << IList->getInit(Index)->getSourceRange().getBegin();
1090 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1091 << *Field;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001092 }
1093
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001094 if (isa<InitListExpr>(IList->getInit(Index)))
1095 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1096 StructuredIndex);
1097 else
1098 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1099 StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001100}
Steve Narofff8ecff22008-05-01 22:18:59 +00001101
Douglas Gregord5846a12009-04-15 06:41:24 +00001102/// \brief Expand a field designator that refers to a member of an
1103/// anonymous struct or union into a series of field designators that
1104/// refers to the field within the appropriate subobject.
1105///
1106/// Field/FieldIndex will be updated to point to the (new)
1107/// currently-designated field.
1108static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001109 DesignatedInitExpr *DIE,
1110 unsigned DesigIdx,
Douglas Gregord5846a12009-04-15 06:41:24 +00001111 FieldDecl *Field,
1112 RecordDecl::field_iterator &FieldIter,
1113 unsigned &FieldIndex) {
1114 typedef DesignatedInitExpr::Designator Designator;
1115
1116 // Build the path from the current object to the member of the
1117 // anonymous struct/union (backwards).
1118 llvm::SmallVector<FieldDecl *, 4> Path;
1119 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregord5846a12009-04-15 06:41:24 +00001121 // Build the replacement designators.
1122 llvm::SmallVector<Designator, 4> Replacements;
1123 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1124 FI = Path.rbegin(), FIEnd = Path.rend();
1125 FI != FIEnd; ++FI) {
1126 if (FI + 1 == FIEnd)
Mike Stump11289f42009-09-09 15:08:12 +00001127 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001128 DIE->getDesignator(DesigIdx)->getDotLoc(),
1129 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1130 else
1131 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1132 SourceLocation()));
1133 Replacements.back().setField(*FI);
1134 }
1135
1136 // Expand the current designator into the set of replacement
1137 // designators, so we have a full subobject path down to where the
1138 // member of the anonymous struct/union is actually stored.
Mike Stump11289f42009-09-09 15:08:12 +00001139 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001140 &Replacements[0] + Replacements.size());
Mike Stump11289f42009-09-09 15:08:12 +00001141
Douglas Gregord5846a12009-04-15 06:41:24 +00001142 // Update FieldIter/FieldIndex;
1143 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001144 FieldIter = Record->field_begin();
Douglas Gregord5846a12009-04-15 06:41:24 +00001145 FieldIndex = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001146 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregord5846a12009-04-15 06:41:24 +00001147 FieldIter != FEnd; ++FieldIter) {
1148 if (FieldIter->isUnnamedBitfield())
1149 continue;
1150
1151 if (*FieldIter == Path.back())
1152 return;
1153
1154 ++FieldIndex;
1155 }
1156
1157 assert(false && "Unable to find anonymous struct/union field");
1158}
1159
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001160/// @brief Check the well-formedness of a C99 designated initializer.
1161///
1162/// Determines whether the designated initializer @p DIE, which
1163/// resides at the given @p Index within the initializer list @p
1164/// IList, is well-formed for a current object of type @p DeclType
1165/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001166/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001167/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001168///
1169/// @param IList The initializer list in which this designated
1170/// initializer occurs.
1171///
Douglas Gregora5324162009-04-15 04:56:10 +00001172/// @param DIE The designated initializer expression.
1173///
1174/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001175///
1176/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1177/// into which the designation in @p DIE should refer.
1178///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001179/// @param NextField If non-NULL and the first designator in @p DIE is
1180/// a field, this will be set to the field declaration corresponding
1181/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001182///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001183/// @param NextElementIndex If non-NULL and the first designator in @p
1184/// DIE is an array designator or GNU array-range designator, this
1185/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001186///
1187/// @param Index Index into @p IList where the designated initializer
1188/// @p DIE occurs.
1189///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001190/// @param StructuredList The initializer list expression that
1191/// describes all of the subobject initializers in the order they'll
1192/// actually be initialized.
1193///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001194/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001195bool
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001196InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001197 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001198 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001199 QualType &CurrentObjectType,
1200 RecordDecl::field_iterator *NextField,
1201 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001202 unsigned &Index,
1203 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001204 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001205 bool FinishSubobjectInit,
1206 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001207 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001208 // Check the actual initialization for the designated object type.
1209 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001210
1211 // Temporarily remove the designator expression from the
1212 // initializer list that the child calls see, so that we don't try
1213 // to re-process the designator.
1214 unsigned OldIndex = Index;
1215 IList->setInit(OldIndex, DIE->getInit());
1216
1217 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001218 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001219
1220 // Restore the designated initializer expression in the syntactic
1221 // form of the initializer list.
1222 if (IList->getInit(OldIndex) != DIE->getInit())
1223 DIE->setInit(IList->getInit(OldIndex));
1224 IList->setInit(OldIndex, DIE);
1225
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001226 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001227 }
1228
Douglas Gregora5324162009-04-15 04:56:10 +00001229 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001230 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001231 "Need a non-designated initializer list to start from");
1232
Douglas Gregora5324162009-04-15 04:56:10 +00001233 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001234 // Determine the structural initializer list that corresponds to the
1235 // current subobject.
1236 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001237 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001238 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001239 SourceRange(D->getStartLocation(),
1240 DIE->getSourceRange().getEnd()));
1241 assert(StructuredList && "Expected a structured initializer list");
1242
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001243 if (D->isFieldDesignator()) {
1244 // C99 6.7.8p7:
1245 //
1246 // If a designator has the form
1247 //
1248 // . identifier
1249 //
1250 // then the current object (defined below) shall have
1251 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001252 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001253 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001254 if (!RT) {
1255 SourceLocation Loc = D->getDotLoc();
1256 if (Loc.isInvalid())
1257 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001258 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1259 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001260 ++Index;
1261 return true;
1262 }
1263
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001264 // Note: we perform a linear search of the fields here, despite
1265 // the fact that we have a faster lookup method, because we always
1266 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001267 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001268 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001269 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001270 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001271 Field = RT->getDecl()->field_begin(),
1272 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001273 for (; Field != FieldEnd; ++Field) {
1274 if (Field->isUnnamedBitfield())
1275 continue;
1276
Douglas Gregord5846a12009-04-15 06:41:24 +00001277 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001278 break;
1279
1280 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001281 }
1282
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001283 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001284 // There was no normal field in the struct with the designated
1285 // name. Perform another lookup for this name, which may find
1286 // something that we can't designate (e.g., a member function),
1287 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001288 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001289 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001290 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001291 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001292 // Name lookup didn't find anything. Determine whether this
1293 // was a typo for another field name.
1294 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1295 Sema::LookupMemberName);
1296 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1297 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1298 ReplacementField->getDeclContext()->getLookupContext()
1299 ->Equals(RT->getDecl())) {
1300 SemaRef.Diag(D->getFieldLoc(),
1301 diag::err_field_designator_unknown_suggest)
1302 << FieldName << CurrentObjectType << R.getLookupName()
1303 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1304 R.getLookupName().getAsString());
1305 } else {
1306 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1307 << FieldName << CurrentObjectType;
1308 ++Index;
1309 return true;
1310 }
1311 } else if (!KnownField) {
1312 // Determine whether we found a field at all.
1313 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1314 }
1315
1316 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001317 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001318 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001319 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001320 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001321 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001322 ++Index;
1323 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001324 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001325
1326 if (!KnownField &&
1327 cast<RecordDecl>((ReplacementField)->getDeclContext())
1328 ->isAnonymousStructOrUnion()) {
1329 // Handle an field designator that refers to a member of an
1330 // anonymous struct or union.
1331 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1332 ReplacementField,
1333 Field, FieldIndex);
1334 D = DIE->getDesignator(DesigIdx);
1335 } else if (!KnownField) {
1336 // The replacement field comes from typo correction; find it
1337 // in the list of fields.
1338 FieldIndex = 0;
1339 Field = RT->getDecl()->field_begin();
1340 for (; Field != FieldEnd; ++Field) {
1341 if (Field->isUnnamedBitfield())
1342 continue;
1343
1344 if (ReplacementField == *Field ||
1345 Field->getIdentifier() == ReplacementField->getIdentifier())
1346 break;
1347
1348 ++FieldIndex;
1349 }
1350 }
Douglas Gregord5846a12009-04-15 06:41:24 +00001351 } else if (!KnownField &&
1352 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001353 ->isAnonymousStructOrUnion()) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001354 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1355 Field, FieldIndex);
1356 D = DIE->getDesignator(DesigIdx);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001357 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001358
1359 // All of the fields of a union are located at the same place in
1360 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001361 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001362 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001363 StructuredList->setInitializedFieldInUnion(*Field);
1364 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001365
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001366 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001367 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001369 // Make sure that our non-designated initializer list has space
1370 // for a subobject corresponding to this field.
1371 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001372 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001373
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001374 // This designator names a flexible array member.
1375 if (Field->getType()->isIncompleteArrayType()) {
1376 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001377 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001378 // We can't designate an object within the flexible array
1379 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001380 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001381 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001382 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001383 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001384 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001385 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001386 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001387 << *Field;
1388 Invalid = true;
1389 }
1390
1391 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1392 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001393 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001394 diag::err_flexible_array_init_needs_braces)
1395 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001396 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001397 << *Field;
1398 Invalid = true;
1399 }
1400
1401 // Handle GNU flexible array initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001402 if (!Invalid && !TopLevelObject &&
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001403 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001404 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001405 diag::err_flexible_array_init_nonempty)
1406 << DIE->getSourceRange().getBegin();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001407 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001408 << *Field;
1409 Invalid = true;
1410 }
1411
1412 if (Invalid) {
1413 ++Index;
1414 return true;
1415 }
1416
1417 // Initialize the array.
1418 bool prevHadError = hadError;
1419 unsigned newStructuredIndex = FieldIndex;
1420 unsigned OldIndex = Index;
1421 IList->setInit(Index, DIE->getInit());
Mike Stump11289f42009-09-09 15:08:12 +00001422 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001423 StructuredList, newStructuredIndex);
1424 IList->setInit(OldIndex, DIE);
1425 if (hadError && !prevHadError) {
1426 ++Field;
1427 ++FieldIndex;
1428 if (NextField)
1429 *NextField = Field;
1430 StructuredIndex = FieldIndex;
1431 return true;
1432 }
1433 } else {
1434 // Recurse to check later designated subobjects.
1435 QualType FieldType = (*Field)->getType();
1436 unsigned newStructuredIndex = FieldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001437 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1438 Index, StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001439 true, false))
1440 return true;
1441 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001442
1443 // Find the position of the next field to be initialized in this
1444 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001445 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001446 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001447
1448 // If this the first designator, our caller will continue checking
1449 // the rest of this struct/class/union subobject.
1450 if (IsFirstDesignator) {
1451 if (NextField)
1452 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001453 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001454 return false;
1455 }
1456
Douglas Gregor17bd0942009-01-28 23:36:17 +00001457 if (!FinishSubobjectInit)
1458 return false;
1459
Douglas Gregord5846a12009-04-15 06:41:24 +00001460 // We've already initialized something in the union; we're done.
1461 if (RT->getDecl()->isUnion())
1462 return hadError;
1463
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001464 // Check the remaining fields within this class/struct/union subobject.
1465 bool prevHadError = hadError;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001466 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1467 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001468 return hadError && !prevHadError;
1469 }
1470
1471 // C99 6.7.8p6:
1472 //
1473 // If a designator has the form
1474 //
1475 // [ constant-expression ]
1476 //
1477 // then the current object (defined below) shall have array
1478 // type and the expression shall be an integer constant
1479 // expression. If the array is of unknown size, any
1480 // nonnegative value is valid.
1481 //
1482 // Additionally, cope with the GNU extension that permits
1483 // designators of the form
1484 //
1485 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001486 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001487 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001488 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001489 << CurrentObjectType;
1490 ++Index;
1491 return true;
1492 }
1493
1494 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001495 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1496 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001497 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001498 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001499 DesignatedEndIndex = DesignatedStartIndex;
1500 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001501 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001502
Mike Stump11289f42009-09-09 15:08:12 +00001503
1504 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001505 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001506 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001507 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001508 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001509
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001510 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001511 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001512 }
1513
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001514 if (isa<ConstantArrayType>(AT)) {
1515 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001516 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1517 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1518 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1519 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1520 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001521 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001522 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001523 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001524 << IndexExpr->getSourceRange();
1525 ++Index;
1526 return true;
1527 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001528 } else {
1529 // Make sure the bit-widths and signedness match.
1530 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1531 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001532 else if (DesignatedStartIndex.getBitWidth() <
1533 DesignatedEndIndex.getBitWidth())
Douglas Gregor17bd0942009-01-28 23:36:17 +00001534 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1535 DesignatedStartIndex.setIsUnsigned(true);
1536 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001539 // Make sure that our non-designated initializer list has space
1540 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001541 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001542 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001543 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001544
Douglas Gregor17bd0942009-01-28 23:36:17 +00001545 // Repeatedly perform subobject initializations in the range
1546 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001547
Douglas Gregor17bd0942009-01-28 23:36:17 +00001548 // Move to the next designator
1549 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1550 unsigned OldIndex = Index;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001551 while (DesignatedStartIndex <= DesignatedEndIndex) {
1552 // Recurse to check later designated subobjects.
1553 QualType ElementType = AT->getElementType();
1554 Index = OldIndex;
Douglas Gregora5324162009-04-15 04:56:10 +00001555 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1556 Index, StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001557 (DesignatedStartIndex == DesignatedEndIndex),
1558 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001559 return true;
1560
1561 // Move to the next index in the array that we'll be initializing.
1562 ++DesignatedStartIndex;
1563 ElementIndex = DesignatedStartIndex.getZExtValue();
1564 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001565
1566 // If this the first designator, our caller will continue checking
1567 // the rest of this array subobject.
1568 if (IsFirstDesignator) {
1569 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001570 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001571 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001572 return false;
1573 }
Mike Stump11289f42009-09-09 15:08:12 +00001574
Douglas Gregor17bd0942009-01-28 23:36:17 +00001575 if (!FinishSubobjectInit)
1576 return false;
1577
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001578 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001579 bool prevHadError = hadError;
Douglas Gregoraef040a2009-02-09 19:45:19 +00001580 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001581 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001582 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001583}
1584
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001585// Get the structured initializer list for a subobject of type
1586// @p CurrentObjectType.
1587InitListExpr *
1588InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1589 QualType CurrentObjectType,
1590 InitListExpr *StructuredList,
1591 unsigned StructuredIndex,
1592 SourceRange InitRange) {
1593 Expr *ExistingInit = 0;
1594 if (!StructuredList)
1595 ExistingInit = SyntacticToSemantic[IList];
1596 else if (StructuredIndex < StructuredList->getNumInits())
1597 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001598
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001599 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1600 return Result;
1601
1602 if (ExistingInit) {
1603 // We are creating an initializer list that initializes the
1604 // subobjects of the current object, but there was already an
1605 // initialization that completely initialized the current
1606 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001607 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001608 // struct X { int a, b; };
1609 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001610 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1612 // designated initializer re-initializes the whole
1613 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001614 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001615 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001616 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001617 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001618 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001619 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001620 << ExistingInit->getSourceRange();
1621 }
1622
Mike Stump11289f42009-09-09 15:08:12 +00001623 InitListExpr *Result
1624 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001625 InitRange.getEnd());
1626
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001627 Result->setType(CurrentObjectType);
1628
Douglas Gregor6d00c992009-03-20 23:58:33 +00001629 // Pre-allocate storage for the structured initializer list.
1630 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001631 unsigned NumInits = 0;
1632 if (!StructuredList)
1633 NumInits = IList->getNumInits();
1634 else if (Index < IList->getNumInits()) {
1635 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1636 NumInits = SubList->getNumInits();
1637 }
1638
Mike Stump11289f42009-09-09 15:08:12 +00001639 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001640 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1641 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1642 NumElements = CAType->getSize().getZExtValue();
1643 // Simple heuristic so that we don't allocate a very large
1644 // initializer with many empty entries at the end.
Douglas Gregor221c9a52009-03-21 18:13:52 +00001645 if (NumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001646 NumElements = 0;
1647 }
John McCall9dd450b2009-09-21 23:43:11 +00001648 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001649 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001650 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001651 RecordDecl *RDecl = RType->getDecl();
1652 if (RDecl->isUnion())
1653 NumElements = 1;
1654 else
Mike Stump11289f42009-09-09 15:08:12 +00001655 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001656 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001657 }
1658
Douglas Gregor221c9a52009-03-21 18:13:52 +00001659 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001660 NumElements = IList->getNumInits();
1661
1662 Result->reserveInits(NumElements);
1663
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001664 // Link this new initializer list into the structured initializer
1665 // lists.
1666 if (StructuredList)
1667 StructuredList->updateInit(StructuredIndex, Result);
1668 else {
1669 Result->setSyntacticForm(IList);
1670 SyntacticToSemantic[IList] = Result;
1671 }
1672
1673 return Result;
1674}
1675
1676/// Update the initializer at index @p StructuredIndex within the
1677/// structured initializer list to the value @p expr.
1678void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1679 unsigned &StructuredIndex,
1680 Expr *expr) {
1681 // No structured initializer list to update
1682 if (!StructuredList)
1683 return;
1684
1685 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1686 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001687 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001688 diag::warn_initializer_overrides)
1689 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001690 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001692 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001693 << PrevInit->getSourceRange();
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001696 ++StructuredIndex;
1697}
1698
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001699/// Check that the given Index expression is a valid array designator
1700/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001701/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001702/// and produces a reasonable diagnostic if there is a
1703/// failure. Returns true if there was an error, false otherwise. If
1704/// everything went okay, Value will receive the value of the constant
1705/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001706static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001707CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001708 SourceLocation Loc = Index->getSourceRange().getBegin();
1709
1710 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001711 if (S.VerifyIntegerConstantExpression(Index, &Value))
1712 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001713
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001714 if (Value.isSigned() && Value.isNegative())
1715 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001716 << Value.toString(10) << Index->getSourceRange();
1717
Douglas Gregor51650d32009-01-23 21:04:18 +00001718 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001719 return false;
1720}
1721
1722Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1723 SourceLocation Loc,
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00001724 bool GNUSyntax,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001725 OwningExprResult Init) {
1726 typedef DesignatedInitExpr::Designator ASTDesignator;
1727
1728 bool Invalid = false;
1729 llvm::SmallVector<ASTDesignator, 32> Designators;
1730 llvm::SmallVector<Expr *, 32> InitExpressions;
1731
1732 // Build designators and check array designator expressions.
1733 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1734 const Designator &D = Desig.getDesignator(Idx);
1735 switch (D.getKind()) {
1736 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00001737 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001738 D.getFieldLoc()));
1739 break;
1740
1741 case Designator::ArrayDesignator: {
1742 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1743 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001744 if (!Index->isTypeDependent() &&
1745 !Index->isValueDependent() &&
1746 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001747 Invalid = true;
1748 else {
1749 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001750 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001751 D.getRBracketLoc()));
1752 InitExpressions.push_back(Index);
1753 }
1754 break;
1755 }
1756
1757 case Designator::ArrayRangeDesignator: {
1758 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1759 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1760 llvm::APSInt StartValue;
1761 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001762 bool StartDependent = StartIndex->isTypeDependent() ||
1763 StartIndex->isValueDependent();
1764 bool EndDependent = EndIndex->isTypeDependent() ||
1765 EndIndex->isValueDependent();
1766 if ((!StartDependent &&
1767 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1768 (!EndDependent &&
1769 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001770 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00001771 else {
1772 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00001773 if (StartDependent || EndDependent) {
1774 // Nothing to compute.
1775 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregor7a95b082009-01-23 22:22:29 +00001776 EndValue.extend(StartValue.getBitWidth());
1777 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1778 StartValue.extend(EndValue.getBitWidth());
1779
Douglas Gregor0f9d4002009-05-21 23:30:39 +00001780 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00001781 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00001782 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00001783 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1784 Invalid = true;
1785 } else {
1786 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00001787 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00001788 D.getEllipsisLoc(),
1789 D.getRBracketLoc()));
1790 InitExpressions.push_back(StartIndex);
1791 InitExpressions.push_back(EndIndex);
1792 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001793 }
1794 break;
1795 }
1796 }
1797 }
1798
1799 if (Invalid || Init.isInvalid())
1800 return ExprError();
1801
1802 // Clear out the expressions within the designation.
1803 Desig.ClearExprs(*this);
1804
1805 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00001806 = DesignatedInitExpr::Create(Context,
1807 Designators.data(), Designators.size(),
1808 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001809 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001810 return Owned(DIE);
1811}
Douglas Gregor85df8d82009-01-29 00:45:39 +00001812
Douglas Gregor723796a2009-12-16 06:35:08 +00001813bool Sema::CheckInitList(const InitializedEntity &Entity,
1814 InitListExpr *&InitList, QualType &DeclType) {
1815 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00001816 if (!CheckInitList.HadError())
1817 InitList = CheckInitList.getFullyStructuredList();
1818
1819 return CheckInitList.HadError();
1820}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00001821
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001822//===----------------------------------------------------------------------===//
1823// Initialization entity
1824//===----------------------------------------------------------------------===//
1825
Douglas Gregor723796a2009-12-16 06:35:08 +00001826InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1827 const InitializedEntity &Parent)
1828 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1829{
Douglas Gregor1b303932009-12-22 15:35:07 +00001830 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType()))
1831 Type = AT->getElementType();
Douglas Gregor723796a2009-12-16 06:35:08 +00001832 else
Douglas Gregor1b303932009-12-22 15:35:07 +00001833 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001834}
1835
1836InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1837 CXXBaseSpecifier *Base)
1838{
1839 InitializedEntity Result;
1840 Result.Kind = EK_Base;
1841 Result.Base = Base;
Douglas Gregor1b303932009-12-22 15:35:07 +00001842 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001843 return Result;
1844}
1845
Douglas Gregor85dabae2009-12-16 01:38:02 +00001846DeclarationName InitializedEntity::getName() const {
1847 switch (getKind()) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00001848 case EK_Parameter:
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00001849 if (!VariableOrMember)
1850 return DeclarationName();
1851 // Fall through
1852
1853 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001854 case EK_Member:
1855 return VariableOrMember->getDeclName();
1856
1857 case EK_Result:
1858 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00001859 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001860 case EK_Temporary:
1861 case EK_Base:
Douglas Gregor723796a2009-12-16 06:35:08 +00001862 case EK_ArrayOrVectorElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001863 return DeclarationName();
1864 }
1865
1866 // Silence GCC warning
1867 return DeclarationName();
1868}
1869
Douglas Gregora4b592a2009-12-19 03:01:41 +00001870DeclaratorDecl *InitializedEntity::getDecl() const {
1871 switch (getKind()) {
1872 case EK_Variable:
1873 case EK_Parameter:
1874 case EK_Member:
1875 return VariableOrMember;
1876
1877 case EK_Result:
1878 case EK_Exception:
1879 case EK_New:
1880 case EK_Temporary:
1881 case EK_Base:
1882 case EK_ArrayOrVectorElement:
1883 return 0;
1884 }
1885
1886 // Silence GCC warning
1887 return 0;
1888}
1889
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001890//===----------------------------------------------------------------------===//
1891// Initialization sequence
1892//===----------------------------------------------------------------------===//
1893
1894void InitializationSequence::Step::Destroy() {
1895 switch (Kind) {
1896 case SK_ResolveAddressOfOverloadedFunction:
1897 case SK_CastDerivedToBaseRValue:
1898 case SK_CastDerivedToBaseLValue:
1899 case SK_BindReference:
1900 case SK_BindReferenceToTemporary:
1901 case SK_UserConversion:
1902 case SK_QualificationConversionRValue:
1903 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00001904 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001905 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001906 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00001907 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00001908 case SK_StringInit:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001909 break;
1910
1911 case SK_ConversionSequence:
1912 delete ICS;
1913 }
1914}
1915
1916void InitializationSequence::AddAddressOverloadResolutionStep(
1917 FunctionDecl *Function) {
1918 Step S;
1919 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1920 S.Type = Function->getType();
1921 S.Function = Function;
1922 Steps.push_back(S);
1923}
1924
1925void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1926 bool IsLValue) {
1927 Step S;
1928 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1929 S.Type = BaseType;
1930 Steps.push_back(S);
1931}
1932
1933void InitializationSequence::AddReferenceBindingStep(QualType T,
1934 bool BindingTemporary) {
1935 Step S;
1936 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1937 S.Type = T;
1938 Steps.push_back(S);
1939}
1940
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001941void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1942 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001943 Step S;
1944 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00001945 S.Type = T;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001946 S.Function = Function;
1947 Steps.push_back(S);
1948}
1949
1950void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1951 bool IsLValue) {
1952 Step S;
1953 S.Kind = IsLValue? SK_QualificationConversionLValue
1954 : SK_QualificationConversionRValue;
1955 S.Type = Ty;
1956 Steps.push_back(S);
1957}
1958
1959void InitializationSequence::AddConversionSequenceStep(
1960 const ImplicitConversionSequence &ICS,
1961 QualType T) {
1962 Step S;
1963 S.Kind = SK_ConversionSequence;
1964 S.Type = T;
1965 S.ICS = new ImplicitConversionSequence(ICS);
1966 Steps.push_back(S);
1967}
1968
Douglas Gregor51e77d52009-12-10 17:56:55 +00001969void InitializationSequence::AddListInitializationStep(QualType T) {
1970 Step S;
1971 S.Kind = SK_ListInitialization;
1972 S.Type = T;
1973 Steps.push_back(S);
1974}
1975
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00001976void
1977InitializationSequence::AddConstructorInitializationStep(
1978 CXXConstructorDecl *Constructor,
1979 QualType T) {
1980 Step S;
1981 S.Kind = SK_ConstructorInitialization;
1982 S.Type = T;
1983 S.Function = Constructor;
1984 Steps.push_back(S);
1985}
1986
Douglas Gregor7dc42e52009-12-15 00:01:57 +00001987void InitializationSequence::AddZeroInitializationStep(QualType T) {
1988 Step S;
1989 S.Kind = SK_ZeroInitialization;
1990 S.Type = T;
1991 Steps.push_back(S);
1992}
1993
Douglas Gregore1314a62009-12-18 05:02:21 +00001994void InitializationSequence::AddCAssignmentStep(QualType T) {
1995 Step S;
1996 S.Kind = SK_CAssignment;
1997 S.Type = T;
1998 Steps.push_back(S);
1999}
2000
Eli Friedman78275202009-12-19 08:11:05 +00002001void InitializationSequence::AddStringInitStep(QualType T) {
2002 Step S;
2003 S.Kind = SK_StringInit;
2004 S.Type = T;
2005 Steps.push_back(S);
2006}
2007
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002008void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2009 OverloadingResult Result) {
2010 SequenceKind = FailedSequence;
2011 this->Failure = Failure;
2012 this->FailedOverloadResult = Result;
2013}
2014
2015//===----------------------------------------------------------------------===//
2016// Attempt initialization
2017//===----------------------------------------------------------------------===//
2018
2019/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregor51e77d52009-12-10 17:56:55 +00002020static void TryListInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002021 const InitializedEntity &Entity,
2022 const InitializationKind &Kind,
2023 InitListExpr *InitList,
2024 InitializationSequence &Sequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00002025 // FIXME: We only perform rudimentary checking of list
2026 // initializations at this point, then assume that any list
2027 // initialization of an array, aggregate, or scalar will be
2028 // well-formed. We we actually "perform" list initialization, we'll
2029 // do all of the necessary checking. C++0x initializer lists will
2030 // force us to perform more checking here.
2031 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2032
Douglas Gregor1b303932009-12-22 15:35:07 +00002033 QualType DestType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00002034
2035 // C++ [dcl.init]p13:
2036 // If T is a scalar type, then a declaration of the form
2037 //
2038 // T x = { a };
2039 //
2040 // is equivalent to
2041 //
2042 // T x = a;
2043 if (DestType->isScalarType()) {
2044 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2045 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2046 return;
2047 }
2048
2049 // Assume scalar initialization from a single value works.
2050 } else if (DestType->isAggregateType()) {
2051 // Assume aggregate initialization works.
2052 } else if (DestType->isVectorType()) {
2053 // Assume vector initialization works.
2054 } else if (DestType->isReferenceType()) {
2055 // FIXME: C++0x defines behavior for this.
2056 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2057 return;
2058 } else if (DestType->isRecordType()) {
2059 // FIXME: C++0x defines behavior for this
2060 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2061 }
2062
2063 // Add a general "list initialization" step.
2064 Sequence.AddListInitializationStep(DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002065}
2066
2067/// \brief Try a reference initialization that involves calling a conversion
2068/// function.
2069///
2070/// FIXME: look intos DRs 656, 896
2071static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2072 const InitializedEntity &Entity,
2073 const InitializationKind &Kind,
2074 Expr *Initializer,
2075 bool AllowRValues,
2076 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002077 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002078 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2079 QualType T1 = cv1T1.getUnqualifiedType();
2080 QualType cv2T2 = Initializer->getType();
2081 QualType T2 = cv2T2.getUnqualifiedType();
2082
2083 bool DerivedToBase;
2084 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2085 T1, T2, DerivedToBase) &&
2086 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002087 (void)DerivedToBase;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002088
2089 // Build the candidate set directly in the initialization sequence
2090 // structure, so that it will persist if we fail.
2091 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2092 CandidateSet.clear();
2093
2094 // Determine whether we are allowed to call explicit constructors or
2095 // explicit conversion operators.
2096 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2097
2098 const RecordType *T1RecordType = 0;
2099 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2100 // The type we're converting to is a class type. Enumerate its constructors
2101 // to see if there is a suitable conversion.
2102 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2103
2104 DeclarationName ConstructorName
2105 = S.Context.DeclarationNames.getCXXConstructorName(
2106 S.Context.getCanonicalType(T1).getUnqualifiedType());
2107 DeclContext::lookup_iterator Con, ConEnd;
2108 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2109 Con != ConEnd; ++Con) {
2110 // Find the constructor (which may be a template).
2111 CXXConstructorDecl *Constructor = 0;
2112 FunctionTemplateDecl *ConstructorTmpl
2113 = dyn_cast<FunctionTemplateDecl>(*Con);
2114 if (ConstructorTmpl)
2115 Constructor = cast<CXXConstructorDecl>(
2116 ConstructorTmpl->getTemplatedDecl());
2117 else
2118 Constructor = cast<CXXConstructorDecl>(*Con);
2119
2120 if (!Constructor->isInvalidDecl() &&
2121 Constructor->isConvertingConstructor(AllowExplicit)) {
2122 if (ConstructorTmpl)
2123 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2124 &Initializer, 1, CandidateSet);
2125 else
2126 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2127 }
2128 }
2129 }
2130
2131 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2132 // The type we're converting from is a class type, enumerate its conversion
2133 // functions.
2134 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2135
2136 // Determine the type we are converting to. If we are allowed to
2137 // convert to an rvalue, take the type that the destination type
2138 // refers to.
2139 QualType ToType = AllowRValues? cv1T1 : DestType;
2140
2141 const UnresolvedSet *Conversions
2142 = T2RecordDecl->getVisibleConversionFunctions();
2143 for (UnresolvedSet::iterator I = Conversions->begin(),
2144 E = Conversions->end();
2145 I != E; ++I) {
2146 NamedDecl *D = *I;
2147 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2148 if (isa<UsingShadowDecl>(D))
2149 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2150
2151 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2152 CXXConversionDecl *Conv;
2153 if (ConvTemplate)
2154 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2155 else
2156 Conv = cast<CXXConversionDecl>(*I);
2157
2158 // If the conversion function doesn't return a reference type,
2159 // it can't be considered for this conversion unless we're allowed to
2160 // consider rvalues.
2161 // FIXME: Do we need to make sure that we only consider conversion
2162 // candidates with reference-compatible results? That might be needed to
2163 // break recursion.
2164 if ((AllowExplicit || !Conv->isExplicit()) &&
2165 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2166 if (ConvTemplate)
2167 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2168 ToType, CandidateSet);
2169 else
2170 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2171 CandidateSet);
2172 }
2173 }
2174 }
2175
2176 SourceLocation DeclLoc = Initializer->getLocStart();
2177
2178 // Perform overload resolution. If it fails, return the failed result.
2179 OverloadCandidateSet::iterator Best;
2180 if (OverloadingResult Result
2181 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2182 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002183
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002184 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002185
2186 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002187 if (isa<CXXConversionDecl>(Function))
2188 T2 = Function->getResultType();
2189 else
2190 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002191
2192 // Add the user-defined conversion step.
2193 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2194
2195 // Determine whether we need to perform derived-to-base or
2196 // cv-qualification adjustments.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002197 bool NewDerivedToBase = false;
2198 Sema::ReferenceCompareResult NewRefRelationship
2199 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2200 NewDerivedToBase);
2201 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2202 "Overload resolution picked a bad conversion function");
2203 (void)NewRefRelationship;
2204 if (NewDerivedToBase)
2205 Sequence.AddDerivedToBaseCastStep(
2206 S.Context.getQualifiedType(T1,
2207 T2.getNonReferenceType().getQualifiers()),
2208 /*isLValue=*/true);
2209
2210 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2211 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2212
2213 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2214 return OR_Success;
2215}
2216
2217/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2218static void TryReferenceInitialization(Sema &S,
2219 const InitializedEntity &Entity,
2220 const InitializationKind &Kind,
2221 Expr *Initializer,
2222 InitializationSequence &Sequence) {
2223 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2224
Douglas Gregor1b303932009-12-22 15:35:07 +00002225 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002226 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2227 QualType T1 = cv1T1.getUnqualifiedType();
2228 QualType cv2T2 = Initializer->getType();
2229 QualType T2 = cv2T2.getUnqualifiedType();
2230 SourceLocation DeclLoc = Initializer->getLocStart();
2231
2232 // If the initializer is the address of an overloaded function, try
2233 // to resolve the overloaded function. If all goes well, T2 is the
2234 // type of the resulting function.
2235 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2236 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2237 T1,
2238 false);
2239 if (!Fn) {
2240 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2241 return;
2242 }
2243
2244 Sequence.AddAddressOverloadResolutionStep(Fn);
2245 cv2T2 = Fn->getType();
2246 T2 = cv2T2.getUnqualifiedType();
2247 }
2248
2249 // FIXME: Rvalue references
2250 bool ForceRValue = false;
2251
2252 // Compute some basic properties of the types and the initializer.
2253 bool isLValueRef = DestType->isLValueReferenceType();
2254 bool isRValueRef = !isLValueRef;
2255 bool DerivedToBase = false;
2256 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2257 Initializer->isLvalue(S.Context);
2258 Sema::ReferenceCompareResult RefRelationship
2259 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2260
2261 // C++0x [dcl.init.ref]p5:
2262 // A reference to type "cv1 T1" is initialized by an expression of type
2263 // "cv2 T2" as follows:
2264 //
2265 // - If the reference is an lvalue reference and the initializer
2266 // expression
2267 OverloadingResult ConvOvlResult = OR_Success;
2268 if (isLValueRef) {
2269 if (InitLvalue == Expr::LV_Valid &&
2270 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2271 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2272 // reference-compatible with "cv2 T2," or
2273 //
2274 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2275 // bit-field when we're determining whether the reference initialization
2276 // can occur. This property will be checked by PerformInitialization.
2277 if (DerivedToBase)
2278 Sequence.AddDerivedToBaseCastStep(
2279 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2280 /*isLValue=*/true);
2281 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2282 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2283 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2284 return;
2285 }
2286
2287 // - has a class type (i.e., T2 is a class type), where T1 is not
2288 // reference-related to T2, and can be implicitly converted to an
2289 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2290 // with "cv3 T3" (this conversion is selected by enumerating the
2291 // applicable conversion functions (13.3.1.6) and choosing the best
2292 // one through overload resolution (13.3)),
2293 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2294 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2295 Initializer,
2296 /*AllowRValues=*/false,
2297 Sequence);
2298 if (ConvOvlResult == OR_Success)
2299 return;
2300 }
2301 }
2302
2303 // - Otherwise, the reference shall be an lvalue reference to a
2304 // non-volatile const type (i.e., cv1 shall be const), or the reference
2305 // shall be an rvalue reference and the initializer expression shall
2306 // be an rvalue.
2307 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2308 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2309 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2310 Sequence.SetOverloadFailure(
2311 InitializationSequence::FK_ReferenceInitOverloadFailed,
2312 ConvOvlResult);
2313 else if (isLValueRef)
2314 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2315 ? (RefRelationship == Sema::Ref_Related
2316 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2317 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2318 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2319 else
2320 Sequence.SetFailed(
2321 InitializationSequence::FK_RValueReferenceBindingToLValue);
2322
2323 return;
2324 }
2325
2326 // - If T1 and T2 are class types and
2327 if (T1->isRecordType() && T2->isRecordType()) {
2328 // - the initializer expression is an rvalue and "cv1 T1" is
2329 // reference-compatible with "cv2 T2", or
2330 if (InitLvalue != Expr::LV_Valid &&
2331 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2332 if (DerivedToBase)
2333 Sequence.AddDerivedToBaseCastStep(
2334 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2335 /*isLValue=*/false);
2336 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2337 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2338 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2339 return;
2340 }
2341
2342 // - T1 is not reference-related to T2 and the initializer expression
2343 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2344 // conversion is selected by enumerating the applicable conversion
2345 // functions (13.3.1.6) and choosing the best one through overload
2346 // resolution (13.3)),
2347 if (RefRelationship == Sema::Ref_Incompatible) {
2348 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2349 Kind, Initializer,
2350 /*AllowRValues=*/true,
2351 Sequence);
2352 if (ConvOvlResult)
2353 Sequence.SetOverloadFailure(
2354 InitializationSequence::FK_ReferenceInitOverloadFailed,
2355 ConvOvlResult);
2356
2357 return;
2358 }
2359
2360 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2361 return;
2362 }
2363
2364 // - If the initializer expression is an rvalue, with T2 an array type,
2365 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2366 // is bound to the object represented by the rvalue (see 3.10).
2367 // FIXME: How can an array type be reference-compatible with anything?
2368 // Don't we mean the element types of T1 and T2?
2369
2370 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2371 // from the initializer expression using the rules for a non-reference
2372 // copy initialization (8.5). The reference is then bound to the
2373 // temporary. [...]
2374 // Determine whether we are allowed to call explicit constructors or
2375 // explicit conversion operators.
2376 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2377 ImplicitConversionSequence ICS
2378 = S.TryImplicitConversion(Initializer, cv1T1,
2379 /*SuppressUserConversions=*/false, AllowExplicit,
2380 /*ForceRValue=*/false,
2381 /*FIXME:InOverloadResolution=*/false,
2382 /*UserCast=*/Kind.isExplicitCast());
2383
2384 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2385 // FIXME: Use the conversion function set stored in ICS to turn
2386 // this into an overloading ambiguity diagnostic. However, we need
2387 // to keep that set as an OverloadCandidateSet rather than as some
2388 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00002389 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2390 Sequence.SetOverloadFailure(
2391 InitializationSequence::FK_ReferenceInitOverloadFailed,
2392 ConvOvlResult);
2393 else
2394 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002395 return;
2396 }
2397
2398 // [...] If T1 is reference-related to T2, cv1 must be the
2399 // same cv-qualification as, or greater cv-qualification
2400 // than, cv2; otherwise, the program is ill-formed.
2401 if (RefRelationship == Sema::Ref_Related &&
2402 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2403 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2404 return;
2405 }
2406
2407 // Perform the actual conversion.
2408 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2409 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2410 return;
2411}
2412
2413/// \brief Attempt character array initialization from a string literal
2414/// (C++ [dcl.init.string], C99 6.7.8).
2415static void TryStringLiteralInitialization(Sema &S,
2416 const InitializedEntity &Entity,
2417 const InitializationKind &Kind,
2418 Expr *Initializer,
2419 InitializationSequence &Sequence) {
Eli Friedman78275202009-12-19 08:11:05 +00002420 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregor1b303932009-12-22 15:35:07 +00002421 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002422}
2423
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002424/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2425/// enumerates the constructors of the initialized entity and performs overload
2426/// resolution to select the best.
2427static void TryConstructorInitialization(Sema &S,
2428 const InitializedEntity &Entity,
2429 const InitializationKind &Kind,
2430 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002431 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002432 InitializationSequence &Sequence) {
Douglas Gregore1314a62009-12-18 05:02:21 +00002433 if (Kind.getKind() == InitializationKind::IK_Copy)
2434 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2435 else
2436 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002437
2438 // Build the candidate set directly in the initialization sequence
2439 // structure, so that it will persist if we fail.
2440 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2441 CandidateSet.clear();
2442
2443 // Determine whether we are allowed to call explicit constructors or
2444 // explicit conversion operators.
2445 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2446 Kind.getKind() == InitializationKind::IK_Value ||
2447 Kind.getKind() == InitializationKind::IK_Default);
2448
2449 // The type we're converting to is a class type. Enumerate its constructors
2450 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002451 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2452 assert(DestRecordType && "Constructor initialization requires record type");
2453 CXXRecordDecl *DestRecordDecl
2454 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2455
2456 DeclarationName ConstructorName
2457 = S.Context.DeclarationNames.getCXXConstructorName(
2458 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2459 DeclContext::lookup_iterator Con, ConEnd;
2460 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2461 Con != ConEnd; ++Con) {
2462 // Find the constructor (which may be a template).
2463 CXXConstructorDecl *Constructor = 0;
2464 FunctionTemplateDecl *ConstructorTmpl
2465 = dyn_cast<FunctionTemplateDecl>(*Con);
2466 if (ConstructorTmpl)
2467 Constructor = cast<CXXConstructorDecl>(
2468 ConstructorTmpl->getTemplatedDecl());
2469 else
2470 Constructor = cast<CXXConstructorDecl>(*Con);
2471
2472 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00002473 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002474 if (ConstructorTmpl)
2475 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2476 Args, NumArgs, CandidateSet);
2477 else
2478 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2479 }
2480 }
2481
2482 SourceLocation DeclLoc = Kind.getLocation();
2483
2484 // Perform overload resolution. If it fails, return the failed result.
2485 OverloadCandidateSet::iterator Best;
2486 if (OverloadingResult Result
2487 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2488 Sequence.SetOverloadFailure(
2489 InitializationSequence::FK_ConstructorOverloadFailed,
2490 Result);
2491 return;
2492 }
2493
2494 // Add the constructor initialization step. Any cv-qualification conversion is
2495 // subsumed by the initialization.
Douglas Gregore1314a62009-12-18 05:02:21 +00002496 if (Kind.getKind() == InitializationKind::IK_Copy) {
2497 Sequence.AddUserConversionStep(Best->Function, DestType);
2498 } else {
2499 Sequence.AddConstructorInitializationStep(
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002500 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregore1314a62009-12-18 05:02:21 +00002501 DestType);
2502 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002503}
2504
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002505/// \brief Attempt value initialization (C++ [dcl.init]p7).
2506static void TryValueInitialization(Sema &S,
2507 const InitializedEntity &Entity,
2508 const InitializationKind &Kind,
2509 InitializationSequence &Sequence) {
2510 // C++ [dcl.init]p5:
2511 //
2512 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00002513 QualType T = Entity.getType();
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002514
2515 // -- if T is an array type, then each element is value-initialized;
2516 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2517 T = AT->getElementType();
2518
2519 if (const RecordType *RT = T->getAs<RecordType>()) {
2520 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2521 // -- if T is a class type (clause 9) with a user-declared
2522 // constructor (12.1), then the default constructor for T is
2523 // called (and the initialization is ill-formed if T has no
2524 // accessible default constructor);
2525 //
2526 // FIXME: we really want to refer to a single subobject of the array,
2527 // but Entity doesn't have a way to capture that (yet).
2528 if (ClassDecl->hasUserDeclaredConstructor())
2529 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2530
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002531 // -- if T is a (possibly cv-qualified) non-union class type
2532 // without a user-provided constructor, then the object is
2533 // zero-initialized and, if T’s implicitly-declared default
2534 // constructor is non-trivial, that constructor is called.
2535 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2536 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2537 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002538 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor4f4b1862009-12-16 18:50:27 +00002539 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2540 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002541 }
2542 }
2543
Douglas Gregor1b303932009-12-22 15:35:07 +00002544 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002545 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2546}
2547
Douglas Gregor85dabae2009-12-16 01:38:02 +00002548/// \brief Attempt default initialization (C++ [dcl.init]p6).
2549static void TryDefaultInitialization(Sema &S,
2550 const InitializedEntity &Entity,
2551 const InitializationKind &Kind,
2552 InitializationSequence &Sequence) {
2553 assert(Kind.getKind() == InitializationKind::IK_Default);
2554
2555 // C++ [dcl.init]p6:
2556 // To default-initialize an object of type T means:
2557 // - if T is an array type, each element is default-initialized;
Douglas Gregor1b303932009-12-22 15:35:07 +00002558 QualType DestType = Entity.getType();
Douglas Gregor85dabae2009-12-16 01:38:02 +00002559 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2560 DestType = Array->getElementType();
2561
2562 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2563 // constructor for T is called (and the initialization is ill-formed if
2564 // T has no accessible default constructor);
2565 if (DestType->isRecordType()) {
2566 // FIXME: If a program calls for the default initialization of an object of
2567 // a const-qualified type T, T shall be a class type with a user-provided
2568 // default constructor.
2569 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2570 Sequence);
2571 }
2572
2573 // - otherwise, no initialization is performed.
2574 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2575
2576 // If a program calls for the default initialization of an object of
2577 // a const-qualified type T, T shall be a class type with a user-provided
2578 // default constructor.
2579 if (DestType.isConstQualified())
2580 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2581}
2582
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002583/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2584/// which enumerates all conversion functions and performs overload resolution
2585/// to select the best.
2586static void TryUserDefinedConversion(Sema &S,
2587 const InitializedEntity &Entity,
2588 const InitializationKind &Kind,
2589 Expr *Initializer,
2590 InitializationSequence &Sequence) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00002591 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2592
Douglas Gregor1b303932009-12-22 15:35:07 +00002593 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00002594 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2595 QualType SourceType = Initializer->getType();
2596 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2597 "Must have a class type to perform a user-defined conversion");
2598
2599 // Build the candidate set directly in the initialization sequence
2600 // structure, so that it will persist if we fail.
2601 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2602 CandidateSet.clear();
2603
2604 // Determine whether we are allowed to call explicit constructors or
2605 // explicit conversion operators.
2606 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2607
2608 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2609 // The type we're converting to is a class type. Enumerate its constructors
2610 // to see if there is a suitable conversion.
2611 CXXRecordDecl *DestRecordDecl
2612 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2613
2614 DeclarationName ConstructorName
2615 = S.Context.DeclarationNames.getCXXConstructorName(
2616 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2617 DeclContext::lookup_iterator Con, ConEnd;
2618 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2619 Con != ConEnd; ++Con) {
2620 // Find the constructor (which may be a template).
2621 CXXConstructorDecl *Constructor = 0;
2622 FunctionTemplateDecl *ConstructorTmpl
2623 = dyn_cast<FunctionTemplateDecl>(*Con);
2624 if (ConstructorTmpl)
2625 Constructor = cast<CXXConstructorDecl>(
2626 ConstructorTmpl->getTemplatedDecl());
2627 else
2628 Constructor = cast<CXXConstructorDecl>(*Con);
2629
2630 if (!Constructor->isInvalidDecl() &&
2631 Constructor->isConvertingConstructor(AllowExplicit)) {
2632 if (ConstructorTmpl)
2633 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2634 &Initializer, 1, CandidateSet);
2635 else
2636 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2637 }
2638 }
2639 }
Eli Friedman78275202009-12-19 08:11:05 +00002640
2641 SourceLocation DeclLoc = Initializer->getLocStart();
2642
Douglas Gregor540c3b02009-12-14 17:27:33 +00002643 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2644 // The type we're converting from is a class type, enumerate its conversion
2645 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00002646
Eli Friedman4afe9a32009-12-20 22:12:03 +00002647 // We can only enumerate the conversion functions for a complete type; if
2648 // the type isn't complete, simply skip this step.
2649 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2650 CXXRecordDecl *SourceRecordDecl
2651 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002652
Eli Friedman4afe9a32009-12-20 22:12:03 +00002653 const UnresolvedSet *Conversions
2654 = SourceRecordDecl->getVisibleConversionFunctions();
2655 for (UnresolvedSet::iterator I = Conversions->begin(),
2656 E = Conversions->end();
2657 I != E; ++I) {
2658 NamedDecl *D = *I;
2659 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2660 if (isa<UsingShadowDecl>(D))
2661 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2662
2663 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2664 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00002665 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00002666 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00002667 else
Eli Friedman4afe9a32009-12-20 22:12:03 +00002668 Conv = cast<CXXConversionDecl>(*I);
2669
2670 if (AllowExplicit || !Conv->isExplicit()) {
2671 if (ConvTemplate)
2672 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2673 Initializer, DestType,
2674 CandidateSet);
2675 else
2676 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2677 CandidateSet);
2678 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00002679 }
2680 }
2681 }
2682
Douglas Gregor540c3b02009-12-14 17:27:33 +00002683 // Perform overload resolution. If it fails, return the failed result.
2684 OverloadCandidateSet::iterator Best;
2685 if (OverloadingResult Result
2686 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2687 Sequence.SetOverloadFailure(
2688 InitializationSequence::FK_UserConversionOverloadFailed,
2689 Result);
2690 return;
2691 }
2692
2693 FunctionDecl *Function = Best->Function;
2694
2695 if (isa<CXXConstructorDecl>(Function)) {
2696 // Add the user-defined conversion step. Any cv-qualification conversion is
2697 // subsumed by the initialization.
2698 Sequence.AddUserConversionStep(Function, DestType);
2699 return;
2700 }
2701
2702 // Add the user-defined conversion step that calls the conversion function.
2703 QualType ConvType = Function->getResultType().getNonReferenceType();
2704 Sequence.AddUserConversionStep(Function, ConvType);
2705
2706 // If the conversion following the call to the conversion function is
2707 // interesting, add it as a separate step.
2708 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2709 Best->FinalConversion.Third) {
2710 ImplicitConversionSequence ICS;
2711 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2712 ICS.Standard = Best->FinalConversion;
2713 Sequence.AddConversionSequenceStep(ICS, DestType);
2714 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002715}
2716
2717/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2718/// non-class type to another.
2719static void TryImplicitConversion(Sema &S,
2720 const InitializedEntity &Entity,
2721 const InitializationKind &Kind,
2722 Expr *Initializer,
2723 InitializationSequence &Sequence) {
2724 ImplicitConversionSequence ICS
Douglas Gregor1b303932009-12-22 15:35:07 +00002725 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 /*SuppressUserConversions=*/true,
2727 /*AllowExplicit=*/false,
2728 /*ForceRValue=*/false,
2729 /*FIXME:InOverloadResolution=*/false,
2730 /*UserCast=*/Kind.isExplicitCast());
2731
2732 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2733 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2734 return;
2735 }
2736
Douglas Gregor1b303932009-12-22 15:35:07 +00002737 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002738}
2739
2740InitializationSequence::InitializationSequence(Sema &S,
2741 const InitializedEntity &Entity,
2742 const InitializationKind &Kind,
2743 Expr **Args,
2744 unsigned NumArgs) {
2745 ASTContext &Context = S.Context;
2746
2747 // C++0x [dcl.init]p16:
2748 // The semantics of initializers are as follows. The destination type is
2749 // the type of the object or reference being initialized and the source
2750 // type is the type of the initializer expression. The source type is not
2751 // defined when the initializer is a braced-init-list or when it is a
2752 // parenthesized list of expressions.
Douglas Gregor1b303932009-12-22 15:35:07 +00002753 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002754
2755 if (DestType->isDependentType() ||
2756 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2757 SequenceKind = DependentSequence;
2758 return;
2759 }
2760
2761 QualType SourceType;
2762 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00002763 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002764 Initializer = Args[0];
2765 if (!isa<InitListExpr>(Initializer))
2766 SourceType = Initializer->getType();
2767 }
2768
2769 // - If the initializer is a braced-init-list, the object is
2770 // list-initialized (8.5.4).
2771 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2772 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00002773 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002774 }
2775
2776 // - If the destination type is a reference type, see 8.5.3.
2777 if (DestType->isReferenceType()) {
2778 // C++0x [dcl.init.ref]p1:
2779 // A variable declared to be a T& or T&&, that is, "reference to type T"
2780 // (8.3.2), shall be initialized by an object, or function, of type T or
2781 // by an object that can be converted into a T.
2782 // (Therefore, multiple arguments are not permitted.)
2783 if (NumArgs != 1)
2784 SetFailed(FK_TooManyInitsForReference);
2785 else
2786 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2787 return;
2788 }
2789
2790 // - If the destination type is an array of characters, an array of
2791 // char16_t, an array of char32_t, or an array of wchar_t, and the
2792 // initializer is a string literal, see 8.5.2.
2793 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2794 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2795 return;
2796 }
2797
2798 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002799 if (Kind.getKind() == InitializationKind::IK_Value ||
2800 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002801 TryValueInitialization(S, Entity, Kind, *this);
2802 return;
2803 }
2804
Douglas Gregor85dabae2009-12-16 01:38:02 +00002805 // Handle default initialization.
2806 if (Kind.getKind() == InitializationKind::IK_Default){
2807 TryDefaultInitialization(S, Entity, Kind, *this);
2808 return;
2809 }
Douglas Gregore1314a62009-12-18 05:02:21 +00002810
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002811 // - Otherwise, if the destination type is an array, the program is
2812 // ill-formed.
2813 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2814 if (AT->getElementType()->isAnyCharacterType())
2815 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2816 else
2817 SetFailed(FK_ArrayNeedsInitList);
2818
2819 return;
2820 }
Eli Friedman78275202009-12-19 08:11:05 +00002821
2822 // Handle initialization in C
2823 if (!S.getLangOptions().CPlusPlus) {
2824 setSequenceKind(CAssignment);
2825 AddCAssignmentStep(DestType);
2826 return;
2827 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002828
2829 // - If the destination type is a (possibly cv-qualified) class type:
2830 if (DestType->isRecordType()) {
2831 // - If the initialization is direct-initialization, or if it is
2832 // copy-initialization where the cv-unqualified version of the
2833 // source type is the same class as, or a derived class of, the
2834 // class of the destination, constructors are considered. [...]
2835 if (Kind.getKind() == InitializationKind::IK_Direct ||
2836 (Kind.getKind() == InitializationKind::IK_Copy &&
2837 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2838 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002839 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregor1b303932009-12-22 15:35:07 +00002840 Entity.getType(), *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002841 // - Otherwise (i.e., for the remaining copy-initialization cases),
2842 // user-defined conversion sequences that can convert from the source
2843 // type to the destination type or (when a conversion function is
2844 // used) to a derived class thereof are enumerated as described in
2845 // 13.3.1.4, and the best one is chosen through overload resolution
2846 // (13.3).
2847 else
2848 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2849 return;
2850 }
2851
Douglas Gregor85dabae2009-12-16 01:38:02 +00002852 if (NumArgs > 1) {
2853 SetFailed(FK_TooManyInitsForScalar);
2854 return;
2855 }
2856 assert(NumArgs == 1 && "Zero-argument case handled above");
2857
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002858 // - Otherwise, if the source type is a (possibly cv-qualified) class
2859 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002860 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002861 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2862 return;
2863 }
2864
2865 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00002866 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002867 // conversions (Clause 4) will be used, if necessary, to convert the
2868 // initializer expression to the cv-unqualified version of the
2869 // destination type; no user-defined conversions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002870 setSequenceKind(StandardConversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002871 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2872}
2873
2874InitializationSequence::~InitializationSequence() {
2875 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2876 StepEnd = Steps.end();
2877 Step != StepEnd; ++Step)
2878 Step->Destroy();
2879}
2880
2881//===----------------------------------------------------------------------===//
2882// Perform initialization
2883//===----------------------------------------------------------------------===//
Douglas Gregore1314a62009-12-18 05:02:21 +00002884static Sema::AssignmentAction
2885getAssignmentAction(const InitializedEntity &Entity) {
2886 switch(Entity.getKind()) {
2887 case InitializedEntity::EK_Variable:
2888 case InitializedEntity::EK_New:
2889 return Sema::AA_Initializing;
2890
2891 case InitializedEntity::EK_Parameter:
2892 // FIXME: Can we tell when we're sending vs. passing?
2893 return Sema::AA_Passing;
2894
2895 case InitializedEntity::EK_Result:
2896 return Sema::AA_Returning;
2897
2898 case InitializedEntity::EK_Exception:
2899 case InitializedEntity::EK_Base:
2900 llvm_unreachable("No assignment action for C++-specific initialization");
2901 break;
2902
2903 case InitializedEntity::EK_Temporary:
2904 // FIXME: Can we tell apart casting vs. converting?
2905 return Sema::AA_Casting;
2906
2907 case InitializedEntity::EK_Member:
2908 case InitializedEntity::EK_ArrayOrVectorElement:
2909 return Sema::AA_Initializing;
2910 }
2911
2912 return Sema::AA_Converting;
2913}
2914
2915static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2916 bool IsCopy) {
2917 switch (Entity.getKind()) {
2918 case InitializedEntity::EK_Result:
2919 case InitializedEntity::EK_Exception:
2920 return !IsCopy;
2921
2922 case InitializedEntity::EK_New:
2923 case InitializedEntity::EK_Variable:
2924 case InitializedEntity::EK_Base:
2925 case InitializedEntity::EK_Member:
2926 case InitializedEntity::EK_ArrayOrVectorElement:
2927 return false;
2928
2929 case InitializedEntity::EK_Parameter:
2930 case InitializedEntity::EK_Temporary:
2931 return true;
2932 }
2933
2934 llvm_unreachable("missed an InitializedEntity kind?");
2935}
2936
2937/// \brief If we need to perform an additional copy of the initialized object
2938/// for this kind of entity (e.g., the result of a function or an object being
2939/// thrown), make the copy.
2940static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2941 const InitializedEntity &Entity,
Douglas Gregora4b592a2009-12-19 03:01:41 +00002942 const InitializationKind &Kind,
Douglas Gregore1314a62009-12-18 05:02:21 +00002943 Sema::OwningExprResult CurInit) {
2944 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00002945
2946 switch (Entity.getKind()) {
2947 case InitializedEntity::EK_Result:
Douglas Gregor1b303932009-12-22 15:35:07 +00002948 if (Entity.getType()->isReferenceType())
Douglas Gregore1314a62009-12-18 05:02:21 +00002949 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00002950 Loc = Entity.getReturnLoc();
2951 break;
2952
2953 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002954 Loc = Entity.getThrowLoc();
2955 break;
2956
2957 case InitializedEntity::EK_Variable:
Douglas Gregor1b303932009-12-22 15:35:07 +00002958 if (Entity.getType()->isReferenceType() ||
Douglas Gregora4b592a2009-12-19 03:01:41 +00002959 Kind.getKind() != InitializationKind::IK_Copy)
2960 return move(CurInit);
2961 Loc = Entity.getDecl()->getLocation();
2962 break;
2963
Douglas Gregore1314a62009-12-18 05:02:21 +00002964 case InitializedEntity::EK_Parameter:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002965 // FIXME: Do we need this initialization for a parameter?
2966 return move(CurInit);
2967
Douglas Gregore1314a62009-12-18 05:02:21 +00002968 case InitializedEntity::EK_New:
2969 case InitializedEntity::EK_Temporary:
2970 case InitializedEntity::EK_Base:
2971 case InitializedEntity::EK_Member:
2972 case InitializedEntity::EK_ArrayOrVectorElement:
2973 // We don't need to copy for any of these initialized entities.
2974 return move(CurInit);
2975 }
2976
2977 Expr *CurInitExpr = (Expr *)CurInit.get();
2978 CXXRecordDecl *Class = 0;
2979 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
2980 Class = cast<CXXRecordDecl>(Record->getDecl());
2981 if (!Class)
2982 return move(CurInit);
2983
2984 // Perform overload resolution using the class's copy constructors.
2985 DeclarationName ConstructorName
2986 = S.Context.DeclarationNames.getCXXConstructorName(
2987 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
2988 DeclContext::lookup_iterator Con, ConEnd;
2989 OverloadCandidateSet CandidateSet;
2990 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
2991 Con != ConEnd; ++Con) {
2992 // Find the constructor (which may be a template).
2993 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
2994 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor507eb872009-12-22 00:34:07 +00002995 !Constructor->isCopyConstructor())
Douglas Gregore1314a62009-12-18 05:02:21 +00002996 continue;
2997
2998 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
2999 }
3000
3001 OverloadCandidateSet::iterator Best;
3002 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3003 case OR_Success:
3004 break;
3005
3006 case OR_No_Viable_Function:
3007 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003008 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003009 << CurInitExpr->getSourceRange();
3010 S.PrintOverloadCandidates(CandidateSet, false);
3011 return S.ExprError();
3012
3013 case OR_Ambiguous:
3014 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003015 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003016 << CurInitExpr->getSourceRange();
3017 S.PrintOverloadCandidates(CandidateSet, true);
3018 return S.ExprError();
3019
3020 case OR_Deleted:
3021 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003022 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00003023 << CurInitExpr->getSourceRange();
3024 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3025 << Best->Function->isDeleted();
3026 return S.ExprError();
3027 }
3028
3029 CurInit.release();
3030 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3031 cast<CXXConstructorDecl>(Best->Function),
3032 /*Elidable=*/true,
3033 Sema::MultiExprArg(S,
3034 (void**)&CurInitExpr, 1));
3035}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003036
3037Action::OwningExprResult
3038InitializationSequence::Perform(Sema &S,
3039 const InitializedEntity &Entity,
3040 const InitializationKind &Kind,
Douglas Gregor51e77d52009-12-10 17:56:55 +00003041 Action::MultiExprArg Args,
3042 QualType *ResultType) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003043 if (SequenceKind == FailedSequence) {
3044 unsigned NumArgs = Args.size();
3045 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3046 return S.ExprError();
3047 }
3048
3049 if (SequenceKind == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00003050 // If the declaration is a non-dependent, incomplete array type
3051 // that has an initializer, then its type will be completed once
3052 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00003053 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00003054 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003055 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003056 if (const IncompleteArrayType *ArrayT
3057 = S.Context.getAsIncompleteArrayType(DeclType)) {
3058 // FIXME: We don't currently have the ability to accurately
3059 // compute the length of an initializer list without
3060 // performing full type-checking of the initializer list
3061 // (since we have to determine where braces are implicitly
3062 // introduced and such). So, we fall back to making the array
3063 // type a dependently-sized array type with no specified
3064 // bound.
3065 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3066 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00003067
Douglas Gregor51e77d52009-12-10 17:56:55 +00003068 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00003069 if (DeclaratorDecl *DD = Entity.getDecl()) {
3070 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3071 TypeLoc TL = TInfo->getTypeLoc();
3072 if (IncompleteArrayTypeLoc *ArrayLoc
3073 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3074 Brackets = ArrayLoc->getBracketsRange();
3075 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00003076 }
3077
3078 *ResultType
3079 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3080 /*NumElts=*/0,
3081 ArrayT->getSizeModifier(),
3082 ArrayT->getIndexTypeCVRQualifiers(),
3083 Brackets);
3084 }
3085
3086 }
3087 }
3088
Eli Friedmana553d4a2009-12-22 02:35:53 +00003089 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003090 return Sema::OwningExprResult(S, Args.release()[0]);
3091
3092 unsigned NumArgs = Args.size();
3093 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3094 SourceLocation(),
3095 (Expr **)Args.release(),
3096 NumArgs,
3097 SourceLocation()));
3098 }
3099
Douglas Gregor85dabae2009-12-16 01:38:02 +00003100 if (SequenceKind == NoInitialization)
3101 return S.Owned((Expr *)0);
3102
Douglas Gregor1b303932009-12-22 15:35:07 +00003103 QualType DestType = Entity.getType().getNonReferenceType();
3104 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00003105 // the same as Entity.getDecl()->getType() in cases involving type merging,
3106 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00003107 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00003108 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00003109 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003110
Douglas Gregor85dabae2009-12-16 01:38:02 +00003111 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3112
3113 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3114
3115 // For initialization steps that start with a single initializer,
3116 // grab the only argument out the Args and place it into the "current"
3117 // initializer.
3118 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003119 case SK_ResolveAddressOfOverloadedFunction:
3120 case SK_CastDerivedToBaseRValue:
3121 case SK_CastDerivedToBaseLValue:
3122 case SK_BindReference:
3123 case SK_BindReferenceToTemporary:
3124 case SK_UserConversion:
3125 case SK_QualificationConversionLValue:
3126 case SK_QualificationConversionRValue:
3127 case SK_ConversionSequence:
3128 case SK_ListInitialization:
3129 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00003130 case SK_StringInit:
Douglas Gregore1314a62009-12-18 05:02:21 +00003131 assert(Args.size() == 1);
3132 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3133 if (CurInit.isInvalid())
3134 return S.ExprError();
3135 break;
3136
3137 case SK_ConstructorInitialization:
3138 case SK_ZeroInitialization:
3139 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003140 }
3141
3142 // Walk through the computed steps for the initialization sequence,
3143 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003144 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003145 for (step_iterator Step = step_begin(), StepEnd = step_end();
3146 Step != StepEnd; ++Step) {
3147 if (CurInit.isInvalid())
3148 return S.ExprError();
3149
3150 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003151 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003152
3153 switch (Step->Kind) {
3154 case SK_ResolveAddressOfOverloadedFunction:
3155 // Overload resolution determined which function invoke; update the
3156 // initializer to reflect that choice.
3157 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3158 break;
3159
3160 case SK_CastDerivedToBaseRValue:
3161 case SK_CastDerivedToBaseLValue: {
3162 // We have a derived-to-base cast that produces either an rvalue or an
3163 // lvalue. Perform that cast.
3164
3165 // Casts to inaccessible base classes are allowed with C-style casts.
3166 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3167 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3168 CurInitExpr->getLocStart(),
3169 CurInitExpr->getSourceRange(),
3170 IgnoreBaseAccess))
3171 return S.ExprError();
3172
3173 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3174 CastExpr::CK_DerivedToBase,
3175 (Expr*)CurInit.release(),
3176 Step->Kind == SK_CastDerivedToBaseLValue));
3177 break;
3178 }
3179
3180 case SK_BindReference:
3181 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3182 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3183 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00003184 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003185 << BitField->getDeclName()
3186 << CurInitExpr->getSourceRange();
3187 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3188 return S.ExprError();
3189 }
3190
3191 // Reference binding does not have any corresponding ASTs.
3192
3193 // Check exception specifications
3194 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3195 return S.ExprError();
3196 break;
3197
3198 case SK_BindReferenceToTemporary:
3199 // Check exception specifications
3200 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3201 return S.ExprError();
3202
3203 // FIXME: At present, we have no AST to describe when we need to make a
3204 // temporary to bind a reference to. We should.
3205 break;
3206
3207 case SK_UserConversion: {
3208 // We have a user-defined conversion that invokes either a constructor
3209 // or a conversion function.
3210 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregore1314a62009-12-18 05:02:21 +00003211 bool IsCopy = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003212 if (CXXConstructorDecl *Constructor
3213 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3214 // Build a call to the selected constructor.
3215 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3216 SourceLocation Loc = CurInitExpr->getLocStart();
3217 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3218
3219 // Determine the arguments required to actually perform the constructor
3220 // call.
3221 if (S.CompleteConstructorCall(Constructor,
3222 Sema::MultiExprArg(S,
3223 (void **)&CurInitExpr,
3224 1),
3225 Loc, ConstructorArgs))
3226 return S.ExprError();
3227
3228 // Build the an expression that constructs a temporary.
3229 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3230 move_arg(ConstructorArgs));
3231 if (CurInit.isInvalid())
3232 return S.ExprError();
3233
3234 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00003235 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3236 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3237 S.IsDerivedFrom(SourceType, Class))
3238 IsCopy = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003239 } else {
3240 // Build a call to the conversion function.
3241 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregore1314a62009-12-18 05:02:21 +00003242
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003243 // FIXME: Should we move this initialization into a separate
3244 // derived-to-base conversion? I believe the answer is "no", because
3245 // we don't want to turn off access control here for c-style casts.
3246 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3247 return S.ExprError();
3248
3249 // Do a little dance to make sure that CurInit has the proper
3250 // pointer.
3251 CurInit.release();
3252
3253 // Build the actual call to the conversion function.
3254 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3255 if (CurInit.isInvalid() || !CurInit.get())
3256 return S.ExprError();
3257
3258 CastKind = CastExpr::CK_UserDefinedConversion;
3259 }
3260
Douglas Gregore1314a62009-12-18 05:02:21 +00003261 if (shouldBindAsTemporary(Entity, IsCopy))
3262 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3263
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003264 CurInitExpr = CurInit.takeAs<Expr>();
3265 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3266 CastKind,
3267 CurInitExpr,
Douglas Gregore1314a62009-12-18 05:02:21 +00003268 false));
3269
3270 if (!IsCopy)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003271 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003272 break;
3273 }
3274
3275 case SK_QualificationConversionLValue:
3276 case SK_QualificationConversionRValue:
3277 // Perform a qualification conversion; these can never go wrong.
3278 S.ImpCastExprToType(CurInitExpr, Step->Type,
3279 CastExpr::CK_NoOp,
3280 Step->Kind == SK_QualificationConversionLValue);
3281 CurInit.release();
3282 CurInit = S.Owned(CurInitExpr);
3283 break;
3284
3285 case SK_ConversionSequence:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003286 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003287 false, false, *Step->ICS))
3288 return S.ExprError();
3289
3290 CurInit.release();
3291 CurInit = S.Owned(CurInitExpr);
3292 break;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003293
3294 case SK_ListInitialization: {
3295 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3296 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00003297 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregor51e77d52009-12-10 17:56:55 +00003298 return S.ExprError();
3299
3300 CurInit.release();
3301 CurInit = S.Owned(InitList);
3302 break;
3303 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003304
3305 case SK_ConstructorInitialization: {
3306 CXXConstructorDecl *Constructor
3307 = cast<CXXConstructorDecl>(Step->Function);
3308
3309 // Build a call to the selected constructor.
3310 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3311 SourceLocation Loc = Kind.getLocation();
3312
3313 // Determine the arguments required to actually perform the constructor
3314 // call.
3315 if (S.CompleteConstructorCall(Constructor, move(Args),
3316 Loc, ConstructorArgs))
3317 return S.ExprError();
3318
3319 // Build the an expression that constructs a temporary.
Douglas Gregor1b303932009-12-22 15:35:07 +00003320 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor39c778b2009-12-20 22:01:25 +00003321 Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003322 move_arg(ConstructorArgs),
3323 ConstructorInitRequiresZeroInit);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003324 if (CurInit.isInvalid())
3325 return S.ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00003326
3327 bool Elidable
3328 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3329 if (shouldBindAsTemporary(Entity, Elidable))
3330 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3331
3332 if (!Elidable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00003333 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003334 break;
3335 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003336
3337 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003338 step_iterator NextStep = Step;
3339 ++NextStep;
3340 if (NextStep != StepEnd &&
3341 NextStep->Kind == SK_ConstructorInitialization) {
3342 // The need for zero-initialization is recorded directly into
3343 // the call to the object's constructor within the next step.
3344 ConstructorInitRequiresZeroInit = true;
3345 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3346 S.getLangOptions().CPlusPlus &&
3347 !Kind.isImplicitValueInit()) {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003348 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3349 Kind.getRange().getBegin(),
3350 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003351 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003352 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003353 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003354 break;
3355 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003356
3357 case SK_CAssignment: {
3358 QualType SourceType = CurInitExpr->getType();
3359 Sema::AssignConvertType ConvTy =
3360 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregor96596c92009-12-22 07:24:36 +00003361
3362 // If this is a call, allow conversion to a transparent union.
3363 if (ConvTy != Sema::Compatible &&
3364 Entity.getKind() == InitializedEntity::EK_Parameter &&
3365 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3366 == Sema::Compatible)
3367 ConvTy = Sema::Compatible;
3368
Douglas Gregore1314a62009-12-18 05:02:21 +00003369 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3370 Step->Type, SourceType,
3371 CurInitExpr, getAssignmentAction(Entity)))
3372 return S.ExprError();
3373
3374 CurInit.release();
3375 CurInit = S.Owned(CurInitExpr);
3376 break;
3377 }
Eli Friedman78275202009-12-19 08:11:05 +00003378
3379 case SK_StringInit: {
3380 QualType Ty = Step->Type;
3381 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3382 break;
3383 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003384 }
3385 }
3386
3387 return move(CurInit);
3388}
3389
3390//===----------------------------------------------------------------------===//
3391// Diagnose initialization failures
3392//===----------------------------------------------------------------------===//
3393bool InitializationSequence::Diagnose(Sema &S,
3394 const InitializedEntity &Entity,
3395 const InitializationKind &Kind,
3396 Expr **Args, unsigned NumArgs) {
3397 if (SequenceKind != FailedSequence)
3398 return false;
3399
Douglas Gregor1b303932009-12-22 15:35:07 +00003400 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003401 switch (Failure) {
3402 case FK_TooManyInitsForReference:
3403 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3404 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3405 break;
3406
3407 case FK_ArrayNeedsInitList:
3408 case FK_ArrayNeedsInitListOrStringLiteral:
3409 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3410 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3411 break;
3412
3413 case FK_AddressOfOverloadFailed:
3414 S.ResolveAddressOfOverloadedFunction(Args[0],
3415 DestType.getNonReferenceType(),
3416 true);
3417 break;
3418
3419 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00003420 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003421 switch (FailedOverloadResult) {
3422 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00003423 if (Failure == FK_UserConversionOverloadFailed)
3424 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3425 << Args[0]->getType() << DestType
3426 << Args[0]->getSourceRange();
3427 else
3428 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3429 << DestType << Args[0]->getType()
3430 << Args[0]->getSourceRange();
3431
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003432 S.PrintOverloadCandidates(FailedCandidateSet, true);
3433 break;
3434
3435 case OR_No_Viable_Function:
3436 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3437 << Args[0]->getType() << DestType.getNonReferenceType()
3438 << Args[0]->getSourceRange();
3439 S.PrintOverloadCandidates(FailedCandidateSet, false);
3440 break;
3441
3442 case OR_Deleted: {
3443 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3444 << Args[0]->getType() << DestType.getNonReferenceType()
3445 << Args[0]->getSourceRange();
3446 OverloadCandidateSet::iterator Best;
3447 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3448 Kind.getLocation(),
3449 Best);
3450 if (Ovl == OR_Deleted) {
3451 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3452 << Best->Function->isDeleted();
3453 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003454 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003455 }
3456 break;
3457 }
3458
3459 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003460 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003461 break;
3462 }
3463 break;
3464
3465 case FK_NonConstLValueReferenceBindingToTemporary:
3466 case FK_NonConstLValueReferenceBindingToUnrelated:
3467 S.Diag(Kind.getLocation(),
3468 Failure == FK_NonConstLValueReferenceBindingToTemporary
3469 ? diag::err_lvalue_reference_bind_to_temporary
3470 : diag::err_lvalue_reference_bind_to_unrelated)
3471 << DestType.getNonReferenceType()
3472 << Args[0]->getType()
3473 << Args[0]->getSourceRange();
3474 break;
3475
3476 case FK_RValueReferenceBindingToLValue:
3477 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3478 << Args[0]->getSourceRange();
3479 break;
3480
3481 case FK_ReferenceInitDropsQualifiers:
3482 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3483 << DestType.getNonReferenceType()
3484 << Args[0]->getType()
3485 << Args[0]->getSourceRange();
3486 break;
3487
3488 case FK_ReferenceInitFailed:
3489 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3490 << DestType.getNonReferenceType()
3491 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3492 << Args[0]->getType()
3493 << Args[0]->getSourceRange();
3494 break;
3495
3496 case FK_ConversionFailed:
Douglas Gregore1314a62009-12-18 05:02:21 +00003497 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3498 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003499 << DestType
3500 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3501 << Args[0]->getType()
3502 << Args[0]->getSourceRange();
Douglas Gregor51e77d52009-12-10 17:56:55 +00003503 break;
3504
3505 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003506 SourceRange R;
3507
3508 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3509 R = SourceRange(InitList->getInit(1)->getLocStart(),
3510 InitList->getLocEnd());
3511 else
3512 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00003513
3514 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor85dabae2009-12-16 01:38:02 +00003515 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00003516 break;
3517 }
3518
3519 case FK_ReferenceBindingToInitList:
3520 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3521 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3522 break;
3523
3524 case FK_InitListBadDestinationType:
3525 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3526 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3527 break;
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003528
3529 case FK_ConstructorOverloadFailed: {
3530 SourceRange ArgsRange;
3531 if (NumArgs)
3532 ArgsRange = SourceRange(Args[0]->getLocStart(),
3533 Args[NumArgs - 1]->getLocEnd());
3534
3535 // FIXME: Using "DestType" for the entity we're printing is probably
3536 // bad.
3537 switch (FailedOverloadResult) {
3538 case OR_Ambiguous:
3539 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3540 << DestType << ArgsRange;
3541 S.PrintOverloadCandidates(FailedCandidateSet, true);
3542 break;
3543
3544 case OR_No_Viable_Function:
3545 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3546 << DestType << ArgsRange;
3547 S.PrintOverloadCandidates(FailedCandidateSet, false);
3548 break;
3549
3550 case OR_Deleted: {
3551 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3552 << true << DestType << ArgsRange;
3553 OverloadCandidateSet::iterator Best;
3554 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3555 Kind.getLocation(),
3556 Best);
3557 if (Ovl == OR_Deleted) {
3558 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3559 << Best->Function->isDeleted();
3560 } else {
3561 llvm_unreachable("Inconsistent overload resolution?");
3562 }
3563 break;
3564 }
3565
3566 case OR_Success:
3567 llvm_unreachable("Conversion did not fail!");
3568 break;
3569 }
3570 break;
3571 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003572
3573 case FK_DefaultInitOfConst:
3574 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3575 << DestType;
3576 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003577 }
3578
3579 return true;
3580}
Douglas Gregore1314a62009-12-18 05:02:21 +00003581
3582//===----------------------------------------------------------------------===//
3583// Initialization helper functions
3584//===----------------------------------------------------------------------===//
3585Sema::OwningExprResult
3586Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3587 SourceLocation EqualLoc,
3588 OwningExprResult Init) {
3589 if (Init.isInvalid())
3590 return ExprError();
3591
3592 Expr *InitE = (Expr *)Init.get();
3593 assert(InitE && "No initialization expression?");
3594
3595 if (EqualLoc.isInvalid())
3596 EqualLoc = InitE->getLocStart();
3597
3598 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3599 EqualLoc);
3600 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3601 Init.release();
3602 return Seq.Perform(*this, Entity, Kind,
3603 MultiExprArg(*this, (void**)&InitE, 1));
3604}