blob: 4d7d48debd4af62dc1815734255f2d47d21397ce [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-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 Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-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 Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-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 Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Anders Carlssonc07b8c02010-01-23 18:35:41 +000069static Sema::OwningExprResult
Anders Carlsson8ff9e862010-01-23 23:23:01 +000070CheckSingleInitializer(const InitializedEntity &Entity,
Anders Carlssonc07b8c02010-01-23 18:35:41 +000071 Sema::OwningExprResult Init, QualType DeclType, Sema &S){
Anders Carlsson8ff9e862010-01-23 23:23:01 +000072 assert(Entity.getType() == DeclType);
Anders Carlssonc07b8c02010-01-23 18:35:41 +000073 Expr *InitExpr = Init.takeAs<Expr>();
74
Chris Lattnerdd8e0062009-02-24 22:27:37 +000075 // Get the type before calling CheckSingleAssignmentConstraints(), since
76 // it can promote the expression.
Anders Carlssonc07b8c02010-01-23 18:35:41 +000077 QualType InitType = InitExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000078
Chris Lattner95e8d652009-02-24 22:46:58 +000079 if (S.getLangOptions().CPlusPlus) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +000080 // C++ [dcl.init.aggr]p2:
81 // Each member is copy-initialized from the corresponding
Anders Carlsson1b36a2f2010-01-24 00:19:41 +000082 // initializer-clause.
83 // FIXME: Use a better EqualLoc here.
Anders Carlsson8ff9e862010-01-23 23:23:01 +000084 Sema::OwningExprResult Result =
85 S.PerformCopyInitialization(Entity, InitExpr->getLocStart(),
86 S.Owned(InitExpr));
Anders Carlsson1f243502010-01-23 19:22:30 +000087
88 return move(Result);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000089 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner95e8d652009-02-24 22:46:58 +000091 Sema::AssignConvertType ConvTy =
Anders Carlssonc07b8c02010-01-23 18:35:41 +000092 S.CheckSingleAssignmentConstraints(DeclType, InitExpr);
93 if (S.DiagnoseAssignmentResult(ConvTy, InitExpr->getLocStart(), DeclType,
94 InitType, InitExpr, Sema::AA_Initializing))
95 return S.ExprError();
96
97 Init.release();
98 return S.Owned(InitExpr);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000099}
100
Chris Lattner79e079d2009-02-24 23:10:27 +0000101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102 // Get the length of the string as parsed.
103 uint64_t StrLength =
104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner79e079d2009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000117 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Eli Friedman8718a6a2009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Eli Friedman8718a6a2009-05-29 18:22:49 +0000122 // C99 6.7.8p14. We have an array of character type with known size. However,
123 // the size may be smaller or larger than the string we are initializing.
124 // FIXME: Avoid truncation for 64-bit length strings.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregor9e80f722009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
155/// arguments, which contains the current the "structured" (semantic)
156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000168namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171 bool hadError;
172 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
173 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000175 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000176 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000177 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000178 unsigned &StructuredIndex,
179 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000185 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000186 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000187 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000193 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000197 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000198 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000199 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckReferenceType(const InitializedEntity &Entity,
203 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000204 unsigned &Index,
205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000207 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000208 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000209 InitListExpr *StructuredList,
210 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000211 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000212 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000213 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000214 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000216 unsigned &StructuredIndex,
217 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000218 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000219 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000224 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000225 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000226 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000227 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 RecordDecl::field_iterator *NextField,
229 llvm::APSInt *NextElementIndex,
230 unsigned &Index,
231 InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000233 bool FinishSubobjectInit,
234 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
236 QualType CurrentObjectType,
237 InitListExpr *StructuredList,
238 unsigned StructuredIndex,
239 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000240 void UpdateStructuredListElement(InitListExpr *StructuredList,
241 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 Expr *expr);
243 int numArrayElements(QualType DeclType);
244 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000245
Douglas Gregord6d37de2009-12-22 00:05:34 +0000246 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
247 const InitializedEntity &ParentEntity,
248 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000249 void FillInValueInitializations(const InitializedEntity &Entity,
250 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000251public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000252 InitListChecker(Sema &S, const InitializedEntity &Entity,
253 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000254 bool HadError() { return hadError; }
255
256 // @brief Retrieves the fully-structured initializer list used for
257 // semantic analysis and code generation.
258 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
259};
Chris Lattner8b419b92009-02-24 22:48:58 +0000260} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000261
Douglas Gregord6d37de2009-12-22 00:05:34 +0000262void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
263 const InitializedEntity &ParentEntity,
264 InitListExpr *ILE,
265 bool &RequiresSecondPass) {
266 SourceLocation Loc = ILE->getSourceRange().getBegin();
267 unsigned NumInits = ILE->getNumInits();
268 InitializedEntity MemberEntity
269 = InitializedEntity::InitializeMember(Field, &ParentEntity);
270 if (Init >= NumInits || !ILE->getInit(Init)) {
271 // FIXME: We probably don't need to handle references
272 // specially here, since value-initialization of references is
273 // handled in InitializationSequence.
274 if (Field->getType()->isReferenceType()) {
275 // C++ [dcl.init.aggr]p9:
276 // If an incomplete or empty initializer-list leaves a
277 // member of reference type uninitialized, the program is
278 // ill-formed.
279 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
280 << Field->getType()
281 << ILE->getSyntacticForm()->getSourceRange();
282 SemaRef.Diag(Field->getLocation(),
283 diag::note_uninit_reference_member);
284 hadError = true;
285 return;
286 }
287
288 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
289 true);
290 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
291 if (!InitSeq) {
292 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
293 hadError = true;
294 return;
295 }
296
297 Sema::OwningExprResult MemberInit
298 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
299 Sema::MultiExprArg(SemaRef, 0, 0));
300 if (MemberInit.isInvalid()) {
301 hadError = true;
302 return;
303 }
304
305 if (hadError) {
306 // Do nothing
307 } else if (Init < NumInits) {
308 ILE->setInit(Init, MemberInit.takeAs<Expr>());
309 } else if (InitSeq.getKind()
310 == InitializationSequence::ConstructorInitialization) {
311 // Value-initialization requires a constructor call, so
312 // extend the initializer list to include the constructor
313 // call and make a note that we'll need to take another pass
314 // through the initializer list.
315 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
316 RequiresSecondPass = true;
317 }
318 } else if (InitListExpr *InnerILE
319 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
320 FillInValueInitializations(MemberEntity, InnerILE,
321 RequiresSecondPass);
322}
323
Douglas Gregor4c678342009-01-28 21:54:33 +0000324/// Recursively replaces NULL values within the given initializer list
325/// with expressions that perform value-initialization of the
326/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000327void
328InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
329 InitListExpr *ILE,
330 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000331 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000332 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000333 SourceLocation Loc = ILE->getSourceRange().getBegin();
334 if (ILE->getSyntacticForm())
335 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremenek6217b802009-07-29 21:53:49 +0000337 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000338 if (RType->getDecl()->isUnion() &&
339 ILE->getInitializedFieldInUnion())
340 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
341 Entity, ILE, RequiresSecondPass);
342 else {
343 unsigned Init = 0;
344 for (RecordDecl::field_iterator
345 Field = RType->getDecl()->field_begin(),
346 FieldEnd = RType->getDecl()->field_end();
347 Field != FieldEnd; ++Field) {
348 if (Field->isUnnamedBitfield())
349 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000350
Douglas Gregord6d37de2009-12-22 00:05:34 +0000351 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000352 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000353
354 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
355 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000357
Douglas Gregord6d37de2009-12-22 00:05:34 +0000358 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000359
Douglas Gregord6d37de2009-12-22 00:05:34 +0000360 // Only look at the first initialization of a union.
361 if (RType->getDecl()->isUnion())
362 break;
363 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000364 }
365
366 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000367 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000368
369 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000371 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 unsigned NumInits = ILE->getNumInits();
373 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000374 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000375 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
377 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000378 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
379 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000380 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000383 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
384 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000386 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000388
Douglas Gregor87fd7032009-02-02 17:43:21 +0000389 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000390 if (hadError)
391 return;
392
Anders Carlssond3d824d2010-01-23 04:34:47 +0000393 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
394 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000395 ElementEntity.setElementIndex(Init);
396
Douglas Gregor87fd7032009-02-02 17:43:21 +0000397 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
399 true);
400 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
401 if (!InitSeq) {
402 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 hadError = true;
404 return;
405 }
406
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407 Sema::OwningExprResult ElementInit
408 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
409 Sema::MultiExprArg(SemaRef, 0, 0));
410 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000411 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000412 return;
413 }
414
415 if (hadError) {
416 // Do nothing
417 } else if (Init < NumInits) {
418 ILE->setInit(Init, ElementInit.takeAs<Expr>());
419 } else if (InitSeq.getKind()
420 == InitializationSequence::ConstructorInitialization) {
421 // Value-initialization requires a constructor call, so
422 // extend the initializer list to include the constructor
423 // call and make a note that we'll need to take another pass
424 // through the initializer list.
425 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
426 RequiresSecondPass = true;
427 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000428 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000429 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
430 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000431 }
432}
433
Chris Lattner68355a52009-01-29 05:10:57 +0000434
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000435InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
436 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000437 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000438 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000439
Eli Friedmanb85f7072008-05-19 19:16:24 +0000440 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000441 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000442 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000443 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000444 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000445 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000446 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000447
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000448 if (!hadError) {
449 bool RequiresSecondPass = false;
450 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000451 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000452 FillInValueInitializations(Entity, FullyStructuredList,
453 RequiresSecondPass);
454 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000455}
456
457int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000458 // FIXME: use a proper constant
459 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000460 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000461 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000462 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
463 }
464 return maxElements;
465}
466
467int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000468 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000469 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000470 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000471 Field = structDecl->field_begin(),
472 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000473 Field != FieldEnd; ++Field) {
474 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
475 ++InitializableMembers;
476 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000477 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000478 return std::min(InitializableMembers, 1);
479 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000480}
481
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000482void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000483 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000484 QualType T, unsigned &Index,
485 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000486 unsigned &StructuredIndex,
487 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000488 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Steve Naroff0cca7492008-05-01 22:18:59 +0000490 if (T->isArrayType())
491 maxElements = numArrayElements(T);
492 else if (T->isStructureType() || T->isUnionType())
493 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000494 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000495 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000496 else
497 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000498
Eli Friedman402256f2008-05-25 13:49:22 +0000499 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000500 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000501 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000502 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000503 hadError = true;
504 return;
505 }
506
Douglas Gregor4c678342009-01-28 21:54:33 +0000507 // Build a structured initializer list corresponding to this subobject.
508 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000509 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
510 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000511 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
512 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000513 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000514
Douglas Gregor4c678342009-01-28 21:54:33 +0000515 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000516 unsigned StartIndex = Index;
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000517 CheckListElementTypes(Entity, ParentIList, T,
518 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000519 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000520 StructuredSubobjectInitIndex,
521 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000522 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000523 StructuredSubobjectInitList->setType(T);
524
Douglas Gregored8a93d2009-03-01 17:12:46 +0000525 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000526 // range corresponds with the end of the last initializer it used.
527 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000528 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000529 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
530 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
531 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000532}
533
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000534void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000535 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000536 unsigned &Index,
537 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000538 unsigned &StructuredIndex,
539 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000540 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000541 SyntacticToSemantic[IList] = StructuredList;
542 StructuredList->setSyntacticForm(IList);
Anders Carlsson46f46592010-01-23 19:55:29 +0000543 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
544 Index, StructuredList, StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000545 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000546 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000547 if (hadError)
548 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000549
Eli Friedman638e1442008-05-25 13:22:35 +0000550 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000551 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000552 if (StructuredIndex == 1 &&
553 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000554 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000555 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000556 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000557 hadError = true;
558 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000559 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000560 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000561 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000562 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000563 // Don't complain for incomplete types, since we'll get an error
564 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000565 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000566 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000567 CurrentObjectType->isArrayType()? 0 :
568 CurrentObjectType->isVectorType()? 1 :
569 CurrentObjectType->isScalarType()? 2 :
570 CurrentObjectType->isUnionType()? 3 :
571 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000572
573 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000574 if (SemaRef.getLangOptions().CPlusPlus) {
575 DK = diag::err_excess_initializers;
576 hadError = true;
577 }
Nate Begeman08634522009-07-07 21:53:06 +0000578 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
579 DK = diag::err_excess_initializers;
580 hadError = true;
581 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000582
Chris Lattner08202542009-02-24 22:50:46 +0000583 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000584 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000585 }
586 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000587
Eli Friedman759f2522009-05-16 11:45:48 +0000588 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000589 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000590 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000591 << CodeModificationHint::CreateRemoval(IList->getLocStart())
592 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000593}
594
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000595void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000596 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000597 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000598 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000599 unsigned &Index,
600 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000601 unsigned &StructuredIndex,
602 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000603 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000604 CheckScalarType(Entity, IList, DeclType, Index,
605 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000606 } else if (DeclType->isVectorType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000607 CheckVectorType(Entity, IList, DeclType, Index,
608 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000609 } else if (DeclType->isAggregateType()) {
610 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000611 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000612 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000613 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000614 StructuredList, StructuredIndex,
615 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000616 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000617 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000618 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000619 false);
Anders Carlsson784f6992010-01-23 20:13:41 +0000620 CheckArrayType(Entity, IList, DeclType, Zero,
621 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000622 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000623 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000625 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
626 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000627 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000628 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000629 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000630 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000631 } else if (DeclType->isRecordType()) {
632 // C++ [dcl.init]p14:
633 // [...] If the class is an aggregate (8.5.1), and the initializer
634 // is a brace-enclosed list, see 8.5.1.
635 //
636 // Note: 8.5.1 is handled below; here, we diagnose the case where
637 // we have an initializer list and a destination type that is not
638 // an aggregate.
639 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000640 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000641 << DeclType << IList->getSourceRange();
642 hadError = true;
643 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000644 CheckReferenceType(Entity, IList, DeclType, Index,
645 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000646 } else {
647 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000648 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000649 assert(0 && "Unsupported initializer type");
650 }
651}
652
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000653void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000654 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000655 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000656 unsigned &Index,
657 InitListExpr *StructuredList,
658 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000659 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000660 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
661 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000662 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000663 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000664 = getStructuredSubobjectInit(IList, Index, ElemType,
665 StructuredList, StructuredIndex,
666 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000667 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000668 newStructuredList, newStructuredIndex);
669 ++StructuredIndex;
670 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000671 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
672 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000673 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000675 } else if (ElemType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000676 CheckScalarType(Entity, IList, ElemType, Index,
677 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000678 } else if (ElemType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000679 CheckReferenceType(Entity, IList, ElemType, Index,
680 StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000681 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000682 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000683 // C++ [dcl.init.aggr]p12:
684 // All implicit type conversions (clause 4) are considered when
685 // initializing the aggregate member with an ini- tializer from
686 // an initializer-list. If the initializer can initialize a
687 // member, the member is initialized. [...]
Anders Carlssond28b4282009-08-27 17:18:13 +0000688
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000689 // FIXME: Better EqualLoc?
690 InitializationKind Kind =
691 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
692 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
693
694 if (Seq) {
695 Sema::OwningExprResult Result =
696 Seq.Perform(SemaRef, Entity, Kind,
697 Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
698 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000699 hadError = true;
Anders Carlsson1b36a2f2010-01-24 00:19:41 +0000700
701 UpdateStructuredListElement(StructuredList, StructuredIndex,
702 Result.takeAs<Expr>());
Douglas Gregor930d8b52009-01-30 22:09:00 +0000703 ++Index;
704 return;
705 }
706
707 // Fall through for subaggregate initialization
708 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000709 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000710 //
711 // The initializer for a structure or union object that has
712 // automatic storage duration shall be either an initializer
713 // list as described below, or a single expression that has
714 // compatible structure or union type. In the latter case, the
715 // initial value of the object, including unnamed members, is
716 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000717 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000718 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000719 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
720 ++Index;
721 return;
722 }
723
724 // Fall through for subaggregate initialization
725 }
726
727 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000728 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000729 // [...] Otherwise, if the member is itself a non-empty
730 // subaggregate, brace elision is assumed and the initializer is
731 // considered for the initialization of the first member of
732 // the subaggregate.
733 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000734 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000735 StructuredIndex);
736 ++StructuredIndex;
737 } else {
738 // We cannot initialize this element, so let
739 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000740 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000741 hadError = true;
742 ++Index;
743 ++StructuredIndex;
744 }
745 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000746}
747
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000748void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000749 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000750 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000751 InitListExpr *StructuredList,
752 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000753 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000754 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000755 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000756 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000757 diag::err_many_braces_around_scalar_init)
758 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000759 hadError = true;
760 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000761 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000762 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000763 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000764 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000765 diag::err_designator_for_scalar_init)
766 << DeclType << expr->getSourceRange();
767 hadError = true;
768 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000769 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000770 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000771 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000772
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000773 Sema::OwningExprResult Result =
Anders Carlsson46f46592010-01-23 19:55:29 +0000774 CheckSingleInitializer(Entity, SemaRef.Owned(expr), DeclType, SemaRef);
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000775
776 Expr *ResultExpr;
777
778 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000779 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000780 else {
781 ResultExpr = Result.takeAs<Expr>();
782
783 if (ResultExpr != expr) {
784 // The type was promoted, update initializer list.
785 IList->setInit(Index, ResultExpr);
786 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000787 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000788 if (hadError)
789 ++StructuredIndex;
790 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000791 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000792 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000793 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000794 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000795 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000796 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000797 ++Index;
798 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000799 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000800 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000801}
802
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000803void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
804 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000805 unsigned &Index,
806 InitListExpr *StructuredList,
807 unsigned &StructuredIndex) {
808 if (Index < IList->getNumInits()) {
809 Expr *expr = IList->getInit(Index);
810 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000811 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000812 << DeclType << IList->getSourceRange();
813 hadError = true;
814 ++Index;
815 ++StructuredIndex;
816 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000817 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000818
819 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000820 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000821 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000822 /*SuppressUserConversions=*/false,
823 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000824 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000825 hadError = true;
826 else if (savExpr != expr) {
827 // The type was promoted, update initializer list.
828 IList->setInit(Index, expr);
829 }
830 if (hadError)
831 ++StructuredIndex;
832 else
833 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
834 ++Index;
835 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000836 // FIXME: It would be wonderful if we could point at the actual member. In
837 // general, it would be useful to pass location information down the stack,
838 // so that we know the location (or decl) of the "current object" being
839 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000840 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000841 diag::err_init_reference_member_uninitialized)
842 << DeclType
843 << IList->getSourceRange();
844 hadError = true;
845 ++Index;
846 ++StructuredIndex;
847 return;
848 }
849}
850
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000851void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000852 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000853 unsigned &Index,
854 InitListExpr *StructuredList,
855 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000856 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000857 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000858 unsigned maxElements = VT->getNumElements();
859 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000860 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Nate Begeman2ef13e52009-08-10 23:49:36 +0000862 if (!SemaRef.getLangOptions().OpenCL) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000863 InitializedEntity ElementEntity =
864 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson46f46592010-01-23 19:55:29 +0000865
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000866 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
867 // Don't attempt to go past the end of the init list
868 if (Index >= IList->getNumInits())
869 break;
Anders Carlsson46f46592010-01-23 19:55:29 +0000870
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000871 ElementEntity.setElementIndex(Index);
872 CheckSubElementType(ElementEntity, IList, elementType, Index,
873 StructuredList, StructuredIndex);
874 }
Nate Begeman2ef13e52009-08-10 23:49:36 +0000875 } else {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000876 InitializedEntity ElementEntity =
877 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
878
Nate Begeman2ef13e52009-08-10 23:49:36 +0000879 // OpenCL initializers allows vectors to be constructed from vectors.
880 for (unsigned i = 0; i < maxElements; ++i) {
881 // Don't attempt to go past the end of the init list
882 if (Index >= IList->getNumInits())
883 break;
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000884
885 ElementEntity.setElementIndex(Index);
886
Nate Begeman2ef13e52009-08-10 23:49:36 +0000887 QualType IType = IList->getInit(Index)->getType();
888 if (!IType->isVectorType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000889 CheckSubElementType(ElementEntity, IList, elementType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000890 StructuredList, StructuredIndex);
891 ++numEltsInit;
892 } else {
John McCall183700f2009-09-21 23:43:11 +0000893 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000894 unsigned numIElts = IVT->getNumElements();
895 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
896 numIElts);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000897 CheckSubElementType(ElementEntity, IList, VecType, Index,
Nate Begeman2ef13e52009-08-10 23:49:36 +0000898 StructuredList, StructuredIndex);
899 numEltsInit += numIElts;
900 }
901 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Nate Begeman2ef13e52009-08-10 23:49:36 +0000904 // OpenCL & AltiVec require all elements to be initialized.
905 if (numEltsInit != maxElements)
906 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
907 SemaRef.Diag(IList->getSourceRange().getBegin(),
908 diag::err_vector_incorrect_num_initializers)
909 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000910 }
911}
912
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000913void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000914 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000915 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000916 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000917 unsigned &Index,
918 InitListExpr *StructuredList,
919 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000920 // Check for the special-case of initializing an array with a string.
921 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000922 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
923 SemaRef.Context)) {
924 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000925 // We place the string literal directly into the resulting
926 // initializer list. This is the only place where the structure
927 // of the structured initializer list doesn't match exactly,
928 // because doing so would involve allocating one character
929 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000930 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000931 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000932 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000933 return;
934 }
935 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000936 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000937 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000938 // Check for VLAs; in standard C it would be possible to check this
939 // earlier, but I don't know where clang accepts VLAs (gcc accepts
940 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000941 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000942 diag::err_variable_object_no_init)
943 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000944 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000945 ++Index;
946 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000947 return;
948 }
949
Douglas Gregor05c13a32009-01-22 00:58:24 +0000950 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000951 llvm::APSInt maxElements(elementIndex.getBitWidth(),
952 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000953 bool maxElementsKnown = false;
954 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000955 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000956 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000957 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000958 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000959 maxElementsKnown = true;
960 }
961
Chris Lattner08202542009-02-24 22:50:46 +0000962 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000963 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000964 while (Index < IList->getNumInits()) {
965 Expr *Init = IList->getInit(Index);
966 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000967 // If we're not the subobject that matches up with the '{' for
968 // the designator, we shouldn't be handling the
969 // designator. Return immediately.
970 if (!SubobjectIsDesignatorContext)
971 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000972
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000973 // Handle this designated initializer. elementIndex will be
974 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000975 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000976 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000977 StructuredList, StructuredIndex, true,
978 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000979 hadError = true;
980 continue;
981 }
982
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000983 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
984 maxElements.extend(elementIndex.getBitWidth());
985 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
986 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000987 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000988
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000989 // If the array is of incomplete type, keep track of the number of
990 // elements in the initializer.
991 if (!maxElementsKnown && elementIndex > maxElements)
992 maxElements = elementIndex;
993
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994 continue;
995 }
996
997 // If we know the maximum number of elements, and we've already
998 // hit it, stop consuming elements in the initializer list.
999 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001000 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001002 InitializedEntity ElementEntity =
Anders Carlsson784f6992010-01-23 20:13:41 +00001003 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001004 Entity);
1005 // Check this element.
1006 CheckSubElementType(ElementEntity, IList, elementType, Index,
1007 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001008 ++elementIndex;
1009
1010 // If the array is of incomplete type, keep track of the number of
1011 // elements in the initializer.
1012 if (!maxElementsKnown && elementIndex > maxElements)
1013 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001014 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001015 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001016 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001017 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001018 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001019 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001020 // Sizing an array implicitly to zero is not allowed by ISO C,
1021 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001022 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001023 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001024 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001025
Mike Stump1eb44332009-09-09 15:08:12 +00001026 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001027 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001028 }
1029}
1030
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001031void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001032 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001033 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001034 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001035 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001036 unsigned &Index,
1037 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001038 unsigned &StructuredIndex,
1039 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001040 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Eli Friedmanb85f7072008-05-19 19:16:24 +00001042 // If the record is invalid, some of it's members are invalid. To avoid
1043 // confusion, we forgo checking the intializer for the entire record.
1044 if (structDecl->isInvalidDecl()) {
1045 hadError = true;
1046 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001047 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001048
1049 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1050 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001052 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001053 Field != FieldEnd; ++Field) {
1054 if (Field->getDeclName()) {
1055 StructuredList->setInitializedFieldInUnion(*Field);
1056 break;
1057 }
1058 }
1059 return;
1060 }
1061
Douglas Gregor05c13a32009-01-22 00:58:24 +00001062 // If structDecl is a forward declaration, this loop won't do
1063 // anything except look at designated initializers; That's okay,
1064 // because an error should get printed out elsewhere. It might be
1065 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001066 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001067 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001068 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001069 while (Index < IList->getNumInits()) {
1070 Expr *Init = IList->getInit(Index);
1071
1072 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001073 // If we're not the subobject that matches up with the '{' for
1074 // the designator, we shouldn't be handling the
1075 // designator. Return immediately.
1076 if (!SubobjectIsDesignatorContext)
1077 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001078
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001079 // Handle this designated initializer. Field will be updated to
1080 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001081 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001082 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001083 StructuredList, StructuredIndex,
1084 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001085 hadError = true;
1086
Douglas Gregordfb5e592009-02-12 19:00:39 +00001087 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001088 continue;
1089 }
1090
1091 if (Field == FieldEnd) {
1092 // We've run out of fields. We're done.
1093 break;
1094 }
1095
Douglas Gregordfb5e592009-02-12 19:00:39 +00001096 // We've already initialized a member of a union. We're done.
1097 if (InitializedSomething && DeclType->isUnionType())
1098 break;
1099
Douglas Gregor44b43212008-12-11 16:49:14 +00001100 // If we've hit the flexible array member at the end, we're done.
1101 if (Field->getType()->isIncompleteArrayType())
1102 break;
1103
Douglas Gregor0bb76892009-01-29 16:53:55 +00001104 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001105 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001106 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001107 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001108 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001109
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001110 InitializedEntity MemberEntity =
1111 InitializedEntity::InitializeMember(*Field, &Entity);
1112 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1113 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001114 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001115
1116 if (DeclType->isUnionType()) {
1117 // Initialize the first field within the union.
1118 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001119 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001120
1121 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001122 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001123
Mike Stump1eb44332009-09-09 15:08:12 +00001124 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001125 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001126 return;
1127
1128 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001129 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001130 (!isa<InitListExpr>(IList->getInit(Index)) ||
1131 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001132 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001133 diag::err_flexible_array_init_nonempty)
1134 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001135 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001136 << *Field;
1137 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001138 ++Index;
1139 return;
1140 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001141 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001142 diag::ext_flexible_array_init)
1143 << IList->getInit(Index)->getSourceRange().getBegin();
1144 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1145 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001146 }
1147
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001148 InitializedEntity MemberEntity =
1149 InitializedEntity::InitializeMember(*Field, &Entity);
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001150
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001151 if (isa<InitListExpr>(IList->getInit(Index)))
1152 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1153 StructuredList, StructuredIndex);
1154 else
1155 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001156 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001157}
Steve Naroff0cca7492008-05-01 22:18:59 +00001158
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001159/// \brief Expand a field designator that refers to a member of an
1160/// anonymous struct or union into a series of field designators that
1161/// refers to the field within the appropriate subobject.
1162///
1163/// Field/FieldIndex will be updated to point to the (new)
1164/// currently-designated field.
1165static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001166 DesignatedInitExpr *DIE,
1167 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001168 FieldDecl *Field,
1169 RecordDecl::field_iterator &FieldIter,
1170 unsigned &FieldIndex) {
1171 typedef DesignatedInitExpr::Designator Designator;
1172
1173 // Build the path from the current object to the member of the
1174 // anonymous struct/union (backwards).
1175 llvm::SmallVector<FieldDecl *, 4> Path;
1176 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001178 // Build the replacement designators.
1179 llvm::SmallVector<Designator, 4> Replacements;
1180 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1181 FI = Path.rbegin(), FIEnd = Path.rend();
1182 FI != FIEnd; ++FI) {
1183 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001184 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001185 DIE->getDesignator(DesigIdx)->getDotLoc(),
1186 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1187 else
1188 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1189 SourceLocation()));
1190 Replacements.back().setField(*FI);
1191 }
1192
1193 // Expand the current designator into the set of replacement
1194 // designators, so we have a full subobject path down to where the
1195 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001196 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001197 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001199 // Update FieldIter/FieldIndex;
1200 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001201 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001202 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001203 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001204 FieldIter != FEnd; ++FieldIter) {
1205 if (FieldIter->isUnnamedBitfield())
1206 continue;
1207
1208 if (*FieldIter == Path.back())
1209 return;
1210
1211 ++FieldIndex;
1212 }
1213
1214 assert(false && "Unable to find anonymous struct/union field");
1215}
1216
Douglas Gregor05c13a32009-01-22 00:58:24 +00001217/// @brief Check the well-formedness of a C99 designated initializer.
1218///
1219/// Determines whether the designated initializer @p DIE, which
1220/// resides at the given @p Index within the initializer list @p
1221/// IList, is well-formed for a current object of type @p DeclType
1222/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001223/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001224/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001225///
1226/// @param IList The initializer list in which this designated
1227/// initializer occurs.
1228///
Douglas Gregor71199712009-04-15 04:56:10 +00001229/// @param DIE The designated initializer expression.
1230///
1231/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001232///
1233/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1234/// into which the designation in @p DIE should refer.
1235///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001236/// @param NextField If non-NULL and the first designator in @p DIE is
1237/// a field, this will be set to the field declaration corresponding
1238/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001239///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001240/// @param NextElementIndex If non-NULL and the first designator in @p
1241/// DIE is an array designator or GNU array-range designator, this
1242/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001243///
1244/// @param Index Index into @p IList where the designated initializer
1245/// @p DIE occurs.
1246///
Douglas Gregor4c678342009-01-28 21:54:33 +00001247/// @param StructuredList The initializer list expression that
1248/// describes all of the subobject initializers in the order they'll
1249/// actually be initialized.
1250///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001251/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001252bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001253InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001254 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001255 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001256 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001257 QualType &CurrentObjectType,
1258 RecordDecl::field_iterator *NextField,
1259 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001260 unsigned &Index,
1261 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001262 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001263 bool FinishSubobjectInit,
1264 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001265 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001266 // Check the actual initialization for the designated object type.
1267 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001268
1269 // Temporarily remove the designator expression from the
1270 // initializer list that the child calls see, so that we don't try
1271 // to re-process the designator.
1272 unsigned OldIndex = Index;
1273 IList->setInit(OldIndex, DIE->getInit());
1274
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001275 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001276 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001277
1278 // Restore the designated initializer expression in the syntactic
1279 // form of the initializer list.
1280 if (IList->getInit(OldIndex) != DIE->getInit())
1281 DIE->setInit(IList->getInit(OldIndex));
1282 IList->setInit(OldIndex, DIE);
1283
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001284 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001285 }
1286
Douglas Gregor71199712009-04-15 04:56:10 +00001287 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001288 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001289 "Need a non-designated initializer list to start from");
1290
Douglas Gregor71199712009-04-15 04:56:10 +00001291 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001292 // Determine the structural initializer list that corresponds to the
1293 // current subobject.
1294 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001295 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001296 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001297 SourceRange(D->getStartLocation(),
1298 DIE->getSourceRange().getEnd()));
1299 assert(StructuredList && "Expected a structured initializer list");
1300
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001301 if (D->isFieldDesignator()) {
1302 // C99 6.7.8p7:
1303 //
1304 // If a designator has the form
1305 //
1306 // . identifier
1307 //
1308 // then the current object (defined below) shall have
1309 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001310 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001311 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001312 if (!RT) {
1313 SourceLocation Loc = D->getDotLoc();
1314 if (Loc.isInvalid())
1315 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001316 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1317 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001318 ++Index;
1319 return true;
1320 }
1321
Douglas Gregor4c678342009-01-28 21:54:33 +00001322 // Note: we perform a linear search of the fields here, despite
1323 // the fact that we have a faster lookup method, because we always
1324 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001325 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001326 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001327 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001328 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001329 Field = RT->getDecl()->field_begin(),
1330 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001331 for (; Field != FieldEnd; ++Field) {
1332 if (Field->isUnnamedBitfield())
1333 continue;
1334
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001335 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001336 break;
1337
1338 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001339 }
1340
Douglas Gregor4c678342009-01-28 21:54:33 +00001341 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001342 // There was no normal field in the struct with the designated
1343 // name. Perform another lookup for this name, which may find
1344 // something that we can't designate (e.g., a member function),
1345 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001346 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001347 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001348 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001350 // Name lookup didn't find anything. Determine whether this
1351 // was a typo for another field name.
1352 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1353 Sema::LookupMemberName);
1354 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1355 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1356 ReplacementField->getDeclContext()->getLookupContext()
1357 ->Equals(RT->getDecl())) {
1358 SemaRef.Diag(D->getFieldLoc(),
1359 diag::err_field_designator_unknown_suggest)
1360 << FieldName << CurrentObjectType << R.getLookupName()
1361 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1362 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001363 SemaRef.Diag(ReplacementField->getLocation(),
1364 diag::note_previous_decl)
1365 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001366 } else {
1367 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1368 << FieldName << CurrentObjectType;
1369 ++Index;
1370 return true;
1371 }
1372 } else if (!KnownField) {
1373 // Determine whether we found a field at all.
1374 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1375 }
1376
1377 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001378 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001379 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001380 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001381 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001382 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001383 ++Index;
1384 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001385 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001386
1387 if (!KnownField &&
1388 cast<RecordDecl>((ReplacementField)->getDeclContext())
1389 ->isAnonymousStructOrUnion()) {
1390 // Handle an field designator that refers to a member of an
1391 // anonymous struct or union.
1392 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1393 ReplacementField,
1394 Field, FieldIndex);
1395 D = DIE->getDesignator(DesigIdx);
1396 } else if (!KnownField) {
1397 // The replacement field comes from typo correction; find it
1398 // in the list of fields.
1399 FieldIndex = 0;
1400 Field = RT->getDecl()->field_begin();
1401 for (; Field != FieldEnd; ++Field) {
1402 if (Field->isUnnamedBitfield())
1403 continue;
1404
1405 if (ReplacementField == *Field ||
1406 Field->getIdentifier() == ReplacementField->getIdentifier())
1407 break;
1408
1409 ++FieldIndex;
1410 }
1411 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001412 } else if (!KnownField &&
1413 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001414 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001415 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1416 Field, FieldIndex);
1417 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001418 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001419
1420 // All of the fields of a union are located at the same place in
1421 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001422 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001423 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001424 StructuredList->setInitializedFieldInUnion(*Field);
1425 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001426
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001427 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001428 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Douglas Gregor4c678342009-01-28 21:54:33 +00001430 // Make sure that our non-designated initializer list has space
1431 // for a subobject corresponding to this field.
1432 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001433 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001434
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001435 // This designator names a flexible array member.
1436 if (Field->getType()->isIncompleteArrayType()) {
1437 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001438 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001439 // We can't designate an object within the flexible array
1440 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001441 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001442 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001443 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001444 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001445 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001446 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001447 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001448 << *Field;
1449 Invalid = true;
1450 }
1451
1452 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1453 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001454 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001455 diag::err_flexible_array_init_needs_braces)
1456 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001457 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 << *Field;
1459 Invalid = true;
1460 }
1461
1462 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001463 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001464 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001465 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001466 diag::err_flexible_array_init_nonempty)
1467 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001468 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001469 << *Field;
1470 Invalid = true;
1471 }
1472
1473 if (Invalid) {
1474 ++Index;
1475 return true;
1476 }
1477
1478 // Initialize the array.
1479 bool prevHadError = hadError;
1480 unsigned newStructuredIndex = FieldIndex;
1481 unsigned OldIndex = Index;
1482 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001483
1484 InitializedEntity MemberEntity =
1485 InitializedEntity::InitializeMember(*Field, &Entity);
1486 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001487 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001488
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001489 IList->setInit(OldIndex, DIE);
1490 if (hadError && !prevHadError) {
1491 ++Field;
1492 ++FieldIndex;
1493 if (NextField)
1494 *NextField = Field;
1495 StructuredIndex = FieldIndex;
1496 return true;
1497 }
1498 } else {
1499 // Recurse to check later designated subobjects.
1500 QualType FieldType = (*Field)->getType();
1501 unsigned newStructuredIndex = FieldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001502
1503 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001504 InitializedEntity::InitializeMember(*Field, &Entity);
1505 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001506 FieldType, 0, 0, Index,
1507 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001508 true, false))
1509 return true;
1510 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001511
1512 // Find the position of the next field to be initialized in this
1513 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001514 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001515 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001516
1517 // If this the first designator, our caller will continue checking
1518 // the rest of this struct/class/union subobject.
1519 if (IsFirstDesignator) {
1520 if (NextField)
1521 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001522 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001523 return false;
1524 }
1525
Douglas Gregor34e79462009-01-28 23:36:17 +00001526 if (!FinishSubobjectInit)
1527 return false;
1528
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001529 // We've already initialized something in the union; we're done.
1530 if (RT->getDecl()->isUnion())
1531 return hadError;
1532
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001533 // Check the remaining fields within this class/struct/union subobject.
1534 bool prevHadError = hadError;
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001535
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001536 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001537 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001538 return hadError && !prevHadError;
1539 }
1540
1541 // C99 6.7.8p6:
1542 //
1543 // If a designator has the form
1544 //
1545 // [ constant-expression ]
1546 //
1547 // then the current object (defined below) shall have array
1548 // type and the expression shall be an integer constant
1549 // expression. If the array is of unknown size, any
1550 // nonnegative value is valid.
1551 //
1552 // Additionally, cope with the GNU extension that permits
1553 // designators of the form
1554 //
1555 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001556 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001557 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001558 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001559 << CurrentObjectType;
1560 ++Index;
1561 return true;
1562 }
1563
1564 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001565 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1566 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001567 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001568 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001569 DesignatedEndIndex = DesignatedStartIndex;
1570 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001571 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001572
Mike Stump1eb44332009-09-09 15:08:12 +00001573
1574 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001575 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001576 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001577 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001578 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001579
Chris Lattner3bf68932009-04-25 21:59:05 +00001580 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001581 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001582 }
1583
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001584 if (isa<ConstantArrayType>(AT)) {
1585 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001586 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1587 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1588 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1589 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1590 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001591 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001592 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001593 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001594 << IndexExpr->getSourceRange();
1595 ++Index;
1596 return true;
1597 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001598 } else {
1599 // Make sure the bit-widths and signedness match.
1600 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1601 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001602 else if (DesignatedStartIndex.getBitWidth() <
1603 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001604 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1605 DesignatedStartIndex.setIsUnsigned(true);
1606 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Douglas Gregor4c678342009-01-28 21:54:33 +00001609 // Make sure that our non-designated initializer list has space
1610 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001611 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001612 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001613 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001614
Douglas Gregor34e79462009-01-28 23:36:17 +00001615 // Repeatedly perform subobject initializations in the range
1616 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617
Douglas Gregor34e79462009-01-28 23:36:17 +00001618 // Move to the next designator
1619 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1620 unsigned OldIndex = Index;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001621
1622 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001623 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001624
Douglas Gregor34e79462009-01-28 23:36:17 +00001625 while (DesignatedStartIndex <= DesignatedEndIndex) {
1626 // Recurse to check later designated subobjects.
1627 QualType ElementType = AT->getElementType();
1628 Index = OldIndex;
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001629
1630 ElementEntity.setElementIndex(ElementIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001631 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001632 ElementType, 0, 0, Index,
1633 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001634 (DesignatedStartIndex == DesignatedEndIndex),
1635 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001636 return true;
1637
1638 // Move to the next index in the array that we'll be initializing.
1639 ++DesignatedStartIndex;
1640 ElementIndex = DesignatedStartIndex.getZExtValue();
1641 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001642
1643 // If this the first designator, our caller will continue checking
1644 // the rest of this array subobject.
1645 if (IsFirstDesignator) {
1646 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001647 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001648 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001649 return false;
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Douglas Gregor34e79462009-01-28 23:36:17 +00001652 if (!FinishSubobjectInit)
1653 return false;
1654
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001655 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001656 bool prevHadError = hadError;
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001657 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001658 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001659 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001660 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001661}
1662
Douglas Gregor4c678342009-01-28 21:54:33 +00001663// Get the structured initializer list for a subobject of type
1664// @p CurrentObjectType.
1665InitListExpr *
1666InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1667 QualType CurrentObjectType,
1668 InitListExpr *StructuredList,
1669 unsigned StructuredIndex,
1670 SourceRange InitRange) {
1671 Expr *ExistingInit = 0;
1672 if (!StructuredList)
1673 ExistingInit = SyntacticToSemantic[IList];
1674 else if (StructuredIndex < StructuredList->getNumInits())
1675 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Douglas Gregor4c678342009-01-28 21:54:33 +00001677 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1678 return Result;
1679
1680 if (ExistingInit) {
1681 // We are creating an initializer list that initializes the
1682 // subobjects of the current object, but there was already an
1683 // initialization that completely initialized the current
1684 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001685 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001686 // struct X { int a, b; };
1687 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001688 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1690 // designated initializer re-initializes the whole
1691 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001692 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001693 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001695 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001696 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001697 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001698 << ExistingInit->getSourceRange();
1699 }
1700
Mike Stump1eb44332009-09-09 15:08:12 +00001701 InitListExpr *Result
1702 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001703 InitRange.getEnd());
1704
Douglas Gregor4c678342009-01-28 21:54:33 +00001705 Result->setType(CurrentObjectType);
1706
Douglas Gregorfa219202009-03-20 23:58:33 +00001707 // Pre-allocate storage for the structured initializer list.
1708 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001709 unsigned NumInits = 0;
1710 if (!StructuredList)
1711 NumInits = IList->getNumInits();
1712 else if (Index < IList->getNumInits()) {
1713 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1714 NumInits = SubList->getNumInits();
1715 }
1716
Mike Stump1eb44332009-09-09 15:08:12 +00001717 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001718 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1719 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1720 NumElements = CAType->getSize().getZExtValue();
1721 // Simple heuristic so that we don't allocate a very large
1722 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001723 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001724 NumElements = 0;
1725 }
John McCall183700f2009-09-21 23:43:11 +00001726 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001727 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001728 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001729 RecordDecl *RDecl = RType->getDecl();
1730 if (RDecl->isUnion())
1731 NumElements = 1;
1732 else
Mike Stump1eb44332009-09-09 15:08:12 +00001733 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001734 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001735 }
1736
Douglas Gregor08457732009-03-21 18:13:52 +00001737 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001738 NumElements = IList->getNumInits();
1739
1740 Result->reserveInits(NumElements);
1741
Douglas Gregor4c678342009-01-28 21:54:33 +00001742 // Link this new initializer list into the structured initializer
1743 // lists.
1744 if (StructuredList)
1745 StructuredList->updateInit(StructuredIndex, Result);
1746 else {
1747 Result->setSyntacticForm(IList);
1748 SyntacticToSemantic[IList] = Result;
1749 }
1750
1751 return Result;
1752}
1753
1754/// Update the initializer at index @p StructuredIndex within the
1755/// structured initializer list to the value @p expr.
1756void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1757 unsigned &StructuredIndex,
1758 Expr *expr) {
1759 // No structured initializer list to update
1760 if (!StructuredList)
1761 return;
1762
1763 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1764 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001765 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001766 diag::warn_initializer_overrides)
1767 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001768 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001770 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001771 << PrevInit->getSourceRange();
1772 }
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Douglas Gregor4c678342009-01-28 21:54:33 +00001774 ++StructuredIndex;
1775}
1776
Douglas Gregor05c13a32009-01-22 00:58:24 +00001777/// Check that the given Index expression is a valid array designator
1778/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001779/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001780/// and produces a reasonable diagnostic if there is a
1781/// failure. Returns true if there was an error, false otherwise. If
1782/// everything went okay, Value will receive the value of the constant
1783/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001784static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001785CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001786 SourceLocation Loc = Index->getSourceRange().getBegin();
1787
1788 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001789 if (S.VerifyIntegerConstantExpression(Index, &Value))
1790 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001791
Chris Lattner3bf68932009-04-25 21:59:05 +00001792 if (Value.isSigned() && Value.isNegative())
1793 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001794 << Value.toString(10) << Index->getSourceRange();
1795
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001796 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001797 return false;
1798}
1799
1800Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1801 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001802 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001803 OwningExprResult Init) {
1804 typedef DesignatedInitExpr::Designator ASTDesignator;
1805
1806 bool Invalid = false;
1807 llvm::SmallVector<ASTDesignator, 32> Designators;
1808 llvm::SmallVector<Expr *, 32> InitExpressions;
1809
1810 // Build designators and check array designator expressions.
1811 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1812 const Designator &D = Desig.getDesignator(Idx);
1813 switch (D.getKind()) {
1814 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001815 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001816 D.getFieldLoc()));
1817 break;
1818
1819 case Designator::ArrayDesignator: {
1820 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1821 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001822 if (!Index->isTypeDependent() &&
1823 !Index->isValueDependent() &&
1824 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001825 Invalid = true;
1826 else {
1827 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001828 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001829 D.getRBracketLoc()));
1830 InitExpressions.push_back(Index);
1831 }
1832 break;
1833 }
1834
1835 case Designator::ArrayRangeDesignator: {
1836 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1837 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1838 llvm::APSInt StartValue;
1839 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001840 bool StartDependent = StartIndex->isTypeDependent() ||
1841 StartIndex->isValueDependent();
1842 bool EndDependent = EndIndex->isTypeDependent() ||
1843 EndIndex->isValueDependent();
1844 if ((!StartDependent &&
1845 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1846 (!EndDependent &&
1847 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001848 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001849 else {
1850 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001851 if (StartDependent || EndDependent) {
1852 // Nothing to compute.
1853 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001854 EndValue.extend(StartValue.getBitWidth());
1855 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1856 StartValue.extend(EndValue.getBitWidth());
1857
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001858 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001859 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001860 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001861 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1862 Invalid = true;
1863 } else {
1864 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001865 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001866 D.getEllipsisLoc(),
1867 D.getRBracketLoc()));
1868 InitExpressions.push_back(StartIndex);
1869 InitExpressions.push_back(EndIndex);
1870 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001871 }
1872 break;
1873 }
1874 }
1875 }
1876
1877 if (Invalid || Init.isInvalid())
1878 return ExprError();
1879
1880 // Clear out the expressions within the designation.
1881 Desig.ClearExprs(*this);
1882
1883 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001884 = DesignatedInitExpr::Create(Context,
1885 Designators.data(), Designators.size(),
1886 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001887 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001888 return Owned(DIE);
1889}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001890
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001891bool Sema::CheckInitList(const InitializedEntity &Entity,
1892 InitListExpr *&InitList, QualType &DeclType) {
1893 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001894 if (!CheckInitList.HadError())
1895 InitList = CheckInitList.getFullyStructuredList();
1896
1897 return CheckInitList.HadError();
1898}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001899
Douglas Gregor20093b42009-12-09 23:02:17 +00001900//===----------------------------------------------------------------------===//
1901// Initialization entity
1902//===----------------------------------------------------------------------===//
1903
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001904InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1905 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001906 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001907{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001908 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1909 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001910 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001911 } else {
1912 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001913 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001914 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001915}
1916
1917InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1918 CXXBaseSpecifier *Base)
1919{
1920 InitializedEntity Result;
1921 Result.Kind = EK_Base;
1922 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001923 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001924 return Result;
1925}
1926
Douglas Gregor99a2e602009-12-16 01:38:02 +00001927DeclarationName InitializedEntity::getName() const {
1928 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001929 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001930 if (!VariableOrMember)
1931 return DeclarationName();
1932 // Fall through
1933
1934 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001935 case EK_Member:
1936 return VariableOrMember->getDeclName();
1937
1938 case EK_Result:
1939 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001940 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001941 case EK_Temporary:
1942 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001943 case EK_ArrayElement:
1944 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001945 return DeclarationName();
1946 }
1947
1948 // Silence GCC warning
1949 return DeclarationName();
1950}
1951
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001952DeclaratorDecl *InitializedEntity::getDecl() const {
1953 switch (getKind()) {
1954 case EK_Variable:
1955 case EK_Parameter:
1956 case EK_Member:
1957 return VariableOrMember;
1958
1959 case EK_Result:
1960 case EK_Exception:
1961 case EK_New:
1962 case EK_Temporary:
1963 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001964 case EK_ArrayElement:
1965 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001966 return 0;
1967 }
1968
1969 // Silence GCC warning
1970 return 0;
1971}
1972
Douglas Gregor20093b42009-12-09 23:02:17 +00001973//===----------------------------------------------------------------------===//
1974// Initialization sequence
1975//===----------------------------------------------------------------------===//
1976
1977void InitializationSequence::Step::Destroy() {
1978 switch (Kind) {
1979 case SK_ResolveAddressOfOverloadedFunction:
1980 case SK_CastDerivedToBaseRValue:
1981 case SK_CastDerivedToBaseLValue:
1982 case SK_BindReference:
1983 case SK_BindReferenceToTemporary:
1984 case SK_UserConversion:
1985 case SK_QualificationConversionRValue:
1986 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001987 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001988 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001989 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001990 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001991 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001992 break;
1993
1994 case SK_ConversionSequence:
1995 delete ICS;
1996 }
1997}
1998
1999void InitializationSequence::AddAddressOverloadResolutionStep(
2000 FunctionDecl *Function) {
2001 Step S;
2002 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2003 S.Type = Function->getType();
2004 S.Function = Function;
2005 Steps.push_back(S);
2006}
2007
2008void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2009 bool IsLValue) {
2010 Step S;
2011 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2012 S.Type = BaseType;
2013 Steps.push_back(S);
2014}
2015
2016void InitializationSequence::AddReferenceBindingStep(QualType T,
2017 bool BindingTemporary) {
2018 Step S;
2019 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2020 S.Type = T;
2021 Steps.push_back(S);
2022}
2023
Eli Friedman03981012009-12-11 02:42:07 +00002024void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2025 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002026 Step S;
2027 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002028 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002029 S.Function = Function;
2030 Steps.push_back(S);
2031}
2032
2033void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2034 bool IsLValue) {
2035 Step S;
2036 S.Kind = IsLValue? SK_QualificationConversionLValue
2037 : SK_QualificationConversionRValue;
2038 S.Type = Ty;
2039 Steps.push_back(S);
2040}
2041
2042void InitializationSequence::AddConversionSequenceStep(
2043 const ImplicitConversionSequence &ICS,
2044 QualType T) {
2045 Step S;
2046 S.Kind = SK_ConversionSequence;
2047 S.Type = T;
2048 S.ICS = new ImplicitConversionSequence(ICS);
2049 Steps.push_back(S);
2050}
2051
Douglas Gregord87b61f2009-12-10 17:56:55 +00002052void InitializationSequence::AddListInitializationStep(QualType T) {
2053 Step S;
2054 S.Kind = SK_ListInitialization;
2055 S.Type = T;
2056 Steps.push_back(S);
2057}
2058
Douglas Gregor51c56d62009-12-14 20:49:26 +00002059void
2060InitializationSequence::AddConstructorInitializationStep(
2061 CXXConstructorDecl *Constructor,
2062 QualType T) {
2063 Step S;
2064 S.Kind = SK_ConstructorInitialization;
2065 S.Type = T;
2066 S.Function = Constructor;
2067 Steps.push_back(S);
2068}
2069
Douglas Gregor71d17402009-12-15 00:01:57 +00002070void InitializationSequence::AddZeroInitializationStep(QualType T) {
2071 Step S;
2072 S.Kind = SK_ZeroInitialization;
2073 S.Type = T;
2074 Steps.push_back(S);
2075}
2076
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002077void InitializationSequence::AddCAssignmentStep(QualType T) {
2078 Step S;
2079 S.Kind = SK_CAssignment;
2080 S.Type = T;
2081 Steps.push_back(S);
2082}
2083
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002084void InitializationSequence::AddStringInitStep(QualType T) {
2085 Step S;
2086 S.Kind = SK_StringInit;
2087 S.Type = T;
2088 Steps.push_back(S);
2089}
2090
Douglas Gregor20093b42009-12-09 23:02:17 +00002091void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2092 OverloadingResult Result) {
2093 SequenceKind = FailedSequence;
2094 this->Failure = Failure;
2095 this->FailedOverloadResult = Result;
2096}
2097
2098//===----------------------------------------------------------------------===//
2099// Attempt initialization
2100//===----------------------------------------------------------------------===//
2101
2102/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002103static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002104 const InitializedEntity &Entity,
2105 const InitializationKind &Kind,
2106 InitListExpr *InitList,
2107 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002108 // FIXME: We only perform rudimentary checking of list
2109 // initializations at this point, then assume that any list
2110 // initialization of an array, aggregate, or scalar will be
2111 // well-formed. We we actually "perform" list initialization, we'll
2112 // do all of the necessary checking. C++0x initializer lists will
2113 // force us to perform more checking here.
2114 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2115
Douglas Gregord6542d82009-12-22 15:35:07 +00002116 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002117
2118 // C++ [dcl.init]p13:
2119 // If T is a scalar type, then a declaration of the form
2120 //
2121 // T x = { a };
2122 //
2123 // is equivalent to
2124 //
2125 // T x = a;
2126 if (DestType->isScalarType()) {
2127 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2128 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2129 return;
2130 }
2131
2132 // Assume scalar initialization from a single value works.
2133 } else if (DestType->isAggregateType()) {
2134 // Assume aggregate initialization works.
2135 } else if (DestType->isVectorType()) {
2136 // Assume vector initialization works.
2137 } else if (DestType->isReferenceType()) {
2138 // FIXME: C++0x defines behavior for this.
2139 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2140 return;
2141 } else if (DestType->isRecordType()) {
2142 // FIXME: C++0x defines behavior for this
2143 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2144 }
2145
2146 // Add a general "list initialization" step.
2147 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002148}
2149
2150/// \brief Try a reference initialization that involves calling a conversion
2151/// function.
2152///
2153/// FIXME: look intos DRs 656, 896
2154static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2155 const InitializedEntity &Entity,
2156 const InitializationKind &Kind,
2157 Expr *Initializer,
2158 bool AllowRValues,
2159 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002160 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002161 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2162 QualType T1 = cv1T1.getUnqualifiedType();
2163 QualType cv2T2 = Initializer->getType();
2164 QualType T2 = cv2T2.getUnqualifiedType();
2165
2166 bool DerivedToBase;
2167 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2168 T1, T2, DerivedToBase) &&
2169 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002170 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002171
2172 // Build the candidate set directly in the initialization sequence
2173 // structure, so that it will persist if we fail.
2174 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2175 CandidateSet.clear();
2176
2177 // Determine whether we are allowed to call explicit constructors or
2178 // explicit conversion operators.
2179 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2180
2181 const RecordType *T1RecordType = 0;
2182 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2183 // The type we're converting to is a class type. Enumerate its constructors
2184 // to see if there is a suitable conversion.
2185 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2186
2187 DeclarationName ConstructorName
2188 = S.Context.DeclarationNames.getCXXConstructorName(
2189 S.Context.getCanonicalType(T1).getUnqualifiedType());
2190 DeclContext::lookup_iterator Con, ConEnd;
2191 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2192 Con != ConEnd; ++Con) {
2193 // Find the constructor (which may be a template).
2194 CXXConstructorDecl *Constructor = 0;
2195 FunctionTemplateDecl *ConstructorTmpl
2196 = dyn_cast<FunctionTemplateDecl>(*Con);
2197 if (ConstructorTmpl)
2198 Constructor = cast<CXXConstructorDecl>(
2199 ConstructorTmpl->getTemplatedDecl());
2200 else
2201 Constructor = cast<CXXConstructorDecl>(*Con);
2202
2203 if (!Constructor->isInvalidDecl() &&
2204 Constructor->isConvertingConstructor(AllowExplicit)) {
2205 if (ConstructorTmpl)
2206 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2207 &Initializer, 1, CandidateSet);
2208 else
2209 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2210 }
2211 }
2212 }
2213
2214 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2215 // The type we're converting from is a class type, enumerate its conversion
2216 // functions.
2217 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2218
2219 // Determine the type we are converting to. If we are allowed to
2220 // convert to an rvalue, take the type that the destination type
2221 // refers to.
2222 QualType ToType = AllowRValues? cv1T1 : DestType;
2223
John McCalleec51cf2010-01-20 00:46:10 +00002224 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002225 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002226 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2227 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002228 NamedDecl *D = *I;
2229 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2230 if (isa<UsingShadowDecl>(D))
2231 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2232
2233 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2234 CXXConversionDecl *Conv;
2235 if (ConvTemplate)
2236 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2237 else
2238 Conv = cast<CXXConversionDecl>(*I);
2239
2240 // If the conversion function doesn't return a reference type,
2241 // it can't be considered for this conversion unless we're allowed to
2242 // consider rvalues.
2243 // FIXME: Do we need to make sure that we only consider conversion
2244 // candidates with reference-compatible results? That might be needed to
2245 // break recursion.
2246 if ((AllowExplicit || !Conv->isExplicit()) &&
2247 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2248 if (ConvTemplate)
2249 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2250 ToType, CandidateSet);
2251 else
2252 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2253 CandidateSet);
2254 }
2255 }
2256 }
2257
2258 SourceLocation DeclLoc = Initializer->getLocStart();
2259
2260 // Perform overload resolution. If it fails, return the failed result.
2261 OverloadCandidateSet::iterator Best;
2262 if (OverloadingResult Result
2263 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2264 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002265
Douglas Gregor20093b42009-12-09 23:02:17 +00002266 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002267
2268 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002269 if (isa<CXXConversionDecl>(Function))
2270 T2 = Function->getResultType();
2271 else
2272 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002273
2274 // Add the user-defined conversion step.
2275 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2276
2277 // Determine whether we need to perform derived-to-base or
2278 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002279 bool NewDerivedToBase = false;
2280 Sema::ReferenceCompareResult NewRefRelationship
2281 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2282 NewDerivedToBase);
2283 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2284 "Overload resolution picked a bad conversion function");
2285 (void)NewRefRelationship;
2286 if (NewDerivedToBase)
2287 Sequence.AddDerivedToBaseCastStep(
2288 S.Context.getQualifiedType(T1,
2289 T2.getNonReferenceType().getQualifiers()),
2290 /*isLValue=*/true);
2291
2292 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2293 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2294
2295 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2296 return OR_Success;
2297}
2298
2299/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2300static void TryReferenceInitialization(Sema &S,
2301 const InitializedEntity &Entity,
2302 const InitializationKind &Kind,
2303 Expr *Initializer,
2304 InitializationSequence &Sequence) {
2305 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2306
Douglas Gregord6542d82009-12-22 15:35:07 +00002307 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002308 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002309 Qualifiers T1Quals;
2310 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002311 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002312 Qualifiers T2Quals;
2313 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002314 SourceLocation DeclLoc = Initializer->getLocStart();
2315
2316 // If the initializer is the address of an overloaded function, try
2317 // to resolve the overloaded function. If all goes well, T2 is the
2318 // type of the resulting function.
2319 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2320 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2321 T1,
2322 false);
2323 if (!Fn) {
2324 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2325 return;
2326 }
2327
2328 Sequence.AddAddressOverloadResolutionStep(Fn);
2329 cv2T2 = Fn->getType();
2330 T2 = cv2T2.getUnqualifiedType();
2331 }
2332
2333 // FIXME: Rvalue references
2334 bool ForceRValue = false;
2335
2336 // Compute some basic properties of the types and the initializer.
2337 bool isLValueRef = DestType->isLValueReferenceType();
2338 bool isRValueRef = !isLValueRef;
2339 bool DerivedToBase = false;
2340 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2341 Initializer->isLvalue(S.Context);
2342 Sema::ReferenceCompareResult RefRelationship
2343 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2344
2345 // C++0x [dcl.init.ref]p5:
2346 // A reference to type "cv1 T1" is initialized by an expression of type
2347 // "cv2 T2" as follows:
2348 //
2349 // - If the reference is an lvalue reference and the initializer
2350 // expression
2351 OverloadingResult ConvOvlResult = OR_Success;
2352 if (isLValueRef) {
2353 if (InitLvalue == Expr::LV_Valid &&
2354 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2355 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2356 // reference-compatible with "cv2 T2," or
2357 //
2358 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2359 // bit-field when we're determining whether the reference initialization
2360 // can occur. This property will be checked by PerformInitialization.
2361 if (DerivedToBase)
2362 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002363 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002364 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002365 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002366 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2367 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2368 return;
2369 }
2370
2371 // - has a class type (i.e., T2 is a class type), where T1 is not
2372 // reference-related to T2, and can be implicitly converted to an
2373 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2374 // with "cv3 T3" (this conversion is selected by enumerating the
2375 // applicable conversion functions (13.3.1.6) and choosing the best
2376 // one through overload resolution (13.3)),
2377 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2378 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2379 Initializer,
2380 /*AllowRValues=*/false,
2381 Sequence);
2382 if (ConvOvlResult == OR_Success)
2383 return;
John McCall1d318332010-01-12 00:44:57 +00002384 if (ConvOvlResult != OR_No_Viable_Function) {
2385 Sequence.SetOverloadFailure(
2386 InitializationSequence::FK_ReferenceInitOverloadFailed,
2387 ConvOvlResult);
2388 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002389 }
2390 }
2391
2392 // - Otherwise, the reference shall be an lvalue reference to a
2393 // non-volatile const type (i.e., cv1 shall be const), or the reference
2394 // shall be an rvalue reference and the initializer expression shall
2395 // be an rvalue.
Chandler Carruth5535c382010-01-12 20:32:25 +00002396 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002397 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2398 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2399 Sequence.SetOverloadFailure(
2400 InitializationSequence::FK_ReferenceInitOverloadFailed,
2401 ConvOvlResult);
2402 else if (isLValueRef)
2403 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2404 ? (RefRelationship == Sema::Ref_Related
2405 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2406 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2407 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2408 else
2409 Sequence.SetFailed(
2410 InitializationSequence::FK_RValueReferenceBindingToLValue);
2411
2412 return;
2413 }
2414
2415 // - If T1 and T2 are class types and
2416 if (T1->isRecordType() && T2->isRecordType()) {
2417 // - the initializer expression is an rvalue and "cv1 T1" is
2418 // reference-compatible with "cv2 T2", or
2419 if (InitLvalue != Expr::LV_Valid &&
2420 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2421 if (DerivedToBase)
2422 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002423 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002424 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002425 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002426 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2427 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2428 return;
2429 }
2430
2431 // - T1 is not reference-related to T2 and the initializer expression
2432 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2433 // conversion is selected by enumerating the applicable conversion
2434 // functions (13.3.1.6) and choosing the best one through overload
2435 // resolution (13.3)),
2436 if (RefRelationship == Sema::Ref_Incompatible) {
2437 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2438 Kind, Initializer,
2439 /*AllowRValues=*/true,
2440 Sequence);
2441 if (ConvOvlResult)
2442 Sequence.SetOverloadFailure(
2443 InitializationSequence::FK_ReferenceInitOverloadFailed,
2444 ConvOvlResult);
2445
2446 return;
2447 }
2448
2449 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2450 return;
2451 }
2452
2453 // - If the initializer expression is an rvalue, with T2 an array type,
2454 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2455 // is bound to the object represented by the rvalue (see 3.10).
2456 // FIXME: How can an array type be reference-compatible with anything?
2457 // Don't we mean the element types of T1 and T2?
2458
2459 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2460 // from the initializer expression using the rules for a non-reference
2461 // copy initialization (8.5). The reference is then bound to the
2462 // temporary. [...]
2463 // Determine whether we are allowed to call explicit constructors or
2464 // explicit conversion operators.
2465 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2466 ImplicitConversionSequence ICS
2467 = S.TryImplicitConversion(Initializer, cv1T1,
2468 /*SuppressUserConversions=*/false, AllowExplicit,
2469 /*ForceRValue=*/false,
2470 /*FIXME:InOverloadResolution=*/false,
2471 /*UserCast=*/Kind.isExplicitCast());
2472
John McCall1d318332010-01-12 00:44:57 +00002473 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002474 // FIXME: Use the conversion function set stored in ICS to turn
2475 // this into an overloading ambiguity diagnostic. However, we need
2476 // to keep that set as an OverloadCandidateSet rather than as some
2477 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002478 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2479 Sequence.SetOverloadFailure(
2480 InitializationSequence::FK_ReferenceInitOverloadFailed,
2481 ConvOvlResult);
2482 else
2483 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002484 return;
2485 }
2486
2487 // [...] If T1 is reference-related to T2, cv1 must be the
2488 // same cv-qualification as, or greater cv-qualification
2489 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002490 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2491 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002492 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002493 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002494 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2495 return;
2496 }
2497
2498 // Perform the actual conversion.
2499 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2500 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2501 return;
2502}
2503
2504/// \brief Attempt character array initialization from a string literal
2505/// (C++ [dcl.init.string], C99 6.7.8).
2506static void TryStringLiteralInitialization(Sema &S,
2507 const InitializedEntity &Entity,
2508 const InitializationKind &Kind,
2509 Expr *Initializer,
2510 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002511 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002512 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002513}
2514
Douglas Gregor20093b42009-12-09 23:02:17 +00002515/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2516/// enumerates the constructors of the initialized entity and performs overload
2517/// resolution to select the best.
2518static void TryConstructorInitialization(Sema &S,
2519 const InitializedEntity &Entity,
2520 const InitializationKind &Kind,
2521 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002522 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002523 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002524 if (Kind.getKind() == InitializationKind::IK_Copy)
2525 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2526 else
2527 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002528
2529 // Build the candidate set directly in the initialization sequence
2530 // structure, so that it will persist if we fail.
2531 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2532 CandidateSet.clear();
2533
2534 // Determine whether we are allowed to call explicit constructors or
2535 // explicit conversion operators.
2536 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2537 Kind.getKind() == InitializationKind::IK_Value ||
2538 Kind.getKind() == InitializationKind::IK_Default);
2539
2540 // The type we're converting to is a class type. Enumerate its constructors
2541 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002542 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2543 assert(DestRecordType && "Constructor initialization requires record type");
2544 CXXRecordDecl *DestRecordDecl
2545 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2546
2547 DeclarationName ConstructorName
2548 = S.Context.DeclarationNames.getCXXConstructorName(
2549 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2550 DeclContext::lookup_iterator Con, ConEnd;
2551 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2552 Con != ConEnd; ++Con) {
2553 // Find the constructor (which may be a template).
2554 CXXConstructorDecl *Constructor = 0;
2555 FunctionTemplateDecl *ConstructorTmpl
2556 = dyn_cast<FunctionTemplateDecl>(*Con);
2557 if (ConstructorTmpl)
2558 Constructor = cast<CXXConstructorDecl>(
2559 ConstructorTmpl->getTemplatedDecl());
2560 else
2561 Constructor = cast<CXXConstructorDecl>(*Con);
2562
2563 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002564 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002565 if (ConstructorTmpl)
2566 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2567 Args, NumArgs, CandidateSet);
2568 else
2569 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2570 }
2571 }
2572
2573 SourceLocation DeclLoc = Kind.getLocation();
2574
2575 // Perform overload resolution. If it fails, return the failed result.
2576 OverloadCandidateSet::iterator Best;
2577 if (OverloadingResult Result
2578 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2579 Sequence.SetOverloadFailure(
2580 InitializationSequence::FK_ConstructorOverloadFailed,
2581 Result);
2582 return;
2583 }
2584
2585 // Add the constructor initialization step. Any cv-qualification conversion is
2586 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002587 if (Kind.getKind() == InitializationKind::IK_Copy) {
2588 Sequence.AddUserConversionStep(Best->Function, DestType);
2589 } else {
2590 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002591 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002592 DestType);
2593 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002594}
2595
Douglas Gregor71d17402009-12-15 00:01:57 +00002596/// \brief Attempt value initialization (C++ [dcl.init]p7).
2597static void TryValueInitialization(Sema &S,
2598 const InitializedEntity &Entity,
2599 const InitializationKind &Kind,
2600 InitializationSequence &Sequence) {
2601 // C++ [dcl.init]p5:
2602 //
2603 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002604 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002605
2606 // -- if T is an array type, then each element is value-initialized;
2607 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2608 T = AT->getElementType();
2609
2610 if (const RecordType *RT = T->getAs<RecordType>()) {
2611 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2612 // -- if T is a class type (clause 9) with a user-declared
2613 // constructor (12.1), then the default constructor for T is
2614 // called (and the initialization is ill-formed if T has no
2615 // accessible default constructor);
2616 //
2617 // FIXME: we really want to refer to a single subobject of the array,
2618 // but Entity doesn't have a way to capture that (yet).
2619 if (ClassDecl->hasUserDeclaredConstructor())
2620 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2621
Douglas Gregor16006c92009-12-16 18:50:27 +00002622 // -- if T is a (possibly cv-qualified) non-union class type
2623 // without a user-provided constructor, then the object is
2624 // zero-initialized and, if T’s implicitly-declared default
2625 // constructor is non-trivial, that constructor is called.
2626 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2627 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2628 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002629 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002630 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2631 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002632 }
2633 }
2634
Douglas Gregord6542d82009-12-22 15:35:07 +00002635 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002636 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2637}
2638
Douglas Gregor99a2e602009-12-16 01:38:02 +00002639/// \brief Attempt default initialization (C++ [dcl.init]p6).
2640static void TryDefaultInitialization(Sema &S,
2641 const InitializedEntity &Entity,
2642 const InitializationKind &Kind,
2643 InitializationSequence &Sequence) {
2644 assert(Kind.getKind() == InitializationKind::IK_Default);
2645
2646 // C++ [dcl.init]p6:
2647 // To default-initialize an object of type T means:
2648 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002649 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002650 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2651 DestType = Array->getElementType();
2652
2653 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2654 // constructor for T is called (and the initialization is ill-formed if
2655 // T has no accessible default constructor);
2656 if (DestType->isRecordType()) {
2657 // FIXME: If a program calls for the default initialization of an object of
2658 // a const-qualified type T, T shall be a class type with a user-provided
2659 // default constructor.
2660 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2661 Sequence);
2662 }
2663
2664 // - otherwise, no initialization is performed.
2665 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2666
2667 // If a program calls for the default initialization of an object of
2668 // a const-qualified type T, T shall be a class type with a user-provided
2669 // default constructor.
2670 if (DestType.isConstQualified())
2671 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2672}
2673
Douglas Gregor20093b42009-12-09 23:02:17 +00002674/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2675/// which enumerates all conversion functions and performs overload resolution
2676/// to select the best.
2677static void TryUserDefinedConversion(Sema &S,
2678 const InitializedEntity &Entity,
2679 const InitializationKind &Kind,
2680 Expr *Initializer,
2681 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002682 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2683
Douglas Gregord6542d82009-12-22 15:35:07 +00002684 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002685 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2686 QualType SourceType = Initializer->getType();
2687 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2688 "Must have a class type to perform a user-defined conversion");
2689
2690 // Build the candidate set directly in the initialization sequence
2691 // structure, so that it will persist if we fail.
2692 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2693 CandidateSet.clear();
2694
2695 // Determine whether we are allowed to call explicit constructors or
2696 // explicit conversion operators.
2697 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2698
2699 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2700 // The type we're converting to is a class type. Enumerate its constructors
2701 // to see if there is a suitable conversion.
2702 CXXRecordDecl *DestRecordDecl
2703 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2704
2705 DeclarationName ConstructorName
2706 = S.Context.DeclarationNames.getCXXConstructorName(
2707 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2708 DeclContext::lookup_iterator Con, ConEnd;
2709 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2710 Con != ConEnd; ++Con) {
2711 // Find the constructor (which may be a template).
2712 CXXConstructorDecl *Constructor = 0;
2713 FunctionTemplateDecl *ConstructorTmpl
2714 = dyn_cast<FunctionTemplateDecl>(*Con);
2715 if (ConstructorTmpl)
2716 Constructor = cast<CXXConstructorDecl>(
2717 ConstructorTmpl->getTemplatedDecl());
2718 else
2719 Constructor = cast<CXXConstructorDecl>(*Con);
2720
2721 if (!Constructor->isInvalidDecl() &&
2722 Constructor->isConvertingConstructor(AllowExplicit)) {
2723 if (ConstructorTmpl)
2724 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2725 &Initializer, 1, CandidateSet);
2726 else
2727 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2728 }
2729 }
2730 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002731
2732 SourceLocation DeclLoc = Initializer->getLocStart();
2733
Douglas Gregor4a520a22009-12-14 17:27:33 +00002734 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2735 // The type we're converting from is a class type, enumerate its conversion
2736 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002737
Eli Friedman33c2da92009-12-20 22:12:03 +00002738 // We can only enumerate the conversion functions for a complete type; if
2739 // the type isn't complete, simply skip this step.
2740 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2741 CXXRecordDecl *SourceRecordDecl
2742 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002743
John McCalleec51cf2010-01-20 00:46:10 +00002744 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002745 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002746 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002747 E = Conversions->end();
2748 I != E; ++I) {
2749 NamedDecl *D = *I;
2750 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2751 if (isa<UsingShadowDecl>(D))
2752 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2753
2754 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2755 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002756 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002757 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002758 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002759 Conv = cast<CXXConversionDecl>(*I);
2760
2761 if (AllowExplicit || !Conv->isExplicit()) {
2762 if (ConvTemplate)
2763 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2764 Initializer, DestType,
2765 CandidateSet);
2766 else
2767 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2768 CandidateSet);
2769 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002770 }
2771 }
2772 }
2773
Douglas Gregor4a520a22009-12-14 17:27:33 +00002774 // Perform overload resolution. If it fails, return the failed result.
2775 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002776 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002777 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2778 Sequence.SetOverloadFailure(
2779 InitializationSequence::FK_UserConversionOverloadFailed,
2780 Result);
2781 return;
2782 }
John McCall1d318332010-01-12 00:44:57 +00002783
Douglas Gregor4a520a22009-12-14 17:27:33 +00002784 FunctionDecl *Function = Best->Function;
2785
2786 if (isa<CXXConstructorDecl>(Function)) {
2787 // Add the user-defined conversion step. Any cv-qualification conversion is
2788 // subsumed by the initialization.
2789 Sequence.AddUserConversionStep(Function, DestType);
2790 return;
2791 }
2792
2793 // Add the user-defined conversion step that calls the conversion function.
2794 QualType ConvType = Function->getResultType().getNonReferenceType();
2795 Sequence.AddUserConversionStep(Function, ConvType);
2796
2797 // If the conversion following the call to the conversion function is
2798 // interesting, add it as a separate step.
2799 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2800 Best->FinalConversion.Third) {
2801 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002802 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002803 ICS.Standard = Best->FinalConversion;
2804 Sequence.AddConversionSequenceStep(ICS, DestType);
2805 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002806}
2807
2808/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2809/// non-class type to another.
2810static void TryImplicitConversion(Sema &S,
2811 const InitializedEntity &Entity,
2812 const InitializationKind &Kind,
2813 Expr *Initializer,
2814 InitializationSequence &Sequence) {
2815 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002816 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002817 /*SuppressUserConversions=*/true,
2818 /*AllowExplicit=*/false,
2819 /*ForceRValue=*/false,
2820 /*FIXME:InOverloadResolution=*/false,
2821 /*UserCast=*/Kind.isExplicitCast());
2822
John McCall1d318332010-01-12 00:44:57 +00002823 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002824 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2825 return;
2826 }
2827
Douglas Gregord6542d82009-12-22 15:35:07 +00002828 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002829}
2830
2831InitializationSequence::InitializationSequence(Sema &S,
2832 const InitializedEntity &Entity,
2833 const InitializationKind &Kind,
2834 Expr **Args,
2835 unsigned NumArgs) {
2836 ASTContext &Context = S.Context;
2837
2838 // C++0x [dcl.init]p16:
2839 // The semantics of initializers are as follows. The destination type is
2840 // the type of the object or reference being initialized and the source
2841 // type is the type of the initializer expression. The source type is not
2842 // defined when the initializer is a braced-init-list or when it is a
2843 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002844 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002845
2846 if (DestType->isDependentType() ||
2847 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2848 SequenceKind = DependentSequence;
2849 return;
2850 }
2851
2852 QualType SourceType;
2853 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002854 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002855 Initializer = Args[0];
2856 if (!isa<InitListExpr>(Initializer))
2857 SourceType = Initializer->getType();
2858 }
2859
2860 // - If the initializer is a braced-init-list, the object is
2861 // list-initialized (8.5.4).
2862 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2863 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002864 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002865 }
2866
2867 // - If the destination type is a reference type, see 8.5.3.
2868 if (DestType->isReferenceType()) {
2869 // C++0x [dcl.init.ref]p1:
2870 // A variable declared to be a T& or T&&, that is, "reference to type T"
2871 // (8.3.2), shall be initialized by an object, or function, of type T or
2872 // by an object that can be converted into a T.
2873 // (Therefore, multiple arguments are not permitted.)
2874 if (NumArgs != 1)
2875 SetFailed(FK_TooManyInitsForReference);
2876 else
2877 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2878 return;
2879 }
2880
2881 // - If the destination type is an array of characters, an array of
2882 // char16_t, an array of char32_t, or an array of wchar_t, and the
2883 // initializer is a string literal, see 8.5.2.
2884 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2885 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2886 return;
2887 }
2888
2889 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002890 if (Kind.getKind() == InitializationKind::IK_Value ||
2891 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 TryValueInitialization(S, Entity, Kind, *this);
2893 return;
2894 }
2895
Douglas Gregor99a2e602009-12-16 01:38:02 +00002896 // Handle default initialization.
2897 if (Kind.getKind() == InitializationKind::IK_Default){
2898 TryDefaultInitialization(S, Entity, Kind, *this);
2899 return;
2900 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002901
Douglas Gregor20093b42009-12-09 23:02:17 +00002902 // - Otherwise, if the destination type is an array, the program is
2903 // ill-formed.
2904 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2905 if (AT->getElementType()->isAnyCharacterType())
2906 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2907 else
2908 SetFailed(FK_ArrayNeedsInitList);
2909
2910 return;
2911 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002912
2913 // Handle initialization in C
2914 if (!S.getLangOptions().CPlusPlus) {
2915 setSequenceKind(CAssignment);
2916 AddCAssignmentStep(DestType);
2917 return;
2918 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002919
2920 // - If the destination type is a (possibly cv-qualified) class type:
2921 if (DestType->isRecordType()) {
2922 // - If the initialization is direct-initialization, or if it is
2923 // copy-initialization where the cv-unqualified version of the
2924 // source type is the same class as, or a derived class of, the
2925 // class of the destination, constructors are considered. [...]
2926 if (Kind.getKind() == InitializationKind::IK_Direct ||
2927 (Kind.getKind() == InitializationKind::IK_Copy &&
2928 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2929 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002930 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002931 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002932 // - Otherwise (i.e., for the remaining copy-initialization cases),
2933 // user-defined conversion sequences that can convert from the source
2934 // type to the destination type or (when a conversion function is
2935 // used) to a derived class thereof are enumerated as described in
2936 // 13.3.1.4, and the best one is chosen through overload resolution
2937 // (13.3).
2938 else
2939 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2940 return;
2941 }
2942
Douglas Gregor99a2e602009-12-16 01:38:02 +00002943 if (NumArgs > 1) {
2944 SetFailed(FK_TooManyInitsForScalar);
2945 return;
2946 }
2947 assert(NumArgs == 1 && "Zero-argument case handled above");
2948
Douglas Gregor20093b42009-12-09 23:02:17 +00002949 // - Otherwise, if the source type is a (possibly cv-qualified) class
2950 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002951 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002952 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2953 return;
2954 }
2955
2956 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002957 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002958 // conversions (Clause 4) will be used, if necessary, to convert the
2959 // initializer expression to the cv-unqualified version of the
2960 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002961 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002962 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2963}
2964
2965InitializationSequence::~InitializationSequence() {
2966 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2967 StepEnd = Steps.end();
2968 Step != StepEnd; ++Step)
2969 Step->Destroy();
2970}
2971
2972//===----------------------------------------------------------------------===//
2973// Perform initialization
2974//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002975static Sema::AssignmentAction
2976getAssignmentAction(const InitializedEntity &Entity) {
2977 switch(Entity.getKind()) {
2978 case InitializedEntity::EK_Variable:
2979 case InitializedEntity::EK_New:
2980 return Sema::AA_Initializing;
2981
2982 case InitializedEntity::EK_Parameter:
2983 // FIXME: Can we tell when we're sending vs. passing?
2984 return Sema::AA_Passing;
2985
2986 case InitializedEntity::EK_Result:
2987 return Sema::AA_Returning;
2988
2989 case InitializedEntity::EK_Exception:
2990 case InitializedEntity::EK_Base:
2991 llvm_unreachable("No assignment action for C++-specific initialization");
2992 break;
2993
2994 case InitializedEntity::EK_Temporary:
2995 // FIXME: Can we tell apart casting vs. converting?
2996 return Sema::AA_Casting;
2997
2998 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002999 case InitializedEntity::EK_ArrayElement:
3000 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003001 return Sema::AA_Initializing;
3002 }
3003
3004 return Sema::AA_Converting;
3005}
3006
3007static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3008 bool IsCopy) {
3009 switch (Entity.getKind()) {
3010 case InitializedEntity::EK_Result:
3011 case InitializedEntity::EK_Exception:
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003012 case InitializedEntity::EK_ArrayElement:
3013 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003014 return !IsCopy;
3015
3016 case InitializedEntity::EK_New:
3017 case InitializedEntity::EK_Variable:
3018 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003019 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003020 return false;
3021
3022 case InitializedEntity::EK_Parameter:
3023 case InitializedEntity::EK_Temporary:
3024 return true;
3025 }
3026
3027 llvm_unreachable("missed an InitializedEntity kind?");
3028}
3029
3030/// \brief If we need to perform an additional copy of the initialized object
3031/// for this kind of entity (e.g., the result of a function or an object being
3032/// thrown), make the copy.
3033static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3034 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003035 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003036 Sema::OwningExprResult CurInit) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003037 Expr *CurInitExpr = (Expr *)CurInit.get();
3038
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003039 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003040
3041 switch (Entity.getKind()) {
3042 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003043 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003044 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003045 Loc = Entity.getReturnLoc();
3046 break;
3047
3048 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003049 Loc = Entity.getThrowLoc();
3050 break;
3051
3052 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003053 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003054 Kind.getKind() != InitializationKind::IK_Copy)
3055 return move(CurInit);
3056 Loc = Entity.getDecl()->getLocation();
3057 break;
3058
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003059 case InitializedEntity::EK_ArrayElement:
3060 case InitializedEntity::EK_Member:
3061 if (Entity.getType()->isReferenceType() ||
3062 Kind.getKind() != InitializationKind::IK_Copy)
3063 return move(CurInit);
3064 Loc = CurInitExpr->getLocStart();
3065 break;
3066
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003067 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003068 // FIXME: Do we need this initialization for a parameter?
3069 return move(CurInit);
3070
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003071 case InitializedEntity::EK_New:
3072 case InitializedEntity::EK_Temporary:
3073 case InitializedEntity::EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003074 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003075 // We don't need to copy for any of these initialized entities.
3076 return move(CurInit);
3077 }
3078
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003079 CXXRecordDecl *Class = 0;
3080 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3081 Class = cast<CXXRecordDecl>(Record->getDecl());
3082 if (!Class)
3083 return move(CurInit);
3084
3085 // Perform overload resolution using the class's copy constructors.
3086 DeclarationName ConstructorName
3087 = S.Context.DeclarationNames.getCXXConstructorName(
3088 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3089 DeclContext::lookup_iterator Con, ConEnd;
3090 OverloadCandidateSet CandidateSet;
3091 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3092 Con != ConEnd; ++Con) {
3093 // Find the constructor (which may be a template).
3094 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3095 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003096 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003097 continue;
3098
3099 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3100 }
3101
3102 OverloadCandidateSet::iterator Best;
3103 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3104 case OR_Success:
3105 break;
3106
3107 case OR_No_Viable_Function:
3108 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003109 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003110 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003111 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3112 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003113 return S.ExprError();
3114
3115 case OR_Ambiguous:
3116 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003117 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003118 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003119 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3120 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003121 return S.ExprError();
3122
3123 case OR_Deleted:
3124 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003125 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003126 << CurInitExpr->getSourceRange();
3127 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3128 << Best->Function->isDeleted();
3129 return S.ExprError();
3130 }
3131
3132 CurInit.release();
3133 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3134 cast<CXXConstructorDecl>(Best->Function),
3135 /*Elidable=*/true,
3136 Sema::MultiExprArg(S,
3137 (void**)&CurInitExpr, 1));
3138}
Douglas Gregor20093b42009-12-09 23:02:17 +00003139
3140Action::OwningExprResult
3141InitializationSequence::Perform(Sema &S,
3142 const InitializedEntity &Entity,
3143 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003144 Action::MultiExprArg Args,
3145 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003146 if (SequenceKind == FailedSequence) {
3147 unsigned NumArgs = Args.size();
3148 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3149 return S.ExprError();
3150 }
3151
3152 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003153 // If the declaration is a non-dependent, incomplete array type
3154 // that has an initializer, then its type will be completed once
3155 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003156 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003157 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003158 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003159 if (const IncompleteArrayType *ArrayT
3160 = S.Context.getAsIncompleteArrayType(DeclType)) {
3161 // FIXME: We don't currently have the ability to accurately
3162 // compute the length of an initializer list without
3163 // performing full type-checking of the initializer list
3164 // (since we have to determine where braces are implicitly
3165 // introduced and such). So, we fall back to making the array
3166 // type a dependently-sized array type with no specified
3167 // bound.
3168 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3169 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003170
Douglas Gregord87b61f2009-12-10 17:56:55 +00003171 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003172 if (DeclaratorDecl *DD = Entity.getDecl()) {
3173 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3174 TypeLoc TL = TInfo->getTypeLoc();
3175 if (IncompleteArrayTypeLoc *ArrayLoc
3176 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3177 Brackets = ArrayLoc->getBracketsRange();
3178 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003179 }
3180
3181 *ResultType
3182 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3183 /*NumElts=*/0,
3184 ArrayT->getSizeModifier(),
3185 ArrayT->getIndexTypeCVRQualifiers(),
3186 Brackets);
3187 }
3188
3189 }
3190 }
3191
Eli Friedman08544622009-12-22 02:35:53 +00003192 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003193 return Sema::OwningExprResult(S, Args.release()[0]);
3194
3195 unsigned NumArgs = Args.size();
3196 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3197 SourceLocation(),
3198 (Expr **)Args.release(),
3199 NumArgs,
3200 SourceLocation()));
3201 }
3202
Douglas Gregor99a2e602009-12-16 01:38:02 +00003203 if (SequenceKind == NoInitialization)
3204 return S.Owned((Expr *)0);
3205
Douglas Gregord6542d82009-12-22 15:35:07 +00003206 QualType DestType = Entity.getType().getNonReferenceType();
3207 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003208 // the same as Entity.getDecl()->getType() in cases involving type merging,
3209 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003210 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003211 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003212 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003213
Douglas Gregor99a2e602009-12-16 01:38:02 +00003214 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3215
3216 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3217
3218 // For initialization steps that start with a single initializer,
3219 // grab the only argument out the Args and place it into the "current"
3220 // initializer.
3221 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003222 case SK_ResolveAddressOfOverloadedFunction:
3223 case SK_CastDerivedToBaseRValue:
3224 case SK_CastDerivedToBaseLValue:
3225 case SK_BindReference:
3226 case SK_BindReferenceToTemporary:
3227 case SK_UserConversion:
3228 case SK_QualificationConversionLValue:
3229 case SK_QualificationConversionRValue:
3230 case SK_ConversionSequence:
3231 case SK_ListInitialization:
3232 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003233 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003234 assert(Args.size() == 1);
3235 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3236 if (CurInit.isInvalid())
3237 return S.ExprError();
3238 break;
3239
3240 case SK_ConstructorInitialization:
3241 case SK_ZeroInitialization:
3242 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003243 }
3244
3245 // Walk through the computed steps for the initialization sequence,
3246 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003247 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003248 for (step_iterator Step = step_begin(), StepEnd = step_end();
3249 Step != StepEnd; ++Step) {
3250 if (CurInit.isInvalid())
3251 return S.ExprError();
3252
3253 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003254 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003255
3256 switch (Step->Kind) {
3257 case SK_ResolveAddressOfOverloadedFunction:
3258 // Overload resolution determined which function invoke; update the
3259 // initializer to reflect that choice.
3260 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3261 break;
3262
3263 case SK_CastDerivedToBaseRValue:
3264 case SK_CastDerivedToBaseLValue: {
3265 // We have a derived-to-base cast that produces either an rvalue or an
3266 // lvalue. Perform that cast.
3267
3268 // Casts to inaccessible base classes are allowed with C-style casts.
3269 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3270 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3271 CurInitExpr->getLocStart(),
3272 CurInitExpr->getSourceRange(),
3273 IgnoreBaseAccess))
3274 return S.ExprError();
3275
3276 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3277 CastExpr::CK_DerivedToBase,
3278 (Expr*)CurInit.release(),
3279 Step->Kind == SK_CastDerivedToBaseLValue));
3280 break;
3281 }
3282
3283 case SK_BindReference:
3284 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3285 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3286 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003287 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003288 << BitField->getDeclName()
3289 << CurInitExpr->getSourceRange();
3290 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3291 return S.ExprError();
3292 }
3293
3294 // Reference binding does not have any corresponding ASTs.
3295
3296 // Check exception specifications
3297 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3298 return S.ExprError();
3299 break;
3300
3301 case SK_BindReferenceToTemporary:
3302 // Check exception specifications
3303 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3304 return S.ExprError();
3305
3306 // FIXME: At present, we have no AST to describe when we need to make a
3307 // temporary to bind a reference to. We should.
3308 break;
3309
3310 case SK_UserConversion: {
3311 // We have a user-defined conversion that invokes either a constructor
3312 // or a conversion function.
3313 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003314 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003315 if (CXXConstructorDecl *Constructor
3316 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3317 // Build a call to the selected constructor.
3318 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3319 SourceLocation Loc = CurInitExpr->getLocStart();
3320 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3321
3322 // Determine the arguments required to actually perform the constructor
3323 // call.
3324 if (S.CompleteConstructorCall(Constructor,
3325 Sema::MultiExprArg(S,
3326 (void **)&CurInitExpr,
3327 1),
3328 Loc, ConstructorArgs))
3329 return S.ExprError();
3330
3331 // Build the an expression that constructs a temporary.
3332 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3333 move_arg(ConstructorArgs));
3334 if (CurInit.isInvalid())
3335 return S.ExprError();
3336
3337 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3339 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3340 S.IsDerivedFrom(SourceType, Class))
3341 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003342 } else {
3343 // Build a call to the conversion function.
3344 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003345
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 // FIXME: Should we move this initialization into a separate
3347 // derived-to-base conversion? I believe the answer is "no", because
3348 // we don't want to turn off access control here for c-style casts.
3349 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3350 return S.ExprError();
3351
3352 // Do a little dance to make sure that CurInit has the proper
3353 // pointer.
3354 CurInit.release();
3355
3356 // Build the actual call to the conversion function.
3357 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3358 if (CurInit.isInvalid() || !CurInit.get())
3359 return S.ExprError();
3360
3361 CastKind = CastExpr::CK_UserDefinedConversion;
3362 }
3363
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003364 if (shouldBindAsTemporary(Entity, IsCopy))
3365 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3366
Douglas Gregor20093b42009-12-09 23:02:17 +00003367 CurInitExpr = CurInit.takeAs<Expr>();
3368 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3369 CastKind,
3370 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003371 false));
3372
3373 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003374 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003375 break;
3376 }
3377
3378 case SK_QualificationConversionLValue:
3379 case SK_QualificationConversionRValue:
3380 // Perform a qualification conversion; these can never go wrong.
3381 S.ImpCastExprToType(CurInitExpr, Step->Type,
3382 CastExpr::CK_NoOp,
3383 Step->Kind == SK_QualificationConversionLValue);
3384 CurInit.release();
3385 CurInit = S.Owned(CurInitExpr);
3386 break;
3387
3388 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003389 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003390 false, false, *Step->ICS))
3391 return S.ExprError();
3392
3393 CurInit.release();
3394 CurInit = S.Owned(CurInitExpr);
3395 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003396
3397 case SK_ListInitialization: {
3398 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3399 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003400 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003401 return S.ExprError();
3402
3403 CurInit.release();
3404 CurInit = S.Owned(InitList);
3405 break;
3406 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003407
3408 case SK_ConstructorInitialization: {
3409 CXXConstructorDecl *Constructor
3410 = cast<CXXConstructorDecl>(Step->Function);
3411
3412 // Build a call to the selected constructor.
3413 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3414 SourceLocation Loc = Kind.getLocation();
3415
3416 // Determine the arguments required to actually perform the constructor
3417 // call.
3418 if (S.CompleteConstructorCall(Constructor, move(Args),
3419 Loc, ConstructorArgs))
3420 return S.ExprError();
3421
3422 // Build the an expression that constructs a temporary.
Douglas Gregord6542d82009-12-22 15:35:07 +00003423 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor745880f2009-12-20 22:01:25 +00003424 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003425 move_arg(ConstructorArgs),
3426 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003427 if (CurInit.isInvalid())
3428 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003429
3430 bool Elidable
3431 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3432 if (shouldBindAsTemporary(Entity, Elidable))
3433 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3434
3435 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003436 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003437 break;
3438 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003439
3440 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003441 step_iterator NextStep = Step;
3442 ++NextStep;
3443 if (NextStep != StepEnd &&
3444 NextStep->Kind == SK_ConstructorInitialization) {
3445 // The need for zero-initialization is recorded directly into
3446 // the call to the object's constructor within the next step.
3447 ConstructorInitRequiresZeroInit = true;
3448 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3449 S.getLangOptions().CPlusPlus &&
3450 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003451 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3452 Kind.getRange().getBegin(),
3453 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003454 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003455 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003456 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003457 break;
3458 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003459
3460 case SK_CAssignment: {
3461 QualType SourceType = CurInitExpr->getType();
3462 Sema::AssignConvertType ConvTy =
3463 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003464
3465 // If this is a call, allow conversion to a transparent union.
3466 if (ConvTy != Sema::Compatible &&
3467 Entity.getKind() == InitializedEntity::EK_Parameter &&
3468 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3469 == Sema::Compatible)
3470 ConvTy = Sema::Compatible;
3471
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003472 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3473 Step->Type, SourceType,
3474 CurInitExpr, getAssignmentAction(Entity)))
3475 return S.ExprError();
3476
3477 CurInit.release();
3478 CurInit = S.Owned(CurInitExpr);
3479 break;
3480 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003481
3482 case SK_StringInit: {
3483 QualType Ty = Step->Type;
3484 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3485 break;
3486 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003487 }
3488 }
3489
3490 return move(CurInit);
3491}
3492
3493//===----------------------------------------------------------------------===//
3494// Diagnose initialization failures
3495//===----------------------------------------------------------------------===//
3496bool InitializationSequence::Diagnose(Sema &S,
3497 const InitializedEntity &Entity,
3498 const InitializationKind &Kind,
3499 Expr **Args, unsigned NumArgs) {
3500 if (SequenceKind != FailedSequence)
3501 return false;
3502
Douglas Gregord6542d82009-12-22 15:35:07 +00003503 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003504 switch (Failure) {
3505 case FK_TooManyInitsForReference:
3506 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3507 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3508 break;
3509
3510 case FK_ArrayNeedsInitList:
3511 case FK_ArrayNeedsInitListOrStringLiteral:
3512 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3513 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3514 break;
3515
3516 case FK_AddressOfOverloadFailed:
3517 S.ResolveAddressOfOverloadedFunction(Args[0],
3518 DestType.getNonReferenceType(),
3519 true);
3520 break;
3521
3522 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003523 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003524 switch (FailedOverloadResult) {
3525 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003526 if (Failure == FK_UserConversionOverloadFailed)
3527 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3528 << Args[0]->getType() << DestType
3529 << Args[0]->getSourceRange();
3530 else
3531 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3532 << DestType << Args[0]->getType()
3533 << Args[0]->getSourceRange();
3534
John McCallcbce6062010-01-12 07:18:19 +00003535 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3536 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003537 break;
3538
3539 case OR_No_Viable_Function:
3540 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3541 << Args[0]->getType() << DestType.getNonReferenceType()
3542 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003543 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3544 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003545 break;
3546
3547 case OR_Deleted: {
3548 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3549 << Args[0]->getType() << DestType.getNonReferenceType()
3550 << Args[0]->getSourceRange();
3551 OverloadCandidateSet::iterator Best;
3552 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3553 Kind.getLocation(),
3554 Best);
3555 if (Ovl == OR_Deleted) {
3556 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3557 << Best->Function->isDeleted();
3558 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003559 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003560 }
3561 break;
3562 }
3563
3564 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003565 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 break;
3567 }
3568 break;
3569
3570 case FK_NonConstLValueReferenceBindingToTemporary:
3571 case FK_NonConstLValueReferenceBindingToUnrelated:
3572 S.Diag(Kind.getLocation(),
3573 Failure == FK_NonConstLValueReferenceBindingToTemporary
3574 ? diag::err_lvalue_reference_bind_to_temporary
3575 : diag::err_lvalue_reference_bind_to_unrelated)
3576 << DestType.getNonReferenceType()
3577 << Args[0]->getType()
3578 << Args[0]->getSourceRange();
3579 break;
3580
3581 case FK_RValueReferenceBindingToLValue:
3582 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3583 << Args[0]->getSourceRange();
3584 break;
3585
3586 case FK_ReferenceInitDropsQualifiers:
3587 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3588 << DestType.getNonReferenceType()
3589 << Args[0]->getType()
3590 << Args[0]->getSourceRange();
3591 break;
3592
3593 case FK_ReferenceInitFailed:
3594 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3595 << DestType.getNonReferenceType()
3596 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3597 << Args[0]->getType()
3598 << Args[0]->getSourceRange();
3599 break;
3600
3601 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003602 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3603 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003604 << DestType
3605 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3606 << Args[0]->getType()
3607 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003608 break;
3609
3610 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003611 SourceRange R;
3612
3613 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3614 R = SourceRange(InitList->getInit(1)->getLocStart(),
3615 InitList->getLocEnd());
3616 else
3617 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003618
3619 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003620 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003621 break;
3622 }
3623
3624 case FK_ReferenceBindingToInitList:
3625 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3626 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3627 break;
3628
3629 case FK_InitListBadDestinationType:
3630 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3631 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3632 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003633
3634 case FK_ConstructorOverloadFailed: {
3635 SourceRange ArgsRange;
3636 if (NumArgs)
3637 ArgsRange = SourceRange(Args[0]->getLocStart(),
3638 Args[NumArgs - 1]->getLocEnd());
3639
3640 // FIXME: Using "DestType" for the entity we're printing is probably
3641 // bad.
3642 switch (FailedOverloadResult) {
3643 case OR_Ambiguous:
3644 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3645 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003646 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003647 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003648 break;
3649
3650 case OR_No_Viable_Function:
3651 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3652 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003653 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3654 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003655 break;
3656
3657 case OR_Deleted: {
3658 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3659 << true << DestType << ArgsRange;
3660 OverloadCandidateSet::iterator Best;
3661 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3662 Kind.getLocation(),
3663 Best);
3664 if (Ovl == OR_Deleted) {
3665 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3666 << Best->Function->isDeleted();
3667 } else {
3668 llvm_unreachable("Inconsistent overload resolution?");
3669 }
3670 break;
3671 }
3672
3673 case OR_Success:
3674 llvm_unreachable("Conversion did not fail!");
3675 break;
3676 }
3677 break;
3678 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003679
3680 case FK_DefaultInitOfConst:
3681 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3682 << DestType;
3683 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003684 }
3685
3686 return true;
3687}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003688
3689//===----------------------------------------------------------------------===//
3690// Initialization helper functions
3691//===----------------------------------------------------------------------===//
3692Sema::OwningExprResult
3693Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3694 SourceLocation EqualLoc,
3695 OwningExprResult Init) {
3696 if (Init.isInvalid())
3697 return ExprError();
3698
3699 Expr *InitE = (Expr *)Init.get();
3700 assert(InitE && "No initialization expression?");
3701
3702 if (EqualLoc.isInvalid())
3703 EqualLoc = InitE->getLocStart();
3704
3705 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3706 EqualLoc);
3707 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3708 Init.release();
3709 return Seq.Perform(*this, Entity, Kind,
3710 MultiExprArg(*this, (void**)&InitE, 1));
3711}